Completed
Pull Request — final (#446)
by Georges
02:34
created

Driver::driverConnect()   D

Complexity

Conditions 9
Paths 80

Size

Total Lines 29
Code Lines 17

Duplication

Lines 29
Ratio 100 %

Importance

Changes 0
Metric Value
dl 29
loc 29
rs 4.909
c 0
b 0
f 0
cc 9
eloc 17
nc 80
nop 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\Memcached;
16
17
use Memcached as MemcachedSoftware;
18
use phpFastCache\Core\DriverAbstract;
19
use phpFastCache\Core\MemcacheDriverCollisionDetectorTrait;
20
use phpFastCache\Entities\driverStatistic;
21
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
22
use phpFastCache\Exceptions\phpFastCacheDriverException;
23
use Psr\Cache\CacheItemInterface;
24
25
/**
26
 * Class Driver
27
 * @package phpFastCache\Drivers
28
 * @property MemcachedSoftware $instance
29
 */
30
class Driver extends DriverAbstract
31
{
32
    use MemcacheDriverCollisionDetectorTrait;
33
34
    /**
35
     * Driver constructor.
36
     * @param array $config
37
     * @throws phpFastCacheDriverException
38
     */
39 View Code Duplication
    public function __construct(array $config = [])
40
    {
41
        self::checkCollision('Memcached');
42
        $this->setup($config);
43
44
        if (!$this->driverCheck()) {
45
            throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
46
        } else {
47
            $this->driverConnect();
48
        }
49
    }
50
51
    /**
52
     * @return bool
53
     */
54
    public function driverCheck()
55
    {
56
        return class_exists('Memcached');
57
    }
58
59
    /**
60
     * @param \Psr\Cache\CacheItemInterface $item
61
     * @return mixed
62
     * @throws \InvalidArgumentException
63
     */
64
    protected function driverWrite(CacheItemInterface $item)
65
    {
66
        /**
67
         * Check for Cross-Driver type confusion
68
         */
69
        if ($item instanceof Item) {
70
            $ttl = $item->getExpirationDate()->getTimestamp() - time();
71
72
            // Memcache will only allow a expiration timer less than 2592000 seconds,
73
            // otherwise, it will assume you're giving it a UNIX timestamp.
74
            if ($ttl > 2592000) {
75
                $ttl = time() + $ttl;
76
            }
77
78
            return $this->instance->set($item->getKey(), $this->driverPreWrap($item), $ttl);
79
        } else {
80
            throw new \InvalidArgumentException('Cross-Driver type confusion detected');
81
        }
82
    }
83
84
    /**
85
     * @param \Psr\Cache\CacheItemInterface $item
86
     * @return mixed
87
     */
88 View Code Duplication
    protected function driverRead(CacheItemInterface $item)
89
    {
90
        $val = $this->instance->get($item->getKey());
91
92
        if ($val === false) {
93
            return null;
94
        } else {
95
            return $val;
96
        }
97
    }
98
99
    /**
100
     * @param \Psr\Cache\CacheItemInterface $item
101
     * @return bool
102
     * @throws \InvalidArgumentException
103
     */
104
    protected function driverDelete(CacheItemInterface $item)
105
    {
106
        /**
107
         * Check for Cross-Driver type confusion
108
         */
109
        if ($item instanceof Item) {
110
            return $this->instance->delete($item->getKey());
111
        } else {
112
            throw new \InvalidArgumentException('Cross-Driver type confusion detected');
113
        }
114
    }
115
116
    /**
117
     * @return bool
118
     */
119
    protected function driverClear()
120
    {
121
        return $this->instance->flush();
122
    }
123
124
    /**
125
     * @return bool
126
     */
127 View Code Duplication
    protected function driverConnect()
128
    {
129
        $this->instance = new MemcachedSoftware();
130
131
        $servers = (!empty($this->config[ 'servers' ]) && is_array($this->config[ 'servers' ]) ? $this->config[ 'servers' ] : []);
132
        if (count($servers) < 1) {
133
            $servers = [
134
              [
135
                'host' =>'127.0.0.1',
136
                'port' => 11211,
137
                'sasl_user' => false,
138
                'sasl_password' => false
139
              ],
140
            ];
141
        }
142
143
        foreach ($servers as $server) {
144
            try {
145
                if (!$this->instance->addServer($server['host'], $server['port'])) {
146
                    $this->fallback = true;
147
                }
148
                if(!empty($server[ 'sasl_user' ]) && !empty($server[ 'sasl_password'])){
149
                    $this->instance->setSaslAuthData($server[ 'sasl_user' ], $server[ 'sasl_password']);
150
                }
151
            } catch (\Exception $e) {
152
                $this->fallback = true;
153
            }
154
        }
155
    }
156
157
    /********************
158
     *
159
     * PSR-6 Extended Methods
160
     *
161
     *******************/
162
163
    /**
164
     * @return driverStatistic
165
     */
166 View Code Duplication
    public function getStats()
167
    {
168
        $stats = (array) $this->instance->getStats();
169
        $stats[ 'uptime' ] = (isset($stats[ 'uptime' ]) ? $stats[ 'uptime' ] : 0);
170
        $stats[ 'version' ] = (isset($stats[ 'version' ]) ? $stats[ 'version' ] : 'UnknownVersion');
171
        $stats[ 'bytes' ] = (isset($stats[ 'bytes' ]) ? $stats[ 'version' ] : 0);
172
173
        $date = (new \DateTime())->setTimestamp(time() - $stats[ 'uptime' ]);
174
175
        return (new driverStatistic())
176
          ->setData(implode(', ', array_keys($this->itemInstances)))
177
          ->setInfo(sprintf("The memcache daemon v%s is up since %s.\n For more information see RawData.", $stats[ 'version' ], $date->format(DATE_RFC2822)))
178
          ->setRawData($stats)
179
          ->setSize($stats[ 'bytes' ]);
180
    }
181
}