Passed
Push — master ( dc91ec...37d931 )
by Divine Niiquaye
07:45
created

TypeHintValueResolver   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Test Coverage

Coverage 92.86%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 36
ccs 13
cts 14
cp 0.9286
rs 10
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B resolve() 0 23 7
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of PHP Invoker.
7
 *
8
 * PHP version 7.1 and above required
9
 *
10
 * @author    Divine Niiquaye Ibok <[email protected]>
11
 * @copyright 2019 Biurad Group (https://biurad.com/)
12
 * @license   https://opensource.org/licenses/BSD-3-Clause License
13
 *
14
 * For the full copyright and license information, please view the LICENSE
15
 * file that was distributed with this source code.
16
 */
17
18
namespace DivineNii\Invoker\ArgumentResolver;
19
20
use DivineNii\Invoker\Interfaces\ArgumentValueResolverInterface;
21
use Psr\Container\ContainerInterface;
22
use ReflectionParameter;
23
24
/**
25
 * Inject entries using type-hints.
26
 * Tries to match type-hints with the parameters provided.
27
 *
28
 * @author Divine Niiquaye Ibok <[email protected]>
29
 */
30
class TypeHintValueResolver implements ArgumentValueResolverInterface
31
{
32
    /** @var null|ContainerInterface */
33
    private $container;
34
35 50
    public function __construct(?ContainerInterface $container = null)
36
    {
37 50
        $this->container = $container;
38 50
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43 28
    public function resolve(ReflectionParameter $parameter, array $providedParameters)
44
    {
45 28
        $parameterType = $parameter->getType();
46
47 28
        if (!$parameterType instanceof \ReflectionType || $parameterType->isBuiltin()) {
48
            // No type and Primitive types are not supported
49 17
            return;
50
        }
51
52 12
        if (!$parameterType instanceof \ReflectionNamedType) {
53
            // Union types are not supported
54
            return;
55
        }
56
57 12
        $parameterType = $parameterType->getName();
58
59
        // Inject entries from a DI container using the type-hints.
60 12
        if (null !== $this->container && $this->container->has($parameterType)) {
61 1
            return $this->container->get($parameterType);
62
        }
63
64 11
        if (\array_key_exists($parameterType, $providedParameters)) {
65 1
            return $providedParameters[$parameterType];
66
        }
67 10
    }
68
}
69