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

Driver::driverRead()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 9
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\Drivers\Couchbase\Driver as CoubaseV2Driver;
26
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...
27
use Phpfastcache\Entities\DriverStatistic;
28
use Phpfastcache\Exceptions\{PhpfastcacheDriverCheckException, PhpfastcacheInvalidArgumentException, PhpfastcacheLogicException};
29
use Psr\Cache\CacheItemInterface;
30
31
/**
32
 * Class Driver
33
 * @package phpFastCache\Drivers
34
 * @property CouchbaseClient $instance Instance of driver service
35
 * @property Config $config Config object
36
 * @method Config getConfig() Return the config object
37
 */
38
class Driver extends CoubaseV2Driver
39
{
40
    /**
41
     * @var CouchbaseScope
42
     */
43
    protected $scope;
44
45
    /**
46
     * @var CouchbaseCollection
47
     */
48
    protected $collection;
49
50
    /**
51
     * @return bool
52
     * @throws PhpfastcacheLogicException
53
     */
54
    protected function driverConnect(): bool
55
    {
56
        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...
57
            throw new PhpfastcacheDriverCheckException('You are using the Couchbase PHP SDK 2.x so please use driver Couchbasev3');
58
        }
59
60
        if ($this->instance instanceof CouchbaseClient) {
0 ignored issues
show
introduced by
$this->instance is always a sub-type of Couchbase\Cluster.
Loading history...
61
            throw new PhpfastcacheLogicException('Already connected to Couchbase server');
62
        }
63
64
        $connectionString = "couchbase://localhost";
65
66
        $options = new \Couchbase\ClusterOptions();
67
        $options->credentials($this->getConfig()->getUsername(), $this->getConfig()->getPassword());
68
        $this->instance = new \Couchbase\Cluster($connectionString, $options);
69
70
        $this->setBucket($this->instance->bucket($this->getConfig()->getBucketName()));
71
        $this->setScope($this->getBucket()->scope($this->getConfig()->getScopeName()));
72
        $this->setCollection($this->getScope()->collection($this->getConfig()->getCollectionName()));
73
74
        return true;
75
    }
76
77
    /**
78
     * @param CacheItemInterface $item
79
     * @return null|array
80
     */
81
    protected function driverRead(CacheItemInterface $item)
82
    {
83
        try {
84
            /**
85
             * CouchbaseBucket::get() returns a GetResult interface
86
             */
87
            return $this->decodeDocument((array)$this->getCollection()->get($item->getEncodedKey())->content());
88
        } catch (DocumentNotFoundException $e) {
89
            return null;
90
        }
91
    }
92
93
    /**
94
     * @param CacheItemInterface $item
95
     * @return bool
96
     * @throws PhpfastcacheInvalidArgumentException
97
     */
98
    protected function driverWrite(CacheItemInterface $item): bool
99
    {
100
        /**
101
         * Check for Cross-Driver type confusion
102
         */
103
        if ($item instanceof Item) {
104
            try {
105
                return (bool)$this->getCollection()->upsert(
106
                    $item->getEncodedKey(),
107
                    $this->encodeDocument($this->driverPreWrap($item)),
108
                    (new UpsertOptions())->expiry($item->getTtl())
109
                );
110
            } catch (CouchbaseException $e) {
111
                return false;
112
            }
113
        }
114
115
        throw new PhpfastcacheInvalidArgumentException('Cross-Driver type confusion detected');
116
    }
117
118
    /**
119
     * @param CacheItemInterface $item
120
     * @return bool
121
     * @throws PhpfastcacheInvalidArgumentException
122
     */
123
    protected function driverDelete(CacheItemInterface $item): bool
124
    {
125
        /**
126
         * Check for Cross-Driver type confusion
127
         */
128
        if ($item instanceof Item) {
129
            try {
130
                $this->getCollection()->remove($item->getEncodedKey());
131
                return true;
132
            } catch (DocumentNotFoundException $e) {
133
                return true;
134
            } catch (CouchbaseException $e) {
135
                return false;
136
            }
137
        }
138
139
        throw new PhpfastcacheInvalidArgumentException('Cross-Driver type confusion detected');
140
    }
141
142
    /**
143
     * @return bool
144
     */
145
    protected function driverClear(): bool
146
    {
147
        $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

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

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