ContainerDelegatorFactory   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 3
eloc 13
dl 0
loc 43
ccs 0
cts 13
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A build() 0 14 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Antidot\Aura\Container;
6
7
use Aura\Di\Container;
8
9
/**
10
 * Aura.Di-compatible delegator factory.
11
 *
12
 * Map an instance of this:
13
 *
14
 * <code>
15
 * $container->set(
16
 *     $serviceName,
17
 *     $container->lazyGetCall(
18
 *         $delegatorFactoryInstance,
19
 *         'build',
20
 *         $container,
21
 *         $serviceName
22
 *     )
23
 * )
24
 * </code>
25
 *
26
 * Instances receive the list of delegator factory names or instances, and a
27
 * closure that can create the initial service instance to pass to the first
28
 * delegator.
29
 */
30
final class ContainerDelegatorFactory
31
{
32
    /**
33
     * @var array Either delegator factory names or instances.
34
     */
35
    private $delegators;
36
37
    /**
38
     * @var callable
39
     */
40
    private $factory;
41
42
    /**
43
     * @param array $delegators Array of delegator factory names or instances.
44
     * @param callable $factory Callable that can return the initial instance.
45
     */
46
    public function __construct(array $delegators, callable $factory)
47
    {
48
        $this->delegators = $delegators;
49
        $this->factory = $factory;
50
    }
51
52
    /**
53
     * Build the instance, invoking each delegator with the result of the previous.
54
     *
55
     * @param Container $container
56
     * @param string $serviceName
57
     * @return mixed
58
     */
59
    public function build(Container $container, $serviceName)
60
    {
61
        $factory = $this->factory;
62
63
        return \array_reduce(
64
            $this->delegators,
65
            static function ($instance, $delegatorName) use ($serviceName, $container) {
66
                $delegator = \is_callable($delegatorName) ? $delegatorName : new $delegatorName();
67
68
                return $delegator($container, $serviceName, static function () use ($instance) {
69
                    return $instance;
70
                });
71
            },
72
            $factory()
73
        );
74
    }
75
}
76