Passed
Push — master ( 357df8...5617f0 )
by Georges
02:00 queued 12s
created

Driver::setCollection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
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\{BaseException as CouchbaseException, Cluster, ClusterOptions, Collection, DocumentNotFoundException, Scope, UpsertOptions};
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...
Bug introduced by
The type Couchbase\BaseException 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...
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...
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...
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...
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...
20
use Phpfastcache\Config\ConfigurationOption;
21
use Phpfastcache\Drivers\Couchbase\Driver as CoubaseV2Driver;
22
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...
23
use Phpfastcache\Entities\DriverStatistic;
24
use Phpfastcache\Exceptions\{PhpfastcacheDriverCheckException, PhpfastcacheInvalidArgumentException, PhpfastcacheLogicException};
25
use Psr\Cache\CacheItemInterface;
26
27
/**
28
 * Class Driver
29
 * @package phpFastCache\Drivers
30
 * @property Cluster $instance Instance of driver service
31
 * @property Config $config Config object
32
 * @method Config getConfig() Return the config object
33
 */
34
class Driver extends CoubaseV2Driver
35
{
36
    /**
37
     * @var Scope
38
     */
39
    protected $scope;
40
41
    /**
42
     * @var Collection
43
     */
44
    protected $collection;
45
46
    public function __construct(ConfigurationOption $config, $instanceId)
47
    {
48
        $this->__baseConstruct($config, $instanceId);
49
    }
50
51
    /**
52
     * @return bool
53
     * @throws PhpfastcacheLogicException
54
     */
55
    protected function driverConnect(): bool
56
    {
57
        if (!\class_exists(ClusterOptions::class)) {
58
            throw new PhpfastcacheDriverCheckException('You are using the Couchbase PHP SDK 2.x so please use driver Couchbasev3');
59
        }
60
61
        $connectionString = "couchbase://{$this->getConfig()->getHost()}:{$this->getConfig()->getPort()}";
62
63
        $options = new ClusterOptions();
64
        $options->credentials($this->getConfig()->getUsername(), $this->getConfig()->getPassword());
65
        $this->instance = new 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

65
        $this->instance = /** @scrutinizer ignore-call */ new 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...
66
67
        $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

67
        $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...
68
        $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

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

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

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