|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Yiisoft\Proxy; |
|
4
|
|
|
|
|
5
|
|
|
final class ClassCache |
|
6
|
|
|
{ |
|
7
|
|
|
private ?string $cachePath = null; |
|
8
|
|
|
|
|
9
|
|
|
public function __construct(string $cachePath = null) |
|
10
|
|
|
{ |
|
11
|
|
|
$this->cachePath = $cachePath; |
|
12
|
|
|
} |
|
13
|
|
|
|
|
14
|
|
|
public function set(string $className, string $classParent, string $classDeclaration): void |
|
15
|
|
|
{ |
|
16
|
|
|
if ($this->cachePath === null) { |
|
17
|
|
|
return; |
|
18
|
|
|
} |
|
19
|
|
|
file_put_contents($this->getClassPath($className, $classParent), "<?php\n\n" . $classDeclaration); |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
public function get(string $className, string $classParent): ?string |
|
23
|
|
|
{ |
|
24
|
|
|
if (!file_exists($this->getClassPath($className, $classParent))) { |
|
25
|
|
|
return null; |
|
26
|
|
|
} |
|
27
|
|
|
try { |
|
28
|
|
|
return file_get_contents($this->getClassPath($className, $classParent)); |
|
29
|
|
|
} catch (\Exception $e) { |
|
30
|
|
|
return null; |
|
31
|
|
|
} |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
public function getClassPath(string $className, string $classParent): string |
|
35
|
|
|
{ |
|
36
|
|
|
[$classFileName, $classFilePath] = $this->getClassFileNameAndPath($className, $classParent); |
|
37
|
|
|
if (!is_dir($classFilePath)) { |
|
38
|
|
|
mkdir($classFilePath, 0777, true); |
|
39
|
|
|
} |
|
40
|
|
|
$path = $classFilePath . DIRECTORY_SEPARATOR . $classFileName; |
|
41
|
|
|
|
|
42
|
|
|
return $path; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
public function getClassFileNameAndPath(string $className, string $classParent): array |
|
46
|
|
|
{ |
|
47
|
|
|
$classParts = explode('\\', $className); |
|
48
|
|
|
$parentClassParts = explode('\\', $classParent); |
|
49
|
|
|
$classFileName = array_pop($classParts) . '.' . array_pop($parentClassParts) . ".php"; |
|
50
|
|
|
$classFilePath = $this->cachePath . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $classParts); |
|
51
|
|
|
|
|
52
|
|
|
return [$classFileName, $classFilePath]; |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|