SimpleCache::set()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 6
rs 10
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: joshgulledge
5
 * Date: 2/28/18
6
 * Time: 11:57 AM
7
 */
8
9
namespace LCI\Blend\Helpers;
10
11
12
class SimpleCache
13
{
14
    use Files;
15
16
    protected $directory = __DIR__;
17
18
    /**
19
     * SimpleCache constructor.
20
     * @param string $directory ~ directory with cache files will live
21
     */
22
    public function __construct($directory)
23
    {
24
        $this->directory = $directory;
25
26
        if (!file_exists(rtrim($this->directory, '/'))) {
27
            mkdir(rtrim($this->directory, '/'), $this->getMode(), true);
28
        }
29
    }
30
31
32
    /**
33
     * @param string $key
34
     * @return bool|mixed
35
     */
36
    public function get($key = 'install-config')
37
    {
38
        $path = $this->getFullKeyPath($key);
39
        $data = false;
40
41
        if (file_exists($path)) {
42
            $data = include $path;
43
        }
44
45
        return $data;
46
    }
47
48
    /**
49
     * @param string $key
50
     * @param array $data
51
     */
52
    public function set($key = 'install-config', $data = [])
53
    {
54
        $content = '<?php '.PHP_EOL.
55
            'return '.var_export($data, true).';';
56
57
        file_put_contents($this->getFullKeyPath($key), $content);
58
    }
59
60
    /**
61
     * @param null|string $key ~ if null will delete the complete directory
62
     */
63
    public function remove($key = null)
64
    {
65
        if (!empty($key)) {
66
            $path = $this->getFullKeyPath($key);
67
            if (file_exists($key)) {
68
                unlink($path);
69
            }
70
71
        } else {
72
            // clean the directory:
73
            $this->deleteDirectory(MODX_PATH.$this->directory);
74
        }
75
    }
76
77
    /**
78
     * @param string $key
79
     * @return string
80
     */
81
    protected function getFullKeyPath($key)
82
    {
83
        return rtrim($this->directory, '/').DIRECTORY_SEPARATOR.
84
            preg_replace('/[^A-Za-z0-9\_\-]/', '', str_replace(['/', ' '], '_', $key)).
85
            '.php';
86
    }
87
88
}