ContainerWrapper::wrap()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 4
nop 1
dl 0
loc 19
ccs 10
cts 10
cp 1
crap 5
rs 9.6111
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of PHPinnacle/Pinnacle.
4
 *
5
 * (c) PHPinnacle Team <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
declare(strict_types = 1);
12
13
namespace PHPinnacle\Ensign\Wrapper;
14
15
use PHPinnacle\Ensign\HandlerWrapper;
16
use Psr\Container\ContainerInterface;
17
18
final class ContainerWrapper implements HandlerWrapper
19
{
20
    /**
21
     * @var ContainerInterface
22
     */
23
    private $container;
24
25
    /**
26
     * @param ContainerInterface $container
27
     */
28 1
    public function __construct(ContainerInterface $container)
29
    {
30 1
        $this->container = $container;
31 1
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36 1
    public function wrap(callable $handler): callable
37
    {
38 1
        $parameters = $this->getParameters($handler);
39 1
        $resolved = [];
40
41 1
        foreach ($parameters as $i => $parameter) {
42 1
            if (!$class = $parameter->getClass()) {
43 1
                continue;
44
            }
45
46 1
            $instance = $this->resolveArgument($class->getName());
47
48 1
            if (\is_object($instance) && $class->isInstance($instance)) {
49 1
                $resolved[$i] = $instance;
50
            }
51
        }
52
53
        return function (...$arguments) use ($handler, $resolved) {
54 1
            return $handler(...array_replace($arguments, $resolved));
55 1
        };
56
    }
57
58
    /**
59
     * @param callable $handler
60
     *
61
     * @return \ReflectionParameter[]
62
     * @throws \ReflectionException
63
     */
64 1
    private function getParameters(callable $handler): array
65
    {
66 1
        return (new \ReflectionMethod(\Closure::fromCallable($handler), '__invoke'))->getParameters();
67
    }
68
69
    /**
70
     * @param string $class
71
     *
72
     * @return mixed
73
     */
74 1
    private function resolveArgument(string $class)
75
    {
76 1
        return $this->container->has($class) ? $this->container->get($class) : null;
77
    }
78
}
79