Completed
Pull Request — master (#7)
by Sergey
02:01
created

CollectMappersCompilePass::process()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 1
1
<?php
2
3
namespace Fesor\RequestObject\DependeyInjection;
4
5
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
6
use Symfony\Component\DependencyInjection\ContainerBuilder;
7
use Symfony\Component\DependencyInjection\Definition;
8
9
class CollectMappersCompilePass implements CompilerPassInterface
10
{
11
    public function process(ContainerBuilder $container)
12
    {
13
        $mappers = $this->getMappers($container);
14
15
        $bindings = [];
16
        foreach ($mappers as $mapperId => $mapper) {
17
            $bindings = array_merge_recursive($bindings, $this->configureBindings($mapperId, $mapper));
18
        }
19
20
        $requestMapperDefinition = $container->getDefinition(RequestObjectExtension::REQUEST_MAPPER_ID);
21
        $requestMapperDefinition->addMethodCall('registerBindings', [$bindings]);
22
    }
23
24
    private function configureBindings(string $id, Definition $mapper)
25
    {
26
        $tag = $mapper->getTag(RequestObjectExtension::MAPPER_TAG);
0 ignored issues
show
Unused Code introduced by
$tag is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
27
28
        $classReflection = new \ReflectionClass($mapper->getClass());
29
        $publicMethods = $classReflection->getMethods(\ReflectionMethod::IS_PUBLIC);
30
31
        $mapperMethods = array_filter($publicMethods, function (\ReflectionMethod $method) {
32
            return $method->hasReturnType();
33
        });
34
35
        $bindings = [];
36
        foreach ($mapperMethods as $method) {
37
            $bindings[(string) $method->getReturnType()][] = [$id, $method->getName()];
38
        }
39
40
        return $bindings;
41
    }
42
43
    private function getMappers(ContainerBuilder $builder)
44
    {
45
        $tags = $builder->findTaggedServiceIds(RequestObjectExtension::MAPPER_TAG);
46
47
        uasort($tags, function ($a, $b) {
48
49
            return ($a['priority'] ?? 0) <=> ($b['priority'] ?? 0);
50
        });
51
52
        $ids = array_keys($tags);
53
54
        return array_combine($ids, array_map(function(string $id) use ($builder) {
55
56
            return $builder->getDefinition($id);
57
        }, $ids));
58
    }
59
}