Completed
Push — phpstan-v0_10 ( fab2f9 )
by Akihito
04:06
created

NewInstance   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 86.36%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 3
dl 0
loc 77
ccs 19
cts 22
cp 0.8636
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 3
A __invoke() 0 17 4
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 30
    public function __construct(
36
        \ReflectionClass $class,
37
        SetterMethods $setterMethods,
38
        Name $constructorName = null
39
    ) {
40 30
        $constructorName = $constructorName ?: new Name(Name::ANY);
41 30
        $this->class = $class->name;
42 30
        $constructor = $class->getConstructor();
43 30
        if ($constructor) {
44 19
            $this->arguments = new Arguments($constructor, $constructorName);
45
        }
46 30
        $this->setterMethods = $setterMethods;
47 30
    }
48
49
    /**
50
     * @param Container $container
51
     *
52
     * @return object
53
     */
54 24
    public function __invoke(Container $container)
55
    {
56
        // constructor injection
57 24
        $instance = $this->arguments instanceof Arguments ? (new \ReflectionClass($this->class))->newInstanceArgs($this->arguments->inject($container)) : new $this->class;
58
59
        // setter injection
60 24
        ($this->setterMethods)($instance, $container);
61
62
        // bind dependency injected interceptors
63 24
        if (! $this->bind instanceof AspectBind) {
64 24
            return $instance;
65
        }
66
        if (! property_exists($instance, 'bindings')) {
67
            throw new \LogicException; // @codeCoverageIgnore
68
        }
69
        $instance->bindings = $this->bind->inject($container);
70
    }
71
72
    /**
73
     * @return string
74
     */
75 1
    public function __toString()
76
    {
77 1
        return $this->class;
78
    }
79
80
    /**
81
     * @param string  $class
82
     * @param AopBind $bind
83
     */
84 1
    public function weaveAspects($class, AopBind $bind)
85
    {
86 1
        $this->class = $class;
87 1
        $this->bind = new AspectBind($bind);
88 1
    }
89
}
90