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; |
|
|
|
|
57
|
|
|
} |
58
|
|
|
protected function getLayoutParams(string $pageContent): array |
59
|
|
|
{ |
60
|
|
|
return ['content' => $pageContent]; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|