1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is part of the Abstract builder package, an RunOpenCode project. |
4
|
|
|
* |
5
|
|
|
* (c) 2017 RunOpenCode |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
namespace RunOpenCode\AbstractBuilder\Ast; |
11
|
|
|
|
12
|
|
|
use PhpParser\NodeTraverser; |
13
|
|
|
use PhpParser\ParserFactory; |
14
|
|
|
use RunOpenCode\AbstractBuilder\Ast\Visitor\ClassIntrospectionVisitor; |
15
|
|
|
use RunOpenCode\AbstractBuilder\Exception\RuntimeException; |
16
|
|
|
|
17
|
|
|
class ClassLoader |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @var \PhpParser\Parser |
21
|
|
|
*/ |
22
|
|
|
private $parser; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var \PhpParser\NodeTraverser |
26
|
|
|
*/ |
27
|
|
|
private $traverser; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var ClassIntrospectionVisitor |
31
|
|
|
*/ |
32
|
|
|
private $introspector; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* ClassLoader constructor. |
36
|
|
|
*/ |
37
|
|
|
public function __construct() |
38
|
|
|
{ |
39
|
|
|
$this->parser = (new ParserFactory())->create(ParserFactory::ONLY_PHP7); |
40
|
|
|
$this->traverser = new NodeTraverser(); |
41
|
|
|
$this->introspector = new ClassIntrospectionVisitor(); |
42
|
|
|
|
43
|
|
|
$this->traverser->addVisitor($this->introspector); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Load class and build its metadata value object |
48
|
|
|
* |
49
|
|
|
* @param string $class Filename or full qualified class name |
50
|
|
|
* |
51
|
|
|
* @return ClassMetadata |
52
|
|
|
* |
53
|
|
|
* @throws \RunOpenCode\AbstractBuilder\Exception\RuntimeException |
54
|
|
|
* @throws \RunOpenCode\AbstractBuilder\Exception\InvalidArgumentException |
55
|
|
|
*/ |
56
|
|
|
public function load($class) |
57
|
|
|
{ |
58
|
|
|
$filename = $class; |
59
|
|
|
|
60
|
|
|
if (class_exists($class, true)) { |
61
|
|
|
$filename = (new \ReflectionClass($class))->getFileName(); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
if (file_exists($filename)) { |
65
|
|
|
|
66
|
|
|
$ast = $this->traverser->traverse($this->parser->parse(file_get_contents($filename))); |
|
|
|
|
67
|
|
|
|
68
|
|
|
return new ClassMetadata( |
69
|
|
|
$ast, |
70
|
|
|
$this->introspector->getNamespace(), |
71
|
|
|
$this->introspector->getClass(), |
72
|
|
|
$filename, |
73
|
|
|
$this->introspector->isFinal(), |
74
|
|
|
$this->introspector->isAbstract() |
75
|
|
|
); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
throw new RuntimeException(sprintf('Unable to load class from "%s".', $class)); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
This check looks at variables that are passed out again to other methods.
If the outgoing method call has stricter type requirements than the method itself, an issue is raised.
An additional type check may prevent trouble.