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

TypeHintValueResolver::resolve()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 23
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 7.0368

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 10
c 1
b 0
f 0
nc 5
nop 2
dl 0
loc 23
ccs 10
cts 11
cp 0.9091
crap 7.0368
rs 8.8333
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