Passed
Pull Request — master (#821)
by Georges
02:00
created

Driver::driverClear()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
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\Couchbase;
18
19
use Couchbase\Exception as CouchbaseException;
20
use Couchbase\PasswordAuthenticator;
21
use Couchbase\Bucket as CouchbaseBucket;
22
use Couchbase\Cluster as CouchbaseClient;
23
use DateTime;
24
use Phpfastcache\Cluster\AggregatablePoolInterface;
25
use Phpfastcache\Core\Pool\{DriverBaseTrait, ExtendedCacheItemPoolInterface};
26
use Phpfastcache\Entities\DriverStatistic;
27
use Phpfastcache\Exceptions\{PhpfastcacheDriverCheckException, PhpfastcacheInvalidArgumentException, PhpfastcacheLogicException};
28
use Psr\Cache\CacheItemInterface;
29
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 implements ExtendedCacheItemPoolInterface, AggregatablePoolInterface
39
{
40
    use DriverBaseTrait;
41
42
    /**
43
     * @var CouchbaseBucket[]
44
     */
45
    protected $bucketInstances = [];
46
47
    /**
48
     * @var CouchbaseBucket
49
     */
50
    protected $bucketInstance;
51
52
    /**
53
     * @var string
54
     */
55
    protected $currentBucket = '';
56
57
    /**
58
     * @return bool
59
     */
60
    public function driverCheck(): bool
61
    {
62
        return extension_loaded('couchbase');
63
    }
64
65
    /**
66
     * @return DriverStatistic
67
     */
68
    public function getStats(): DriverStatistic
69
    {
70
        $info = $this->getBucket()->manager()->info();
71
72
        return (new DriverStatistic())
73
            ->setSize($info['basicStats']['diskUsed'])
74
            ->setRawData($info)
75
            ->setData(implode(', ', array_keys($this->itemInstances)))
76
            ->setInfo(
77
                'CouchBase version ' . $info['nodes'][0]['version'] . ', Uptime (in days): ' . round(
78
                    $info['nodes'][0]['uptime'] / 86400,
79
                    1
80
                ) . "\n For more information see RawData."
81
            );
82
    }
83
84
    /**
85
     * @return bool
86
     * @throws PhpfastcacheLogicException
87
     */
88
    protected function driverConnect(): bool
89
    {
90
        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...
91
            throw new PhpfastcacheDriverCheckException('You are using the Couchbase PHP SDK 3.x so please use driver Couchbasev3');
92
        }
93
94
        if ($this->instance instanceof CouchbaseClient) {
0 ignored issues
show
introduced by
$this->instance is always a sub-type of Couchbase\Cluster.
Loading history...
95
            throw new PhpfastcacheLogicException('Already connected to Couchbase server');
96
        }
97
98
        $clientConfig = $this->getConfig();
99
100
        $authenticator = new PasswordAuthenticator();
101
        $authenticator->username($clientConfig->getUsername())->password($clientConfig->getPassword());
102
103
        $this->instance = new CouchbaseClient(
104
            'couchbase://' . $clientConfig->getHost() . ($clientConfig->getPort() ? ":{$clientConfig->getPort()}" : '')
105
        );
106
107
        $this->instance->authenticate($authenticator);
108
        $this->setBucket($this->instance->openBucket($clientConfig->getBucketName()));
109
110
        return true;
111
    }
112
113
    /**
114
     * @param CouchbaseBucket $CouchbaseBucket
115
     */
116
    protected function setBucket(CouchbaseBucket $CouchbaseBucket)
117
    {
118
        $this->bucketInstance = $CouchbaseBucket;
119
    }
120
121
    /**
122
     * @param CacheItemInterface $item
123
     * @return null|array
124
     */
125
    protected function driverRead(CacheItemInterface $item)
126
    {
127
        try {
128
            /**
129
             * CouchbaseBucket::get() returns a CouchbaseMetaDoc object
130
             */
131
            return $this->decodeDocument((array) $this->getBucket()->get($item->getEncodedKey())->value);
132
        } catch (CouchbaseException $e) {
133
            return null;
134
        }
135
    }
136
137
    /**
138
     * @return CouchbaseBucket
139
     */
140
    protected function getBucket(): CouchbaseBucket
141
    {
142
        return $this->bucketInstance;
143
    }
144
145
    /**
146
     * @param CacheItemInterface $item
147
     * @return bool
148
     * @throws PhpfastcacheInvalidArgumentException
149
     */
150
    protected function driverWrite(CacheItemInterface $item): bool
151
    {
152
        /**
153
         * Check for Cross-Driver type confusion
154
         */
155
        if ($item instanceof Item) {
156
            try {
157
                return (bool)$this->getBucket()->upsert(
158
                    $item->getEncodedKey(),
159
                    $this->encodeDocument($this->driverPreWrap($item)),
160
                    ['expiry' => $item->getTtl()]
161
                );
162
            } catch (CouchbaseException $e) {
163
                return false;
164
            }
165
        }
166
167
        throw new PhpfastcacheInvalidArgumentException('Cross-Driver type confusion detected');
168
    }
169
170
    /**
171
     * @param CacheItemInterface $item
172
     * @return bool
173
     * @throws PhpfastcacheInvalidArgumentException
174
     */
175
    protected function driverDelete(CacheItemInterface $item): bool
176
    {
177
        /**
178
         * Check for Cross-Driver type confusion
179
         */
180
        if ($item instanceof Item) {
181
            try {
182
                return (bool)$this->getBucket()->remove($item->getEncodedKey());
183
            } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The type Phpfastcache\Drivers\Couchbase\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
184
                return $e->getCode() === COUCHBASE_KEY_ENOENT;
185
            }
186
        }
187
188
        throw new PhpfastcacheInvalidArgumentException('Cross-Driver type confusion detected');
189
    }
190
191
    /**
192
     * @param array $data
193
     * @return array
194
     */
195
    protected function encodeDocument(array $data): array
196
    {
197
        $data[ExtendedCacheItemPoolInterface::DRIVER_DATA_WRAPPER_INDEX] = $this->encode($data[ExtendedCacheItemPoolInterface::DRIVER_DATA_WRAPPER_INDEX]);
198
        $data[ExtendedCacheItemPoolInterface::DRIVER_EDATE_WRAPPER_INDEX] = $data[ExtendedCacheItemPoolInterface::DRIVER_EDATE_WRAPPER_INDEX]->format(\DateTime::ATOM);
199
200
        if($this->getConfig()->isItemDetailedDate()){
201
            $data[ExtendedCacheItemPoolInterface::DRIVER_CDATE_WRAPPER_INDEX] = $data[ExtendedCacheItemPoolInterface::DRIVER_CDATE_WRAPPER_INDEX]->format(\DateTime::ATOM);
202
            $data[ExtendedCacheItemPoolInterface::DRIVER_MDATE_WRAPPER_INDEX] = $data[ExtendedCacheItemPoolInterface::DRIVER_MDATE_WRAPPER_INDEX]->format(\DateTime::ATOM);
203
        }
204
205
        return $data;
206
    }
207
208
    /**
209
     * @param array $data
210
     * @return array
211
     */
212
    protected function decodeDocument(array $data): array
213
    {
214
        $data[ExtendedCacheItemPoolInterface::DRIVER_DATA_WRAPPER_INDEX] = $this->decode($data[ExtendedCacheItemPoolInterface::DRIVER_DATA_WRAPPER_INDEX]);
215
        $data[ExtendedCacheItemPoolInterface::DRIVER_EDATE_WRAPPER_INDEX] = \DateTime::createFromFormat(
216
            \DateTime::ATOM,
217
            $data[ExtendedCacheItemPoolInterface::DRIVER_EDATE_WRAPPER_INDEX]
218
        );
219
220
        if($this->getConfig()->isItemDetailedDate()){
221
            $data[ExtendedCacheItemPoolInterface::DRIVER_CDATE_WRAPPER_INDEX] = \DateTime::createFromFormat(
222
                \DateTime::ATOM,
223
                $data[ExtendedCacheItemPoolInterface::DRIVER_CDATE_WRAPPER_INDEX]
224
            );
225
226
            $data[ExtendedCacheItemPoolInterface::DRIVER_MDATE_WRAPPER_INDEX] = \DateTime::createFromFormat(
227
                \DateTime::ATOM,
228
                $data[ExtendedCacheItemPoolInterface::DRIVER_MDATE_WRAPPER_INDEX]
229
            );
230
        }
231
232
        return $data;
233
    }
234
    /********************
235
     *
236
     * PSR-6 Extended Methods
237
     *
238
     *******************/
239
240
    /**
241
     * @return bool
242
     */
243
    protected function driverClear(): bool
244
    {
245
        $this->getBucket()->manager()->flush();
246
        return true;
247
    }
248
}
249