Test Failed
Pull Request — master (#37)
by Divine Niiquaye
11:51
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, Resolvers\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($resolvers = $this->resolvers)) {
169 9
            \ksort($resolvers);
170
            $this->compileToConstructor($this->resolveParameters($resolvers), $containerNode, 'resolvers');
171 16
        }
172 12
173
        if (!empty($processedData[1])) {
174 8
            unset($processedData[1][self::SERVICE_CONTAINER]);
175 7
            $containerNode->addStmt($this->resolver->getBuilder()->property('methodsMap')->makeProtected()->setType('array')->setDefault($processedData[1]));
176
        }
177 2
178 1
        if (!empty($processedData[3])) {
179
            $containerNode->addStmt($this->resolver->getBuilder()->property('types')->makeProtected()->setType('array')->setDefault($processedData[3]));
180
        }
181 1
182
        if (!empty($processedData[4])) {
183
            $containerNode->addStmt($this->resolver->getBuilder()->property('tags')->makeProtected()->setType('array')->setDefault($processedData[4]));
184
        }
185
186
        $astNodes[] = $containerNode->addStmts($processedData[2])->getNode();
187
188 39
        if (null !== $this->nodeTraverser) {
189
            $astNodes = $this->nodeTraverser->traverse($astNodes);
190 39
        }
191
192
        if ($options['printToString']) {
193
            unset($options['strictType'], $options['printToString'], $options['containerClass']);
194
195
            return Builder\CodePrinter::print($astNodes, $options);
196 1
        }
197
198 1
        return $astNodes;
199 1
    }
200
201
    /**
202 1
     * @param mixed $definition
203 1
     *
204
     * @return mixed
205
     */
206
    public function dumpObject(string $id, $definition)
207
    {
208 11
        $method = $this->resolver->getBuilder()->method($this->resolver->createMethod($id))->makeProtected();
209
210 11
        if ($definition instanceof Expression) {
211
            $definition = $definition->expr;
212
        }
213
214
        if ($definition instanceof \PhpParser\Node) {
215
            if ($definition instanceof Expr\Array_) {
216
                $method->setReturnType('array');
217
            } elseif ($definition instanceof Expr\New_) {
218 2
                $method->setReturnType($definition->class->toString());
0 ignored issues
show
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

218
                $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\Expr. ( Ignorable by Annotation )

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

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