Completed
Branch 2.x (dc1b30)
by Akihito
02:25
created

Injector::__wakeup()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2.0054

Importance

Changes 6
Bugs 1 Features 1
Metric Value
dl 0
loc 13
cc 2
eloc 6
c 6
b 1
f 1
nc 1
nop 0
ccs 8
cts 9
cp 0.8889
crap 2.0054
rs 9.4285
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 33
        } 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 3
    public function __wakeup()
71
    {
72 3
        spl_autoload_register(
73 3
            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 3
            }
81 3
        );
82 3
    }
83
}
84