Passed
Pull Request — master (#75)
by
unknown
14:51
created

WebViewConverter   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
eloc 24
c 1
b 0
f 0
dl 0
loc 46
rs 10

5 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
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Stream\Data;
6
7
use Yiisoft\Aliases\Aliases;
8
use Yiisoft\View\WebView;
9
10
class WebViewConverter implements Converter, \Yiisoft\View\ViewContextInterface
11
{
12
    protected WebView $webView;
13
    protected Aliases $aliases;
14
    protected ?string $viewPath = null;
15
16
    public function __construct(WebView $webView, Aliases $aliases)
17
    {
18
        $this->webView = $webView;
19
        $this->aliases = $aliases;
20
    }
21
    public static function getFormat(): string
22
    {
23
        return 'text/html';
24
    }
25
    public function convert($data, array $params = []): string
26
    {
27
        if (!array_key_exists('view', $params)) {
28
            throw new \InvalidArgumentException('View should be defined in the params array');
29
        }
30
        if (array_key_exists('viewPath', $params)) {
31
            $this->viewPath =  $this->aliases->get($params['viewPath']);
32
        }
33
        $page = $this->webView->render(
34
            $this->aliases->get($params['view']),
35
            $data,
36
            $this->viewPath !== null ? $this : null
37
        );
38
        // render layout
39
        if (!array_key_exists('layout', $params)) {
40
            return $page;
41
        } else {
42
            return $this->webView->renderFile(
43
                $this->aliases->get($params['layout']),
44
                $this->getLayoutParams($page),
45
                $this->viewPath !== null ? $this : null
46
            );
47
        }
48
    }
49
    public function getViewPath(): string
50
    {
51
        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...
52
    }
53
    protected function getLayoutParams(string $pageContent): array
54
    {
55
        return ['content' => $pageContent];
56
    }
57
}
58