Completed
Push — master ( ae5755...43fa87 )
by yuuki
10s
created

CouchbaseConnection::disconnect()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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