1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the ICanBoogie package. |
5
|
|
|
* |
6
|
|
|
* (c) Olivier Laviale <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace ICanBoogie\Render\EngineProvider; |
13
|
|
|
|
14
|
|
|
use ICanBoogie\Render\Engine; |
15
|
|
|
use ICanBoogie\Render\EngineProvider; |
16
|
|
|
use ICanBoogie\Render\ExtensionResolver; |
17
|
|
|
use IteratorAggregate; |
18
|
|
|
use Psr\Container\ContainerInterface; |
19
|
|
|
use Traversable; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* An engine provider that uses a container. |
23
|
|
|
* |
24
|
|
|
* @implements IteratorAggregate<string, Engine> |
25
|
|
|
* Where _key_ is a file extension. |
26
|
|
|
*/ |
27
|
|
|
final class Container implements EngineProvider, IteratorAggregate |
28
|
|
|
{ |
29
|
|
|
/** |
30
|
|
|
* @param array<string, string> $mapping |
31
|
|
|
* Where _key_ is a file extension and _value_ a service identifier. |
32
|
|
|
*/ |
33
|
|
|
public function __construct( |
34
|
|
|
private readonly ContainerInterface $container, |
35
|
|
|
private readonly array $mapping |
36
|
|
|
) { |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function engine_for_extension(string $extension): ?Engine |
40
|
|
|
{ |
41
|
|
|
ExtensionResolver::assert_extension($extension); |
42
|
|
|
|
43
|
|
|
$id = $this->mapping[$extension] ?? null; |
44
|
|
|
|
45
|
|
|
if (!$id) { |
46
|
|
|
return null; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return $this->container->get($id); // @phpstan-ignore-line |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function getIterator(): Traversable |
53
|
|
|
{ |
54
|
|
|
foreach ($this->mapping as $extension => $id) { |
55
|
|
|
yield $extension => $this->makeProxy($id); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function makeProxy(string $id): Engine |
60
|
|
|
{ |
61
|
|
|
return new class ($id, $this->container) implements Engine { |
62
|
|
|
public function __construct( |
63
|
|
|
private readonly string $id, |
64
|
|
|
private readonly ContainerInterface $container |
65
|
|
|
) { |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
public function render( |
69
|
|
|
string $template_pathname, |
70
|
|
|
mixed $content, |
71
|
|
|
array $variables |
72
|
|
|
): string { |
73
|
|
|
return $this->container->get($this->id)->render( // @phpstan-ignore-line |
74
|
|
|
$template_pathname, |
75
|
|
|
$content, |
76
|
|
|
$variables |
77
|
|
|
); |
78
|
|
|
} |
79
|
|
|
}; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|