CouchbaseStore::getMetaDoc()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4.0218

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
nc 4
nop 1
dl 0
loc 16
ccs 8
cts 9
cp 0.8889
crap 4.0218
rs 9.2
c 1
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
/**
5
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
6
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
7
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
8
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
9
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
10
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
11
 * THE SOFTWARE.
12
 */
13
14
namespace Ytake\LaravelCouchbase\Cache;
15
16
use Couchbase\Bucket;
17
use Couchbase\Cluster;
18
use Couchbase\Exception as CouchbaseException;
19
use Illuminate\Cache\RetrievesMultipleKeys;
20
use Illuminate\Cache\TaggableStore;
21
use Illuminate\Contracts\Cache\Lock;
22
use Illuminate\Contracts\Cache\Store;
23
use Ytake\LaravelCouchbase\Exceptions\FlushException;
24
25
/**
26
 * Class CouchbaseStore.
27
 *
28
 * @author Yuuki Takezawa<[email protected]>
29
 */
30
class CouchbaseStore extends TaggableStore implements Store
31
{
32
    use RetrievesMultipleKeys;
33
34
    /** @var string */
35
    protected $prefix;
36
37
    /** @var Bucket */
38
    protected $bucket;
39
40
    /** @var Cluster */
41
    protected $cluster;
42
43
    /**
44
     * CouchbaseStore constructor.
45
     *
46
     * @param Cluster     $cluster
47
     * @param string      $bucket
48
     * @param string      $password
49
     * @param string|null $prefix
50
     * @param string      $serialize
51
     */
52 32
    public function __construct(
53
        Cluster $cluster,
54
        string $bucket,
55
        string $password = '',
56
        string $prefix = null,
57
        string $serialize = 'php'
58
    ) {
59 32
        $this->cluster = $cluster;
60 32
        $this->setBucket($bucket, $password, $serialize);
61 32
        $this->setPrefix($prefix);
62 32
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67 18
    public function get($key)
68
    {
69
        try {
70 18
            $result = $this->bucket->get($this->resolveKey($key));
71
72 12
            return $this->getMetaDoc($result);
73 8
        } catch (CouchbaseException $e) {
0 ignored issues
show
Bug introduced by
The class Couchbase\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
74 8
            return;
75
        }
76
    }
77
78
    /**
79
     * Store an item in the cache if the key doesn't exist.
80
     *
81
     * @param string|array $key
82
     * @param mixed        $value
83
     * @param int          $minutes
84
     *
85
     * @return bool
86
     */
87 14
    public function add($key, $value, $minutes = 0): bool
88
    {
89 14
        $options = ($minutes === 0) ? [] : ['expiry' => ($minutes * 60)];
90
        try {
91 14
            $this->bucket->insert($this->resolveKey($key), $value, $options);
92
93 14
            return true;
94 2
        } catch (CouchbaseException $e) {
0 ignored issues
show
Bug introduced by
The class Couchbase\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
95 2
            return false;
96
        }
97
    }
98
99
    /**
100
     * {@inheritdoc}
101
     */
102 2
    public function put($key, $value, $minutes)
103
    {
104 2
        $this->bucket->upsert($this->resolveKey($key), $value, ['expiry' => $minutes * 60]);
105 2
    }
106
107
    /**
108
     * {@inheritdoc}
109
     */
110 2
    public function increment($key, $value = 1)
111
    {
112 2
        return $this->bucket
113 2
            ->counter($this->resolveKey($key), $value, ['initial' => abs($value)])->value;
114
    }
115
116
    /**
117
     * {@inheritdoc}
118
     */
119 2
    public function decrement($key, $value = 1)
120
    {
121 2
        return $this->bucket
122 2
            ->counter($this->resolveKey($key), (0 - abs($value)), ['initial' => (0 - abs($value))])->value;
123
    }
124
125
    /**
126
     * {@inheritdoc}
127
     */
128 2
    public function forever($key, $value)
129
    {
130
        try {
131 2
            $this->bucket->insert($this->resolveKey($key), $value);
132 2
        } catch (CouchbaseException $e) {
0 ignored issues
show
Bug introduced by
The class Couchbase\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
133
            // bucket->insert when called from resetTag in TagSet can throw CAS exceptions, ignore.\
134 2
            $this->bucket->upsert($this->resolveKey($key), $value);
135
        }
136 2
    }
137
138
    /**
139
     * {@inheritdoc}
140
     */
141 18
    public function forget($key)
142
    {
143
        try {
144 18
            $this->bucket->remove($this->resolveKey($key));
145 2
        } catch (\Exception $e) {
146
            // Ignore exceptions from remove
147
        }
148 18
    }
149
150
    /**
151
     * flush bucket.
152
     *
153
     * @throws FlushException
154
     * @codeCoverageIgnore
155
     */
156
    public function flush()
157
    {
158
        $result = $this->bucket->manager()->flush();
159
        if (isset($result['_'])) {
160
            throw new FlushException($result);
161
        }
162
    }
163
164
    /**
165
     * {@inheritdoc}
166
     */
167 2
    public function getPrefix()
168
    {
169 2
        return $this->prefix;
170
    }
171
172
    /**
173
     * Set the cache key prefix.
174
     *
175
     * @param string $prefix
176
     */
177 32
    public function setPrefix(string $prefix)
178
    {
179 32
        $this->prefix = !empty($prefix) ? $prefix . ':' : '';
180 32
    }
181
182
    /**
183
     * @param string $bucket
184
     * @param string $password
185
     * @param string $serialize
186
     *
187
     * @return CouchbaseStore
188
     */
189 32
    public function setBucket(string $bucket, string $password = '', string $serialize = 'php'): CouchbaseStore
190
    {
191 32
        $this->bucket = $this->cluster->openBucket($bucket, $password);
192 32
        if ($serialize === 'php') {
193 32
            $this->bucket->setTranscoder('couchbase_php_serialize_encoder', 'couchbase_default_decoder');
194
        }
195
196 32
        return $this;
197
    }
198
199
    /**
200
     * @param $keys
201
     *
202
     * @return array|string
203
     */
204 24
    private function resolveKey($keys)
205
    {
206 24
        if (is_array($keys)) {
207 2
            $result = [];
208 2
            foreach ($keys as $key) {
209 2
                $result[] = $this->prefix . $key;
210
            }
211
212 2
            return $result;
213
        }
214
215 22
        return $this->prefix . $keys;
216
    }
217
218
    /**
219
     * @param $meta
220
     *
221
     * @return array|null
222
     */
223 12
    protected function getMetaDoc($meta)
224
    {
225 12
        if ($meta instanceof \Couchbase\Document) {
0 ignored issues
show
Bug introduced by
The class Couchbase\Document 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...
226 12
            return $meta->value;
227
        }
228 2
        if (is_array($meta)) {
229 2
            $result = [];
230 2
            foreach ($meta as $row) {
231 2
                $result[] = $this->getMetaDoc($row);
232
            }
233
234 2
            return $result;
235
        }
236
237
        return null;
238
    }
239
240
    /**
241
     * Get a lock instance.
242
     *
243
     * @param  string  $name
244
     * @param  int  $seconds
245
     * @return \Illuminate\Contracts\Cache\Lock
246
     */
247 2
    public function lock(string $name, int $seconds = 0): Lock
248
    {
249 2
        return new CouchbaseLock($this->bucket, $this->prefix.$name, $seconds);
250
    }
251
}
252