Passed
Pull Request — master (#405)
by Kirill
08:21 queued 04:03
created

Instantiator   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 17
c 2
b 0
f 0
dl 0
loc 58
rs 10
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A getTraitConstructors() 0 13 4
A getConstructor() 0 15 4
1
<?php
2
3
/**
4
 * This file is part of Spiral Framework package.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Attributes\Internal\Instantiator;
13
14
use Spiral\Attributes\Internal\ContextRenderer;
15
16
abstract class Instantiator implements InstantiatorInterface
17
{
18
    /**
19
     * @var string
20
     */
21
    private const CONSTRUCTOR_NAME = '__construct';
22
23
    /**
24
     * @var ContextRenderer
25
     */
26
    protected $renderer;
27
28
    /**
29
     * @param ContextRenderer|null $renderer
30
     */
31
    public function __construct(ContextRenderer $renderer = null)
32
    {
33
        $this->renderer = $renderer ?? new ContextRenderer();
34
    }
35
36
    /**
37
     * @param \ReflectionClass $class
38
     * @return \ReflectionMethod|null
39
     */
40
    protected function getConstructor(\ReflectionClass $class): ?\ReflectionMethod
41
    {
42
        if ($class->hasMethod(self::CONSTRUCTOR_NAME)) {
43
            return $class->getMethod(self::CONSTRUCTOR_NAME);
44
        }
45
46
        if ($constructor = $this->getTraitConstructors($class)) {
47
            return $constructor;
48
        }
49
50
        if ($parent = $class->getParentClass()) {
51
            return $this->getConstructor($parent);
52
        }
53
54
        return null;
55
    }
56
57
    /**
58
     * @param \ReflectionClass $class
59
     * @return \ReflectionMethod|null
60
     */
61
    private function getTraitConstructors(\ReflectionClass $class): ?\ReflectionMethod
62
    {
63
        foreach ($class->getTraits() as $trait) {
64
            if ($constructor = $this->getConstructor($trait)) {
65
                return $constructor;
66
            }
67
68
            if ($constructor = $this->getTraitConstructors($trait)) {
69
                return $constructor;
70
            }
71
        }
72
73
        return null;
74
    }
75
}
76