Completed
Push — develop ( 0e6100...5d337c )
by yuuki
02:33 queued 31s
created

CouchbaseConnection::select()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2.0055

Importance

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