Passed
Push — master ( 3eb4db...99d5ff )
by Kirill
03:12
created

Memory::loadData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 12
rs 10
cc 3
nc 3
nop 2
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Boot;
13
14
use Spiral\Files\FilesInterface;
15
16
/**
17
 * File based memory storage.
18
 */
19
final class Memory implements MemoryInterface
20
{
21
    // data file extension
22
    private const EXTENSION = 'php';
23
24
    /** @var string */
25
    private $directory;
26
27
    /** @var FilesInterface */
28
    private $files = null;
29
30
    /**
31
     * @param string         $directory
32
     * @param FilesInterface $files
33
     */
34
    public function __construct(string $directory, FilesInterface $files)
35
    {
36
        $this->directory = rtrim($directory, '/');
37
        $this->files = $files;
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     *
43
     * @param string $filename Cache filename.
44
     */
45
    public function loadData(string $section, string &$filename = null)
46
    {
47
        $filename = $this->getFilename($section);
48
49
        if (!file_exists($filename)) {
50
            return null;
51
        }
52
53
        try {
54
            return include($filename);
55
        } catch (\Throwable $e) {
56
            return null;
57
        }
58
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63
    public function saveData(string $section, $data): void
64
    {
65
        $this->files->write(
66
            $this->getFilename($section),
67
            '<?php return ' . var_export($data, true) . ';',
68
            FilesInterface::RUNTIME,
69
            true
70
        );
71
    }
72
73
    /**
74
     * Get extension to use for runtime data or configuration cache.
75
     *
76
     * @param string $name Runtime data file name (without extension).
77
     *
78
     * @return string
79
     */
80
    private function getFilename(string $name): string
81
    {
82
        //Runtime cache
83
        return sprintf(
84
            '%s/%s.%s',
85
            $this->directory,
86
            strtolower(str_replace(['/', '\\'], '-', $name)),
87
            self::EXTENSION
88
        );
89
    }
90
}
91