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

AutoWired   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 60%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 36
ccs 9
cts 15
cp 0.6
rs 10
c 2
b 0
f 0
wmc 4
lcom 1
cbo 2

1 Method

Rating   Name   Duplication   Size   Complexity  
B onBindProperty() 0 24 4
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