VisitorFactory   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 5
eloc 15
c 2
b 0
f 0
dl 0
loc 34
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 21 4
A __construct() 0 3 1
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
Bug introduced by
This use statement conflicts with another class in this namespace, Ray\Aop\ReflectionClass. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/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 before OtherDir/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:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
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)) {
0 ignored issues
show
introduced by
The condition is_bool($fileName) is always false.
Loading history...
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