Passed
Pull Request — master (#101)
by Evgeniy
09:40 queued 07:19
created

Compiler   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 27
dl 0
loc 59
ccs 26
cts 26
cp 1
rs 10
c 2
b 1
f 0
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A compile() 0 7 1
A getClass() 0 6 2
A compileClasses() 0 15 2
A __construct() 0 3 1
A autowire() 0 10 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cekta\DI;
6
7
use Cekta\DI\Loader\Factory;
8
use Cekta\DI\Loader\FactoryVariadic;
9
10
class Compiler
11
{
12
    /**
13
     * @var Reflection
14
     */
15
    private $reflection;
16
    private $classes = [];
17
    private $variadic = [];
18
19 9
    public function __construct(Reflection $reflection)
20
    {
21 9
        $this->reflection = $reflection;
22 9
    }
23
24 9
    public function autowire(string $name): self
25
    {
26 9
        if (!$this->reflection->isInstantiable($name)) {
27 3
            return $this;
28
        }
29 6
        if ($this->reflection->isVariadic($name)) {
30 3
            $this->variadic[] = $name;
31
        }
32 6
        $this->classes[$name] = $this->reflection->getDependencies($name);
33 6
        return $this;
34
    }
35
36 9
    public function compile(): string
37
    {
38 3
        return "<?php
39
40
declare(strict_types=1);
41
42 9
return [{$this->compileClasses()}
43
];";
44
    }
45
46 9
    private function compileClasses(): string
47
    {
48 9
        $compiledContainers = '';
49 9
        foreach ($this->classes as $name => $dependencies) {
50 6
            $class = $this->getClass($name);
51 6
            $dependenciesString = str_replace("\n", "\n        ", var_export($dependencies, true));
52
            $compiledContainers .= <<<TAG
53
54 6
    '$name' => new $class(
55 6
        '$name',
56 6
        ...$dependenciesString
57
    ),
58
TAG;
59
        }
60 9
        return $compiledContainers;
61
    }
62
63 6
    private function getClass($name): string
64
    {
65 6
        if (in_array($name, $this->variadic)) {
66 3
            return FactoryVariadic::class;
67
        }
68 3
        return Factory::class;
69
    }
70
}
71