Completed
Push — master ( b2545f...e44389 )
by Divine Niiquaye
02:25
created

MemoryCache::getFilename()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of BiuradPHP opensource projects.
7
 *
8
 * PHP version 7.1 and above required
9
 *
10
 * @author    Divine Niiquaye Ibok <[email protected]>
11
 * @copyright 2019 Biurad Group (https://biurad.com/)
12
 * @license   https://opensource.org/licenses/BSD-3-Clause License
13
 *
14
 * For the full copyright and license information, please view the LICENSE
15
 * file that was distributed with this source code.
16
 */
17
18
namespace Biurad\Cache;
19
20
use Biurad\Cache\Interfaces\MemoryInterface;
21
use Throwable;
22
23
/**
24
 * File based memory storage.
25
 */
26
final class MemoryCache implements MemoryInterface
27
{
28
    // data file extension
29
    private const EXTENSION = 'php';
30
31
    /** @var string */
32
    private $directory;
33
34
    public function __construct(string $directory)
35
    {
36
        $this->directory = \rtrim($directory, '/');
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function loadData(string $section, string &$filename = null)
43
    {
44
        $filename = $this->getFilename($section);
45
46
        if (!\file_exists($filename)) {
47
            return null;
48
        }
49
50
        try {
51
            return include $filename;
52
        } catch (Throwable $e) {
53
            return null;
54
        }
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function saveData(string $section, $data): void
61
    {
62
        \file_put_contents(
63
            $this->getFilename($section),
64
            '<?php return ' . \var_export($data, true) . ';',
65
            \FILE_APPEND | \LOCK_EX
66
        );
67
    }
68
69
    /**
70
     * Get extension to use for runtime data or configuration cache.
71
     *
72
     * @param string $name runtime data file name (without extension)
73
     */
74
    private function getFilename(string $name): string
75
    {
76
        //Runtime cache
77
        return \sprintf(
78
            '%s/%s.%s',
79
            $this->directory,
80
            \strtolower(\str_replace(['/', '\\'], '-', $name)),
81
            self::EXTENSION
82
        );
83
    }
84
}
85