Passed
Pull Request — master (#821)
by Georges
01:43
created

Driver::getCollection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
/**
4
 *
5
 * This file is part of phpFastCache.
6
 *
7
 * @license MIT License (MIT)
8
 *
9
 * For full copyright and license information, please see the docs/CREDITS.txt file.
10
 *
11
 * @author Khoa Bui (khoaofgod)  <[email protected]> https://www.phpfastcache.com
12
 * @author Georges.L (Geolim4)  <[email protected]>
13
 *
14
 */
15
declare(strict_types=1);
16
17
namespace Phpfastcache\Drivers\Couchbasev3;
18
19
use Couchbase\DocumentNotFoundException;
0 ignored issues
show
Bug introduced by
The type Couchbase\DocumentNotFoundException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
20
use Couchbase\Cluster as CouchbaseClient;
21
use Couchbase\Collection as CouchbaseCollection;
0 ignored issues
show
Bug introduced by
The type Couchbase\Collection was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
22
use Couchbase\Scope as CouchbaseScope;
0 ignored issues
show
Bug introduced by
The type Couchbase\Scope was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
23
use Couchbase\UpsertOptions;
0 ignored issues
show
Bug introduced by
The type Couchbase\UpsertOptions was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
24
use CouchbaseException;
25
use Phpfastcache\Config\ConfigurationOption;
26
use Phpfastcache\Drivers\Couchbase\Driver as CoubaseV2Driver;
27
use Phpfastcache\Drivers\Couchbase\Item;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Phpfastcache\Drivers\Couchbasev3\Item. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
28
use Phpfastcache\Entities\DriverStatistic;
29
use Phpfastcache\Exceptions\{PhpfastcacheDriverCheckException, PhpfastcacheInvalidArgumentException, PhpfastcacheLogicException};
30
use Psr\Cache\CacheItemInterface;
31
32
/**
33
 * Class Driver
34
 * @package phpFastCache\Drivers
35
 * @property CouchbaseClient $instance Instance of driver service
36
 * @property Config $config Config object
37
 * @method Config getConfig() Return the config object
38
 */
39
class Driver extends CoubaseV2Driver
40
{
41
    /**
42
     * @var CouchbaseScope
43
     */
44
    protected $scope;
45
46
    /**
47
     * @var CouchbaseCollection
48
     */
49
    protected $collection;
50
51
    public function __construct(ConfigurationOption $config, $instanceId)
52
    {
53
        $this->__baseConstruct($config, $instanceId);
54
    }
55
56
    /**
57
     * @return bool
58
     * @throws PhpfastcacheLogicException
59
     */
60
    protected function driverConnect(): bool
61
    {
62
        if (!\class_exists(\Couchbase\ClusterOptions::class)) {
0 ignored issues
show
Bug introduced by
The type Couchbase\ClusterOptions was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
63
            throw new PhpfastcacheDriverCheckException('You are using the Couchbase PHP SDK 2.x so please use driver Couchbasev3');
64
        }
65
66
        if ($this->instance instanceof CouchbaseClient) {
0 ignored issues
show
introduced by
$this->instance is always a sub-type of Couchbase\Cluster.
Loading history...
67
            throw new PhpfastcacheLogicException('Already connected to Couchbase server');
68
        }
69
70
        $connectionString = "couchbase://localhost:" . $this->getConfig()->getPort();
71
72
        $options = new \Couchbase\ClusterOptions();
73
        $options->credentials($this->getConfig()->getUsername(), $this->getConfig()->getPassword());
74
        $this->instance = new \Couchbase\Cluster($connectionString, $options);
75
76
        $this->setBucket($this->instance->bucket($this->getConfig()->getBucketName()));
77
        $this->setScope($this->getBucket()->scope($this->getConfig()->getScopeName()));
78
        $this->setCollection($this->getScope()->collection($this->getConfig()->getCollectionName()));
79
80
        return true;
81
    }
82
83
    /**
84
     * @param CacheItemInterface $item
85
     * @return null|array
86
     */
87
    protected function driverRead(CacheItemInterface $item)
88
    {
89
        try {
90
            /**
91
             * CouchbaseBucket::get() returns a GetResult interface
92
             */
93
            return $this->decodeDocument((array)$this->getCollection()->get($item->getEncodedKey())->content());
94
        } catch (DocumentNotFoundException $e) {
95
            return null;
96
        }
97
    }
98
99
    /**
100
     * @param CacheItemInterface $item
101
     * @return bool
102
     * @throws PhpfastcacheInvalidArgumentException
103
     */
104
    protected function driverWrite(CacheItemInterface $item): bool
105
    {
106
        /**
107
         * Check for Cross-Driver type confusion
108
         */
109
        if ($item instanceof Item) {
110
            try {
111
                return (bool)$this->getCollection()->upsert(
112
                    $item->getEncodedKey(),
113
                    $this->encodeDocument($this->driverPreWrap($item)),
114
                    (new UpsertOptions())->expiry($item->getTtl())
115
                );
116
            } catch (CouchbaseException $e) {
117
                return false;
118
            }
119
        }
120
121
        throw new PhpfastcacheInvalidArgumentException('Cross-Driver type confusion detected');
122
    }
123
124
    /**
125
     * @param CacheItemInterface $item
126
     * @return bool
127
     * @throws PhpfastcacheInvalidArgumentException
128
     */
129
    protected function driverDelete(CacheItemInterface $item): bool
130
    {
131
        /**
132
         * Check for Cross-Driver type confusion
133
         */
134
        if ($item instanceof Item) {
135
            try {
136
                $this->getCollection()->remove($item->getEncodedKey());
137
                return true;
138
            } catch (DocumentNotFoundException $e) {
139
                return true;
140
            } catch (CouchbaseException $e) {
141
                return false;
142
            }
143
        }
144
145
        throw new PhpfastcacheInvalidArgumentException('Cross-Driver type confusion detected');
146
    }
147
148
    /**
149
     * @return bool
150
     */
151
    protected function driverClear(): bool
152
    {
153
        $this->instance->buckets()->flush($this->getConfig()->getBucketName());
0 ignored issues
show
Bug introduced by
The method buckets() does not exist on Couchbase\Cluster. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

153
        $this->instance->/** @scrutinizer ignore-call */ 
154
                         buckets()->flush($this->getConfig()->getBucketName());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
154
        return true;
155
    }
156
157
    /**
158
     * @return DriverStatistic
159
     */
160
    public function getStats(): DriverStatistic
161
    {
162
        /**
163
         * Between SDK 2 and 3 we lost a lot of useful information :(
164
         * @see https://docs.couchbase.com/java-sdk/current/project-docs/migrating-sdk-code-to-3.n.html#management-apis
165
         */
166
        $info = $this->getBucket()->diagnostics(\bin2hex(\random_bytes(16)));
0 ignored issues
show
Bug introduced by
The method diagnostics() does not exist on Couchbase\Bucket. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

166
        $info = $this->getBucket()->/** @scrutinizer ignore-call */ diagnostics(\bin2hex(\random_bytes(16)));

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
167
168
        return (new DriverStatistic())
169
            ->setSize(0)
170
            ->setRawData($info)
171
            ->setData(implode(', ', array_keys($this->itemInstances)))
172
            ->setInfo( $info['sdk'] . "\n For more information see RawData.");
173
    }
174
175
    /**
176
     * @return CouchbaseCollection
177
     */
178
    public function getCollection(): CouchbaseCollection
179
    {
180
        return $this->collection;
181
    }
182
183
    /**
184
     * @param CouchbaseCollection $collection
185
     * @return Driver
186
     */
187
    public function setCollection(CouchbaseCollection $collection): Driver
188
    {
189
        $this->collection = $collection;
190
        return $this;
191
    }
192
193
    /**
194
     * @return CouchbaseScope
195
     */
196
    public function getScope(): CouchbaseScope
197
    {
198
        return $this->scope;
199
    }
200
201
    /**
202
     * @param CouchbaseScope $scope
203
     * @return Driver
204
     */
205
    public function setScope(CouchbaseScope $scope): Driver
206
    {
207
        $this->scope = $scope;
208
        return $this;
209
    }
210
}
211