Completed
Branch final (ad8b8d)
by Georges
03:08 queued 28s
created

Driver::driverConnect()   D

Complexity

Conditions 9
Paths 97

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 14
c 1
b 0
f 0
nc 97
nop 0
dl 0
loc 26
rs 4.909
1
<?php
2
/**
3
 *
4
 * This file is part of phpFastCache.
5
 *
6
 * @license MIT License (MIT)
7
 *
8
 * For full copyright and license information, please see the docs/CREDITS.txt file.
9
 *
10
 * @author Khoa Bui (khoaofgod)  <[email protected]> http://www.phpfastcache.com
11
 * @author Georges.L (Geolim4)  <[email protected]>
12
 *
13
 */
14
15
namespace phpFastCache\Drivers\Couchbase;
16
17
use CouchbaseCluster as CouchbaseClient;
18
use phpFastCache\Core\DriverAbstract;
19
use phpFastCache\Core\StandardPsr6StructureTrait;
20
use phpFastCache\Entities\driverStatistic;
21
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
22
use phpFastCache\Exceptions\phpFastCacheDriverException;
23
use Psr\Cache\CacheItemInterface;
24
25
/**
26
 * Class Driver
27
 * @package phpFastCache\Drivers
28
 */
29
class Driver extends DriverAbstract
30
{
31
    /**
32
     * @var CouchbaseClient
33
     */
34
    public $instance;
35
36
    /**
37
     * @var \CouchbaseBucket[]
38
     */
39
    protected $bucketInstances = [];
40
41
    /**
42
     * @var string
43
     */
44
    protected $bucketCurrent = '';
45
46
    /**
47
     * Driver constructor.
48
     * @param array $config
49
     * @throws phpFastCacheDriverException
50
     */
51
    public function __construct(array $config = [])
52
    {
53
        $this->setup($config);
54
55
        if (!$this->driverCheck()) {
56
            throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
57
        } else {
58
            $this->driverConnect();
59
        }
60
    }
61
62
    /**
63
     * @return bool
64
     */
65
    public function driverCheck()
66
    {
67
        return extension_loaded('Couchbase');
68
    }
69
70
    /**
71
     * @param \Psr\Cache\CacheItemInterface $item
72
     * @return mixed
73
     * @throws \InvalidArgumentException
74
     */
75
    protected function driverWrite(CacheItemInterface $item)
76
    {
77
        /**
78
         * Check for Cross-Driver type confusion
79
         */
80
        if ($item instanceof Item) {
81
            return $this->getBucket()->upsert($item->getKey(), $this->encode($this->driverPreWrap($item)), ['expiry' => $item->getTtl()]);
82
        } else {
83
            throw new \InvalidArgumentException('Cross-Driver type confusion detected');
84
        }
85
    }
86
87
    /**
88
     * @param \Psr\Cache\CacheItemInterface $item
89
     * @return mixed
90
     */
91
    protected function driverRead(CacheItemInterface $item)
92
    {
93
        try {
94
            /**
95
             * CouchbaseBucket::get() returns a CouchbaseMetaDoc object
96
             */
97
            return $this->decode($this->getBucket()->get($item->getKey())->value);
98
        } catch (\CouchbaseException $e) {
1 ignored issue
show
Bug introduced by
The class CouchbaseException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
99
            return null;
100
        }
101
    }
102
103
    /**
104
     * @param \Psr\Cache\CacheItemInterface $item
105
     * @return bool
106
     * @throws \InvalidArgumentException
107
     */
108
    protected function driverDelete(CacheItemInterface $item)
109
    {
110
        /**
111
         * Check for Cross-Driver type confusion
112
         */
113
        if ($item instanceof Item) {
114
            return $this->getBucket()->remove($item->getKey());
115
        } else {
116
            throw new \InvalidArgumentException('Cross-Driver type confusion detected');
117
        }
118
    }
119
120
    /**
121
     * @return bool
122
     */
123
    protected function driverClear()
124
    {
125
        return $this->getBucket()->manager()->flush();
126
    }
127
128
    /**
129
     * @return bool
130
     */
131
    protected function driverConnect()
132
    {
133
        if ($this->instance instanceof CouchbaseClient) {
1 ignored issue
show
Bug introduced by
The class CouchbaseCluster does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
134
            throw new \LogicException('Already connected to Couchbase server');
135
        } else {
136
137
138
            $host = isset($this->config[ 'host' ]) ? $this->config[ 'host' ] : '127.0.0.1';
139
            //$port = isset($server[ 'port' ]) ? $server[ 'port' ] : '11211';
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
140
            $password = isset($this->config[ 'password' ]) ? $this->config[ 'password' ] : '';
141
            $username = isset($this->config[ 'username' ]) ? $this->config[ 'username' ] : '';
142
            $buckets = isset($this->config[ 'buckets' ]) ? $this->config[ 'buckets' ] : [
143
              [
144
                'bucket' => 'default',
145
                'password' => '',
146
              ],
147
            ];
148
149
            $this->instance = $this->instance ?: new CouchbaseClient("couchbase://{$host}", $username, $password);
150
151
            foreach ($buckets as $bucket) {
152
                $this->bucketCurrent = $this->bucketCurrent ?: $bucket[ 'bucket' ];
153
                $this->setBucket($bucket[ 'bucket' ], $this->instance->openBucket($bucket[ 'bucket' ], $bucket[ 'password' ]));
154
            }
155
        }
156
    }
157
158
    /**
159
     * @return \CouchbaseBucket
160
     */
161
    protected function getBucket()
162
    {
163
        return $this->bucketInstances[ $this->bucketCurrent ];
164
    }
165
166
    /**
167
     * @param $bucketName
168
     * @param \CouchbaseBucket $CouchbaseBucket
169
     * @throws \LogicException
170
     */
171
    protected function setBucket($bucketName, \CouchbaseBucket $CouchbaseBucket)
172
    {
173
        if (!array_key_exists($bucketName, $this->bucketInstances)) {
174
            $this->bucketInstances[ $bucketName ] = $CouchbaseBucket;
175
        } else {
176
            throw new \LogicException('A bucket instance with this name already exists.');
177
        }
178
    }
179
180
    /********************
181
     *
182
     * PSR-6 Extended Methods
183
     *
184
     *******************/
185
186
    /**
187
     * @return driverStatistic
188
     */
189
    public function getStats()
190
    {
191
        $info = $this->getBucket()->manager()->info();
192
193
        return (new driverStatistic())
194
          ->setSize($info[ 'basicStats' ][ 'diskUsed' ])
195
          ->setRawData($info)
196
          ->setData(implode(', ', array_keys($this->itemInstances)))
197
          ->setInfo('CouchBase version ' . $info[ 'nodes' ][ 0 ][ 'version' ] . ', Uptime (in days): ' . round($info[ 'nodes' ][ 0 ][ 'uptime' ] / 86400, 1) . "\n For more information see RawData.");
198
    }
199
}