Passed
Pull Request — master (#1137)
by f
11:08
created

Memory   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 96.43%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 27
c 1
b 0
f 0
dl 0
loc 62
ccs 27
cts 28
cp 0.9643
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A loadData() 0 19 4
A getFilename() 0 8 1
A saveData() 0 7 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 438
    public function __construct(
20
        string $directory,
21
        private readonly FilesInterface $files
22
    ) {
23 438
        $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 (!flock($fp, LOCK_SH | LOCK_NB)) {
40
                return null;
41
            }
42 4
            $data = include($filename);
43 3
            flock($fp, LOCK_UN);
44 3
            fclose($fp);
45 3
            return $data;
46 1
        } catch (\Throwable) {
47 1
            return null;
48
        }
49
    }
50
51 436
    public function saveData(string $section, mixed $data): void
52
    {
53 436
        $this->files->write(
54 436
            $this->getFilename($section),
55 436
            '<?php return ' . \var_export($data, true) . ';',
56 436
            FilesInterface::RUNTIME,
57 436
            true
58 436
        );
59
    }
60
61
    /**
62
     * Get extension to use for runtime data or configuration cache.
63
     *
64
     * @param string $name Runtime data file name (without extension).
65
     */
66 437
    private function getFilename(string $name): string
67
    {
68
        //Runtime cache
69 437
        return \sprintf(
70 437
            '%s/%s.%s',
71 437
            $this->directory,
72 437
            \strtolower(\str_replace(['/', '\\'], '-', $name)),
73 437
            self::EXTENSION
74 437
        );
75
    }
76
}
77