Test Failed
Pull Request — master (#37)
by Divine Niiquaye
02:57
created

ContainerBuilder::doResolveClass()   B

Complexity

Conditions 10
Paths 19

Size

Total Lines 25
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 10.0454

Importance

Changes 0
Metric Value
eloc 13
c 0
b 0
f 0
dl 0
loc 25
ccs 12
cts 13
cp 0.9231
rs 7.6666
cc 10
nc 19
nop 3
crap 10.0454

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of DivineNii opensource projects.
7
 *
8
 * PHP version 7.4 and above required
9
 *
10
 * @author    Divine Niiquaye Ibok <[email protected]>
11
 * @copyright 2021 DivineNii (https://divinenii.com/)
12
 * @license   https://opensource.org/licenses/BSD-3-Clause License
13
 *
14
 * For the full copyright and license information, please view the LICENSE
15
 * file that was distributed with this source code.
16
 */
17
18
namespace Rade\DI;
19
20
use PhpParser\Node\{Expr, Name, Scalar, Scalar\String_};
21
use PhpParser\Node\Stmt\{ClassMethod, Declare_, DeclareDeclare, Expression, Nop};
22
use Rade\DI\Definitions\{DefinitionInterface, ShareableDefinitionInterface};
23
use Rade\DI\Exceptions\ServiceCreationException;
24
use Symfony\Component\Config\Resource\ResourceInterface;
25
26
/**
27
 * A compilable container to build services easily.
28
 *
29
 * Generates a compiled container. This means that there is no runtime performance impact.
30
 *
31
 * @author Divine Niiquaye Ibok <[email protected]>
32
 */
33
class ContainerBuilder extends AbstractContainer
34
{
35
    public const BUILD_SERVICE_DEFINITION = 3;
36
37
    /** @var array<string,ResourceInterface>|null */
38
    private ?array $resources;
39
40
    /** Name of the compiled container parent class. */
41
    private string $containerParentClass;
42
43
    private ?\PhpParser\NodeTraverser $nodeTraverser = null;
44
45
    /**
46
     * Compile the container for optimum performances.
47
     *
48
     * @param string $containerParentClass Name of the compiled container parent class. Customize only if necessary.
49
     */
50
    public function __construct(string $containerParentClass = Container::class)
51
    {
52
        if (!\class_exists(\PhpParser\BuilderFactory::class)) {
53
            throw new \RuntimeException('ContainerBuilder uses "nikic/php-parser" v4, do composer require the nikic/php-parser package.');
54
        }
55
56
        $this->containerParentClass = $c = $containerParentClass;
57
        $this->resources = \interface_exists(ResourceInterface::class) ? [] : null;
58 40
        $this->resolver = new Resolver($this, new \PhpParser\BuilderFactory());
59
        $this->services[self::SERVICE_CONTAINER] = new Expr\Variable('this');
60 40
        $this->type(self::SERVICE_CONTAINER, \array_keys((\class_implements($c) ?: []) + (\class_parents($c) ?: []) + [$c => $c]));
61 40
    }
62
63 40
    /**
64 40
     * {@inheritdoc}
65
     */
66 40
    public function set(string $id, object $definition = null): object
67 40
    {
68 40
        if ($definition instanceof \PhpParser\Node) {
69
            $definition = new Definitions\ValueDefinition($definition);
70
        }
71
72
        return parent::set($id, $definition);
73 17
    }
74
75 17
    /**
76 1
     * {@inheritdoc}
77
     */
78
    public function reset(): void
79 16
    {
80 16
        parent::reset();
81
        $this->nodeTraverser = null;
82 16
83
        if (isset($this->resources)) {
84
            $this->resources = [];
85
        }
86 16
    }
87
88
    /**
89
     * Returns an array of resources loaded to build this configuration.
90
     *
91
     * @return ResourceInterface[] An array of resources
92
     */
93
    public function getResources(): array
94
    {
95
        return \array_values($this->resources ?? []);
96
    }
97
98
    /**
99
     * Add a resource to allow re-build of container.
100 2
     *
101
     * @return $this
102 2
     */
103
    public function addResource(ResourceInterface $resource)
104 2
    {
105 1
        if (\is_array($this->resources)) {
106
            $this->resources[(string) $resource] = $resource;
107
        }
108
109 1
        return $this;
110
    }
111 1
112
    /**
113
     * Add a node visitor to traverse the generated ast.
114
     *
115
     * @return $this
116
     */
117 17
    public function addNodeVisitor(\PhpParser\NodeVisitor $nodeVisitor)
118
    {
119 17
        if (null === $this->nodeTraverser) {
120
            $this->nodeTraverser = new \PhpParser\NodeTraverser();
121
        }
122
123
        $this->nodeTraverser->addVisitor($nodeVisitor);
124
125
        return $this;
126
    }
127
128
    /**
129 10
     * Compiles the container.
130
     * This method main job is to manipulate and optimize the container.
131 10
     *
132 1
     * supported $options config (defaults):
133 1
     * - strictType => true,
134
     * - printToString => true,
135
     * - shortArraySyntax => true,
136
     * - maxLineLength => 200,
137 9
     * - containerClass => CompiledContainer,
138
     *
139
     * @throws \ReflectionException
140
     *
141
     * @return \PhpParser\Node[]|string
142
     */
143
    public function compile(array $options = [])
144
    {
145
        $options += ['strictType' => true, 'printToString' => true, 'containerClass' => 'CompiledContainer'];
146
        $astNodes = $options['strictType'] ? [new Declare_([new DeclareDeclare('strict_types', $this->resolver->getBuilder()->val(1))])] : [];
147 49
148
        $processedData = $this->doAnalyse($this->definitions);
149 49
        $containerNode = $this->resolver->getBuilder()->class($options['containerClass'])->extend($this->containerParentClass)->setDocComment(Builder\CodePrinter::COMMENT);
150
151 49
        if (!empty($processedData[0])) {
152 49
            $containerNode->addStmt($this->resolver->getBuilder()->property('aliases')->makeProtected()->setType('array')->setDefault($processedData[0]));
153 22
        }
154
155
        if (!empty($parameters = $this->parameters)) {
156 49
            \ksort($parameters);
157
            $this->compileToConstructor($this->resolveParameters($parameters), $containerNode, 'parameters');
158
        }
159 49
160
        if (!empty($processedData[1]) && count($processedData[1]) > 1) {
161
            unset($processedData[1][self::SERVICE_CONTAINER]);
162
            $containerNode->addStmt($this->resolver->getBuilder()->property('methodsMap')->makeProtected()->setType('array')->setDefault($processedData[1]));
163
        }
164
165 17
        if (!empty($processedData[3])) {
166
            $containerNode->addStmt($this->resolver->getBuilder()->property('types')->makeProtected()->setType('array')->setDefault($processedData[3]));
167
        }
168 17
169 9
        if (!empty($processedData[4])) {
170
            $containerNode->addStmt($this->resolver->getBuilder()->property('tags')->makeProtected()->setType('array')->setDefault($processedData[4]));
171 16
        }
172 12
173
        if (!empty($processedData[2])) {
174 8
            $containerNode->addStmts($processedData[2]);
175 7
        }
176
177 2
        $astNodes[] = $containerNode->getNode(); // Build the container class
178 1
179
        if (null !== $this->nodeTraverser) {
180
            $astNodes = $this->nodeTraverser->traverse($astNodes);
181 1
        }
182
183
        if ($options['printToString']) {
184
            unset($options['strictType'], $options['printToString'], $options['containerClass']);
185
186
            return Builder\CodePrinter::print($astNodes, $options);
187
        }
188 39
189
        return $astNodes;
190 39
    }
191
192
    /**
193
     * @param mixed $definition
194
     *
195
     * @return mixed
196 1
     */
197
    public function dumpObject(string $id, $definition)
198 1
    {
199 1
        $method = $this->resolver->getBuilder()->method($this->resolver::createMethod($id))->makeProtected();
200
        $cachedService = new Expr\ArrayDimFetch(new Expr\PropertyFetch(new Expr\Variable('this'), 'services'), new String_($id));
201
202 1
        if ($definition instanceof Expression) {
203 1
            $definition = $definition->expr;
204
        }
205
206
        if ($definition instanceof \PhpParser\Node) {
207
            if ($definition instanceof Expr\Array_) {
208 11
                $method->setReturnType('array');
209
            } elseif ($definition instanceof Expr\New_) {
210 11
                $method->setReturnType($definition->class->toString());
0 ignored issues
show
Bug introduced by
The method toString() does not exist on PhpParser\Node\Expr. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

210
                $method->setReturnType($definition->class->/** @scrutinizer ignore-call */ toString());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method toString() does not exist on PhpParser\Node\Stmt\Class_. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

210
                $method->setReturnType($definition->class->/** @scrutinizer ignore-call */ toString());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
211
            }
212
        } elseif (\is_object($definition)) {
213
            if ($definition instanceof \Closure) {
214
                throw new ServiceCreationException(\sprintf('Cannot dump closure for service "%s".', $id));
215
            }
216
217
            if ($definition instanceof \stdClass) {
218 2
                $method->setReturnType('object');
219
                $definition = new Expr\Cast\Object_($this->resolver->getBuilder()->val($this->resolver->resolveArguments((array) $definition)));
220 2
            } elseif ($definition instanceof \IteratorAggregate) {
221
                $method->setReturnType('iterable');
222
                $definition = $this->resolver->getBuilder()->new(\get_class($definition), [$this->resolver->resolveArguments(\iterator_to_array($definition))]);
223
            } else {
224
                $method->setReturnType(\get_class($definition));
225
                $definition = $this->resolver->getBuilder()->funcCall('\\unserialize', [new String_(\serialize($definition), ['docLabel' => 'SERIALIZED', 'kind' => String_::KIND_NOWDOC])]);
226
            }
227
        }
228 51
229
        return $method->addStmt(new \PhpParser\Node\Stmt\Return_(new Expr\Assign($cachedService, $this->resolver->getBuilder()->val($definition))));
230 51
    }
231 51
232
    /**
233
     * {@inheritdoc}
234 51
     */
235
    protected function doCreate(string $id, $definition, int $invalidBehavior)
236
    {
237
        if ($definition instanceof String_ && $id === $definition->value) {
238
            unset($this->services[$id]);
239
240
            return null;
241
        }
242
243
        $compiledDefinition = $definition instanceof DefinitionInterface ? $definition->build($id, $this->resolver) : $this->dumpObject($id, $definition);
244
245
        if (self::BUILD_SERVICE_DEFINITION !== $invalidBehavior) {
246
            $resolved = $this->resolver->getBuilder()->methodCall($this->resolver->getBuilder()->var('this'), $this->resolver::createMethod($id));
247
            $serviceType = 'services';
248
249
            if ($definition instanceof ShareableDefinitionInterface) {
250 49
                if (!$definition->isShared()) {
251
                    return $this->services[$id] = $resolved;
252 49
                }
253
254
                if (!$definition->isPublic()) {
255
                    $serviceType = 'privates';
256
                }
257
            }
258
259
            $service = $this->resolver->getBuilder()->propertyFetch($this->resolver->getBuilder()->var('this'), $serviceType);
260
            $createdService = new Expr\BinaryOp\Coalesce(new Expr\ArrayDimFetch($service, new String_($id)), $resolved);
261
262
            return $this->services[$id] = $createdService;
263
        }
264
265
        return $compiledDefinition->getNode();
266
    }
267
268
    /**
269
     * Analyse all definitions, build definitions and return results.
270 12
     *
271
     * @param DefinitionInterface[] $definitions
272 12
     */
273 12
    protected function doAnalyse(array $definitions, bool $onlyDefinitions = false): array
274
    {
275 12
        $methodsMap = $serviceMethods = $wiredTypes = [];
276 1
277 1
        if (!isset($methodsMap[self::SERVICE_CONTAINER])) {
278 1
            $methodsMap[self::SERVICE_CONTAINER] = true;
279 1
        }
280
281
        foreach ($definitions as $id => $definition) {
282 1
            if ($this->tagged('container.remove_services', $id)) {
283 1
                continue;
284
            }
285
286
            $methodsMap[$id] = $this->resolver::createMethod($id);
287 12
288 12
            if ($definition instanceof ShareableDefinitionInterface) {
289
                if (!$definition->isPublic()) {
290
                    unset($methodsMap[$id]);
291 12
                }
292 12
293
                if ($definition->isAbstract()) {
294 12
                    unset($methodsMap[$id]);
295 12
                    continue;
296
                }
297
            }
298 1
299
            $serviceMethods[] = $this->doCreate($id, $definition, self::BUILD_SERVICE_DEFINITION);
300
        }
301
302
        if ($onlyDefinitions) {
303
            return [$methodsMap, $serviceMethods];
304
        }
305
306 18
        if ($newDefinitions = \array_diff_key($this->definitions, $definitions)) {
307
            $processedData = $this->doAnalyse($newDefinitions, true);
308 18
            $methodsMap = \array_merge($methodsMap, $processedData[0]);
309 6
            $serviceMethods = [...$serviceMethods, ...$processedData[1]];
310
        }
311
312
        $aliases = \array_filter($this->aliases, static fn (string $aliased): bool => isset($methodsMap[$aliased]));
313 18
        $tags = \array_filter($this->tags, static fn (array $tagged): bool => isset($methodsMap[\key($tagged)]));
314
315 18
        // Prevent autowired private services from be exported.
316 3
        foreach ($this->types as $type => $ids) {
317
            $ids = \array_filter($ids, static fn (string $id): bool => isset($methodsMap[$id]));
318
319
            if ([] !== $ids) {
320 18
                $ids = \array_values($ids); // If $ids are filtered, keys should not be preserved.
321
                $wiredTypes[] = new Expr\ArrayItem($this->resolver->getBuilder()->val($ids), new String_($type));
322 12
            }
323
        }
324 18
325
        \natsort($aliases);
326
        \ksort($methodsMap);
327
        \ksort($tags, \SORT_NATURAL);
328
        \usort($serviceMethods, fn (ClassMethod $a, ClassMethod $b): int => \strnatcmp($a->name->toString(), $b->name->toString()));
329
        \usort($wiredTypes, fn (Expr\ArrayItem $a, Expr\ArrayItem $b): int => \strnatcmp($a->key->value, $b->key->value));
330
331 12
        return [$aliases, $methodsMap, $serviceMethods, $wiredTypes, $tags];
332
    }
333 12
334 12
    /**
335
     * Build parameters + dynamic parameters in compiled container class.
336 12
     *
337
     * @param array<int,array<string,mixed>> $parameters
338 3
     */
339 3
    protected function compileToConstructor(array $parameters, \PhpParser\Builder\Class_ &$containerNode, string $name): void
340 3
    {
341 3
        [$resolvedParameters, $dynamicParameters] = $parameters;
342
343
        if (!empty($dynamicParameters)) {
344
            $resolver = $this->resolver;
345
            $container = $this->containerParentClass;
346 12
            $containerNode = \Closure::bind(function (\PhpParser\Builder\Class_ $node) use ($dynamicParameters, $resolver, $container, $name) {
347 12
                $endMethod = \array_pop($node->methods);
0 ignored issues
show
Bug introduced by
The property methods is declared protected in PhpParser\Builder\Class_ and cannot be accessed from this context.
Loading history...
348 12
                $constructorNode = $resolver->getBuilder()->method('__construct');
349 12
350 12
                if ($endMethod instanceof ClassMethod && '__construct' === $endMethod->name->name) {
351 12
                    $constructorNode->addStmts([...$endMethod->stmts, new Nop()]);
352 12
                } elseif (\method_exists($container, '__construct')) {
353 12
                    $constructorNode->addStmt($resolver->getBuilder()->staticCall(new Name('parent'), '__construct'));
354 12
                }
355 12
356 12
                foreach ($dynamicParameters as $offset => $value) {
357 12
                    $parameter = $resolver->getBuilder()->propertyFetch($resolver->getBuilder()->var('this'), $name);
358 12
                    $constructorNode->addStmt(new Expr\Assign(new Expr\ArrayDimFetch($parameter, new String_($offset)), $resolver->getBuilder()->val($value)));
359 12
                }
360
361
                return $node->addStmt($constructorNode->makePublic());
362
            }, $containerNode, $containerNode)($containerNode);
363
        }
364
365
        if (!empty($resolvedParameters)) {
366
            $containerNode->addStmt($this->resolver->getBuilder()->property($name)->makePublic()->setType('array')->setDefault($resolvedParameters));
367
        }
368 12
    }
369
370 12
    /**
371 12
     * Resolve parameter's and retrieve dynamic type parameter.
372
     *
373 12
     * @param array<string,mixed> $parameters
374 11
     *
375
     * @return array<int,mixed>
376 11
     */
377 3
    protected function resolveParameters(array $parameters, bool $recursive = false): array
378
    {
379 3
        $resolvedParameters = $dynamicParameters = [];
380
381
        if (!$recursive) {
382 10
            $parameters = $this->resolver->resolveArguments($parameters);
383
        }
384
385
        foreach ($parameters as $parameter => $value) {
386 12
            if (\is_array($value)) {
387 2
                $arrayParameters = $this->resolveParameters($value, $recursive);
388 1
389
                if (!empty($arrayParameters[1])) {
390
                    $grouped = $arrayParameters[1] + $arrayParameters[0];
391
                    \uksort($grouped, fn ($a, $b) => (\is_int($a) && \is_int($b) ? $a <=> $b : 0));
392
                    $dynamicParameters[$parameter] = $grouped;
393 12
                } else {
394 12
                    $resolvedParameters[$parameter] = $arrayParameters[0];
395 1
                }
396
397
                continue;
398 12
            }
399 12
400
            if ($value instanceof Scalar || $value instanceof Expr\ConstFetch) {
401 12
                $resolvedParameters[$parameter] = $value;
402
403
                continue;
404 12
            }
405
406
            $dynamicParameters[$parameter] = $value;
407
        }
408
409
        return [$resolvedParameters, $dynamicParameters];
410 12
    }
411
}
412