1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Yiisoft\Proxy; |
4
|
|
|
|
5
|
|
|
final class ProxyManager |
6
|
|
|
{ |
7
|
|
|
private ?string $cachePath = null; |
8
|
|
|
|
9
|
|
|
private ClassRenderer $classRenderer; |
10
|
|
|
|
11
|
|
|
private ClassConfigurator $classConfigurtor; |
12
|
|
|
|
13
|
|
|
private ClassCache $classCache; |
14
|
|
|
|
15
|
|
|
public function __construct(string $cachePath = null) |
16
|
|
|
{ |
17
|
|
|
$this->cachePath = $cachePath; |
18
|
|
|
$this->classCache = new ClassCache($cachePath); |
19
|
|
|
$this->classRenderer = new ClassRenderer(); |
20
|
|
|
$this->classConfigurtor = new ClassConfigurator(); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function createObjectProxyFromInterface(string $interface, string $parentProxyClass, array $constructorArguments = null): ?object |
24
|
|
|
{ |
25
|
|
|
$className = $interface . 'Proxy'; |
26
|
|
|
[$classFileName] = $this->classCache->getClassFileNameAndPath($className, $parentProxyClass); |
27
|
|
|
$shortClassName = substr($classFileName, 0, strpos($classFileName, '.')); |
28
|
|
|
|
29
|
|
|
if (!($classDeclaration = $this->classCache->get($className, $parentProxyClass))) { |
30
|
|
|
$classConfig = $this->generateInterfaceProxyClassConfig($this->classConfigurtor->getInterfaceConfig($interface), $parentProxyClass); |
31
|
|
|
$classDeclaration = $this->classRenderer->render($classConfig); |
32
|
|
|
$this->classCache->set($className, $parentProxyClass, $classDeclaration); |
33
|
|
|
} |
34
|
|
|
if ($this->cachePath === null) { |
35
|
|
|
eval(str_replace('<?php', '', $classDeclaration)); |
|
|
|
|
36
|
|
|
} else { |
37
|
|
|
$path = $this->classCache->getClassPath($className, $parentProxyClass); |
38
|
|
|
require $path; |
39
|
|
|
} |
40
|
|
|
$proxy = new $shortClassName(...$constructorArguments); |
41
|
|
|
|
42
|
|
|
return $proxy; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
private function generateInterfaceProxyClassConfig(ClassConfig $interfaceConfig, string $parentProxyClass): ClassConfig |
46
|
|
|
{ |
47
|
|
|
$interfaceConfig->isInterface = false; |
48
|
|
|
$interfaceConfig->parent = $parentProxyClass; |
49
|
|
|
$interfaceConfig->interfaces = [$interfaceConfig->name]; |
50
|
|
|
$interfaceConfig->shortName .= 'Proxy'; |
51
|
|
|
$interfaceConfig->name .= 'Proxy'; |
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
|
|
|
|