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

NamedValueResolver   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 24
ccs 9
cts 9
cp 1
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A resolve() 0 11 5
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
 * Tries to map an associative array (string-indexed) to the parameter names.
26
 * E.g. `->call($callable, ['foo' => 'bar'])` will inject the string `'bar'`
27
 * in the parameter named `$foo`.
28
 * Parameters that are not indexed by a string are ignored.
29
 *
30
 * @author Divine Niiquaye Ibok <[email protected]>
31
 */
32
final class NamedValueResolver 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 18
    public function resolve(ReflectionParameter $parameter, array $providedParameters)
46
    {
47 18
        $name  = $parameter->name;
48
49
        // Inject entries from a DI container using the parameter names.
50 18
        if ($name && (null !== $this->container && $this->container->has($name))) {
51 2
            return $this->container->get($name);
52
        }
53
54 16
        if (\array_key_exists($name, $providedParameters)) {
55 14
            return $providedParameters[$name];
56
        }
57 10
    }
58
}
59