Completed
Pull Request — master (#67)
by Ross
04:58
created

TypeHintMapping   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 2
dl 0
loc 33
ccs 15
cts 15
cp 1
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 57
    protected function isSupported(Definition $definition, array $tagAttributes): bool
32
    {
33 57
        return isset($tagAttributes['typehints']) && $tagAttributes['typehints'] === true;
34
    }
35
36 33
    protected function findCommandsForService(Definition $definition, array $tagAttributes): array
37
    {
38 33
        $results = [];
39
40 33
        $reflClass = new ReflectionClass($definition->getClass());
41
42 33
        foreach($reflClass->getMethods() as $method) {
43 33
            if (!$method->isPublic()) {
44 3
                continue;
45
            }
46
47 30
            if ($method->getNumberOfParameters() !== 1) {
48 12
                continue;
49
            }
50
51 30
            $parameter = $method->getParameters()[0];
52 30
            if(!$parameter->hasType() || $parameter->getType()->isBuiltin()) {
53 6
                continue;
54
            }
55
56 24
            $results[] = (string)$parameter->getType();
57
        }
58
59 33
        return $results;
60
    }
61
}
62