Completed
Push — master ( 27c785...736581 )
by Ryuichi
02:59
created

Memcached::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 4
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 2
1
<?php
2
namespace WebStream\Cache\Driver;
3
4
use WebStream\DI\Injector;
5
use WebStream\Container\Container;
6
7
/**
8
 * Memcached
9
 * @author Ryuichi Tanaka
10
 * @since 2015/07/08
11
 * @version 0.7
12
 */
13
class Memcached implements ICache
14
{
15
    use Injector;
16
17
    /**
18
     * @var Container キャッシュ依存コンテナ
19
     */
20
    private $cacheContainer;
21
22
    /**
23
     * @var string キャッシュ接頭辞
24
     */
25
    private $cachePrefix;
26
27
    /**
28
     * {@inheritdoc}
29
     */
30
    public function __construct(Container $cacheContainer)
31
    {
32
        $this->cacheContainer = $cacheContainer;
33
        $this->cachePrefix = $this->cacheContainer->cachePrefix . '.' . $this->cacheContainer->classPrefix . '.';
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39 4
    public function add($key, $value, $ttl = 0, $overwrite = false): bool
40
    {
41 4
        if (!$this->isAvailableCacheLibrary()) {
42
            return false;
43
        }
44 4
        $key = $this->cachePrefix . $key;
45 4
        $result = null;
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
46
47 4
        if ($ttl > 0) {
48
            if ($overwrite) {
49
                $result = $this->cacheContainer->driver->replace($key, $value, $ttl);
50
                if ($result === false) {
51
                    $result = $this->cacheContainer->driver->set($key, $value, $ttl);
52
                }
53
            } else {
54
                $result = $this->cacheContainer->driver->set($key, $value, $ttl);
55
            }
56
        } else {
57 4
            if ($overwrite) {
58 3
                $result = $this->cacheContainer->driver->replace($key, $value);
59 3
                if ($result === false) {
60 1
                    $result = $this->cacheContainer->driver->set($key, $value);
61
                }
62
            } else {
63 1
                $result = $this->cacheContainer->driver->set($key, $value);
64
            }
65
        }
66
67 4
        $this->logger->info("Execute cache save: " . $key);
68 4
        $this->verifyReturnCode($this->cacheContainer->codes['success']);
69
70 4
        return $result;
71
    }
72
73
    /**
74
     * {@inheritdoc}
75
     */
76 4
    public function get($key)
77
    {
78 4
        if (!$this->isAvailableCacheLibrary()) {
79
            return false;
80
        }
81 4
        $key = $this->cachePrefix . $key;
82 4
        $result = $this->cacheContainer->driver->get($key);
83
84 4
        if ($result !== false) {
85 2
            $this->logger->info("Execute cache read: " . $key);
86
        } else {
87 2
            $this->logger->warn("Failed to read cache: " . $key);
88
        }
89
90 4
        return $this->verifyReturnCode($this->cacheContainer->codes['success']) ? $result : null;
91
    }
92
93
    /**
94
     * {@inheritdoc}
95
     */
96 1
    public function delete($key): bool
97
    {
98 1
        if (!$this->isAvailableCacheLibrary()) {
99
            return false;
100
        }
101 1
        $key = $this->cachePrefix . $key;
102 1
        $this->cacheContainer->driver->delete($key);
103
104 1
        if ($this->verifyReturnCode($this->cacheContainer->codes['notfound'])) {
105
            $this->logger->info("Execute cache cleared: " . $key);
106
            return true;
107
        } else {
108 1
            $this->logger->warn("Failed to clear cache: " . $key);
109 1
            return false;
110
        }
111
    }
112
113
    /**
114
     * {@inheritdoc}
115
     */
116 1
    public function clear(): bool
117
    {
118 1
        if (!$this->isAvailableCacheLibrary()) {
119
            return false;
120
        }
121 1
        $allKeys = $this->cacheContainer->driver->getAllKeys();
122 1
        if ($allKeys === false) {
123 1
            $this->logger->warn("Can't get cache keys: " . $this->cachePrefix . "*");
124 1
            $this->cacheContainer->driver->flush();
125
126 1
            return true;
127
        }
128
129
        $prefixLength = strlen($this->cachePrefix);
130
        $targetKeys = [];
131
        foreach ($allKeys as $key) {
132
            if (substr($key, 0, $prefixLength)) {
133
                $targetKeys[] = $key;
134
            }
135
        }
136
137
        $this->cacheContainer->driver->deleteMulti($targetKeys);
138
139
        if ($this->verifyReturnCode($this->cacheContainer->codes['notfound'])) {
140
            $this->logger->info("Execute all cache cleared: " . $this->cachePrefix . "*");
141
            return true;
142
        } else {
143
            $this->logger->warn("Failed to clear all cache: " . $this->cachePrefix . "*");
144
            return false;
145
        }
146
    }
147
148
    /**
149
     * リターンコードを検証する
150
     * @param int $code 想定コード
151
     * @return bool 検証結果
152
     */
153 4
    private function verifyReturnCode(int $code): bool
154
    {
155 4
        if ($code !== $this->cacheContainer->driver->getResultCode()) {
156 2
            $message = $this->cacheContainer->driver->getResultMessage();
157 2
            $this->logger->warn("Error $code interacting with memcached: $message");
158
159 2
            return false;
160
        }
161
162 4
        return true;
163
    }
164
165
    /**
166
     * キャッシュライブラリが使用可能か検査する
167
     * @return bool 使用可能でtrue
168
     */
169 4
    private function isAvailableCacheLibrary(): bool
170
    {
171 4
        if ($this->cacheContainer->available) {
172 4
            return true;
173
        }
174
175
        $this->logger->warn("Memcached cache library is unavailable.");
176
177
        return false;
178
    }
179
}
180