Completed
Push — 2.x ( d6b11c...5f03c1 )
by Akihito
04:42 queued 02:33
created

Injector   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 76.47%

Importance

Changes 10
Bugs 1 Features 1
Metric Value
wmc 8
c 10
b 1
f 1
lcom 1
cbo 4
dl 0
loc 72
ccs 13
cts 17
cp 0.7647
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getInstance() 0 11 2
A __construct() 0 9 3
A bind() 0 7 1
A __wakeup() 0 13 2
1
<?php
2
/**
3
 * This file is part of the Ray.Di package.
4
 *
5
 * @license http://opensource.org/licenses/MIT MIT
6
 */
7
namespace Ray\Di;
8
9
use Ray\Aop\Compiler;
10
use Ray\Di\Exception\Untargetted;
11
12
class Injector implements InjectorInterface
13
{
14
    /**
15
     * @var string
16
     */
17
    private $classDir;
18
19
    /**
20
     * @var Container
21
     */
22
    private $container;
23
24
    /**
25
     * @param AbstractModule $module
26
     * @param string         $classDir
27
     */
28 4
    public function __construct(AbstractModule $module = null, $classDir = null)
29
    {
30 4
        $this->classDir = $classDir ?: sys_get_temp_dir();
31
        $this->container =  $module ? $module->getContainer() : new Container;
32
        $this->container->weaveAspects(new Compiler($this->classDir));
33
34
        // builtin injection
35
        (new Bind($this->container, 'Ray\Di\InjectorInterface'))->toInstance($this);
36
    }
37
38
    /**
39
     * @param string $interface
40
     * @param string $name
41
     *
42
     * @return mixed
43
     */
44 21
    public function getInstance($interface, $name = Name::ANY)
45
    {
46
        try {
47 2
            $instance = $this->container->getInstance($interface, $name);
48
        } catch (Untargetted $e) {
49 1
            $this->bind($interface);
50
            $instance = $this->getInstance($interface, $name);
51 17
        }
52
53 16
        return $instance;
54 21
    }
55
56
    /**
57
     * @param string $class
58
     */
59 9
    private function bind($class)
60
    {
61
        new Bind($this->container, $class);
62
        /* @var $bound Dependency */
63
        $bound = $this->container->getContainer()[$class . '-' . Name::ANY];
64
        $this->container->weaveAspect(new Compiler($this->classDir), $bound)->getInstance($class, Name::ANY);
65 9
    }
66
67
    /**
68
     * Wakeup
69
     */
70
    public function __wakeup()
71
    {
72
        spl_autoload_register(
73 3
            function ($class) {
74
                $file = $this->classDir . DIRECTORY_SEPARATOR . $class . '.php';
75
                if (file_exists($file)) {
76
                    // @codeCoverageIgnoreStart
77
                    include $file;
78
                    // @codeCoverageIgnoreEnd
79
                }
80 3
            }
81
        );
82 3
    }
83
}
84