Completed
Push — master ( e5df79...d2de4e )
by Peter
06:03
created

Shmop::getIdByKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * AnimeDb package
4
 *
5
 * @package   AnimeDb
6
 * @author    Peter Gribanov <[email protected]>
7
 * @copyright Copyright (c) 2014, Peter Gribanov
8
 * @license   http://opensource.org/licenses/MIT
9
 */
10
11
namespace AnimeDb\Bundle\CacheTimeKeeperBundle\Service\Driver;
12
13
use AnimeDb\Shmop\FixedBlock as BlockShmop;
14
15
/**
16
 * Shmop driver
17
 *
18
 * @package AnimeDb\Bundle\CacheTimeKeeperBundle\Service\Driver
19
 * @author  Peter Gribanov <[email protected]>
20
 */
21
class Shmop extends Base
22
{
23
    /**
24
     * Cache key salt
25
     *
26
     * @var string
27
     */
28
    protected $salt;
29
30
    /**
31
     * @param string $salt
32
     */
33 8
    public function __construct($salt)
34
    {
35 8
        $this->salt = $salt;
36 8
    }
37
38
    /**
39
     * Get time for key
40
     *
41
     * @param string $key
42
     *
43
     * @return \DateTime|null
44
     */
45 5
    public function get($key)
46
    {
47 5
        $sh = new BlockShmop($this->getIdByKey($key), 10);
48 5
        if ($time = $sh->read()) {
49 3
            return new \DateTime(date('Y-m-d H:i:s', $time));
50
        }
51
52 2
        return null;
53
    }
54
55
    /**
56
     * Set time for key
57
     *
58
     * @param string $key
59
     * @param \DateTime $time
60
     *
61
     * @return boolean
62
     */
63 5
    public function set($key, \DateTime $time)
64
    {
65 5
        $sh = new BlockShmop($this->getIdByKey($key), 10);
66 5
        if (!($old_time = $sh->read()) || $old_time < $time->getTimestamp()) {
67 5
            $sh->write($time->getTimestamp());
68 5
        }
69
70 5
        return true;
71
    }
72
73
    /**
74
     * Remove time for key
75
     *
76
     * @param string $key
77
     *
78
     * @return boolean
79
     */
80 1
    public function remove($key)
81
    {
82 1
        $sh = new BlockShmop($this->getIdByKey($key), 10);
83
84 1
        return $sh->delete();
85
    }
86
87
    /**
88
     * Get id
89
     *
90
     * @param string $key
91
     *
92
     * @return integer
93
     */
94 8
    public function getIdByKey($key)
95
    {
96 8
        return (int)sprintf('%u', crc32($key.$this->salt));
97
    }
98
}
99