Completed
Push — master ( 7e3d04...dc7866 )
by Changwan
06:39
created

AutoWired::onBindProperty()   B

Complexity

Conditions 4
Paths 1

Size

Total Lines 24
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5.024

Importance

Changes 0
Metric Value
cc 4
eloc 19
nc 1
nop 4
dl 0
loc 24
ccs 9
cts 15
cp 0.6
crap 5.024
rs 8.6845
c 0
b 0
f 0
1
<?php
2
namespace Wandu\DI\Annotations;
3
4
use Doctrine\Common\Annotations\Annotation\Required;
5
use Doctrine\Common\Annotations\Annotation\Target;
6
use Exception;
7
use ReflectionClass;
8
use ReflectionProperty;
9
use Throwable;
10
use Wandu\DI\ContainerInterface;
11
use Wandu\DI\Contracts\PropertyDecoratorInterface;
12
use Wandu\DI\Descriptor;
13
14
/**
15
 * @Annotation
16
 * @Target({"PROPERTY"})
17
 */
18
class AutoWired implements PropertyDecoratorInterface
19
{
20
    /** @var array  */
21
    static protected $callStack = []; 
22
    
23
    /** @Required @var string */
24
    public $name;
25
26
    /**
27
     * {@inheritdoc}
28
     */
29
    public function onBindProperty(
30
        ReflectionProperty $reflProperty,
31
        ReflectionClass $reflClass,
32
        Descriptor $desc,
33
        ContainerInterface $container
34
    ) {
35 2
        $desc->after(function ($instance) use ($reflProperty, $container) {
36 2
            if (in_array($instance, static::$callStack)) {
37 1
                return; // return when a circular call is detected.
38
            }
39 2
            array_push(static::$callStack, $instance);
40
            try {
41 2
                $reflProperty->setAccessible(true);
42 2
                $reflProperty->setValue($instance, $container->get($this->name));
43
            } catch (Exception $e) {
44
                array_pop(static::$callStack);
45
                throw $e;
46
            } catch (Throwable $e) {
47
                array_pop(static::$callStack);
48
                throw $e;
49
            }
50 2
            array_pop(static::$callStack);
51 2
        });
52 2
    }
53
}
54