MutableAnnotationLoader   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
c 1
b 0
f 0
lcom 1
cbo 3
dl 0
loc 71
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A add() 0 10 2
A load() 0 9 2
A extractCallables() 0 14 3
1
<?php
2
3
namespace Tonic\Component\ApiLayer\JsonRpc\Method\Loader;
4
5
use Doctrine\Common\Annotations\Reader;
6
use Tonic\Component\ApiLayer\JsonRpc\Annotation\Method;
7
use Tonic\Component\ApiLayer\JsonRpc\Method\MethodCollection;
8
9
/**
10
 * Allows to load methods from annotations.
11
 */
12
class MutableAnnotationLoader implements LoaderInterface
13
{
14
    /**
15
     * @var Reader
16
     */
17
    private $annotationReader;
18
19
    /**
20
     * @var object[]
21
     */
22
    private $services = [];
23
24
    /**
25
     * Constructor.
26
     *
27
     * @param Reader $annotationReader
28
     */
29
    public function __construct(Reader $annotationReader)
30
    {
31
        $this->annotationReader = $annotationReader;
32
    }
33
34
    /**
35
     * @param object $service
36
     *
37
     * @return MutableAnnotationLoader
38
     */
39
    public function add($service)
40
    {
41
        if (!is_object($service)) {
42
            throw new \InvalidArgumentException('Supports only objects');
43
        }
44
45
        $this->services[] = $service;
46
47
        return $this;
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function load()
54
    {
55
        $methods = [];
56
        foreach ($this->services as $service) {
57
            $methods = array_merge($methods, $this->extractCallables($service));
58
        }
59
60
        return new MethodCollection($methods);
61
    }
62
63
    /**
64
     * @param object $service
65
     *
66
     * @return callable[]
67
     */
68
    private function extractCallables($service)
69
    {
70
        $methods = [];
71
        $reflectionClass = new \ReflectionClass($service);
72
        foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
73
            /** @var Method $methodAnnotation */
74
            $methodAnnotation = $this->annotationReader->getMethodAnnotation($reflectionMethod, Method::class);
75
            if ($methodAnnotation instanceof Method) {
76
                $methods[$methodAnnotation->name] = [$service, $reflectionMethod->name];
77
            }
78
        }
79
80
        return $methods;
81
    }
82
}
83