Completed
Pull Request — master (#44)
by yuuki
01:19
created

CouchbaseStore::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 9
nc 1
nop 5
dl 0
loc 11
rs 9.4285
c 0
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
    public function __construct(
53
        Cluster $cluster,
54
        string $bucket,
55
        string $password = '',
56
        string $prefix = null,
57
        string $serialize = 'php'
58
    ) {
59
        $this->cluster = $cluster;
60
        $this->setBucket($bucket, $password, $serialize);
61
        $this->setPrefix($prefix);
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function get($key)
68
    {
69
        try {
70
            $result = $this->bucket->get($this->resolveKey($key));
71
72
            return $this->getMetaDoc($result);
73
        } 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
            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
    public function add($key, $value, $minutes = 0): bool
88
    {
89
        $options = ($minutes === 0) ? [] : ['expiry' => ($minutes * 60)];
90
        try {
91
            $this->bucket->insert($this->resolveKey($key), $value, $options);
92
93
            return true;
94
        } 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
            return false;
96
        }
97
    }
98
99
    /**
100
     * {@inheritdoc}
101
     */
102
    public function put($key, $value, $minutes)
103
    {
104
        $this->bucket->upsert($this->resolveKey($key), $value, ['expiry' => $minutes * 60]);
105
    }
106
107
    /**
108
     * {@inheritdoc}
109
     */
110
    public function increment($key, $value = 1)
111
    {
112
        return $this->bucket
113
            ->counter($this->resolveKey($key), $value, ['initial' => abs($value)])->value;
114
    }
115
116
    /**
117
     * {@inheritdoc}
118
     */
119
    public function decrement($key, $value = 1)
120
    {
121
        return $this->bucket
122
            ->counter($this->resolveKey($key), (0 - abs($value)), ['initial' => (0 - abs($value))])->value;
123
    }
124
125
    /**
126
     * {@inheritdoc}
127
     */
128
    public function forever($key, $value)
129
    {
130
        try {
131
            $this->bucket->insert($this->resolveKey($key), $value);
132
        } 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
            $this->bucket->upsert($this->resolveKey($key), $value);
135
        }
136
    }
137
138
    /**
139
     * {@inheritdoc}
140
     */
141
    public function forget($key)
142
    {
143
        try {
144
            $this->bucket->remove($this->resolveKey($key));
145
        } catch (\Exception $e) {
146
            // Ignore exceptions from remove
147
        }
148
    }
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
    public function getPrefix()
168
    {
169
        return $this->prefix;
170
    }
171
172
    /**
173
     * Set the cache key prefix.
174
     *
175
     * @param string $prefix
176
     */
177
    public function setPrefix(string $prefix)
178
    {
179
        $this->prefix = !empty($prefix) ? $prefix . ':' : '';
180
    }
181
182
    /**
183
     * @param string $bucket
184
     * @param string $password
185
     * @param string $serialize
186
     *
187
     * @return CouchbaseStore
188
     */
189
    public function setBucket(string $bucket, string $password = '', string $serialize = 'php'): CouchbaseStore
190
    {
191
        $this->bucket = $this->cluster->openBucket($bucket, $password);
192
        if ($serialize === 'php') {
193
            $this->bucket->setTranscoder('couchbase_php_serialize_encoder', 'couchbase_default_decoder');
194
        }
195
196
        return $this;
197
    }
198
199
    /**
200
     * @param $keys
201
     *
202
     * @return array|string
203
     */
204
    private function resolveKey($keys)
205
    {
206
        if (is_array($keys)) {
207
            $result = [];
208
            foreach ($keys as $key) {
209
                $result[] = $this->prefix . $key;
210
            }
211
212
            return $result;
213
        }
214
215
        return $this->prefix . $keys;
216
    }
217
218
    /**
219
     * @param $meta
220
     *
221
     * @return array|null
222
     */
223
    protected function getMetaDoc($meta)
224
    {
225
        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
            return $meta->value;
227
        }
228
        if (is_array($meta)) {
229
            $result = [];
230
            foreach ($meta as $row) {
231
                $result[] = $this->getMetaDoc($row);
232
            }
233
234
            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
    public function lock(string $name, int $seconds = 0): Lock
248
    {
249
        return new CouchbaseLock($this->bucket, $this->prefix.$name, $seconds);
250
    }
251
}
252