Completed
Push — 2.x ( 26569f...004d76 )
by Akihito
02:57
created

Injector::__construct()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 4
nop 2
crap 3
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 40
    public function __construct(AbstractModule $module = null, $classDir = null)
29
    {
30 40
        if (is_null($module)) {
31 5
            $module = new NullModule;
32
        }
33 40
        $module->install(new AssistedModule);
34 40
        $this->container = $module->getContainer();
35 40
        $this->classDir = $classDir ?: sys_get_temp_dir();
36 40
        $this->container->weaveAspects(new Compiler($this->classDir));
37
38
        // builtin injection
39 40
        (new Bind($this->container, 'Ray\Di\InjectorInterface'))->toInstance($this);
40 40
    }
41
42
    /**
43
     * Wakeup
44
     */
45 7
    public function __wakeup()
46
    {
47 3
        spl_autoload_register(
48 7
            function ($class) {
49 4
                $file = $this->classDir . DIRECTORY_SEPARATOR . $class . '.php';
50 4
                if (file_exists($file)) {
51
                    // @codeCoverageIgnoreStart
52
                    include $file;
53
                    // @codeCoverageIgnoreEnd
54
                }
55 7
            }
56
        );
57 3
    }
58
59
    /**
60
     * @param string $interface
61
     * @param string $name
62
     *
63
     * @return mixed
64
     */
65 40
    public function getInstance($interface, $name = Name::ANY)
66
    {
67
        try {
68 40
            $instance = $this->container->getInstance($interface, $name);
69 16
        } catch (Untargetted $e) {
70 15
            $this->bind($interface);
71 14
            $instance = $this->getInstance($interface, $name);
72
        }
73
74 38
        return $instance;
75
    }
76
77
    /**
78
     * @param string $class
79
     */
80 15
    private function bind($class)
81
    {
82 15
        new Bind($this->container, $class);
83
        /* @var $bound Dependency */
84 15
        $bound = $this->container->getContainer()[$class . '-' . Name::ANY];
85 15
        $this->container->weaveAspect(new Compiler($this->classDir), $bound)->getInstance($class, Name::ANY);
86 14
    }
87
}
88