Completed
Push — master ( 0d9cbc...8d7e77 )
by yuuki
02:23
created

CouchbaseConnection   B

Complexity

Total Complexity 38

Size/Duplication

Total Lines 326
Duplicated Lines 8.9 %

Coupling/Cohesion

Components 2
Dependencies 6

Test Coverage

Coverage 75.51%

Importance

Changes 9
Bugs 0 Features 4
Metric Value
c 9
b 0
f 4
dl 29
loc 326
ccs 74
cts 98
cp 0.7551
rs 8.3999
wmc 38
lcom 2
cbo 6

26 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A setBucketPassword() 0 6 1
A openBucket() 0 4 1
A getDefaultPostProcessor() 0 4 1
A getDefaultQueryGrammar() 0 4 1
B getManagedConfigure() 0 13 6
A createConnection() 0 4 1
A getDriverName() 0 4 1
A getCouchbase() 0 4 1
A table() 0 6 1
A bucket() 0 6 1
A select() 0 14 2
A insert() 0 4 1
A affectingStatement() 14 14 3
A positionalStatement() 15 15 3
A transaction() 0 4 1
A beginTransaction() 0 4 1
A commit() 0 4 1
A rollBack() 0 4 1
A reconnectIfMissingConnection() 0 6 2
A disconnect() 0 4 1
A enableN1ql() 0 9 2
A upsert() 0 4 1
A query() 0 6 1
A update() 0 4 1
A delete() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
    /**
51
     * @param array $config
52
     */
53 23
    public function __construct(array $config)
54
    {
55 23
        $this->connection = $this->createConnection($config);
56 23
        $this->getManagedConfigure($config);
57
58 23
        $this->useDefaultQueryGrammar();
59
60 23
        $this->useDefaultPostProcessor();
61 23
    }
62
63
    /**
64
     * @param $password
65
     *
66
     * @return $this
67
     */
68
    public function setBucketPassword($password)
69
    {
70
        $this->bucketPassword = $password;
71
72
        return $this;
73
    }
74
75
    /**
76
     * @param $name
77
     *
78
     * @return \CouchbaseBucket
79
     */
80 5
    public function openBucket($name)
81
    {
82 5
        return $this->connection->openBucket($name, $this->bucketPassword);
83
    }
84
85
    /**
86
     * @return Processor
87
     */
88 23
    protected function getDefaultPostProcessor()
89
    {
90 23
        return new Processor();
91
    }
92
93
    /**
94
     * @return Grammar
95
     */
96 23
    protected function getDefaultQueryGrammar()
97
    {
98 23
        return new Grammar();
99
    }
100
101
    /**
102
     * @param array $config
103
     */
104 23
    protected function getManagedConfigure(array $config)
105
    {
106 23
        $this->enableN1qlServers = (isset($config['enables'])) ? $config['enables'] : [];
107 23
        $manager = (isset($config['manager'])) ? $config['manager'] : null;
108 23
        if (is_null($manager)) {
109 23
            $this->managerUser = (isset($config['user'])) ? $config['user'] : null;
110 23
            $this->managerPassword = (isset($config['password'])) ? $config['password'] : null;
111
112 23
            return;
113
        }
114
        $this->managerUser = $config['manager']['user'];
115
        $this->managerPassword = $config['manager']['password'];
116
    }
117
118
    /**
119
     * @param $dsn
120
     *
121
     * @return \CouchbaseCluster
122
     */
123 23
    protected function createConnection($dsn)
124
    {
125 23
        return (new CouchbaseConnector())->connect($dsn);
126
    }
127
128
    /**
129
     * {@inheritdoc}
130
     */
131
    public function getDriverName()
132
    {
133
        return 'couchbase';
134
    }
135
136
    /**
137
     * @return \CouchbaseCluster
138
     */
139 15
    public function getCouchbase()
140
    {
141 15
        return $this->connection;
142
    }
143
144
    /**
145
     * @param string $table
146
     *
147
     * @return \Ytake\LaravelCouchbase\Database\QueryBuilder
148
     */
149 5
    public function table($table)
150
    {
151 5
        $this->bucket = $table;
152
153 5
        return $this->query()->from($table);
154
    }
155
156
    /**
157
     * @param string $bucket
158
     *
159
     * @return $this
160
     */
161
    public function bucket($bucket)
162
    {
163
        $this->bucket = $bucket;
164
165
        return $this;
166
    }
167
168
    /**
169
     * {@inheritdoc}
170
     */
171 2
    public function select($query, $bindings = [], $useReadPdo = true)
172
    {
173
        return $this->run($query, $bindings, function ($me, $query, $bindings) {
174 2
            if ($me->pretending()) {
175
                return [];
176
            }
177 2
            $query = \CouchbaseN1qlQuery::fromString($query);
178 2
            $query->options['args'] = $bindings;
179 2
            $query->consistency(\CouchbaseN1qlQuery::NOT_BOUNDED);
180 2
            $bucket = $this->openBucket($this->bucket);
181
182 2
            return $bucket->query($query);
183 2
        });
184
    }
185
186
    /**
187
     * @param string $query
188
     * @param array  $bindings
189
     *
190
     * @return int|mixed
191
     */
192 4
    public function insert($query, $bindings = [])
193
    {
194 4
        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...
195
    }
196
197
    /**
198
     * {@inheritdoc}
199
     */
200 5 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...
201
    {
202
        return $this->run($query, $bindings, function ($me, $query, $bindings) {
203 5
            if ($me->pretending()) {
204
                return 0;
205
            }
206 5
            $query = \CouchbaseN1qlQuery::fromString($query);
207 5
            $query->consistency(\CouchbaseN1qlQuery::REQUEST_PLUS);
208 5
            $bucket = $this->openBucket($this->bucket);
209 5
            $result = $bucket->query($query, ['parameters' => $bindings]);
210
211 5
            return (isset($result[0])) ? $result[0] : false;
212 5
        });
213
    }
214
215
    /**
216
     * @param       $query
217
     * @param array $bindings
218
     *
219
     * @return mixed
220
     */
221 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...
222
    {
223 5
        return $this->run($query, $bindings, function ($me, $query, $bindings) {
224 5
            if ($me->pretending()) {
225
                return 0;
226
            }
227 5
            $query = \CouchbaseN1qlQuery::fromString($query);
228 5
            $query->consistency(\CouchbaseN1qlQuery::REQUEST_PLUS);
229 5
            $query->options['args'] = $bindings;
230 5
            $bucket = $this->openBucket($this->bucket);
231 5
            $result = $bucket->query($query);
232
233 5
            return (isset($result[0])) ? $result[0] : false;
234 5
        });
235
    }
236
237
    /**
238
     * {@inheritdoc}
239
     */
240 1
    public function transaction(Closure $callback)
241
    {
242 1
        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...
243
    }
244
245
    /**
246
     * {@inheritdoc}
247
     */
248 1
    public function beginTransaction()
249
    {
250 1
        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...
251
    }
252
253
    /**
254
     * {@inheritdoc}
255
     */
256 1
    public function commit()
257
    {
258 1
        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...
259
    }
260
261
    /**
262
     * {@inheritdoc}
263
     */
264 1
    public function rollBack()
265
    {
266 1
        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...
267
    }
268
269
    /**
270
     * {@inheritdoc}
271
     */
272 5
    protected function reconnectIfMissingConnection()
273
    {
274 5
        if (is_null($this->connection)) {
275
            $this->reconnect();
276
        }
277 5
    }
278
279
    /**
280
     * {@inheritdoc}
281
     */
282
    public function disconnect()
283
    {
284
        $this->connection = null;
285
    }
286
287
    /**
288
     * @param CouchbaseBucket $bucket
289
     *
290
     * @return CouchbaseBucket
291
     */
292
    protected function enableN1ql(CouchbaseBucket $bucket)
293
    {
294
        if (!count($this->enableN1qlServers)) {
295
            return $bucket;
296
        }
297
        $bucket->enableN1ql($this->enableN1qlServers);
298
299
        return $bucket;
300
    }
301
302
    /**
303
     * N1QL upsert query.
304
     *
305
     * @param string $query
306
     * @param array  $bindings
307
     *
308
     * @return int
309
     */
310 1
    public function upsert($query, $bindings = [])
311
    {
312 1
        return $this->affectingStatement($query, $bindings);
313
    }
314
315
    /**
316
     * Get a new query builder instance.
317
     *
318
     * @return \Illuminate\Database\Query\Builder
319
     */
320 5
    public function query()
321
    {
322 5
        return new QueryBuilder(
323 5
            $this, $this->getQueryGrammar(), $this->getPostProcessor()
324 5
        );
325
    }
326
327
    /**
328
     * Run an update statement against the database.
329
     *
330
     * @param string $query
331
     * @param array  $bindings
332
     *
333
     * @return int|\stdClass
334
     */
335 1
    public function update($query, $bindings = [])
336
    {
337 1
        return $this->positionalStatement($query, $bindings);
338
    }
339
340
    /**
341
     * Run a delete statement against the database.
342
     *
343
     * @param string $query
344
     * @param array  $bindings
345
     *
346
     * @return int|\stdClass
347
     */
348 5
    public function delete($query, $bindings = [])
349
    {
350 5
        return $this->positionalStatement($query, $bindings);
351
    }
352
}
353