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