These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more
1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace Ray\Aop; |
||
6 | |||
7 | use PhpParser\NodeTraverser; |
||
8 | use PhpParser\Parser; |
||
9 | use Ray\Aop\Exception\InvalidSourceClassException; |
||
10 | use ReflectionClass; |
||
0 ignored issues
–
show
|
|||
11 | use RuntimeException; |
||
12 | |||
13 | use function file_get_contents; |
||
14 | use function get_class; |
||
15 | use function is_array; |
||
16 | use function is_bool; |
||
17 | |||
18 | final class VisitorFactory |
||
19 | { |
||
20 | /** @var Parser */ |
||
21 | private $parser; |
||
22 | |||
23 | public function __construct(Parser $parser) |
||
24 | { |
||
25 | $this->parser = $parser; |
||
26 | } |
||
27 | |||
28 | /** |
||
29 | * @param ReflectionClass<object> $class |
||
30 | */ |
||
31 | public function __invoke(ReflectionClass $class): CodeVisitor |
||
32 | { |
||
33 | $traverser = new NodeTraverser(); |
||
34 | $visitor = new CodeVisitor(); |
||
35 | $traverser->addVisitor($visitor); |
||
36 | $fileName = $class->getFileName(); |
||
37 | if (is_bool($fileName)) { |
||
38 | throw new InvalidSourceClassException(get_class($class)); |
||
39 | } |
||
40 | |||
41 | $file = file_get_contents($fileName); |
||
42 | if ($file === false) { |
||
43 | throw new RuntimeException($fileName); // @codeCoverageIgnore |
||
44 | } |
||
45 | |||
46 | $stmts = $this->parser->parse($file); |
||
47 | if (is_array($stmts)) { |
||
48 | $traverser->traverse($stmts); |
||
49 | } |
||
50 | |||
51 | return $visitor; |
||
52 | } |
||
53 | } |
||
54 |
Let’s assume that you have a directory layout like this:
and let’s assume the following content of
Bar.php
:If both files
OtherDir/Foo.php
andSomeDir/Foo.php
are loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php
However, as
OtherDir/Foo.php
does not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php
, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: