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

ClassValueResolver::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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 Psr\Container\NotFoundExceptionInterface;
23
use ReflectionClass;
24
use ReflectionParameter;
25
26
/**
27
 * Inject or create a class instance from a DI container or return existing instance
28
 * from $providedParameters using the type-hints.
29
 *
30
 * @author Divine Niiquaye Ibok <[email protected]>
31
 */
32
class ClassValueResolver implements ArgumentValueResolverInterface
33
{
34
    /** @var ContainerInterface|null */
35
    private $container;
36
37 50
    public function __construct(?ContainerInterface $container = null)
38
    {
39 50
        $this->container = $container;
40 50
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45 26
    public function resolve(ReflectionParameter $parameter, array $providedParameters)
46
    {
47 26
        $parameterClass = $parameter->getClass();
48
49 26
        if (!$parameterClass instanceof ReflectionClass) {
0 ignored issues
show
introduced by
$parameterClass is always a sub-type of ReflectionClass.
Loading history...
50 17
            return;
51
        }
52
53
        // Inject entries from a DI container using the type-hints.
54 10
        if (null !== $this->container) {
55
            try {
56 3
                return $this->container->get($parameterClass->name);
57 1
            } catch (NotFoundExceptionInterface $e) {
58
                // We need no exception thrown here
59
            }
60
        }
61
62
        // If an instance is detected
63 8
        foreach ($providedParameters as $key => $value) {
64 4
            if (\is_a($value, $parameterClass->name, true)) {
65 4
                return $providedParameters[$key];
66
            }
67
        }
68
69 4
        return $parameterClass->isInstantiable() ? $parameterClass->newInstance() : null;
70
    }
71
}
72