Test Failed
Pull Request — master (#1137)
by f
05:31
created

Memory::saveData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
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 7
ccs 6
cts 6
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
1
e<?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, '/');
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 1
            if (!flock($fp, LOCK_SH | LOCK_NB)) {
40 1
                return null;
41
            }
42
            $data = include($filename);
43
            flock($fp, LOCK_UN);
44 436
            fclose($fp);
45
            return $data;
46 436
        } catch (\Throwable) {
47 436
            return null;
48 436
        }
49 436
    }
50 436
51 436
    public function saveData(string $section, mixed $data): void
52
    {
53
        $this->files->write(
54
            $this->getFilename($section),
55
            '<?php return ' . \var_export($data, true) . ';',
56
            FilesInterface::RUNTIME,
57
            true
58
        );
59 437
    }
60
61
    /**
62 437
     * Get extension to use for runtime data or configuration cache.
63 437
     *
64 437
     * @param string $name Runtime data file name (without extension).
65 437
     */
66 437
    private function getFilename(string $name): string
67 437
    {
68
        //Runtime cache
69
        return \sprintf(
70
            '%s/%s.%s',
71
            $this->directory,
72
            \strtolower(\str_replace(['/', '\\'], '-', $name)),
73
            self::EXTENSION
74
        );
75
    }
76
}
0 ignored issues
show
Bug introduced by
A parse error occurred: Namespace declaration statement has to be the very first statement in the script
Loading history...
77