File::get()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
c 0
b 0
f 0
ccs 5
cts 5
cp 1
rs 9.6666
cc 2
eloc 5
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * AnimeDb package.
4
 *
5
 * @author    Peter Gribanov <[email protected]>
6
 * @copyright Copyright (c) 2014, Peter Gribanov
7
 * @license   http://opensource.org/licenses/MIT
8
 */
9
10
namespace AnimeDb\Bundle\CacheTimeKeeperBundle\Service\Driver;
11
12
class File extends BaseDriver
13
{
14
    /**
15
     * @var string
16
     */
17
    const FILENAME_SUFFIX = '.key';
18
19
    /**
20
     * @var string
21
     */
22
    protected $dir;
23
24
    /**
25
     * @param string $dir
26
     */
27 9
    public function __construct($dir)
28
    {
29 9
        $this->dir = $dir;
30 9
    }
31
32
    /**
33
     * @param string $key
34
     *
35
     * @return \DateTime|null
36
     */
37 5
    public function get($key)
38
    {
39 5
        $file = $this->getFilename($key);
40 5
        if (file_exists($file)) {
41 3
            return (new \DateTime())->setTimestamp(filemtime($file));
42
        }
43
44 2
        return;
45
    }
46
47
    /**
48
     * @param string $key
49
     * @param \DateTime $time
50
     *
51
     * @return bool
52
     */
53 6
    public function set($key, \DateTime $time)
54
    {
55 6
        $time = $time->getTimestamp();
56 6
        $file = $this->getFilename($key);
57 6
        if (!file_exists($file) || $time > filemtime($file)) {
58 6
            return touch($file, $time);
59
        }
60
61 1
        return true;
62
    }
63
64
    /**
65
     * @param string $key
66
     *
67
     * @return bool
68
     */
69 3
    public function remove($key)
70
    {
71 3
        $file = $this->getFilename($key);
72 3
        if (file_exists($file)) {
73 2
            return unlink($file);
74
        }
75
76 1
        return false;
77
    }
78
79
    /**
80
     * @param string $key
81
     *
82
     * @return string
83
     */
84 8
    protected function getFilename($key)
85
    {
86 8
        if (!is_dir($this->dir)) {
87 1
            mkdir($this->dir, 0755, true);
88 1
        }
89
90 8
        return $this->dir.'/'.md5($key).self::FILENAME_SUFFIX;
91
    }
92
}
93