Passed
Push — master ( c565c6...6d601b )
by Alexander
36:25 queued 21:24
created

Controller   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 8
eloc 29
c 2
b 0
f 0
dl 0
loc 67
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
A findLayoutFile() 0 11 3
A getViewPath() 0 3 1
A renderProxy() 0 16 2
A render() 0 5 1
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
        $contentRenderer = fn () => $this->renderProxy($view, $parameters);
37
38
        return $this->responseFactory->createResponse($contentRenderer);
39
    }
40
41
    private function renderProxy(string $view, array $parameters = []): string
42
    {
43
        $content = $this->view->render($view, $parameters, $this);
44
        $user = $this->user->getIdentity();
45
        $layout = $this->findLayoutFile($this->layout);
46
47
        if ($layout === null) {
0 ignored issues
show
introduced by
The condition $layout === null is always false.
Loading history...
48
            return $content;
49
        }
50
        return $this->view->renderFile(
51
            $layout,
52
            [
53
                'content' => $content,
54
                'user' => $user,
55
            ],
56
            $this
57
        );
58
    }
59
60
    public function getViewPath(): string
61
    {
62
        return $this->aliases->get('@views') . '/' . $this->getId();
63
    }
64
65
    private function findLayoutFile(?string $file): ?string
66
    {
67
        if ($file === null) {
68
            return null;
69
        }
70
71
        if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
72
            return $file;
73
        }
74
75
        return $file . '.' . $this->view->getDefaultExtension();
76
    }
77
78
    abstract protected function getId(): string;
79
}
80