Completed
Push — V6 ( b4a639...6bde60 )
by Georges
02:29
created

Driver::driverClear()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
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\Memcached;
16
17
use Memcached as MemcachedSoftware;
18
use phpFastCache\Core\Pool\DriverBaseTrait;
19
use phpFastCache\Core\Pool\ExtendedCacheItemPoolInterface;
20
use phpFastCache\Entities\driverStatistic;
21
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
22
use phpFastCache\Exceptions\phpFastCacheDriverException;
23
use phpFastCache\Exceptions\phpFastCacheInvalidArgumentException;
24
use phpFastCache\Util\MemcacheDriverCollisionDetectorTrait;
25
use Psr\Cache\CacheItemInterface;
26
27
/**
28
 * Class Driver
29
 * @package phpFastCache\Drivers
30
 */
31
class Driver implements ExtendedCacheItemPoolInterface
32
{
33
    use DriverBaseTrait, MemcacheDriverCollisionDetectorTrait;
34
35
    /**
36
     * Driver constructor.
37
     * @param array $config
38
     * @throws phpFastCacheDriverException
39
     */
40 View Code Duplication
    public function __construct(array $config = [])
41
    {
42
        self::checkCollision('Memcached');
43
        $this->setup($config);
44
45
        if (!$this->driverCheck()) {
46
            throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
47
        } else {
48
            $this->instance = new MemcachedSoftware();
49
            $this->driverConnect();
50
        }
51
    }
52
53
    /**
54
     * @return bool
55
     */
56
    public function driverCheck()
57
    {
58
        return class_exists('Memcached');
59
    }
60
61
    /**
62
     * @param \Psr\Cache\CacheItemInterface $item
63
     * @return mixed
64
     * @throws phpFastCacheInvalidArgumentException
65
     */
66
    protected function driverWrite(CacheItemInterface $item)
67
    {
68
        /**
69
         * Check for Cross-Driver type confusion
70
         */
71
        if ($item instanceof Item) {
72
            $ttl = $item->getExpirationDate()->getTimestamp() - time();
73
74
            // Memcache will only allow a expiration timer less than 2592000 seconds,
75
            // otherwise, it will assume you're giving it a UNIX timestamp.
76
            if ($ttl > 2592000) {
77
                $ttl = time() + $ttl;
78
            }
79
80
            return $this->instance->set($item->getKey(), $this->driverPreWrap($item), $ttl);
81
        } else {
82
            throw new phpFastCacheInvalidArgumentException('Cross-Driver type confusion detected');
83
        }
84
    }
85
86
    /**
87
     * @param \Psr\Cache\CacheItemInterface $item
88
     * @return mixed
89
     */
90 View Code Duplication
    protected function driverRead(CacheItemInterface $item)
91
    {
92
        $val = $this->instance->get($item->getKey());
93
94
        if ($val === false) {
95
            return null;
96
        } else {
97
            return $val;
98
        }
99
    }
100
101
    /**
102
     * @param \Psr\Cache\CacheItemInterface $item
103
     * @return bool
104
     * @throws phpFastCacheInvalidArgumentException
105
     */
106
    protected function driverDelete(CacheItemInterface $item)
107
    {
108
        /**
109
         * Check for Cross-Driver type confusion
110
         */
111
        if ($item instanceof Item) {
112
            return $this->instance->delete($item->getKey());
113
        } else {
114
            throw new phpFastCacheInvalidArgumentException('Cross-Driver type confusion detected');
115
        }
116
    }
117
118
    /**
119
     * @return bool
120
     */
121
    protected function driverClear()
122
    {
123
        return $this->instance->flush();
124
    }
125
126
    /**
127
     * @return bool
128
     */
129 View Code Duplication
    protected function driverConnect()
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
}