1: <?php
2:
3: namespace Charcoal\Cms\Route;
4:
5:
6: use Pimple\Container;
7:
8:
9: use Psr\Http\Message\RequestInterface;
10: use Psr\Http\Message\ResponseInterface;
11:
12:
13: use Charcoal\Translator\TranslatorAwareTrait;
14:
15:
16: use Charcoal\App\Route\TemplateRoute;
17:
18:
19: use Charcoal\Cms\SectionInterface;
20: use Charcoal\Object\RoutableInterface;
21:
22: 23: 24:
25: class SectionRoute extends TemplateRoute
26: {
27: use TranslatorAwareTrait;
28:
29: 30: 31: 32: 33:
34: private $path;
35:
36: 37: 38: 39: 40:
41: private $section;
42:
43: 44: 45: 46: 47:
48: private $objType = 'charcoal/cms/section';
49:
50: 51: 52:
53: public function __construct(array $data)
54: {
55: parent::__construct($data);
56:
57: $this->path = ltrim($data['path'], '/');
58: }
59:
60: 61: 62: 63: 64: 65:
66: public function pathResolvable(Container $container)
67: {
68: $section = $this->loadSectionFromPath($container);
69: return !!$section->id();
70: }
71:
72: 73: 74: 75: 76: 77:
78: public function __invoke(
79: Container $container,
80: RequestInterface $request,
81: ResponseInterface $response
82: ) {
83: $config = $this->config();
84:
85: $section = $this->loadSectionFromPath($container);
86:
87: $templateIdent = (string)$section->templateIdent();
88: $templateController = (string)$section->templateIdent();
89:
90: if (!$templateController) {
91: return $response->withStatus(404);
92: }
93:
94: $templateFactory = $container['template/factory'];
95: $templateFactory->setDefaultClass($config['default_controller']);
96:
97: $template = $templateFactory->create($templateController);
98: $template->init($request);
99:
100:
101: $template->setData($config['template_data']);
102: $template->setSection($section);
103:
104: $templateContent = $container['view']->render($templateIdent, $template);
105:
106: $response->write($templateContent);
107:
108: return $response;
109: }
110:
111: 112: 113: 114: 115:
116: protected function loadSectionFromPath(Container $container)
117: {
118: if (!$this->section) {
119: $config = $this->config();
120: $objType = (isset($config['obj_type']) ? $config['obj_type'] : $this->objType);
121:
122: $this->section = $container['model/factory']->create($objType);
123:
124: $langs = $container['translator']->availableLocales();
125: $lang = $this->section->loadFromL10n('slug', $this->path, $langs);
126: $container['translator']->setLocale($lang);
127: }
128:
129: return $this->section;
130: }
131: }
132: