Completed
Push — master ( 2dd80e...b85147 )
by Koldo
02:33
created

ContainerDelegatorFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 2
c 1
b 0
f 1
dl 0
loc 4
rs 10
ccs 3
cts 3
cp 1
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Antidot\Container;
6
7
use Psr\Container\ContainerInterface;
8
use function array_reduce;
9
use function is_callable;
10
11
/**
12
 * @deprecated will remove in version 1.0.0
13
 *
14
 * Aura.Di-compatible delegator factory.
15
 *
16
 * Map an instance of this:
17
 *
18
 * <code>
19
 * $container->set(
20
 *     $serviceName,
21
 *     $container->lazyGetCall(
22
 *         $delegatorFactoryInstance,
23
 *         'build',
24
 *         $container,
25
 *         $serviceName
26
 *     )
27
 * )
28
 * </code>
29
 *
30
 * Instances receive the list of delegator factory names or instances, and a
31
 * closure that can create the initial service instance to pass to the first
32
 * delegator.
33
 */
34
final class ContainerDelegatorFactory
35
{
36
    /**
37
     * @var array Either delegator factory names or instances.
38
     */
39
    private $delegators;
40
41
    /**
42
     * @var callable
43
     */
44
    private $factory;
45
46
    /**
47
     * @param array $delegators Array of delegator factory names or instances.
48
     * @param callable $factory Callable that can return the initial instance.
49
     */
50 1
    public function __construct(array $delegators, callable $factory)
51
    {
52 1
        $this->delegators = $delegators;
53 1
        $this->factory = $factory;
54 1
    }
55
56
    /**
57
     * Build the instance, invoking each delegator with the result of the previous.
58
     *
59
     * @param ContainerInterface $container
60
     * @param string $serviceName
61
     * @return mixed
62
     */
63 1
    public function __invoke(ContainerInterface $container, $serviceName)
64
    {
65 1
        $factory = $this->factory;
66
67 1
        return array_reduce(
68 1
            $this->delegators,
69
            static function ($instance, $delegatorName) use ($serviceName, $container) {
70 1
                if (is_string($delegatorName) && $container->has($delegatorName)) {
71 1
                    $delegatorName = $container->get($delegatorName);
72
                }
73
74 1
                $delegator = is_callable($delegatorName) ? $delegatorName : new $delegatorName();
75
76
                return $delegator($container, $serviceName, static function () use ($instance) {
77 1
                    return $instance;
78 1
                });
79 1
            },
80 1
            $factory($container)
81
        );
82
    }
83
}
84