Completed
Push — spike ( 2414ba )
by Akihito
06:46
created

NewInstance   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 95%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 3
dl 0
loc 75
ccs 19
cts 20
cp 0.95
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 3
A __invoke() 0 15 3
A __toString() 0 4 1
A weaveAspects() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
/**
5
 * This file is part of the Ray.Di package.
6
 *
7
 * @license http://opensource.org/licenses/MIT MIT
8
 */
9
namespace Ray\Di;
10
11
use Ray\Aop\Bind as AopBind;
12
13
final class NewInstance
14
{
15
    /**
16
     * @var string
17
     */
18
    private $class;
19
20
    /**
21
     * @var SetterMethods
22
     */
23
    private $setterMethods;
24
25
    /**
26
     * @var Arguments
27
     */
28
    private $arguments;
29
30
    /**
31
     * @var AspectBind
32
     */
33
    private $bind;
34
35 31
    public function __construct(
36
        \ReflectionClass $class,
37
        SetterMethods $setterMethods,
38
        Name $constructorName = null
39
    ) {
40 31
        $constructorName = $constructorName ?: new Name(Name::ANY);
41 31
        $this->class = $class->name;
42 31
        $constructor = $class->getConstructor();
43 31
        if ($constructor) {
44 20
            $this->arguments = new Arguments($constructor, $constructorName);
45
        }
46 31
        $this->setterMethods = $setterMethods;
47 31
    }
48
49
    /**
50
     * @param Container $container
51
     *
52
     * @return object
53
     */
54 25
    public function __invoke(Container $container)
55
    {
56
        // constructor injection
57 25
        $instance = $this->arguments ? (new \ReflectionClass($this->class))->newInstanceArgs($this->arguments->inject($container)) : new $this->class;
58
59
        // setter injection
60 25
        ($this->setterMethods)($instance, $container);
61
62
        // bind dependency injected interceptors
63 25
        if ($this->bind instanceof AspectBind) {
64
            $instance->bindings = $this->bind->inject($container);
65
        }
66
67 25
        return $instance;
68
    }
69
70
    /**
71
     * @return string
72
     */
73 1
    public function __toString()
74
    {
75 1
        return $this->class;
76
    }
77
78
    /**
79
     * @param string  $class
80
     * @param AopBind $bind
81
     */
82 1
    public function weaveAspects($class, AopBind $bind)
83
    {
84 1
        $this->class = $class;
85 1
        $this->bind = new AspectBind($bind);
86 1
    }
87
}
88