Completed
Push — master ( 115986...2f9cff )
by yuuki
09:05
created

CouchbaseConnection::consistency()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 6
ccs 0
cts 1
cp 0
crap 2
rs 9.4285
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\Database;
14
15
use Closure;
16
use CouchbaseBucket;
17
use Illuminate\Database\Connection;
18
use Ytake\LaravelCouchbase\Query\Grammar;
19
use Ytake\LaravelCouchbase\Query\Processor;
20
use Ytake\LaravelCouchbase\Exceptions\NotSupportedException;
21
22
/**
23
 * Class CouchbaseConnection.
24
 *
25
 * @author Yuuki Takezawa<[email protected]>
26
 */
27
class CouchbaseConnection extends Connection
28
{
29
    /** @var string */
30
    protected $bucket;
31
32
    /** @var \CouchbaseCluster */
33
    protected $connection;
34
35
    /** @var */
36
    protected $managerUser;
37
38
    /** @var */
39
    protected $managerPassword;
40
41
    /** @var int */
42
    protected $fetchMode = 0;
43
44
    /** @var array */
45
    protected $enableN1qlServers = [];
46
47
    /** @var string  */
48
    protected $bucketPassword = '';
49
50
    /** @var int */
51
    protected $consistency = \CouchbaseN1qlQuery::NOT_BOUNDED;
52
53 25
    /**
54
     * @param array $config
55 25
     */
56 25
    public function __construct(array $config)
57
    {
58 25
        $this->connection = $this->createConnection($config);
59
        $this->getManagedConfigure($config);
60 25
61 25
        $this->useDefaultQueryGrammar();
62
63
        $this->useDefaultPostProcessor();
64
    }
65
66
    /**
67
     * @param $password
68
     *
69
     * @return $this
70
     */
71
    public function setBucketPassword($password)
72
    {
73
        $this->bucketPassword = $password;
74
75
        return $this;
76
    }
77
78
    /**
79
     * @param $name
80 5
     *
81
     * @return \CouchbaseBucket
82 5
     */
83
    public function openBucket($name)
84
    {
85
        return $this->connection->openBucket($name, $this->bucketPassword);
86
    }
87
88 25
    /**
89
     * @return Processor
90 25
     */
91
    protected function getDefaultPostProcessor()
92
    {
93
        return new Processor();
94
    }
95
96 25
    /**
97
     * @return Grammar
98 25
     */
99
    protected function getDefaultQueryGrammar()
100
    {
101
        return new Grammar();
102
    }
103
104 25
    /**
105
     * @param array $config
106 25
     */
107 25
    protected function getManagedConfigure(array $config)
108 25
    {
109 25
        $this->enableN1qlServers = (isset($config['enables'])) ? $config['enables'] : [];
110 25
        $manager = (isset($config['manager'])) ? $config['manager'] : null;
111
        if (is_null($manager)) {
112 25
            $this->managerUser = (isset($config['user'])) ? $config['user'] : null;
113
            $this->managerPassword = (isset($config['password'])) ? $config['password'] : null;
114
115
            return;
116
        }
117
        $this->managerUser = $config['manager']['user'];
118
        $this->managerPassword = $config['manager']['password'];
119
    }
120
121
    /**
122
     * @param $dsn
123 25
     *
124
     * @return \CouchbaseCluster
125 25
     */
126
    protected function createConnection($dsn)
127
    {
128
        return (new CouchbaseConnector())->connect($dsn);
129
    }
130
131
    /**
132
     * {@inheritdoc}
133
     */
134
    public function getDriverName()
135
    {
136
        return 'couchbase';
137
    }
138
139 15
    /**
140
     * @return \CouchbaseCluster
141 15
     */
142
    public function getCouchbase()
143
    {
144
        return $this->connection;
145
    }
146
147
    /**
148
     * @param string $table
149 5
     *
150
     * @return \Ytake\LaravelCouchbase\Database\QueryBuilder
151 5
     */
152
    public function table($table)
153 5
    {
154
        $this->bucket = $table;
155
156
        return $this->query()->from($table);
157
    }
158
159
    /**
160
     * @param int $consistency
161
     *
162
     * @return $this
163
     */
164
    public function consistency($consistency)
165
    {
166
        $this->consistency = $consistency;
167
168
        return $this;
169
    }
170
171 1
    /**
172
     * @param string $bucket
173
     *
174 1
     * @return $this
175
     */
176
    public function bucket($bucket)
177 1
    {
178 1
        $this->bucket = $bucket;
179 1
180 1
        return $this;
181
    }
182 1
183 1
    /**
184
     * {@inheritdoc}
185
     */
186
    public function select($query, $bindings = [], $useReadPdo = true)
187
    {
188
        return $this->run($query, $bindings, function ($me, $query, $bindings) {
189
            if ($me->pretending()) {
190
                return [];
191
            }
192 4
            $query = \CouchbaseN1qlQuery::fromString($query);
193
            $query->options['args'] = $bindings;
194 4
            $query->consistency($this->consistency);
195
            $bucket = $this->openBucket($this->bucket);
196
197
            return $bucket->query($query);
198
        });
199
    }
200 5
201
    /**
202
     * @param string $query
203 5
     * @param array  $bindings
204
     *
205
     * @return int|mixed
206 5
     */
207 5
    public function insert($query, $bindings = [])
208 5
    {
209 5
        return $this->affectingStatement($query, $bindings);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->affectingS...ent($query, $bindings); (integer) is incompatible with the return type declared by the interface Illuminate\Database\ConnectionInterface::insert of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
210
    }
211 5
212 5
    /**
213
     * {@inheritdoc}
214
     */
215 View Code Duplication
    public function affectingStatement($query, $bindings = [])
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...
216
    {
217
        return $this->run($query, $bindings, function ($me, $query, $bindings) {
218
            if ($me->pretending()) {
219
                return 0;
220
            }
221
            $query = \CouchbaseN1qlQuery::fromString($query);
222
            $query->consistency($this->consistency);
223 5
            $bucket = $this->openBucket($this->bucket);
224 5
            $result = $bucket->query($query, ['parameters' => $bindings]);
225
226
            return (isset($result[0])) ? $result[0] : false;
227 5
        });
228 5
    }
229 5
230 5
    /**
231 5
     * @param       $query
232
     * @param array $bindings
233 5
     *
234 5
     * @return mixed
235
     */
236 View Code Duplication
    public function positionalStatement($query, array $bindings = [])
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...
237
    {
238
        return $this->run($query, $bindings, function ($me, $query, $bindings) {
239
            if ($me->pretending()) {
240 1
                return 0;
241
            }
242 1
            $query = \CouchbaseN1qlQuery::fromString($query);
243
            $query->consistency($this->consistency);
244
            $query->options['args'] = $bindings;
245
            $bucket = $this->openBucket($this->bucket);
246
            $result = $bucket->query($query);
247
248 1
            return (isset($result[0])) ? $result[0] : false;
249
        });
250 1
    }
251
252
    /**
253
     * {@inheritdoc}
254
     */
255
    public function transaction(Closure $callback)
256 1
    {
257
        throw new NotSupportedException(__METHOD__);
0 ignored issues
show
Documentation introduced by
__METHOD__ is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
258 1
    }
259
260
    /**
261
     * {@inheritdoc}
262
     */
263
    public function beginTransaction()
264 1
    {
265
        throw new NotSupportedException(__METHOD__);
0 ignored issues
show
Documentation introduced by
__METHOD__ is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
266 1
    }
267
268
    /**
269
     * {@inheritdoc}
270
     */
271
    public function commit()
272 5
    {
273
        throw new NotSupportedException(__METHOD__);
0 ignored issues
show
Documentation introduced by
__METHOD__ is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
274 5
    }
275
276
    /**
277 5
     * {@inheritdoc}
278
     */
279
    public function rollBack()
280
    {
281
        throw new NotSupportedException(__METHOD__);
0 ignored issues
show
Documentation introduced by
__METHOD__ is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
282
    }
283
284
    /**
285
     * {@inheritdoc}
286
     */
287
    protected function reconnectIfMissingConnection()
288
    {
289
        if (is_null($this->connection)) {
290
            $this->reconnect();
291
        }
292
    }
293
294
    /**
295
     * {@inheritdoc}
296
     */
297
    public function disconnect()
298
    {
299
        $this->connection = null;
300
    }
301
302
    /**
303
     * @param CouchbaseBucket $bucket
304
     *
305
     * @return CouchbaseBucket
306
     */
307
    protected function enableN1ql(CouchbaseBucket $bucket)
308
    {
309
        if (!count($this->enableN1qlServers)) {
310 1
            return $bucket;
311
        }
312 1
        $bucket->enableN1ql($this->enableN1qlServers);
313
314
        return $bucket;
315
    }
316
317
    /**
318
     * N1QL upsert query.
319
     *
320 5
     * @param string $query
321
     * @param array  $bindings
322 5
     *
323 5
     * @return int
324 5
     */
325
    public function upsert($query, $bindings = [])
326
    {
327
        return $this->affectingStatement($query, $bindings);
328
    }
329
330
    /**
331
     * Get a new query builder instance.
332
     *
333
     * @return \Illuminate\Database\Query\Builder
334
     */
335 1
    public function query()
336
    {
337 1
        return new QueryBuilder(
338
            $this, $this->getQueryGrammar(), $this->getPostProcessor()
339
        );
340
    }
341
342
    /**
343
     * Run an update statement against the database.
344
     *
345
     * @param string $query
346
     * @param array  $bindings
347
     *
348 5
     * @return int|\stdClass
349
     */
350 5
    public function update($query, $bindings = [])
351
    {
352
        return $this->positionalStatement($query, $bindings);
353
    }
354
355
    /**
356
     * Run a delete statement against the database.
357
     *
358
     * @param string $query
359
     * @param array  $bindings
360
     *
361
     * @return int|\stdClass
362
     */
363
    public function delete($query, $bindings = [])
364
    {
365
        return $this->positionalStatement($query, $bindings);
366
    }
367
}
368