|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Ray\Aop; |
|
6
|
|
|
|
|
7
|
|
|
use PhpParser\BuilderFactory; |
|
8
|
|
|
use PhpParser\Parser; |
|
9
|
|
|
use ReflectionClass; |
|
|
|
|
|
|
10
|
|
|
|
|
11
|
|
|
use function array_merge; |
|
12
|
|
|
use function implode; |
|
13
|
|
|
|
|
14
|
|
|
final class CodeGen implements CodeGenInterface |
|
15
|
|
|
{ |
|
16
|
|
|
/** @var BuilderFactory */ |
|
17
|
|
|
private $factory; |
|
18
|
|
|
|
|
19
|
|
|
/** @var VisitorFactory */ |
|
20
|
|
|
private $visitoryFactory; |
|
21
|
|
|
|
|
22
|
|
|
/** @var AopClass */ |
|
23
|
|
|
private $aopClass; |
|
24
|
|
|
|
|
25
|
|
|
public function __construct( |
|
26
|
|
|
Parser $parser, |
|
27
|
|
|
BuilderFactory $factory, |
|
28
|
|
|
AopClassName $aopClassName |
|
29
|
|
|
) { |
|
30
|
|
|
$this->factory = $factory; |
|
31
|
|
|
$this->visitoryFactory = new VisitorFactory($parser); |
|
32
|
|
|
$this->aopClass = new AopClass($parser, $factory, $aopClassName); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* {@inheritdoc} |
|
37
|
|
|
* |
|
38
|
|
|
* @param ReflectionClass<object> $sourceClass |
|
|
|
|
|
|
39
|
|
|
*/ |
|
40
|
|
|
public function generate(ReflectionClass $sourceClass, BindInterface $bind): Code |
|
41
|
|
|
{ |
|
42
|
|
|
$visitor = ($this->visitoryFactory)($sourceClass); |
|
43
|
|
|
$classStm = ($this->aopClass)($visitor, $sourceClass, $bind); |
|
44
|
|
|
$ns = $this->getNamespace($visitor); |
|
45
|
|
|
$stmt = $this->factory->namespace($ns) |
|
46
|
|
|
->addStmt($this->factory->use(WeavedInterface::class)) |
|
47
|
|
|
->addStmt($this->factory->use(ReflectiveMethodInvocation::class)->as('Invocation')) |
|
48
|
|
|
->addStmts($visitor->use) |
|
49
|
|
|
->addStmt($classStm) |
|
50
|
|
|
->getNode(); |
|
51
|
|
|
|
|
52
|
|
|
return new Code(array_merge($visitor->declare, [$stmt])); |
|
53
|
|
|
} |
|
54
|
33 |
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* @return string|null |
|
57
|
|
|
*/ |
|
58
|
|
|
private function getNamespace(CodeVisitor $source) |
|
59
|
33 |
|
{ |
|
60
|
33 |
|
$parts = $source->namespace->name->parts ?? []; |
|
61
|
33 |
|
$ns = implode('\\', $parts); |
|
62
|
33 |
|
|
|
63
|
33 |
|
return $ns ? $ns : null; |
|
64
|
33 |
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|
Let’s assume that you have a directory layout like this:
. |-- OtherDir | |-- Bar.php | `-- Foo.php `-- SomeDir `-- Foo.phpand let’s assume the following content of
Bar.php:If both files
OtherDir/Foo.phpandSomeDir/Foo.phpare 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.phpHowever, as
OtherDir/Foo.phpdoes 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: