Completed
Pull Request — 2.x (#137)
by Akihito
02:14
created

Injector   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

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

4 Methods

Rating   Name   Duplication   Size   Complexity  
A bind() 0 7 1
A __construct() 0 9 3
A getInstance() 0 11 2
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 33
    public function __construct(AbstractModule $module = null, $classDir = null)
29
    {
30 33
        $this->classDir = $classDir ?: sys_get_temp_dir();
31 33
        $this->container =  $module ? $module->getContainer() : new Container;
32 33
        $this->container->weaveAspects(new Compiler($this->classDir));
33
34
        // builtin injection
35 33
        (new Bind($this->container, 'Ray\Di\InjectorInterface'))->toInstance($this);
36 33
    }
37
38
    /**
39
     * @param string $interface
40
     * @param string $name
41
     *
42
     * @return mixed
43
     */
44 33
    public function getInstance($interface, $name = Name::ANY)
45
    {
46
        try {
47 33
            $instance = $this->container->getInstance($interface, $name);
48 11
        } catch (Untargetted $e) {
49 10
            $this->bind($interface);
50 9
            $instance = $this->getInstance($interface, $name);
51
        }
52
53 31
        return $instance;
54
    }
55
56
    /**
57
     * @param string $class
58
     */
59 10
    private function bind($class)
60
    {
61 10
        new Bind($this->container, $class);
62
        /* @var $bound Dependency */
63 10
        $bound = $this->container->getContainer()[$class . '-' . Name::ANY];
64 10
        $this->container->weaveAspect(new Compiler($this->classDir), $bound)->getInstance($class, Name::ANY);
65 9
    }
66
67
    /**
68
     * Wakeup
69
     */
70 6
    public function __wakeup()
71
    {
72 3
        spl_autoload_register(
73 6
            function ($class) {
74 3
                $file = $this->classDir . DIRECTORY_SEPARATOR . $class . '.php';
75 3
                if (file_exists($file)) {
76
                    // @codeCoverageIgnoreStart
77
                    include $file;
78
                    // @codeCoverageIgnoreEnd
79
                }
80 6
            }
81
        );
82 3
    }
83
}
84