Completed
Push — master ( e099bf...2f0857 )
by Lars
04:09
created

AdapterArray   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 118
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 68.42%

Importance

Changes 0
Metric Value
wmc 14
lcom 1
cbo 0
dl 0
loc 118
ccs 26
cts 38
cp 0.6842
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A exists() 0 6 1
A get() 0 4 2
A installed() 0 4 1
A remove() 0 12 2
A removeAll() 0 7 1
A set() 0 6 1
A setExpired() 0 7 1
B removeExpired() 0 22 5
1
<?php
2
3
namespace voku\cache;
4
5
/**
6
 * AdapterArray: simple array-cache adapter
7
 *
8
 * @package voku\cache
9
 */
10
class AdapterArray implements iAdapter
11
{
12
13
  /**
14
   * @var array
15
   */
16
  private static $values = array();
17
18
  /**
19
   * @var array
20
   */
21
  private static $expired = array();
22
23
  /**
24
   * @inheritdoc
25
   */
26 6
  public function exists($key)
27
  {
28 6
    $this->removeExpired($key);
29
30 6
    return array_key_exists($key, self::$values);
31
  }
32
33
  /**
34
   * @inheritdoc
35
   */
36 5
  public function get($key)
37
  {
38 5
    return $this->exists($key) ? self::$values[$key] : null;
39
  }
40
41
  /**
42
   * @inheritdoc
43
   */
44
  public function installed()
45
  {
46
    return true;
47
  }
48
49
  /**
50
   * @inheritdoc
51
   */
52
  public function remove($key)
53
  {
54
    $this->removeExpired($key);
55
56
    if (array_key_exists($key, self::$values) === true) {
57
      unset(self::$values[$key]);
58
59
      return true;
60
    }
61
62
    return false;
63
  }
64
65
  /**
66
   * @inheritdoc
67
   */
68
  public function removeAll()
69
  {
70
    self::$values = array();
71
    self::$expired = array();
72
73
    return true;
74
  }
75
76
  /**
77
   * @inheritdoc
78
   */
79 3
  public function set($key, $value)
80
  {
81 3
    self::$values[$key] = $value;
82
83 3
    return true;
84
  }
85
86
  /**
87
   * @inheritdoc
88
   */
89 1
  public function setExpired($key, $value, $ttl)
90
  {
91 1
    self::$values[$key] = $value;
92 1
    self::$expired[$key] = array(time(), $ttl);
93
94 1
    return true;
95
  }
96
97
  /**
98
   * Remove expired cache.
99
   *
100
   * @param string $key
101
   *
102
   * @return boolean
103
   */
104 6
  private function removeExpired($key)
105
  {
106
    if (
107 6
        array_key_exists($key, self::$expired) === false
108 6
        ||
109 1
        array_key_exists($key, self::$values) === false
110 6
    ) {
111 5
      return false;
112
    }
113
114 1
    list($time, $ttl) = self::$expired[$key];
115
116 1
    if (time() > ($time + $ttl)) {
117 1
      unset(self::$values[$key]);
118 1
    }
119
120 1
    if (!isset(self::$values[$key])) {
121 1
      unset(self::$expired[$key]);
122 1
    }
123
124 1
    return true;
125
  }
126
127
}
128