Completed
Pull Request — final (#409)
by Georges
04:43 queued 02:11
created

Driver::driverConnect()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 0
dl 0
loc 13
rs 9.4285
c 0
b 0
f 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\Predis;
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 Predis\Client as PredisClient;
23
use Psr\Cache\CacheItemInterface;
24
25
/**
26
 * Class Driver
27
 * @package phpFastCache\Drivers
28
 */
29
class Driver extends DriverAbstract
30
{
31
    /**
32
     * @var PredisClient Instance of driver service
33
     */
34
    public $instance;
35
36
    /**
37
     * Driver constructor.
38
     * @param array $config
39
     * @throws phpFastCacheDriverException
40
     */
41
    public function __construct(array $config = [])
42
    {
43
        $this->setup($config);
44
45 View Code Duplication
        if (!$this->driverCheck()) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across 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...
46
            throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
47
        } else {
48
            $this->driverConnect();
49
        }
50
    }
51
52
    /**
53
     * @return bool
54
     */
55
    public function driverCheck()
56
    {
57
        if (extension_loaded('Redis')) {
58
            trigger_error('The native Redis extension is installed, you should use Redis instead of Predis to increase performances', E_USER_NOTICE);
59
        }
60
61
        return class_exists('Predis\Client');
62
    }
63
64
    /**
65
     * @param \Psr\Cache\CacheItemInterface $item
66
     * @return mixed
67
     * @throws \InvalidArgumentException
68
     */
69 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...
70
    {
71
        /**
72
         * Check for Cross-Driver type confusion
73
         */
74
        if ($item instanceof Item) {
75
            $ttl = $item->getExpirationDate()->getTimestamp() - time();
76
77
            return $this->instance->setex($item->getKey(), $ttl, $this->encode($this->driverPreWrap($item)));
78
        } else {
79
            throw new \InvalidArgumentException('Cross-Driver type confusion detected');
80
        }
81
    }
82
83
    /**
84
     * @param \Psr\Cache\CacheItemInterface $item
85
     * @return mixed
86
     */
87 View Code Duplication
    protected function driverRead(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...
88
    {
89
        $val = $this->instance->get($item->getKey());
90
        if ($val == false) {
91
            return null;
92
        } else {
93
            return $this->decode($val);
94
        }
95
    }
96
97
    /**
98
     * @param \Psr\Cache\CacheItemInterface $item
99
     * @return bool
100
     * @throws \InvalidArgumentException
101
     */
102
    protected function driverDelete(CacheItemInterface $item)
103
    {
104
        /**
105
         * Check for Cross-Driver type confusion
106
         */
107
        if ($item instanceof Item) {
108
            return $this->instance->del($item->getKey());
109
        } else {
110
            throw new \InvalidArgumentException('Cross-Driver type confusion detected');
111
        }
112
    }
113
114
    /**
115
     * @return bool
116
     */
117
    protected function driverClear()
118
    {
119
        return $this->instance->flushDB();
120
    }
121
122
    /**
123
     * @return bool
124
     */
125
    protected function driverConnect()
126
    {
127
        $config = isset($this->config[ 'redis' ]) ? $this->config[ 'redis' ] : [];
128
129
        $this->instance = new PredisClient(array_merge([
130
          'host' => '127.0.0.1',
131
          'port' => '6379',
132
          'password' => '',
133
          'database' => '',
134
        ], $config));
135
136
        return true;
137
    }
138
139
    /********************
140
     *
141
     * PSR-6 Extended Methods
142
     *
143
     *******************/
144
145
    /**
146
     * @return driverStatistic
147
     */
148
    public function getStats()
149
    {
150
        $info = $this->instance->info();
151
        $size = (isset($info['Memory']['used_memory']) ? $info['Memory']['used_memory'] : 0);
152
        $version = (isset($info['Server']['redis_version']) ? $info['Server']['redis_version'] : 0);
153
        $date = (isset($info['Server'][ 'uptime_in_seconds' ]) ? (new \DateTime())->setTimestamp(time() - $info['Server'][ 'uptime_in_seconds' ]) : 'unknown date');
154
155
        return (new driverStatistic())
156
          ->setData(implode(', ', array_keys($this->itemInstances)))
157
          ->setRawData($this->instance->info())
158
          ->setSize($size)
159
          ->setInfo(sprintf("The Redis daemon v%s is up since %s.\n For more information see RawData. \n Driver size includes the memory allocation size.", $version, $date->format(DATE_RFC2822)));
160
    }
161
}