1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App; |
4
|
|
|
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
6
|
|
|
use Yiisoft\Aliases\Aliases; |
7
|
|
|
use Yiisoft\View\ViewContextInterface; |
8
|
|
|
use Yiisoft\View\WebView; |
9
|
|
|
use Yiisoft\Yii\Web\User\User; |
10
|
|
|
use Yiisoft\Yii\Web\Data\DataResponseFactoryInterface; |
11
|
|
|
|
12
|
|
|
abstract class Controller implements ViewContextInterface |
13
|
|
|
{ |
14
|
|
|
protected DataResponseFactoryInterface $responseFactory; |
15
|
|
|
protected User $user; |
16
|
|
|
|
17
|
|
|
private Aliases $aliases; |
18
|
|
|
private WebView $view; |
19
|
|
|
private string $layout; |
20
|
|
|
|
21
|
|
|
public function __construct( |
22
|
|
|
DataResponseFactoryInterface $responseFactory, |
23
|
|
|
User $user, |
24
|
|
|
Aliases $aliases, |
25
|
|
|
WebView $view |
26
|
|
|
) { |
27
|
|
|
$this->responseFactory = $responseFactory; |
28
|
|
|
$this->user = $user; |
29
|
|
|
$this->aliases = $aliases; |
30
|
|
|
$this->view = $view; |
31
|
|
|
$this->layout = $aliases->get('@views') . '/layout/main'; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
protected function render(string $view, array $parameters = []): ResponseInterface |
35
|
|
|
{ |
36
|
|
|
$self = $this; |
37
|
|
|
$contentRenderer = static function () use ($view, $parameters, $self) { |
38
|
|
|
return $self->renderProxy($view, $parameters); |
39
|
|
|
}; |
40
|
|
|
|
41
|
|
|
return $this->responseFactory->createResponse($contentRenderer); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
private function renderProxy($view, $parameters): string |
45
|
|
|
{ |
46
|
|
|
$content = $this->view->render($view, $parameters, $this); |
47
|
|
|
$user = $this->user->getIdentity(); |
48
|
|
|
$layout = $this->findLayoutFile($this->layout); |
49
|
|
|
|
50
|
|
|
if ($layout === null) { |
|
|
|
|
51
|
|
|
return $content; |
52
|
|
|
} |
53
|
|
|
return $this->view->renderFile( |
54
|
|
|
$layout, |
55
|
|
|
[ |
56
|
|
|
'content' => $content, |
57
|
|
|
'user' => $user, |
58
|
|
|
], |
59
|
|
|
$this |
60
|
|
|
); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public function getViewPath(): string |
64
|
|
|
{ |
65
|
|
|
return $this->aliases->get('@views') . '/' . $this->getId(); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
private function findLayoutFile(?string $file): ?string |
69
|
|
|
{ |
70
|
|
|
if ($file === null) { |
71
|
|
|
return null; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
if (pathinfo($file, PATHINFO_EXTENSION) !== '') { |
75
|
|
|
return $file; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return $file . '.' . $this->view->getDefaultExtension(); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
abstract protected function getId(): string; |
82
|
|
|
} |
83
|
|
|
|