1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Proxy; |
6
|
|
|
|
7
|
|
|
final class ProxyManager |
8
|
|
|
{ |
9
|
|
|
private ?string $cachePath = null; |
10
|
|
|
|
11
|
|
|
private ClassRenderer $classRenderer; |
12
|
|
|
|
13
|
|
|
private ClassConfigurator $classConfigurator; |
14
|
|
|
|
15
|
|
|
private ClassCache $classCache; |
16
|
|
|
|
17
|
|
|
public function __construct(string $cachePath = null) |
18
|
|
|
{ |
19
|
|
|
$this->cachePath = $cachePath; |
20
|
|
|
$this->classCache = new ClassCache($cachePath); |
21
|
|
|
$this->classRenderer = new ClassRenderer(); |
22
|
|
|
$this->classConfigurator = new ClassConfigurator(); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function createObjectProxyFromInterface(string $interface, string $parentProxyClass, array $constructorArguments = null): ?object |
26
|
|
|
{ |
27
|
|
|
$className = $interface . 'Proxy'; |
28
|
|
|
$shortClassName = $this->getProxyClassName($className); |
29
|
|
|
|
30
|
|
|
if (!($classDeclaration = $this->classCache->get($className, $parentProxyClass))) { |
31
|
|
|
$classConfig = $this->generateInterfaceProxyClassConfig($this->classConfigurator->getInterfaceConfig($interface), $parentProxyClass); |
32
|
|
|
$classDeclaration = $this->classRenderer->render($classConfig); |
33
|
|
|
$this->classCache->set($className, $parentProxyClass, $classDeclaration); |
34
|
|
|
} |
35
|
|
|
if ($this->cachePath === null) { |
36
|
|
|
eval(str_replace('<?php', '', $classDeclaration)); |
|
|
|
|
37
|
|
|
} else { |
38
|
|
|
$path = $this->classCache->getClassPath($className, $parentProxyClass); |
39
|
|
|
require $path; |
40
|
|
|
} |
41
|
|
|
return new $shortClassName(...$constructorArguments); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
private function generateInterfaceProxyClassConfig(ClassConfig $interfaceConfig, string $parentProxyClass): ClassConfig |
45
|
|
|
{ |
46
|
|
|
$interfaceConfig->isInterface = false; |
47
|
|
|
$interfaceConfig->parent = $parentProxyClass; |
48
|
|
|
$interfaceConfig->interfaces = [$interfaceConfig->name]; |
49
|
|
|
$interfaceConfig->name .= 'Proxy'; |
50
|
|
|
$interfaceConfig->shortName = $this->getProxyClassName($interfaceConfig->name); |
51
|
|
|
|
52
|
|
|
foreach ($interfaceConfig->methods as $methodIndex => $method) { |
53
|
|
|
foreach ($method->modifiers as $index => $modifier) { |
54
|
|
|
if ($modifier === 'abstract') { |
55
|
|
|
unset($interfaceConfig->methods[$methodIndex]->modifiers[$index]); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return $interfaceConfig; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
private function getProxyClassName(string $fullClassName) |
64
|
|
|
{ |
65
|
|
|
return str_replace('\\', '_', $fullClassName); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|