ServiceArgumentResolver   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 9
lcom 0
cbo 1
dl 0
loc 38
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A resolveArguments() 0 8 2
A resolveConstructorArguments() 0 12 4
A resolve() 0 6 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Zalas\Behat\NoExtension\Context\Argument;
5
6
use Behat\Behat\Context\Argument\ArgumentResolver;
7
use Psr\Container\ContainerInterface;
8
use ReflectionClass;
9
use ReflectionMethod;
10
11
/**
12
 * Resolves context arguments with services found in a psr container.
13
 */
14
final class ServiceArgumentResolver implements ArgumentResolver
15
{
16
    private $container;
17
18
    public function __construct(ContainerInterface $container)
19
    {
20
        $this->container = $container;
21
    }
22
23
    public function resolveArguments(ReflectionClass $classReflection, array $arguments): array
24
    {
25
        if ($constructor = $classReflection->getConstructor()) {
26
            return $this->resolveConstructorArguments($constructor, $arguments);
27
        }
28
29
        return $arguments;
30
    }
31
32
    private function resolveConstructorArguments(ReflectionMethod $constructor, array $arguments): array
33
    {
34
        $constructorParameters = $constructor->getParameters();
35
36
        foreach ($constructorParameters as $position => $parameter) {
37
            if ($parameter->getClass() && $service = $this->resolve($parameter->getClass())) {
38
                $arguments[$position] = $service;
39
            }
40
        }
41
42
        return $arguments;
43
    }
44
45
    private function resolve(ReflectionClass $class)
46
    {
47
        if ($this->container->has($class->getName())) {
48
            return $this->container->get($class->getName());
49
        }
50
    }
51
}
52