Completed
Push — V6 ( 799449...64bc5e )
by Georges
02:30
created

Driver   B

Complexity

Total Complexity 37

Size/Duplication

Total Lines 235
Duplicated Lines 4.26 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 37
lcom 1
cbo 6
dl 10
loc 235
rs 8.6
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 10 10 2
A driverCheck() 0 9 3
B driverWrite() 0 27 5
A driverRead() 0 14 2
A driverDelete() 0 16 2
A driverClear() 0 15 1
F driverConnect() 0 27 15
A getCollection() 0 4 1
B getStats() 0 51 6

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
 * @author Fabio Covolo Mazzo (fabiocmazzo) <[email protected]>
13
 *
14
 */
15
16
namespace phpFastCache\Drivers\Mongodb;
17
18
use MongoDB\Driver\Command;
19
use MongoDB\Driver\Exception\Exception as MongoDBException;
20
use LogicException;
21
use MongoDB\Collection;
22
use MongoDB\DeleteResult;
23
use MongoDB\Driver\Manager as MongodbManager;
24
use phpFastCache\Core\Pool\DriverBaseTrait;
25
use phpFastCache\Core\Pool\ExtendedCacheItemPoolInterface;
26
use phpFastCache\Entities\driverStatistic;
27
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
28
use phpFastCache\Exceptions\phpFastCacheDriverException;
29
use Psr\Cache\CacheItemInterface;
30
use MongoDB\BSON\UTCDateTime;
31
use MongoDB\BSON\Binary;
32
33
/**
34
 * Class Driver
35
 * @package phpFastCache\Drivers
36
 * @property MongodbManager $instance Instance of driver service
37
 */
38
class Driver implements ExtendedCacheItemPoolInterface
39
{
40
    use DriverBaseTrait;
41
42
    /**
43
     * @var Collection
44
     */
45
    public $collection;
46
47
    /**
48
     * Driver constructor.
49
     * @param array $config
50
     * @throws phpFastCacheDriverCheckException
51
     */
52 View Code Duplication
    public function __construct(array $config = [])
53
    {
54
        $this->setup($config);
55
56
        if (!$this->driverCheck()) {
57
            throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
58
        } else {
59
            $this->driverConnect();
60
        }
61
    }
62
63
    /**
64
     * @return bool
65
     */
66
    public function driverCheck()
67
    {
68
        if(!class_exists('MongoDB\Driver\Manager') && class_exists('MongoClient')){
69
            trigger_error('This driver is used to support the pecl MongoDb extension with mongo-php-library.
70
            For MongoDb with Mongo PECL support use Mongo Driver.', E_USER_ERROR);
71
        }
72
73
        return extension_loaded('Mongodb');
74
    }
75
76
    /**
77
     * @param \Psr\Cache\CacheItemInterface $item
78
     * @return mixed
79
     * @throws \InvalidArgumentException
80
     * @throws phpFastCacheDriverException
81
     */
82
    protected function driverWrite(CacheItemInterface $item)
83
    {
84
        /**
85
         * Check for Cross-Driver type confusion
86
         */
87
        if ($item instanceof Item) {
88
            try {
89
                $result = (array) $this->getCollection()->updateOne(
90
                  ['_id' => $item->getEncodedKey()],
91
                  [
92
                    '$set' => [
93
                      self::DRIVER_DATA_WRAPPER_INDEX => new Binary($this->encode($item->get()), Binary::TYPE_GENERIC),
94
                      self::DRIVER_TAGS_WRAPPER_INDEX => new Binary($this->encode($item->getTags()), Binary::TYPE_GENERIC),
95
                      self::DRIVER_EDATE_WRAPPER_INDEX => ($item->getTtl() > 0 ? new UTCDateTime((time() + $item->getTtl()) * 1000) : new UTCDateTime(time()*1000)),
96
                    ],
97
                  ],
98
                  ['upsert' => true, 'multiple' => false]
99
                );
100
            } catch (MongoDBException $e) {
0 ignored issues
show
Bug introduced by
The class MongoDB\Driver\Exception\Exception 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...
101
                throw new phpFastCacheDriverException('Got an exception while trying to write data to MongoDB server', null, $e);
102
            }
103
104
            return isset($result[ 'ok' ]) ? $result[ 'ok' ] == 1 : true;
105
        } else {
106
            throw new \InvalidArgumentException('Cross-Driver type confusion detected');
107
        }
108
    }
109
110
    /**
111
     * @param \Psr\Cache\CacheItemInterface $item
112
     * @return mixed
113
     */
114
    protected function driverRead(CacheItemInterface $item)
115
    {
116
        $document = $this->getCollection()->findOne(['_id' => $item->getEncodedKey()]);
117
118
        if ($document) {
119
            return [
120
              self::DRIVER_DATA_WRAPPER_INDEX => $this->decode($document[ self::DRIVER_DATA_WRAPPER_INDEX ]->getData()),
121
              self::DRIVER_TAGS_WRAPPER_INDEX => $this->decode($document[ self::DRIVER_TAGS_WRAPPER_INDEX ]->getData()),
122
              self::DRIVER_EDATE_WRAPPER_INDEX => (new \DateTime())->setTimestamp($document[ self::DRIVER_EDATE_WRAPPER_INDEX ]->toDateTime()->getTimestamp()),
123
            ];
124
        } else {
125
            return null;
126
        }
127
    }
128
129
    /**
130
     * @param \Psr\Cache\CacheItemInterface $item
131
     * @return bool
132
     * @throws \InvalidArgumentException
133
     */
134
    protected function driverDelete(CacheItemInterface $item)
135
    {
136
        /**
137
         * Check for Cross-Driver type confusion
138
         */
139
        if ($item instanceof Item) {
140
            /**
141
             * @var DeleteResult $deletionResult
142
             */
143
            $deletionResult = $this->getCollection()->deleteOne(['_id' => $item->getEncodedKey()]);
144
145
            return $deletionResult->isAcknowledged();
146
        } else {
147
            throw new \InvalidArgumentException('Cross-Driver type confusion detected');
148
        }
149
    }
150
151
    /**
152
     * @return bool
153
     */
154
    protected function driverClear()
155
    {
156
        /**
157
         * @var \MongoDB\Model\BSONDocument $result
158
         */
159
        $result = $this->getCollection()->drop()->getArrayCopy();
160
        $this->collection = new Collection($this->instance,'phpFastCache','Cache');
161
162
        /**
163
         * This will rebuild automatically the Collection indexes
164
         */
165
        $this->save($this->getItem('__PFC_CACHE_CLEARED__')->set(true));
166
167
        return !empty($result['ok']);
168
    }
169
170
    /**
171
     * @return bool
172
     * @throws MongodbException
173
     * @throws LogicException
174
     */
175
    protected function driverConnect()
176
    {
177
        if ($this->instance instanceof \MongoDB\Driver\Manager) {
1 ignored issue
show
Bug introduced by
The class MongoDB\Driver\Manager 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...
178
            throw new LogicException('Already connected to Mongodb server');
179
        } else {
180
            $host = isset($this->config[ 'host' ]) ? $this->config[ 'host' ] : '127.0.0.1';
181
            $port = isset($server[ 'port' ]) ? $server[ 'port' ] : '27017';
0 ignored issues
show
Bug introduced by
The variable $server seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
182
            $timeout = isset($server[ 'timeout' ]) ? $server[ 'timeout' ] : 3;
183
            $password = isset($this->config[ 'password' ]) ? $this->config[ 'password' ] : '';
184
            $username = isset($this->config[ 'username' ]) ? $this->config[ 'username' ] : '';
185
            $collectionName = isset($this->config[ 'collectionName' ]) ? $this->config[ 'collectionName' ] : 'Cache';
186
            $databaseName = isset($this->config[ 'databaseName' ]) ? $this->config[ 'databaseName' ] : 'phpFastCache';
187
188
189
            /**
190
             * @todo make an url builder
191
             */
192
            $this->instance = $this->instance ?: (new MongodbManager('mongodb://' .
193
              ($username ?: '') .
194
              ($password ? ":{$password}" : '') .
195
              ($username ? '@' : '') . "{$host}" .
196
              ($port != '27017' ? ":{$port}" : ''), ['connectTimeoutMS' => $timeout * 1000]));
197
            $this->collection = $this->collection ?: new Collection($this->instance,$databaseName, $collectionName);
198
199
            return true;
200
        }
201
    }
202
203
204
    /**
205
     * @return Collection
206
     */
207
    protected function getCollection()
208
    {
209
        return $this->collection;
210
    }
211
212
    /********************
213
     *
214
     * PSR-6 Extended Methods
215
     *
216
     *******************/
217
218
    /**
219
     * @return driverStatistic
220
     */
221
    public function getStats()
222
    {
223
        $serverStats = $this->instance->executeCommand('phpFastCache', new Command([
224
          'serverStatus' => 1,
225
          'recordStats' => 0,
226
          'repl' => 0,
227
          'metrics' => 0,
228
        ]))->toArray()[0];
229
230
        $collectionStats = $this->instance->executeCommand('phpFastCache', new Command([
231
          'collStats' => (isset($this->config[ 'collectionName' ]) ? $this->config[ 'collectionName' ] : 'Cache'),
232
          'verbose' => true,
233
        ]))->toArray()[0];
234
235
        $array_filter_recursive = function( $array, callable $callback = null ) use(&$array_filter_recursive) {
236
            $array = $callback($array);
237
238
            if(is_object($array) ||is_array($array)){
239
                foreach ( $array as &$value ) {
240
                    $value = call_user_func( $array_filter_recursive, $value, $callback );
241
                }
242
            }
243
244
            return $array;
245
        };
246
247
        $callback = function($item)
248
        {
249
            /**
250
             * Remove unserializable properties
251
             */
252
            if($item instanceof \MongoDB\BSON\UTCDateTime){
0 ignored issues
show
Bug introduced by
The class MongoDB\BSON\UTCDateTime 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...
253
                return (string) $item;
254
            }
255
            return $item;
256
        };
257
258
        $serverStats = $array_filter_recursive($serverStats, $callback);
259
        $collectionStats = $array_filter_recursive($collectionStats, $callback);
260
261
        $stats = (new driverStatistic())
262
          ->setInfo('MongoDB version ' . $serverStats->version . ', Uptime (in days): ' . round($serverStats->uptime / 86400, 1) . "\n For more information see RawData.")
263
          ->setSize($collectionStats->size)
264
          ->setData(implode(', ', array_keys($this->itemInstances)))
265
          ->setRawData([
266
            'serverStatus' => $serverStats,
267
            'collStats' => $collectionStats,
268
          ]);
269
270
        return $stats;
271
    }
272
}