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

Driver::driverConnect()   C

Complexity

Conditions 12
Paths 65

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 14
c 1
b 0
f 0
nc 65
nop 0
dl 0
loc 23
rs 5.2987

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 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\Core\StandardPsr6StructureTrait;
26
use phpFastCache\Entities\driverStatistic;
27
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
28
use phpFastCache\Exceptions\phpFastCacheDriverException;
29
use Psr\Cache\CacheItemInterface;
30
31
/**
32
 * Class Driver
33
 * @package phpFastCache\Drivers
34
 */
35
class Driver extends DriverAbstract
36
{
37
    /**
38
     * @var MongodbClient
39
     */
40
    public $instance;
41
42
    /**
43
     * Driver constructor.
44
     * @param array $config
45
     * @throws phpFastCacheDriverException
46
     */
47
    public function __construct(array $config = [])
48
    {
49
        $this->setup($config);
50
51
        if (!$this->driverCheck()) {
52
            throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
53
        } else {
54
            $this->driverConnect();
55
        }
56
    }
57
58
    /**
59
     * @return bool
60
     */
61
    public function driverCheck()
62
    {
63
        return extension_loaded('Mongodb');
64
    }
65
66
    /**
67
     * @param \Psr\Cache\CacheItemInterface $item
68
     * @return mixed
69
     * @throws \InvalidArgumentException
70
     */
71
    protected function driverWrite(CacheItemInterface $item)
72
    {
73
        /**
74
         * Check for Cross-Driver type confusion
75
         */
76
        if ($item instanceof Item) {
77
            try {
78
                $result = (array) $this->getCollection()->update(
79
                  ['_id' => $item->getKey()],
80
                  [
81
                    '$set' => [
82
                      self::DRIVER_TIME_WRAPPER_INDEX => ($item->getTtl() > 0 ? new MongoDate(time() + $item->getTtl()) : new MongoDate(time())),
83
                      self::DRIVER_DATA_WRAPPER_INDEX => new MongoBinData($this->encode($item->get()), MongoBinData::BYTE_ARRAY),
84
                      self::DRIVER_TAGS_WRAPPER_INDEX => new MongoBinData($this->encode($item->getTags()), MongoBinData::BYTE_ARRAY),
85
                    ],
86
                  ],
87
                  ['upsert' => true, 'multiple' => false]
88
                );
89
            } catch (MongoCursorException $e) {
90
                return false;
91
            }
92
93
            return isset($result[ 'ok' ]) ? $result[ 'ok' ] == 1 : true;
94
        } else {
95
            throw new \InvalidArgumentException('Cross-Driver type confusion detected');
96
        }
97
    }
98
99
    /**
100
     * @param \Psr\Cache\CacheItemInterface $item
101
     * @return mixed
102
     */
103
    protected function driverRead(CacheItemInterface $item)
104
    {
105
        $document = $this->getCollection()
106
          ->findOne(['_id' => $item->getKey()],
107
            [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
    protected 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
    protected 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
    protected 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
     *
187
     * PSR-6 Extended Methods
188
     *
189
     *******************/
190
191
    /**
192
     * @return driverStatistic
193
     */
194
    public function getStats()
195
    {
196
        $serverStatus = $this->getCollection()->db->command([
197
          'serverStatus' => 1,
198
          'recordStats' => 0,
199
          'repl' => 0,
200
          'metrics' => 0,
201
        ]);
202
203
        $collStats = $this->getCollection()->db->command([
204
          'collStats' => 'Cache',
205
          'verbose' => true,
206
        ]);
207
208
        $stats = (new driverStatistic())
209
          ->setInfo('MongoDB version ' . $serverStatus[ 'version' ] . ', Uptime (in days): ' . round($serverStatus[ 'uptime' ] / 86400, 1) . "\n For more information see RawData.")
210
          ->setSize((int) @$collStats[ 'size' ])
211
          ->setData(implode(', ', array_keys($this->itemInstances)))
212
          ->setRawData([
213
            'serverStatus' => $serverStatus,
214
            'collStats' => $collStats,
215
          ]);
216
217
        return $stats;
218
    }
219
}