Passed
Pull Request — master (#21)
by
unknown
02:17
created

ClassCache::set()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 3
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 2
rs 10
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 5
    public function __construct(string $cachePath = null)
16
    {
17 5
        $this->cachePath = $cachePath;
18
    }
19
20 4
    public function set(string $className, string $classParent, string $classDeclaration): void
21
    {
22 4
        if ($this->cachePath === null) {
23 2
            return;
24
        }
25 2
        file_put_contents($this->getClassPath($className, $classParent), "<?php\n\n" . $classDeclaration, LOCK_EX);
26
    }
27
28 3
    public function get(string $className, string $classParent): ?string
29
    {
30 3
        if ($this->cachePath === null) {
31 1
            return null;
32
        }
33
34 2
        if (!file_exists($this->getClassPath($className, $classParent))) {
35 1
            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 4
    public function getClassPath(string $className, string $classParent): string
52
    {
53 4
        [$classFileName, $classFilePath] = $this->getClassFileNameAndPath($className, $classParent);
54
55
        try {
56 4
            FileHelper::ensureDirectory($classFilePath, 0777);
57 1
        } catch (RuntimeException) {
58 1
            throw new RuntimeException(sprintf('Directory "%s" was not created', $classFilePath));
59
        }
60
61 3
        return $classFilePath . DIRECTORY_SEPARATOR . $classFileName;
62
    }
63
64 4
    private function getClassFileNameAndPath(string $className, string $classParent): array
65
    {
66 4
        $classParts = explode('\\', $className);
67 4
        $parentClassParts = explode('\\', $classParent);
68 4
        $classFileName = array_pop($classParts) . '.' . array_pop($parentClassParts) . '.php';
69 4
        $classFilePath = $this->cachePath . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $classParts);
70
71 4
        return [$classFileName, $classFilePath];
72
    }
73
}
74