Completed
Push — 2.x ( 61d327...82deb5 )
by Akihito
14s queued 11s
created

Weaver::loadClass()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ray\Aop;
6
7
final class Weaver
8
{
9
    /**
10
     * @var BindInterface
11
     */
12
    private $bind;
13
14
    /**
15
     * @var string
16
     */
17
    private $bindName;
18
19
    /**
20
     * @var string
21
     */
22
    private $classDir;
23
24
    /**
25
     * @var AopClassName
26
     */
27
    private $aopClassName;
28
29
    /**
30
     * @var Compiler
31
     */
32
    private $compiler;
33
34
    public function __construct(BindInterface $bind, string $classDir)
35
    {
36
        $this->bind = $bind;
37
        $this->bindName = $bind->toString('');
38
        $this->compiler = new Compiler($classDir);
39
        $this->classDir = $classDir;
40
        $this->aopClassName = new AopClassName;
41
    }
42
43
    public function newInstance(string $class, array $args)
44
    {
45
        $aopClass = $this->weave($class);
46
        $instance = (new ReflectionClass($aopClass))->newInstanceArgs($args);
47
        $instance->bindings = $this->bind->getBindings();
48
49
        return $instance;
50
    }
51
52
    public function weave(string $class) : string
53
    {
54
        $aopClass = ($this->aopClassName)($class, $this->bindName);
55
        if (class_exists($aopClass, false)) {
56
            return $aopClass;
57
        }
58
        if ($this->loadClass($aopClass)) {
59
            return $aopClass;
60
        }
61
        $this->compiler->compile($class, $this->bind);
62
        assert(class_exists($aopClass));
63
64
        return $aopClass;
65
    }
66
67
    private function loadClass(string $class) : bool
68
    {
69
        $file = sprintf('%s/%s.php', $this->classDir, str_replace('\\', '_', $class));
70
        if (file_exists($file)) {
71
            require $file;
72
73
            return true;
74
        }
75
76
        return false;
77
    }
78
}
79