Completed
Push — master ( 9b11b5...839864 )
by yuuki
10:11 queued 03:03
created

CouchbaseConnection::setBucketPassword()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 1
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 20
    public function __construct(array $config)
51
    {
52 20
        $this->connection = $this->createConnection($config);
53 20
        $this->getManagedConfigure($config);
54
55 20
        $this->useDefaultQueryGrammar();
56
57 20
        $this->useDefaultPostProcessor();
58 20
    }
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 20
    protected function getDefaultPostProcessor()
85
    {
86 20
        return new Processor();
87
    }
88
89
    /**
90
     * @return Grammar
91
     */
92 20
    protected function getDefaultQueryGrammar()
93
    {
94 20
        return new Grammar();
95
    }
96
97
    /**
98
     * @param array $config
99
     */
100 20
    protected function getManagedConfigure(array $config)
101
    {
102 20
        $this->enableN1qlServers = (isset($config['enables'])) ? $config['enables'] : [];
103 20
        $manager = (isset($config['manager'])) ? $config['manager'] : null;
104 20
        if (is_null($manager)) {
105 20
            $this->managerUser = $config['user'];
106 20
            $this->managerPassword = $config['password'];
107
108 20
            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 20
    protected function createConnection($dsn)
120
    {
121 20
        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 11
    public function getCouchbase()
136
    {
137 11
        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 16
    public function setFetchMode($fetchMode)
270
    {
271 16
        $this->fetchMode = null;
272 16
    }
273
274
    /**
275
     * {@inheritdoc}
276
     */
277 5
    protected function reconnectIfMissingConnection()
278
    {
279 5
        if (is_null($this->connection)) {
280
            $this->reconnect();
281
        }
282 5
    }
283
284
    /**
285
     * {@inheritdoc}
286
     */
287
    public function disconnect()
288
    {
289
        $this->connection = null;
290
    }
291
292
    /**
293
     * @param CouchbaseBucket $bucket
294
     *
295
     * @return CouchbaseBucket
296
     */
297
    protected function enableN1ql(CouchbaseBucket $bucket)
298
    {
299
        if (!count($this->enableN1qlServers)) {
300
            return $bucket;
301
        }
302
        $bucket->enableN1ql($this->enableN1qlServers);
303
304
        return $bucket;
305
    }
306
307
    /**
308
     * N1QL upsert query.
309
     *
310
     * @param string $query
311
     * @param array  $bindings
312
     *
313
     * @return int
314
     */
315 1
    public function upsert($query, $bindings = [])
316
    {
317 1
        return $this->affectingStatement($query, $bindings);
318
    }
319
320
    /**
321
     * Get a new query builder instance.
322
     *
323
     * @return \Illuminate\Database\Query\Builder
324
     */
325 5
    public function query()
326
    {
327 5
        return new QueryBuilder(
328 5
            $this, $this->getQueryGrammar(), $this->getPostProcessor()
329 5
        );
330
    }
331
332
    /**
333
     * Run an update statement against the database.
334
     *
335
     * @param string $query
336
     * @param array  $bindings
337
     *
338
     * @return int|\stdClass
339
     */
340 1
    public function update($query, $bindings = [])
341
    {
342 1
        return $this->positionalStatement($query, $bindings);
343
    }
344
345
    /**
346
     * Run a delete statement against the database.
347
     *
348
     * @param string $query
349
     * @param array  $bindings
350
     *
351
     * @return int|\stdClass
352
     */
353 5
    public function delete($query, $bindings = [])
354
    {
355 5
        return $this->positionalStatement($query, $bindings);
356
    }
357
}
358