Completed
Push — 2.x ( b6ae1b...61ad4a )
by Akihito
9s
created

Injector::__wakeup()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

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