Passed
Push — master ( 392556...a36e60 )
by PHPinnacle
06:42 queued 04:41
created

ContainerWrapper   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 59
ccs 0
cts 28
cp 0
rs 10
c 0
b 0
f 0
wmc 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
A resolveArgument() 0 3 2
A wrap() 0 19 5
A getParameters() 0 3 1
A __construct() 0 3 1
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
    public function __construct(ContainerInterface $container)
29
    {
30
        $this->container = $container;
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36
    public function wrap(callable $handler): callable
37
    {
38
        $parameters = $this->getParameters($handler);
39
        $resolved = [];
40
41
        foreach ($parameters as $i => $parameter) {
42
            if (!$class = $parameter->getClass()) {
43
                continue;
44
            }
45
46
            $instance = $this->resolveArgument($class->getName());
47
48
            if (\is_object($instance) && $class->isInstance($instance)) {
49
                $resolved[$i] = $instance;
50
            }
51
        }
52
53
        return function (...$arguments) use ($handler, $resolved) {
54
            return $handler(...array_replace($arguments, $resolved));
55
        };
56
    }
57
58
    /**
59
     * @param callable $handler
60
     *
61
     * @return \ReflectionParameter[]
62
     * @throws \ReflectionException
63
     */
64
    private function getParameters(callable $handler): array
65
    {
66
        return (new \ReflectionMethod(\Closure::fromCallable($handler), '__invoke'))->getParameters();
67
    }
68
69
    /**
70
     * @param string $class
71
     *
72
     * @return mixed
73
     */
74
    private function resolveArgument(string $class)
75
    {
76
        return $this->container->has($class) ? $this->container->get($class) : null;
77
    }
78
}
79