Passed
Pull Request — master (#101)
by Evgeniy
15:16
created

Compiler::getDependenciesString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
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
    public function __construct(Reflection $reflection)
20
    {
21 15
        $this->reflection = $reflection;
22
    }
23 15
24 15
    public function autowire(string $name): self
25
    {
26 9
        if (!$this->reflection->isInstantiable($name)) {
27
            return $this;
28 9
        }
29 3
        if ($this->reflection->isVariadic($name)) {
30
            $this->variadic[] = $name;
31 6
        }
32 3
        $this->classes[$name] = $this->reflection->getDependencies($name);
33
        return $this;
34 6
    }
35 6
36 6
    public function compile(): string
37
    {
38
        return "<?php
39
40 9
declare(strict_types=1);
41
42 9
return [{$this->compileClasses()}
43 9
];";
44
    }
45
46 3
    private function compileClasses(): string
47
    {
48 3
        $compiledContainers = '';
49 3
        foreach ($this->classes as $name => $dependencies) {
50
            $class = $this->getClass($name);
51
            $dependenciesString = str_replace("\n", "\n        ", var_export($dependencies, true));
52 15
            $compiledContainers .= <<<TAG
53
54 5
    '$name' => new $class(
55
        '$name',
56
        ...$dependenciesString
57
    ),
58 15
TAG;
59
        }
60
        return $compiledContainers;
61
    }
62 15
63
    private function getClass($name): string
64 15
    {
65 15
        if (in_array($name, $this->variadic)) {
66 15
            return FactoryVariadic::class;
67 3
        }
68
        return Factory::class;
69 15
    }
70
}
71