Completed
Pull Request — master (#67)
by Ross
02:06
created

TypeHintMapping   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 2
dl 0
loc 33
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A isSupported() 0 4 2
B findCommandsForService() 0 25 6
1
<?php
2
declare(strict_types=1);
3
4
namespace League\Tactician\Bundle\DependencyInjection\HandlerMapping;
5
6
use Symfony\Component\DependencyInjection\Definition;
7
use ReflectionClass;
8
9
/**
10
 * Routes commands based on typehints in the handler.
11
 *
12
 * If your handler has a public method with a single, non-scalar type hinted
13
 * parameter, we'll assume that typehint is a command and route it to this
14
 * service definition as the handler.
15
 *
16
 * So, a class like this:
17
 *
18
 * class MyHandler
19
 * {
20
 *     public function handle(RegisterUser $command) {...}
21
 *     private function foobar(SomeObject $obj) {...}
22
 *     public function checkThings(OtherObject $obj, WhatObject $obj2)
23
 * }
24
 *
25
 * would have RegisterUser routed to it, but not SomeObject (because it's
26
 * used in a private method) and not OtherObject or WhatObject (because they
27
 * don't appear as the only parameter).
28
 */
29
final class TypeHintMapping extends TagBasedMapping
30
{
31
    protected function isSupported(Definition $definition, array $tagAttributes): bool
32
    {
33
        return isset($tagAttributes['auto']) && $tagAttributes['auto'] === true;
34
    }
35
36
    protected function findCommandsForService(Definition $definition, array $tagAttributes): array
37
    {
38
        $results = [];
39
40
        $reflClass = new ReflectionClass($definition->getClass());
41
42
        foreach($reflClass->getMethods() as $method) {
43
            if (!$method->isPublic()) {
44
                continue;
45
            }
46
47
            if ($method->getNumberOfParameters() !== 1) {
48
                continue;
49
            }
50
51
            $parameter = $method->getParameters()[0];
52
            if(!$parameter->hasType() || $parameter->getType()->isBuiltin()) {
53
                continue;
54
            }
55
56
            $results[] = $parameter->getType()->getName();
57
        }
58
59
        return $results;
60
    }
61
}
62