Passed
Pull Request — final (#524)
by Georges
02:22
created

Driver::driverConnect()   D

Complexity

Conditions 9
Paths 97

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 4.909
c 0
b 0
f 0
cc 9
eloc 16
nc 97
nop 0
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\Pool\DriverBaseTrait;
19
use phpFastCache\Core\Pool\ExtendedCacheItemPoolInterface;
20
use phpFastCache\Entities\DriverStatistic;
21
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
22
use phpFastCache\Exceptions\phpFastCacheDriverException;
23
use phpFastCache\Exceptions\phpFastCacheInvalidArgumentException;
24
use phpFastCache\Exceptions\phpFastCacheLogicException;
25
use Psr\Cache\CacheItemInterface;
26
27
/**
28
 * Class Driver
29
 * @package phpFastCache\Drivers
30
 * @property CouchbaseClient $instance Instance of driver service
31
 */
32
class Driver implements ExtendedCacheItemPoolInterface
33
{
34
    use DriverBaseTrait;
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 phpFastCacheInvalidArgumentException
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->getEncodedKey(), $this->encode($this->driverPreWrap($item)), ['expiry' => $item->getTtl()]);
82
        } else {
83
            throw new phpFastCacheInvalidArgumentException('Cross-Driver type confusion detected');
84
        }
85
    }
86
87
    /**
88
     * @param \Psr\Cache\CacheItemInterface $item
89
     * @return null|array
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->getEncodedKey())->value);
98
        } catch (\CouchbaseException $e) {
99
            return null;
100
        }
101
    }
102
103
    /**
104
     * @param \Psr\Cache\CacheItemInterface $item
105
     * @return bool
106
     * @throws phpFastCacheInvalidArgumentException
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->getEncodedKey());
115
        } else {
116
            throw new phpFastCacheInvalidArgumentException('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
     * @throws phpFastCacheLogicException
131
     */
132
    protected function driverConnect()
133
    {
134
        if ($this->instance instanceof CouchbaseClient) {
135
            throw new phpFastCacheLogicException('Already connected to Couchbase server');
136
        } else {
137
138
139
            $host = isset($this->config[ 'host' ]) ? $this->config[ 'host' ] : '127.0.0.1';
140
            $port = isset($this->config[ 'port' ]) ? $this->config[ 'port' ] : 8091;
141
            $password = isset($this->config[ 'password' ]) ? $this->config[ 'password' ] : '';
142
            $username = isset($this->config[ 'username' ]) ? $this->config[ 'username' ] : '';
143
            $buckets = isset($this->config[ 'buckets' ]) ? $this->config[ 'buckets' ] : [
144
              [
145
                'bucket' => 'default',
146
                'password' => '',
147
              ],
148
            ];
149
150
            $this->instance = new CouchbaseClient("couchbase://{$host}:{$port}", $username, $password);
151
152
            foreach ($buckets as $bucket) {
153
                $this->bucketCurrent = $this->bucketCurrent ?: $bucket[ 'bucket' ];
154
                $this->setBucket($bucket[ 'bucket' ], $this->instance->openBucket($bucket[ 'bucket' ], $bucket[ 'password' ]));
155
            }
156
        }
157
158
        return true;
159
    }
160
161
    /**
162
     * @return \CouchbaseBucket
163
     */
164
    protected function getBucket()
165
    {
166
        return $this->bucketInstances[ $this->bucketCurrent ];
167
    }
168
169
    /**
170
     * @param $bucketName
171
     * @param \CouchbaseBucket $CouchbaseBucket
172
     * @throws phpFastCacheLogicException
173
     */
174
    protected function setBucket($bucketName, \CouchbaseBucket $CouchbaseBucket)
175
    {
176
        if (!array_key_exists($bucketName, $this->bucketInstances)) {
177
            $this->bucketInstances[ $bucketName ] = $CouchbaseBucket;
178
        } else {
179
            throw new phpFastCacheLogicException('A bucket instance with this name already exists.');
180
        }
181
    }
182
183
    /********************
184
     *
185
     * PSR-6 Extended Methods
186
     *
187
     *******************/
188
189
    /**
190
     * @return DriverStatistic
191
     */
192
    public function getStats()
193
    {
194
        $info = $this->getBucket()->manager()->info();
195
196
        return (new DriverStatistic())
197
          ->setSize($info[ 'basicStats' ][ 'diskUsed' ])
198
          ->setRawData($info)
199
          ->setData(implode(', ', array_keys($this->itemInstances)))
200
          ->setInfo('CouchBase version ' . $info[ 'nodes' ][ 0 ][ 'version' ] . ', Uptime (in days): ' . round($info[ 'nodes' ][ 0 ][ 'uptime' ] / 86400,
201
              1) . "\n For more information see RawData.");
202
    }
203
}