Completed
Push — master ( 8ad0a5...af5d94 )
by yuuki
10s
created

CouchbaseStore::resolveKey()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 1
dl 0
loc 13
ccs 0
cts 11
cp 0
crap 12
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10
 * THE SOFTWARE.
11
 */
12
13
namespace Ytake\LaravelCouchbase\Cache;
14
15
use CouchbaseBucket;
16
use CouchbaseCluster;
17
use CouchbaseException;
18
use Illuminate\Cache\TaggableStore;
19
use Illuminate\Contracts\Cache\Store;
20
use Illuminate\Cache\RetrievesMultipleKeys;
21
use Ytake\LaravelCouchbase\Exceptions\FlushException;
22
23
/**
24
 * Class CouchbaseStore.
25
 *
26
 * @author Yuuki Takezawa<[email protected]>
27
 */
28
class CouchbaseStore extends TaggableStore implements Store
29
{
30
    use RetrievesMultipleKeys;
31
32
    /** @var string */
33
    protected $prefix;
34
35
    /** @var CouchbaseBucket */
36
    protected $bucket;
37
38
    /** @var CouchbaseCluster */
39
    protected $cluster;
40
41
    /**
42
     * CouchbaseStore constructor.
43
     *
44
     * @param CouchbaseCluster $cluster
45
     * @param                  $bucket
46
     * @param string           $password
47
     * @param null             $prefix
48
     * @param string           $serialize
49
     */
50
    public function __construct(CouchbaseCluster $cluster, $bucket, $password = '', $prefix = null, $serialize = 'php')
51
    {
52
        $this->cluster = $cluster;
53
        $this->setBucket($bucket, $password, $serialize);
54
        $this->setPrefix($prefix);
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function get($key)
61
    {
62
        try {
63
            $result = $this->bucket->get($this->resolveKey($key));
64
65
            return $this->getMetaDoc($result);
66
        } catch (CouchbaseException $e) {
0 ignored issues
show
Bug introduced by
The class CouchbaseException does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
67
            return;
68
        }
69
    }
70
71
    /**
72
     * Store an item in the cache if the key doesn't exist.
73
     *
74
     * @param string|array $key
75
     * @param mixed        $value
76
     * @param int          $minutes
77
     *
78
     * @return bool
79
     */
80
    public function add($key, $value, $minutes = 0)
81
    {
82
        $options = ($minutes === 0) ? [] : ['expiry' => ($minutes * 60)];
83
        try {
84
            $this->bucket->insert($this->resolveKey($key), $value, $options);
85
86
            return true;
87
        } catch (CouchbaseException $e) {
0 ignored issues
show
Bug introduced by
The class CouchbaseException does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
88
            return false;
89
        }
90
    }
91
92
    /**
93
     * {@inheritdoc}
94
     */
95
    public function put($key, $value, $minutes)
96
    {
97
        $this->bucket->upsert($this->resolveKey($key), $value, ['expiry' => $minutes * 60]);
98
    }
99
100
    /**
101
     * {@inheritdoc}
102
     */
103
    public function increment($key, $value = 1)
104
    {
105
        return $this->bucket
106
            ->counter($this->resolveKey($key), $value, ['initial' => abs($value)])->value;
107
    }
108
109
    /**
110
     * {@inheritdoc}
111
     */
112
    public function decrement($key, $value = 1)
113
    {
114
        return $this->bucket
115
            ->counter($this->resolveKey($key), (0 - abs($value)), ['initial' => (0 - abs($value))])->value;
116
    }
117
118
    /**
119
     * {@inheritdoc}
120
     */
121
    public function forever($key, $value)
122
    {
123
        try {
124
            $this->bucket->insert($this->resolveKey($key), $value);
125
        } catch (CouchbaseException $e) {
0 ignored issues
show
Bug introduced by
The class CouchbaseException does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
126
            // bucket->insert when called from resetTag in TagSet can throw CAS exceptions, ignore.\
127
            $this->bucket->upsert($this->resolveKey($key), $value);
128
        }
129
    }
130
131
    /**
132
     * {@inheritdoc}
133
     */
134
    public function forget($key)
135
    {
136
        try {
137
            $this->bucket->remove($this->resolveKey($key));
138
        } catch (\Exception $e) {
139
            // Ignore exceptions from remove
140
        }
141
    }
142
143
    /**
144
     * flush bucket.
145
     *
146
     * @throws FlushException
147
     * @codeCoverageIgnore
148
     */
149
    public function flush()
150
    {
151
        $result = $this->bucket->manager()->flush();
152
        if (isset($result['_'])) {
153
            throw new FlushException($result);
154
        }
155
    }
156
157
    /**
158
     * {@inheritdoc}
159
     */
160
    public function getPrefix()
161
    {
162
        return $this->prefix;
163
    }
164
165
    /**
166
     * Set the cache key prefix.
167
     *
168
     * @param string $prefix
169
     */
170
    public function setPrefix($prefix)
171
    {
172
        $this->prefix = !empty($prefix) ? $prefix . ':' : '';
173
    }
174
175
    /**
176
     * @param        $bucket
177
     * @param string $password
178
     * @param string $serialize
179
     *
180
     * @return $this
181
     */
182
    public function setBucket($bucket, $password = '', $serialize = 'php')
183
    {
184
        $this->bucket = $this->cluster->openBucket($bucket, $password);
185
        if ($serialize === 'php') {
186
            $this->bucket->setTranscoder('couchbase_php_serialize_encoder', 'couchbase_default_decoder');
187
        }
188
189
        return $this;
190
    }
191
192
    /**
193
     * @param $keys
194
     *
195
     * @return array|string
196
     */
197
    private function resolveKey($keys)
198
    {
199
        if (is_array($keys)) {
200
            $result = [];
201
            foreach ($keys as $key) {
202
                $result[] = $this->prefix . $key;
203
            }
204
205
            return $result;
206
        }
207
208
        return $this->prefix . $keys;
209
    }
210
211
    /**
212
     * @param $meta
213
     *
214
     * @return array|null
215
     */
216 View Code Duplication
    protected function getMetaDoc($meta)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
217
    {
218
        if ($meta instanceof \CouchbaseMetaDoc) {
0 ignored issues
show
Bug introduced by
The class CouchbaseMetaDoc does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
219
            return $meta->value;
220
        }
221
        if (is_array($meta)) {
222
            $result = [];
223
            foreach ($meta as $row) {
224
                $result[] = $this->getMetaDoc($row);
225
            }
226
227
            return $result;
228
        }
229
230
        return null;
231
    }
232
}
233