-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContainer.php
74 lines (64 loc) · 1.87 KB
/
Container.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
namespace ICanBoogie\Render\EngineProvider;
use Closure;
use ICanBoogie\Render\Engine;
use ICanBoogie\Render\EngineProvider;
use ICanBoogie\Render\ExtensionResolver;
use IteratorAggregate;
use Psr\Container\ContainerInterface;
use Traversable;
/**
* An engine provider that uses a container.
*
* @implements IteratorAggregate<string, Engine>
* Where _key_ is a file extension.
*/
final readonly class Container implements EngineProvider, IteratorAggregate
{
/**
* @param array<string, string> $mapping
* Where _key_ is a file extension and _value_ a service identifier.
*/
public function __construct(
private ContainerInterface $container,
private array $mapping
) {
}
public function engine_for_extension(string $extension): ?Engine
{
ExtensionResolver::assert_extension($extension);
$id = $this->mapping[$extension] ?? null;
if (!$id) {
return null;
}
/** @var Engine */
return $this->container->get($id);
}
public function getIterator(): Traversable
{
foreach ($this->mapping as $extension => $id) {
yield $extension => $this->makeProxy($id);
}
}
public function makeProxy(string $id): Engine
{
return new class ($id, $this->container->get(...)) implements Engine {
public function __construct(
private readonly string $id,
private readonly Closure $get,
) {
}
public function render(
string $template_pathname,
mixed $content,
array $variables
): string {
return ($this->get)($this->id)->render(
$template_pathname,
$content,
$variables
);
}
};
}
}