Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
PhpdiContainerBuilder
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
4 / 4
7
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 build
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 buildSingle
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 resolveArgument
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2
3declare(strict_types=1);
4
5namespace pvc\container\container_builder;
6
7use DI\ContainerBuilder;
8use DI\Definition\Helper\DefinitionHelper;
9use Psr\Container\ContainerInterface;
10use pvc\container\defs\DefinitionCollection;
11use pvc\interfaces\container\ContainerBuilderInterface;
12use pvc\interfaces\container\DefinitionInterface;
13
14use function DI\create;
15use function DI\get;
16
17class PhpdiContainerBuilder implements ContainerBuilderInterface
18{
19
20
21    public function __construct(
22        protected DefinitionCollection $definitionCollection,
23    ) {}
24
25    /**
26     * build
27     *
28     * @param  array<DefinitionInterface>  $definitions
29     *
30     * @return ContainerInterface
31     */
32    public function build(array $definitions): ContainerInterface
33    {
34        $this->definitionCollection->hydrate($definitions);
35
36        $phpdiDefinitionsArray = array_map([$this, 'buildSingle'], iterator_to_array($this->definitionCollection));
37        $builder = new ContainerBuilder();
38        $builder->addDefinitions($phpdiDefinitionsArray);
39        return $builder->build();
40    }
41
42    /**
43     * phpdi is clumsy at best.  This logic should be built into the phpdi package itself...
44     */
45    protected function  buildSingle(DefinitionInterface $pvcDefinition): DefinitionHelper
46    {
47        $phpdiDefinition = create($pvcDefinition->getClassString());
48
49        $phpdiDefinition->constructor(... array_map([$this, 'resolveArgument'], $pvcDefinition->getConstructorArgs()));
50
51        foreach ($pvcDefinition->getMethodCalls() as $methodCall) {
52            $phpdiDefinition->method($methodCall->getMethodName(), ... array_map([$this, 'resolveArgument'], $methodCall->getArguments()));
53        }
54
55        return $phpdiDefinition;
56    }
57
58    /**
59     * resolveArgument
60     * @param mixed $arg
61     *
62     * @return mixed
63     */
64    protected function resolveArgument($arg): mixed
65    {
66        $resolved = $arg;
67        if (is_string($arg) && $this->definitionCollection->hasKey($arg)) {
68            $resolved = get($arg);
69        }
70        return $resolved;
71    }
72}