Passed
Pull Request — master (#1151)
by
unknown
10:36
created

Memory::getFilename()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Boot;
6
7
use Spiral\Files\FilesInterface;
8
9
/**
10
 * File based memory storage.
11
 */
12
final class Memory implements MemoryInterface
13
{
14
    // data file extension
15
    private const EXTENSION = 'php';
16
17
    private readonly string $directory;
18
19 437
    public function __construct(
20
        string $directory,
21
        private readonly FilesInterface $files
22
    ) {
23 437
        $this->directory = \rtrim($directory, '/');
0 ignored issues
show
Bug introduced by
The property directory is declared read-only in Spiral\Boot\Memory.
Loading history...
24
    }
25
26
    /**
27
     * @param string $filename Cache filename.
28
     */
29 25
    public function loadData(string $section, string &$filename = null): mixed
30
    {
31 25
        $filename = $this->getFilename($section);
32
33 25
        if (!\file_exists($filename)) {
34 25
            return null;
35
        }
36
37
        try {
38 4
            $fp = \fopen($filename, 'r');
39 4
            if ($fp === false) {
40
                return null;
41
            }
42
43 4
            if (!\flock($fp, \LOCK_SH | \LOCK_NB)) {
44
                \fclose($fp);
45
                return null;
46
            }
47
48 4
            $data = include($filename);
49
50 3
            \flock($fp, \LOCK_UN);
51 1
        } catch (\Throwable) {
52 1
            return null;
53
        } finally {
54 4
            if (isset($fp)) {
55 4
                \fclose($fp);
56
            }
57
        }
58
59 3
        return $data;
60
    }
61
62 435
    public function saveData(string $section, mixed $data): void
63
    {
64 435
        $this->files->write(
65 435
            $this->getFilename($section),
66 435
            '<?php return ' . \var_export($data, true) . ';',
67 435
            FilesInterface::RUNTIME,
68 435
            true
69 435
        );
70
    }
71
72
    /**
73
     * Get extension to use for runtime data or configuration cache.
74
     *
75
     * @param string $name Runtime data file name (without extension).
76
     */
77 436
    private function getFilename(string $name): string
78
    {
79
        //Runtime cache
80 436
        return \sprintf(
81 436
            '%s/%s.%s',
82 436
            $this->directory,
83 436
            \strtolower(\str_replace(['/', '\\'], '-', $name)),
84 436
            self::EXTENSION
85 436
        );
86
    }
87
}
88