|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Cekta\DI; |
|
6
|
|
|
|
|
7
|
|
|
use Cekta\DI\Loader\Alias; |
|
8
|
|
|
use Cekta\DI\Loader\Factory; |
|
9
|
|
|
use Cekta\DI\Loader\FactoryVariadic; |
|
10
|
|
|
|
|
11
|
|
|
class Compiler |
|
12
|
|
|
{ |
|
13
|
|
|
/** |
|
14
|
|
|
* @var Reflection |
|
15
|
|
|
*/ |
|
16
|
|
|
private $reflection; |
|
17
|
|
|
private $classes = []; |
|
18
|
|
|
private $alias = []; |
|
19
|
|
|
private $variadic = []; |
|
20
|
|
|
|
|
21
|
12 |
|
public function __construct(Reflection $reflection) |
|
22
|
|
|
{ |
|
23
|
12 |
|
$this->reflection = $reflection; |
|
24
|
12 |
|
} |
|
25
|
|
|
|
|
26
|
6 |
|
public function autowire(string $name): self |
|
27
|
|
|
{ |
|
28
|
6 |
|
if ($this->reflection->isVariadic($name)) { |
|
29
|
3 |
|
$this->variadic[] = true; |
|
30
|
|
|
} |
|
31
|
6 |
|
return $this->registerClass( |
|
32
|
6 |
|
$name, |
|
33
|
6 |
|
...$this->reflection->getDependencies($name) |
|
34
|
|
|
); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
9 |
|
public function registerClass(string $name, string ...$dependencies): self |
|
38
|
|
|
{ |
|
39
|
9 |
|
$this->classes[$name] = $dependencies; |
|
40
|
9 |
|
return $this; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
3 |
|
public function registerInterface(string $name, string $implementation): self |
|
44
|
|
|
{ |
|
45
|
3 |
|
$this->alias[$name] = $implementation; |
|
46
|
3 |
|
return $this; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
12 |
|
public function compile(): string |
|
50
|
|
|
{ |
|
51
|
4 |
|
return "<?php |
|
52
|
|
|
|
|
53
|
|
|
declare(strict_types=1); |
|
54
|
|
|
|
|
55
|
12 |
|
return [{$this->compileAlias()}{$this->compileClasses()} |
|
56
|
|
|
];"; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
12 |
|
private function compileAlias(): string |
|
60
|
|
|
{ |
|
61
|
12 |
|
$compiledContainers = ''; |
|
62
|
12 |
|
$class = Alias::class; |
|
63
|
12 |
|
foreach ($this->alias as $name => $implementation) { |
|
64
|
3 |
|
$compiledContainers .= "\n '$name' => new $class('$implementation'),"; |
|
65
|
|
|
} |
|
66
|
12 |
|
return $compiledContainers; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
12 |
|
private function compileClasses(): string |
|
70
|
|
|
{ |
|
71
|
12 |
|
$compiledContainers = ''; |
|
72
|
12 |
|
foreach ($this->classes as $name => $dependencies) { |
|
73
|
9 |
|
$class = Factory::class; |
|
74
|
9 |
|
if (in_array($name, $this->variadic)) { |
|
75
|
3 |
|
$class = FactoryVariadic::class; |
|
76
|
|
|
} |
|
77
|
9 |
|
$dependenciesExported = str_replace(PHP_EOL, '', var_export($dependencies, true)); |
|
78
|
|
|
$compiledContainers .= <<<TAG |
|
79
|
|
|
|
|
80
|
9 |
|
'$name' => new $class( |
|
81
|
9 |
|
'$name', |
|
82
|
9 |
|
...$dependenciesExported |
|
83
|
|
|
), |
|
84
|
|
|
TAG; |
|
85
|
|
|
} |
|
86
|
12 |
|
return $compiledContainers; |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|