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

Memory   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Test Coverage

Coverage 90.63%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 9
eloc 32
c 2
b 1
f 0
dl 0
loc 73
ccs 29
cts 32
cp 0.9063
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getFilename() 0 8 1
A saveData() 0 7 1
A loadData() 0 31 6
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