Completed
Push — v5 ( 0b505a...012ddd )
by Georges
02:41
created

Driver::getStats()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 25
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
cc 1
eloc 17
c 2
b 1
f 1
nc 1
nop 0
dl 0
loc 25
rs 8.8571
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\Mongodb;
16
17
use phpFastCache\Core\DriverAbstract;
18
use phpFastCache\Core\StandardPsr6StructureTrait;
19
use phpFastCache\Entities\driverStatistic;
20
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
21
use phpFastCache\Exceptions\phpFastCacheDriverException;
22
use Psr\Cache\CacheItemInterface;
23
use MongoClient as MongodbClient;
24
use MongoBinData;
25
use MongoCollection;
26
use MongoCursorException;
27
use MongoDate;
28
use MongoConnectionException;
29
use LogicException;
30
31
/**
32
 * Class Driver
33
 * @package phpFastCache\Drivers
34
 */
35
class Driver extends DriverAbstract
36
{
37
    use StandardPsr6StructureTrait;
38
39
    /**
40
     * @var MongodbClient
41
     */
42
    public $instance;
43
44
    /**
45
     * Driver constructor.
46
     * @param array $config
47
     * @throws phpFastCacheDriverException
48
     */
49
    public function __construct(array $config = [])
50
    {
51
        $this->setup($config);
52
53
        if (!$this->driverCheck()) {
54
            throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
55
        } else {
56
            $this->driverConnect();
57
        }
58
    }
59
60
    /**
61
     * @return bool
62
     */
63
    public function driverCheck()
64
    {
65
        return extension_loaded('Mongodb');
66
    }
67
68
    /**
69
     * @param \Psr\Cache\CacheItemInterface $item
70
     * @return mixed
71
     * @throws \InvalidArgumentException
72
     */
73
    public function driverWrite(CacheItemInterface $item)
74
    {
75
        /**
76
         * Check for Cross-Driver type confusion
77
         */
78
        if ($item instanceof Item) {
79
            try {
80
                $result = (array) $this->getCollection()->update(
81
                  ['_id' => $item->getKey()],
82
                  [
83
                    '$set' => [
84
                      self::DRIVER_TIME_WRAPPER_INDEX => ($item->getTtl() > 0 ? new MongoDate(time() + $item->getTtl()) : new MongoDate(time())),
85
                      self::DRIVER_DATA_WRAPPER_INDEX => new MongoBinData($this->encode($item->get()), MongoBinData::BYTE_ARRAY),
86
                      self::DRIVER_TAGS_WRAPPER_INDEX => new MongoBinData($this->encode($item->getTags()), MongoBinData::BYTE_ARRAY),
87
                    ],
88
                  ],
89
                  ['upsert' => true, 'multiple' => false]
90
                );
91
            } catch (MongoCursorException $e) {
92
                return false;
93
            }
94
95
            return isset($result[ 'ok' ]) ? $result[ 'ok' ] == 1 : true;
96
        } else {
97
            throw new \InvalidArgumentException('Cross-Driver type confusion detected');
98
        }
99
    }
100
101
    /**
102
     * @param string $key
103
     * @return mixed
104
     */
105
    public function driverRead($key)
106
    {
107
        $document = $this->getCollection()->findOne(['_id' => $key], [self::DRIVER_DATA_WRAPPER_INDEX, self::DRIVER_TIME_WRAPPER_INDEX, self::DRIVER_TAGS_WRAPPER_INDEX  /*'d', 'e'*/]);
108
109
        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...
110
            return [
111
              self::DRIVER_DATA_WRAPPER_INDEX => $this->decode($document[ self::DRIVER_DATA_WRAPPER_INDEX ]->bin),
112
              self::DRIVER_TIME_WRAPPER_INDEX => (new \DateTime())->setTimestamp($document[ self::DRIVER_TIME_WRAPPER_INDEX ]->sec),
113
              self::DRIVER_TAGS_WRAPPER_INDEX => $this->decode($document[ self::DRIVER_TAGS_WRAPPER_INDEX ]->bin),
114
            ];
115
        } else {
116
            return null;
117
        }
118
    }
119
120
    /**
121
     * @param \Psr\Cache\CacheItemInterface $item
122
     * @return bool
123
     * @throws \InvalidArgumentException
124
     */
125
    public function driverDelete(CacheItemInterface $item)
126
    {
127
        /**
128
         * Check for Cross-Driver type confusion
129
         */
130
        if ($item instanceof Item) {
131
            $deletionResult = (array) $this->getCollection()->remove(['_id' => $item->getKey()], ["w" => 1]);
132
133
            return (int) $deletionResult[ 'ok' ] === 1 && !$deletionResult[ 'err' ];
134
        } else {
135
            throw new \InvalidArgumentException('Cross-Driver type confusion detected');
136
        }
137
    }
138
139
    /**
140
     * @return bool
141
     */
142
    public function driverClear()
143
    {
144
        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...
145
    }
146
147
    /**
148
     * @return bool
149
     * @throws MongoConnectionException
150
     * @throws LogicException
151
     */
152
    public function driverConnect()
153
    {
154
        if ($this->instance instanceof MongodbClient) {
155
            throw new LogicException('Already connected to Mongodb server');
156
        } else {
157
            $host = isset($this->config[ 'host' ]) ? $this->config[ 'host' ] : '127.0.0.1';
158
            $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...
159
            $timeout = isset($server[ 'timeout' ]) ? $server[ 'timeout' ] : 3;
160
            $password = isset($this->config[ 'password' ]) ? $this->config[ 'password' ] : '';
161
            $username = isset($this->config[ 'username' ]) ? $this->config[ 'username' ] : '';
162
163
164
            /**
165
             * @todo make an url builder
166
             */
167
            $this->instance = $this->instance ?: (new MongodbClient('mongodb://' .
168
              ($username ?: '') .
169
              ($password ? ":{$password}" : '') .
170
              ($username ? '@' : '') . "{$host}" .
171
              ($port != '27017' ? ":{$port}" : ''), ['connectTimeoutMS' => $timeout * 1000]))->phpFastCache;
172
            // $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...
173
        }
174
    }
175
176
177
    /**
178
     * @return \MongoCollection
179
     */
180
    protected function getCollection()
181
    {
182
        return $this->instance->Cache;
183
    }
184
185
    /**
186
     * @param \Psr\Cache\CacheItemInterface $item
187
     * @return bool
188
     * @throws \InvalidArgumentException
189
     */
190
    public function driverIsHit(CacheItemInterface $item)
191
    {
192
        $document = $this->getCollection()->findOne(['_id' => $item->getKey()], [self::DRIVER_TIME_WRAPPER_INDEX  /*'d', 'e'*/]);
193
        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...
194
            return $document[ self::DRIVER_TIME_WRAPPER_INDEX ]->sec >= time();
195
        } else {
196
            return null;
197
        }
198
    }
199
200
    /********************
201
     *
202
     * PSR-6 Extended Methods
203
     *
204
     *******************/
205
206
    /**
207
     * @return driverStatistic
208
     */
209
    public function getStats()
210
    {
211
        $serverStatus = $this->getCollection()->db->command([
212
          'serverStatus' => 1,
213
          'recordStats' => 0,
214
          'repl' => 0,
215
          'metrics' => 0,
216
        ]);
217
218
        $collStats = $this->getCollection()->db->command([
219
          'collStats' => 'Cache',
220
          'verbose' => true,
221
        ]);
222
223
        $stats = (new driverStatistic())
224
          ->setInfo('MongoDB version ' . $serverStatus[ 'version' ] . ', Uptime (in days): ' . round($serverStatus[ 'uptime' ] / 86400, 1) . "\n For more information see RawData.")
225
          ->setSize((int) $collStats[ 'size' ])
226
          ->setData(implode(', ', array_keys($this->itemInstances)))
227
          ->setRawData([
228
            'serverStatus' => $serverStatus,
229
            'collStats' => $collStats,
230
          ]);
231
232
        return $stats;
233
    }
234
}