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

ClassCache::get()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 2
b 0
f 0
nc 3
nop 2
dl 0
loc 13
ccs 7
cts 7
cp 1
crap 3
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 9
    public function __construct(string $cachePath = null)
16
    {
17 9
        $this->cachePath = $cachePath;
18
    }
19
20 6
    public function set(string $className, string $classParent, string $classDeclaration): void
21
    {
22 6
        if ($this->cachePath === null) {
23 3
            return;
24
        }
25 3
        file_put_contents($this->getClassPath($className, $classParent), "<?php\n\n" . $classDeclaration, LOCK_EX);
26
    }
27
28 5
    public function get(string $className, string $classParent): ?string
29
    {
30 5
        if ($this->cachePath === null) {
31 2
            return null;
32
        }
33
34
        try {
35 3
            $content = file_get_contents($this->getClassPath($className, $classParent));
36 2
        } catch (Exception) {
37 2
            return null;
38
        }
39
40 1
        return $content;
41
    }
42
43 5
    public function getClassPath(string $className, string $classParent): string
44
    {
45 5
        [$classFileName, $classFilePath] = $this->getClassFileNameAndPath($className, $classParent);
46
47
        try {
48 5
            FileHelper::ensureDirectory($classFilePath, 0777);
49 1
        } catch (RuntimeException) {
50 1
            throw new RuntimeException(sprintf('Directory "%s" was not created', $classFilePath));
51
        }
52
53 4
        return $classFilePath . DIRECTORY_SEPARATOR . $classFileName;
54
    }
55
56 5
    private function getClassFileNameAndPath(string $className, string $classParent): array
57
    {
58 5
        $classParts = explode('\\', $className);
59 5
        $parentClassParts = explode('\\', $classParent);
60 5
        $classFileName = array_pop($classParts) . '.' . array_pop($parentClassParts) . '.php';
61 5
        $classFilePath = $this->cachePath . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $classParts);
62
63 5
        return [$classFileName, $classFilePath];
64
    }
65
}
66