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

Driver::__construct()   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 2
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
        $connectionString = "couchbase://{$this->getConfig()->getHost()}}:{$this->getConfig()->getPort()}";
67
68
        $options = new \Couchbase\ClusterOptions();
69
        $options->credentials($this->getConfig()->getUsername(), $this->getConfig()->getPassword());
70
        $this->instance = new \Couchbase\Cluster($connectionString, $options);
0 ignored issues
show
Unused Code introduced by
The call to Couchbase\Cluster::__construct() has too many arguments starting with $options. ( Ignorable by Annotation )

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

70
        $this->instance = /** @scrutinizer ignore-call */ new \Couchbase\Cluster($connectionString, $options);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
71
72
        $this->setBucket($this->instance->bucket($this->getConfig()->getBucketName()));
0 ignored issues
show
Bug introduced by
The method bucket() 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

72
        $this->setBucket($this->instance->/** @scrutinizer ignore-call */ bucket($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...
73
        $this->setScope($this->getBucket()->scope($this->getConfig()->getScopeName()));
0 ignored issues
show
Bug introduced by
The method scope() 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

73
        $this->setScope($this->getBucket()->/** @scrutinizer ignore-call */ scope($this->getConfig()->getScopeName()));

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...
74
        $this->setCollection($this->getScope()->collection($this->getConfig()->getCollectionName()));
75
76
        return true;
77
    }
78
79
    /**
80
     * @param CacheItemInterface $item
81
     * @return null|array
82
     */
83
    protected function driverRead(CacheItemInterface $item)
84
    {
85
        try {
86
            /**
87
             * CouchbaseBucket::get() returns a GetResult interface
88
             */
89
            return $this->decodeDocument((array)$this->getCollection()->get($item->getEncodedKey())->content());
90
        } catch (DocumentNotFoundException $e) {
91
            return null;
92
        }
93
    }
94
95
    /**
96
     * @param CacheItemInterface $item
97
     * @return bool
98
     * @throws PhpfastcacheInvalidArgumentException
99
     */
100
    protected function driverWrite(CacheItemInterface $item): bool
101
    {
102
        /**
103
         * Check for Cross-Driver type confusion
104
         */
105
        if ($item instanceof Item) {
106
            try {
107
                return (bool)$this->getCollection()->upsert(
108
                    $item->getEncodedKey(),
109
                    $this->encodeDocument($this->driverPreWrap($item)),
110
                    (new UpsertOptions())->expiry($item->getTtl())
111
                );
112
            } catch (CouchbaseException $e) {
113
                return false;
114
            }
115
        }
116
117
        throw new PhpfastcacheInvalidArgumentException('Cross-Driver type confusion detected');
118
    }
119
120
    /**
121
     * @param CacheItemInterface $item
122
     * @return bool
123
     * @throws PhpfastcacheInvalidArgumentException
124
     */
125
    protected function driverDelete(CacheItemInterface $item): bool
126
    {
127
        /**
128
         * Check for Cross-Driver type confusion
129
         */
130
        if ($item instanceof Item) {
131
            try {
132
                $this->getCollection()->remove($item->getEncodedKey());
133
                return true;
134
            } catch (DocumentNotFoundException $e) {
135
                return true;
136
            } catch (CouchbaseException $e) {
137
                return false;
138
            }
139
        }
140
141
        throw new PhpfastcacheInvalidArgumentException('Cross-Driver type confusion detected');
142
    }
143
144
    /**
145
     * @return bool
146
     */
147
    protected function driverClear(): bool
148
    {
149
        $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

149
        $this->instance->/** @scrutinizer ignore-call */ 
150
                         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...
150
        return true;
151
    }
152
153
    /**
154
     * @return DriverStatistic
155
     */
156
    public function getStats(): DriverStatistic
157
    {
158
        /**
159
         * Between SDK 2 and 3 we lost a lot of useful information :(
160
         * @see https://docs.couchbase.com/java-sdk/current/project-docs/migrating-sdk-code-to-3.n.html#management-apis
161
         */
162
        $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

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