FileStorageDriver::__construct()   B
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 8
nc 4
nop 1
1
<?php
2
3
namespace Millennium\Cache\Drivers;
4
5
use Millennium\Cache\Exceptions\FileStorage\FileStorageMisconfiguration;
6
use Millennium\Cache\Interfaces\CacheDriverInterface;
7
8
class FileStorageDriver implements CacheDriverInterface
9
{
10
    /**
11
     * @var string
12
     */
13
    private $cachePath;
14
15
    /**
16
     * @param array $options
17
     *
18
     * @throws FileStorageMisconfiguration
19
     */
20
    public function __construct(array $options = null)
21
    {
22
        if (null === $options) {
23
            throw new FileStorageMisconfiguration();
24
        }
25
        if (!isset($options['path'])) {
26
            throw new FileStorageMisconfiguration('Please set path for file storage driver.');
27
        }
28
        if (!is_dir($options['path']) || !is_readable($options['path'])) {
29
            throw new \Millennium\Cache\Exceptions\FileStorage\FileStorageDirectoryNotReadableException($options['path']);
30
        }
31
        $this->cachePath = rtrim($options['path'], DIRECTORY_SEPARATOR);
32
    }
33
34
    /**
35
     * @param string $key
36
     *
37
     * @return bool
38
     */
39
    public function fetch($key)
40
    {
41
        if (file_exists($this->cachePath.DIRECTORY_SEPARATOR.$key.'.cache')) {
42
            list($expire, $data) = unserialize(file_get_contents($this->cachePath.DIRECTORY_SEPARATOR.$key.'.cache'));
43
            if (filemtime($this->cachePath.DIRECTORY_SEPARATOR.$key.'.cache') <= $expire) {
44
                return $data;
45
            }
46
            unlink($this->cachePath.DIRECTORY_SEPARATOR.$key.'.cache');
47
        }
48
49
        return false;
50
    }
51
52
    /**
53
     * @param string $key
54
     *
55
     * @return bool
56
     */
57
    public function remove($key)
58
    {
59
        if (file_exists($this->cachePath.DIRECTORY_SEPARATOR.$key.'.cache')) {
60
            unlink($this->cachePath.DIRECTORY_SEPARATOR.$key.'.cache');
61
        }
62
63
        return true;
64
    }
65
66
    /**
67
     * @param string $key
68
     * @param array  $data
69
     *
70
     * @return bool
71
     */
72
    public function store($key, $data, $expire = 3600)
73
    {
74
        return file_put_contents($this->cachePath.DIRECTORY_SEPARATOR.$key.'.cache', serialize([time() + $expire, $data]));
75
    }
76
}
77