Passed
Pull Request — master (#75)
by
unknown
11:38
created

WebViewConverter::getViewPath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Stream\Data;
6
7
use Psr\Http\Message\MessageInterface;
8
use Yiisoft\Aliases\Aliases;
9
use Yiisoft\View\WebView;
10
11
class WebViewConverter implements Converter, \Yiisoft\View\ViewContextInterface
12
{
13
    protected WebView $webView;
14
    protected Aliases $aliases;
15
    protected ?string $viewPath = null;
16
17
    public function __construct(WebView $webView, Aliases $aliases)
18
    {
19
        $this->webView = $webView;
20
        $this->aliases = $aliases;
21
    }
22
    public static function getFormat(): string
23
    {
24
        return 'text/html';
25
    }
26
    public function setHeaders(MessageInterface $message): MessageInterface
27
    {
28
        return $message->withHeader('Content-Type', self::getFormat());
29
    }
30
    public function convert($data, array $params = []): string
31
    {
32
        if (!array_key_exists('view', $params)) {
33
            throw new \InvalidArgumentException('View should be defined in the params array');
34
        }
35
        if (array_key_exists('viewPath', $params)) {
36
            $this->viewPath =  $this->aliases->get($params['viewPath']);
37
        }
38
        $page = $this->webView->render(
39
            $this->aliases->get($params['view']),
40
            $data,
41
            $this->viewPath !== null ? $this : null
42
        );
43
        // render layout
44
        if (!array_key_exists('layout', $params)) {
45
            return $page;
46
        } else {
47
            return $this->webView->renderFile(
48
                $this->aliases->get($params['layout']),
49
                $this->getLayoutParams($page),
50
                $this->viewPath !== null ? $this : null
51
            );
52
        }
53
    }
54
    public function getViewPath(): string
55
    {
56
        return $this->viewPath;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->viewPath could return the type null which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
57
    }
58
    protected function getLayoutParams(string $pageContent): array
59
    {
60
        return ['content' => $pageContent];
61
    }
62
}
63