Test Failed
Pull Request — master (#37)
by Divine Niiquaye
02:47
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
    private 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
        parent::__construct();
57
58 40
        $this->containerParentClass = $containerParentClass;
59
        $this->resources = \interface_exists(ResourceInterface::class) ? [] : null;
60 40
61 40
        $this->type(self::SERVICE_CONTAINER, Resolver::autowireService($containerParentClass));
62
    }
63 40
64 40
    /**
65
     * {@inheritdoc}
66 40
     */
67 40
    public function set(string $id, ?object $definition = null): object
68 40
    {
69
        if ($definition instanceof \PhpParser\Node) {
70
            $definition = new Definitions\ValueDefinition($definition);
71
        }
72
73 17
        return parent::set($id, $definition);
74
    }
75 17
76 1
    /**
77
     * {@inheritdoc}
78
     */
79 16
    public function get(string $id, int $invalidBehavior = /* self::EXCEPTION_ON_MULTIPLE_SERVICE */ 1)
80 16
    {
81
        if (isset($this->services[$id])) {
82 16
            return $this->services[$id];
83
        }
84
85
        if (\array_key_exists($id, $this->aliases)) {
86 16
            return $this->services[$id = $this->aliases[$id]] ?? $this->get($id);
87
        }
88
89
        if (self::SERVICE_CONTAINER === $id) {
90
            return $this->services[$id] = new Expr\Variable('this');
91
        }
92
93
        return parent::get($id, $invalidBehavior);
94
    }
95
96
    /**
97
     * Returns an array of resources loaded to build this configuration.
98
     *
99
     * @return ResourceInterface[] An array of resources
100 2
     */
101
    public function getResources(): array
102 2
    {
103
        return \array_values($this->resources ?? []);
104 2
    }
105 1
106
    /**
107
     * Add a resource to allow re-build of container.
108
     *
109 1
     * @return $this
110
     */
111 1
    public function addResource(ResourceInterface $resource)
112
    {
113
        if (\is_array($this->resources)) {
114
            $this->resources[(string) $resource] = $resource;
115
        }
116
117 17
        return $this;
118
    }
119 17
120
    /**
121
     * Add a node visitor to traverse the generated ast.
122
     *
123
     * @return $this
124
     */
125
    public function addNodeVisitor(\PhpParser\NodeVisitor $nodeVisitor)
126
    {
127
        if (null === $this->nodeTraverser) {
128
            $this->nodeTraverser = new \PhpParser\NodeTraverser();
129 10
        }
130
131 10
        $this->nodeTraverser->addVisitor($nodeVisitor);
132 1
133 1
        return $this;
134
    }
135
136
    /**
137 9
     * Compiles the container.
138
     * This method main job is to manipulate and optimize the container.
139
     *
140
     * supported $options config (defaults):
141
     * - strictType => true,
142
     * - printToString => true,
143
     * - shortArraySyntax => true,
144
     * - maxLineLength => 200,
145
     * - containerClass => CompiledContainer,
146
     *
147 49
     * @throws \ReflectionException
148
     *
149 49
     * @return \PhpParser\Node[]|string
150
     */
151 49
    public function compile(array $options = [])
152 49
    {
153 22
        $options += ['strictType' => true, 'printToString' => true, 'containerClass' => 'CompiledContainer'];
154
        $astNodes = $options['strictType'] ? [new Declare_([new DeclareDeclare('strict_types', $this->resolver->getBuilder()->val(1))])] : [];
155
156 49
        $processedData = $this->doAnalyse($this->definitions);
157
        $containerNode = $this->resolver->getBuilder()->class($options['containerClass'])->extend($this->containerParentClass)->setDocComment(Builder\CodePrinter::COMMENT);
158
159 49
        if (!empty($processedData[0])) {
160
            $containerNode->addStmt($this->resolver->getBuilder()->property('aliases')->makeProtected()->setType('array')->setDefault($processedData[0]));
161
        }
162
163
        if (!empty($parameters = $this->parameters)) {
164
            ksort($parameters);
165 17
            $this->compileToConstructor($this->resolveParameters($parameters), $containerNode, 'parameters');
166
        }
167
168 17
        if (!empty($processedData[1])) {
169 9
            unset($processedData[1][self::SERVICE_CONTAINER]);
170
            $containerNode->addStmt($this->resolver->getBuilder()->property('methodsMap')->makeProtected()->setType('array')->setDefault($processedData[1]));
171 16
        }
172 12
173
        if (!empty($processedData[3])) {
174 8
            $containerNode->addStmt($this->resolver->getBuilder()->property('types')->makeProtected()->setType('array')->setDefault($processedData[3]));
175 7
        }
176
177 2
        if (!empty($processedData[4])) {
178 1
            $containerNode->addStmt($this->resolver->getBuilder()->property('tags')->makeProtected()->setType('array')->setDefault($processedData[4]));
179
        }
180
181 1
        $astNodes[] = $containerNode->addStmts($processedData[2])->getNode();
182
183
        if (null !== $this->nodeTraverser) {
184
            $astNodes = $this->nodeTraverser->traverse($astNodes);
185
        }
186
187
        if ($options['printToString']) {
188 39
            unset($options['strictType'], $options['printToString'], $options['containerClass']);
189
190 39
            return Builder\CodePrinter::print($astNodes, $options);
191
        }
192
193
        return $astNodes;
194
    }
195
196 1
    /**
197
     * @param mixed $definition
198 1
     *
199 1
     * @return mixed
200
     */
201
    public function dumpObject(string $id, $definition)
202 1
    {
203 1
        $method = $this->resolver->getBuilder()->method($this->resolver->createMethod($id))->makeProtected();
204
205
        if ($definition instanceof Expression) {
206
            $definition = $definition->expr;
207
        }
208 11
209
        if ($definition instanceof \PhpParser\Node) {
210 11
            if ($definition instanceof Expr\Array_) {
211
                $method->setReturnType('array');
212
            } elseif ($definition instanceof Expr\New_) {
213
                $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

213
                $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

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