Passed
Pull Request — master (#75)
by
unknown
22:37 queued 07:36
created

WebViewConverter   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
eloc 25
c 1
b 0
f 0
dl 0
loc 50
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getViewPath() 0 3 1
A getLayoutParams() 0 3 1
A getFormat() 0 3 1
A convert() 0 21 6
A setHeaders() 0 3 1
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