Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
11 / 11 |
|
100.00% |
4 / 4 |
CRAP | |
100.00% |
1 / 1 |
| Renderer | |
100.00% |
11 / 11 |
|
100.00% |
4 / 4 |
6 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| render | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
2 | |||
| createEngine | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
| contentType | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Cosray\View\Boiler; |
| 6 | |
| 7 | use Celema\Boiler\Engine; |
| 8 | use Cosray\Markup; |
| 9 | use Cosray\Renderer as RendererInterface; |
| 10 | use Cosray\Value\Value; |
| 11 | use Override; |
| 12 | |
| 13 | /** @phpstan-import-type DirsInput from \Celema\Boiler\Engine */ |
| 14 | class Renderer implements RendererInterface |
| 15 | { |
| 16 | /** Cosray's classes whose string conversion is safe HTML, trusted by every Boiler renderer. */ |
| 17 | public const array TRUSTED = [Value::class, Markup::class]; |
| 18 | |
| 19 | /** |
| 20 | * @param DirsInput $dirs |
| 21 | * @param array<string, mixed> $defaults |
| 22 | * @param list<class-string> $trusted |
| 23 | */ |
| 24 | public function __construct( |
| 25 | protected string|array $dirs, |
| 26 | protected array $defaults = [], |
| 27 | protected array $trusted = [], |
| 28 | protected bool $autoescape = true, |
| 29 | protected string $contentType = 'text/html', |
| 30 | ) {} |
| 31 | |
| 32 | /** |
| 33 | * @param non-empty-string $id |
| 34 | * @param array<string, mixed> $context |
| 35 | */ |
| 36 | #[Override] |
| 37 | public function render(string $id, array $context): string |
| 38 | { |
| 39 | $dirs = $this->dirs; |
| 40 | |
| 41 | if (count((array) $dirs) === 0) { |
| 42 | throw new RendererException('Provide at least one template directory'); |
| 43 | } |
| 44 | |
| 45 | $engine = $this->createEngine($dirs); |
| 46 | |
| 47 | return $engine->render($id, $context); |
| 48 | } |
| 49 | |
| 50 | /** @param DirsInput $dirs */ |
| 51 | protected function createEngine(string|array $dirs): Engine |
| 52 | { |
| 53 | $trusted = [...self::TRUSTED, ...$this->trusted]; |
| 54 | |
| 55 | return $this->autoescape |
| 56 | ? Engine::create($dirs, $this->defaults, $trusted) |
| 57 | : Engine::unescaped($dirs, $this->defaults, $trusted); |
| 58 | } |
| 59 | |
| 60 | #[Override] |
| 61 | public function contentType(): string |
| 62 | { |
| 63 | return $this->contentType; |
| 64 | } |
| 65 | } |