Completed
Pull Request — final (#326)
by
unknown
02:48
created

Driver::driverClear()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
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\Mongo;
16
17
use LogicException;
18
use MongoBinData;
19
use MongoClient as MongodbClient;
20
use MongoCollection;
21
use MongoConnectionException;
22
use MongoCursorException;
23
use MongoDate;
24
use phpFastCache\Core\DriverAbstract;
25
use phpFastCache\Entities\driverStatistic;
26
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
27
use phpFastCache\Exceptions\phpFastCacheDriverException;
28
use Psr\Cache\CacheItemInterface;
29
30
/**
31
 * Class Driver
32
 * @package phpFastCache\Drivers
33
 */
34
class Driver extends DriverAbstract
35
{
36
    /**
37
     * @var MongodbClient
38
     */
39
    public $instance;
40
41
    /**
42
     * Driver constructor.
43
     * @param array $config
44
     * @throws phpFastCacheDriverException
45
     */
46 View Code Duplication
    public function __construct(array $config = [])
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
47
    {
48
        $this->setup($config);
49
50
        if (!$this->driverCheck()) {
51
            throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
52
        } else {
53
            $this->driverConnect();
54
        }
55
    }
56
57
    /**
58
     * @return bool
59
     */
60
    public function driverCheck()
61
    {
62
        if(class_exists('MongoDB\Driver\Manager')){
63
            trigger_error('This driver is used to support the pecl Mongo extension.<br />
64
            For MongoDb support use MongoDb Driver.', E_USER_ERROR);
65
        }
66
67
        return extension_loaded('Mongodb');
68
    }
69
70
    /**
71
     * @param \Psr\Cache\CacheItemInterface $item
72
     * @return mixed
73
     * @throws \InvalidArgumentException
74
     */
75 View Code Duplication
    protected function driverWrite(CacheItemInterface $item)
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
76
    {
77
        /**
78
         * Check for Cross-Driver type confusion
79
         */
80
        if ($item instanceof Item) {
81
            try {
82
                $result = (array) $this->getCollection()->update(
83
                  ['_id' => $item->getKey()],
84
                  [
85
                    '$set' => [
86
                      self::DRIVER_TIME_WRAPPER_INDEX => ($item->getTtl() > 0 ? new MongoDate(time() + $item->getTtl()) : new MongoDate(time())),
87
                      self::DRIVER_DATA_WRAPPER_INDEX => new MongoBinData($this->encode($item->get()), MongoBinData::BYTE_ARRAY),
88
                      self::DRIVER_TAGS_WRAPPER_INDEX => new MongoBinData($this->encode($item->getTags()), MongoBinData::BYTE_ARRAY),
89
                    ],
90
                  ],
91
                  ['upsert' => true, 'multiple' => false]
92
                );
93
            } catch (MongoCursorException $e) {
94
                return false;
95
            }
96
97
            return isset($result[ 'ok' ]) ? $result[ 'ok' ] == 1 : true;
98
        } else {
99
            throw new \InvalidArgumentException('Cross-Driver type confusion detected');
100
        }
101
    }
102
103
    /**
104
     * @param \Psr\Cache\CacheItemInterface $item
105
     * @return mixed
106
     */
107
    protected function driverRead(CacheItemInterface $item)
108
    {
109
        $document = $this->getCollection()
110
          ->findOne(['_id' => $item->getKey()],
111
            [self::DRIVER_DATA_WRAPPER_INDEX, self::DRIVER_TIME_WRAPPER_INDEX, self::DRIVER_TAGS_WRAPPER_INDEX  /*'d', 'e'*/]);
112
113
        if ($document) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $document of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
114
            return [
115
              self::DRIVER_DATA_WRAPPER_INDEX => $this->decode($document[ self::DRIVER_DATA_WRAPPER_INDEX ]->bin),
116
              self::DRIVER_TIME_WRAPPER_INDEX => (new \DateTime())->setTimestamp($document[ self::DRIVER_TIME_WRAPPER_INDEX ]->sec),
117
              self::DRIVER_TAGS_WRAPPER_INDEX => $this->decode($document[ self::DRIVER_TAGS_WRAPPER_INDEX ]->bin),
118
            ];
119
        } else {
120
            return null;
121
        }
122
    }
123
124
    /**
125
     * @param \Psr\Cache\CacheItemInterface $item
126
     * @return bool
127
     * @throws \InvalidArgumentException
128
     */
129
    protected function driverDelete(CacheItemInterface $item)
130
    {
131
        /**
132
         * Check for Cross-Driver type confusion
133
         */
134
        if ($item instanceof Item) {
135
            $deletionResult = (array) $this->getCollection()->remove(['_id' => $item->getKey()], ["w" => 1]);
136
137
            return (int) $deletionResult[ 'ok' ] === 1 && !$deletionResult[ 'err' ];
138
        } else {
139
            throw new \InvalidArgumentException('Cross-Driver type confusion detected');
140
        }
141
    }
142
143
    /**
144
     * @return bool
145
     */
146
    protected function driverClear()
147
    {
148
        return $this->getCollection()->drop();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->getCollection()->drop(); (array) is incompatible with the return type declared by the abstract method phpFastCache\Core\DriverAbstract::driverClear of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
149
    }
150
151
    /**
152
     * @return bool
153
     * @throws MongoConnectionException
154
     * @throws LogicException
155
     */
156
    protected function driverConnect()
157
    {
158
        if ($this->instance instanceof MongodbClient) {
159
            throw new LogicException('Already connected to Mongodb server');
160
        } else {
161
            $host = isset($this->config[ 'host' ]) ? $this->config[ 'host' ] : '127.0.0.1';
162
            $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...
163
            $timeout = isset($server[ 'timeout' ]) ? $server[ 'timeout' ] : 3;
164
            $password = isset($this->config[ 'password' ]) ? $this->config[ 'password' ] : '';
165
            $username = isset($this->config[ 'username' ]) ? $this->config[ 'username' ] : '';
166
167
168
            /**
169
             * @todo make an url builder
170
             */
171
            $this->instance = $this->instance ?: (new MongodbClient('mongodb://' .
172
              ($username ?: '') .
173
              ($password ? ":{$password}" : '') .
174
              ($username ? '@' : '') . "{$host}" .
175
              ($port != '27017' ? ":{$port}" : ''), ['connectTimeoutMS' => $timeout * 1000]))->phpFastCache;
176
            // $this->instance->Cache->createIndex([self::DRIVER_TIME_WRAPPER_INDEX => 1], ['expireAfterSeconds' => 0]);
0 ignored issues
show
Unused Code Comprehensibility introduced by
66% 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...
177
        }
178
    }
179
180
181
    /**
182
     * @return \MongoCollection
183
     */
184
    protected function getCollection()
185
    {
186
        return $this->instance->Cache;
187
    }
188
189
    /********************
190
     *
191
     * PSR-6 Extended Methods
192
     *
193
     *******************/
194
195
    /**
196
     * @return driverStatistic
197
     */
198
    public function getStats()
199
    {
200
        $serverStatus = $this->getCollection()->db->command([
201
          'serverStatus' => 1,
202
          'recordStats' => 0,
203
          'repl' => 0,
204
          'metrics' => 0,
205
        ]);
206
207
        $collStats = $this->getCollection()->db->command([
208
          'collStats' => 'Cache',
209
          'verbose' => true,
210
        ]);
211
212
        $stats = (new driverStatistic())
213
          ->setInfo('MongoDB version ' . $serverStatus[ 'version' ] . ', Uptime (in days): ' . round($serverStatus[ 'uptime' ] / 86400, 1) . "\n For more information see RawData.")
214
          ->setSize((int) @$collStats[ 'size' ])
215
          ->setData(implode(', ', array_keys($this->itemInstances)))
216
          ->setRawData([
217
            'serverStatus' => $serverStatus,
218
            'collStats' => $collStats,
219
          ]);
220
221
        return $stats;
222
    }
223
}