Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
namespace Syna;
class Engine
{
protected $sharedData = [];
/** @var HelperLocator */
protected $helperLocator;
/** @var ViewLocator */
protected $viewLocator;
/** @var ViewLocator[] */
protected $namedLocators = [];
/**
* Engine constructor.
* @param ViewLocator $viewLocator
* @param HelperLocator $helperLocator
* @param ViewLocator $layoutLocator
*/
public function __construct(
ViewLocator $viewLocator,
HelperLocator $helperLocator = null,
ViewLocator $layoutLocator = null
) {
$this->viewLocator = $viewLocator;
$this->helperLocator = $helperLocator ?? new HelperLocator();
!$layoutLocator ||
$this->namedLocators['layout'] = $layoutLocator;
}
public function addLocator(string $name, HelperLocator $locator): self
{
$this->namedLocators[$name] = $locator;
return $this;
}
public function addSharedData(array $data): self
{
$this->sharedData = array_merge($this->sharedData, $data);
return $this;
}
public function getSharedData()
{
return $this->sharedData;
}
public function view(string $name, array $data = []): View
{
$viewLocator = $this->viewLocator;
if (strpos($name, '::', 1) !== false) {
list($locatorName, $name) = explode('::', $name);
if (!isset($this->namedLocators[$locatorName])) {
throw new \LogicException('No locator for ' . $locatorName . ' defined');
}
$viewLocator = $this->namedLocators[$locatorName];
}
if (!$viewLocator->has($name)) {
throw new \Exception('View ' . $name . ' not found');
}
return new View($this, $viewLocator->getPath($name), $data);
}
public function render(string $name, array $data = [], string $layout = null): string
{
$view = $this->view($name, $data);
$content = $view->render();
if ($layout && isset($this->namedLocators['layout'])) {
$layout = $this->view('layout::' . $layout);
$layout->setSections(array_merge($view->getSections(), ['content' => $content]));
$content = $layout->render();
}
return $content;
}
public function helper(View $view, $function, ...$arguments)
{
if ($this->helperLocator->has($function)) {
$helper = $this->helperLocator->getHelper($function);
$helper->setView($view);
/** @noinspection PhpMethodParametersCountMismatchInspection */
return $helper(...$arguments);
} elseif (is_callable($function)) {
return call_user_func($function, ...$arguments);
}
throw new \LogicException('$function has to be callable or a registered view helper');
}
}