Passed
Push — master ( 489ba2...382a6c )
by Alexander
01:29
created

ClassCache::getClassPath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 9
ccs 0
cts 8
cp 0
crap 6
rs 10
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