Test Failed
Pull Request — master (#78)
by Alexander
02:13
created

ArrayDefinitionBuilder::injectArguments()   B

Complexity

Conditions 9
Paths 36

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 17
nc 36
nop 2
dl 0
loc 23
rs 8.0555
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Factory\Definitions;
6
7
use Psr\Container\ContainerInterface;
8
use Yiisoft\Factory\Exceptions\InvalidConfigException;
9
use Yiisoft\Factory\Exceptions\NotInstantiableException;
10
use Yiisoft\Factory\Extractors\DefinitionExtractor;
11
12
use function array_key_exists;
13
use function call_user_func_array;
14
use function is_string;
15
16
/**
17
 * @internal Builds object by ArrayDefinition.
18
 */
19
final class ArrayDefinitionBuilder
20
{
21
    private static ?self $instance = null;
22
    private static ?DefinitionExtractor $extractor = null;
23
24
    /**
25
     * @psalm-var array<string, array<string, DefinitionInterface>>
26
     */
27
    private static array $dependencies = [];
28
29
    private function __construct()
30
    {
31
    }
32
33
    public static function getInstance(): self
34
    {
35
        if (self::$instance === null) {
36
            self::$instance = new self();
37
        }
38
39
        return self::$instance;
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::instance could return the type null which is incompatible with the type-hinted return Yiisoft\Factory\Definitions\ArrayDefinitionBuilder. Consider adding an additional type-check to rule them out.
Loading history...
40
    }
41
42
    /**
43
     * @throws NotInstantiableException
44
     * @throws InvalidConfigException
45
     */
46
    public function build(ContainerInterface $container, ArrayDefinition $definition): object
47
    {
48
        $class = $definition->getClass();
49
        $dependencies = $this->getDependencies($class);
50
        $constructorArguments = $definition->getConstructorArguments();
51
52
        $this->injectArguments($dependencies, $constructorArguments);
53
54
        $resolved = DefinitionResolver::resolveArray($container, $dependencies);
55
56
        /** @psalm-suppress MixedMethodCall */
57
        $object = new $class(...array_values($resolved));
58
59
        $properties = DefinitionResolver::resolveArray($container, $definition->getSetProperties());
60
        /** @var mixed $value */
61
        foreach ($properties as $property => $value) {
62
            $object->$property = $value;
63
        }
64
65
        /** @psalm-var array<string,array> $calls */
66
        $calls = DefinitionResolver::resolveArray($container, $definition->getMethodCalls());
67
        foreach ($calls as $method => $arguments) {
68
            /** @var mixed */
69
            $setter = call_user_func_array([$object, $method], $arguments);
70
            if ($setter instanceof $object) {
71
                /** @var object */
72
                $object = $setter;
73
            }
74
        }
75
76
        return $object;
77
    }
78
79
    /**
80
     * @psalm-param array<string, DefinitionInterface> $dependencies
81
     *
82
     * @throws InvalidConfigException
83
     */
84
    private function injectArguments(array &$dependencies, array $arguments): void
85
    {
86
        $isIntegerIndexed = $this->isIntegerIndexed($arguments);
87
        $dependencyIndex = 0;
88
        $usedArguments = [];
89
        $isVariadic = false;
90
        foreach ($dependencies as $key => &$value) {
91
            if ($value instanceof ParameterDefinition && $value->getParameter()->isVariadic()) {
92
                $isVariadic = true;
93
            }
94
            $index = $isIntegerIndexed ? $dependencyIndex : $key;
95
            if (array_key_exists($index, $arguments)) {
96
                $value = DefinitionResolver::ensureResolvable($arguments[$index]);
97
                $usedArguments[$index] = 1;
98
            }
99
            $dependencyIndex++;
100
        }
101
        unset($value);
102
        if ($isVariadic) {
103
            /** @var mixed $value */
104
            foreach ($arguments as $index => $value) {
105
                if (!isset($usedArguments[$index])) {
106
                    $dependencies[$index] = DefinitionResolver::ensureResolvable($value);
107
                }
108
            }
109
        }
110
        /** @psalm-var array<string, DefinitionInterface> $dependencies */
111
    }
112
113
    private function isIntegerIndexed(array $arguments): bool
114
    {
115
        $hasStringIndex = false;
116
        $hasIntegerIndex = false;
117
118
        foreach ($arguments as $index => $_argument) {
119
            if (is_string($index)) {
120
                $hasStringIndex = true;
121
                if ($hasIntegerIndex) {
122
                    break;
123
                }
124
            } else {
125
                $hasIntegerIndex = true;
126
                if ($hasStringIndex) {
127
                    break;
128
                }
129
            }
130
        }
131
        if ($hasIntegerIndex && $hasStringIndex) {
132
            throw new InvalidConfigException(
133
                'Arguments indexed both by name and by position are not allowed in the same array.'
134
            );
135
        }
136
137
        return $hasIntegerIndex;
138
    }
139
140
    /**
141
     * Returns the dependencies of the specified class.
142
     *
143
     * @param class-string $class Class name or interface name.
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string.
Loading history...
144
     *
145
     * @throws NotInstantiableException
146
     *
147
     * @return DefinitionInterface[] The dependencies of the specified class.
148
     * @psalm-return array<string, DefinitionInterface>
149
     */
150
    private function getDependencies(string $class): array
151
    {
152
        if (!isset(self::$dependencies[$class])) {
153
            self::$dependencies[$class] = $this->getExtractor()->fromClassName($class);
154
        }
155
156
        return self::$dependencies[$class];
157
    }
158
159
    private function getExtractor(): DefinitionExtractor
160
    {
161
        if (self::$extractor === null) {
162
            // For now use hard coded extractor.
163
            self::$extractor = new DefinitionExtractor();
164
        }
165
166
        return self::$extractor;
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::extractor could return the type null which is incompatible with the type-hinted return Yiisoft\Factory\Extractors\DefinitionExtractor. Consider adding an additional type-check to rule them out.
Loading history...
167
    }
168
}
169