1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Proxy; |
6
|
|
|
|
7
|
|
|
use Exception; |
8
|
|
|
use RuntimeException; |
9
|
|
|
use Yiisoft\Files\FileHelper; |
10
|
|
|
|
11
|
|
|
final class ClassCache |
12
|
|
|
{ |
13
|
|
|
private ?string $cachePath; |
14
|
|
|
|
15
|
6 |
|
public function __construct(string $cachePath = null) |
16
|
|
|
{ |
17
|
6 |
|
$this->cachePath = $cachePath; |
18
|
|
|
} |
19
|
|
|
|
20
|
5 |
|
public function set(string $className, string $classParent, string $classDeclaration): void |
21
|
|
|
{ |
22
|
5 |
|
if ($this->cachePath === null) { |
23
|
2 |
|
return; |
24
|
|
|
} |
25
|
3 |
|
file_put_contents($this->getClassPath($className, $classParent), "<?php\n\n" . $classDeclaration, LOCK_EX); |
26
|
|
|
} |
27
|
|
|
|
28
|
4 |
|
public function get(string $className, string $classParent): ?string |
29
|
|
|
{ |
30
|
4 |
|
if ($this->cachePath === null) { |
31
|
1 |
|
return null; |
32
|
|
|
} |
33
|
|
|
|
34
|
3 |
|
if (!file_exists($this->getClassPath($className, $classParent))) { |
35
|
2 |
|
return null; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
try { |
39
|
1 |
|
$content = file_get_contents($this->getClassPath($className, $classParent)); |
40
|
|
|
} catch (Exception) { |
41
|
|
|
return null; |
42
|
|
|
} |
43
|
|
|
|
44
|
1 |
|
if ($content === false) { |
45
|
|
|
return null; |
46
|
|
|
} |
47
|
|
|
|
48
|
1 |
|
return $content; |
49
|
|
|
} |
50
|
|
|
|
51
|
5 |
|
public function getClassPath(string $className, string $classParent): string |
52
|
|
|
{ |
53
|
5 |
|
[$classFileName, $classFilePath] = $this->getClassFileNameAndPath($className, $classParent); |
54
|
|
|
|
55
|
|
|
try { |
56
|
5 |
|
FileHelper::ensureDirectory($classFilePath, 0777); |
57
|
1 |
|
} catch (RuntimeException) { |
58
|
1 |
|
throw new RuntimeException(sprintf('Directory "%s" was not created', $classFilePath)); |
59
|
|
|
} |
60
|
|
|
|
61
|
4 |
|
return $classFilePath . DIRECTORY_SEPARATOR . $classFileName; |
62
|
|
|
} |
63
|
|
|
|
64
|
5 |
|
private function getClassFileNameAndPath(string $className, string $classParent): array |
65
|
|
|
{ |
66
|
5 |
|
$classParts = explode('\\', $className); |
67
|
5 |
|
$parentClassParts = explode('\\', $classParent); |
68
|
5 |
|
$classFileName = array_pop($classParts) . '.' . array_pop($parentClassParts) . '.php'; |
69
|
5 |
|
$classFilePath = $this->cachePath . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $classParts); |
70
|
|
|
|
71
|
5 |
|
return [$classFileName, $classFilePath]; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|