Passed
Push — master ( e17d1c...4946a9 )
by Divine Niiquaye
02:05
created

TypeHintValueResolver::resolve()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 6
eloc 8
c 2
b 0
f 0
nc 4
nop 2
dl 0
loc 18
ccs 9
cts 9
cp 1
crap 6
rs 9.2222
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 52
    public function __construct(?ContainerInterface $container = null)
36
    {
37 52
        $this->container = $container;
38 52
    }
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 \ReflectionNamedType || $parameterType->isBuiltin()) {
48
            // No type, Primitive types and Union types are not supported
49 17
            return;
50
        }
51
52 12
        $parameterType = $parameterType->getName();
53
54
        // Inject entries from a DI container using the type-hints.
55 12
        if (null !== $this->container && $this->container->has($parameterType)) {
56 1
            return $this->container->get($parameterType);
57
        }
58
59 11
        if (\array_key_exists($parameterType, $providedParameters)) {
60 1
            return $providedParameters[$parameterType];
61
        }
62 10
    }
63
}
64