Passed
Pull Request — master (#81)
by Evgeniy
03:11
created

Compiler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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