Passed
Push — master ( fd0d63...16794a )
by smiley
01:53
created

MemcachedCache::setMultiple()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
/**
3
 * Class MemcachedCache
4
 *
5
 * @filesource   MemcachedCache.php
6
 * @created      25.05.2017
7
 * @package      chillerlan\SimpleCache
8
 * @author       Smiley <[email protected]>
9
 * @copyright    2017 Smiley
10
 * @license      MIT
11
 */
12
13
namespace chillerlan\SimpleCache;
14
15
use chillerlan\Settings\SettingsContainerInterface;
16
use Memcached;
17
18
class MemcachedCache extends CacheDriverAbstract{
19
20
	/**
21
	 * @var \Memcached
22
	 */
23
	protected $memcached;
24
25
	/**
26
	 * MemcachedCache constructor.
27
	 *
28
	 * @param \Memcached                                           $memcached
29
	 * @param \chillerlan\Settings\SettingsContainerInterface|null $options
30
	 *
31
	 * @throws \chillerlan\SimpleCache\CacheException
32
	 */
33
	public function __construct(Memcached $memcached, SettingsContainerInterface $options = null){
34
		parent::__construct($options);
35
36
		$this->memcached = $memcached;
37
38
		if(empty($this->memcached->getServerList())){
39
			$msg = 'no memcache server available';
40
41
			$this->logger->error($msg);
42
			throw new CacheException($msg);
43
		}
44
45
	}
46
47
	/** @inheritdoc */
48
	public function get($key, $default = null){
49
		$this->checkKey($key);
50
51
		$value = $this->memcached->get($key);
52
53
		return $value ?: $default;
54
	}
55
56
	/** @inheritdoc */
57
	public function set($key, $value, $ttl = null):bool{
58
		$this->checkKey($key);
59
60
		return $this->memcached->set($key, $value, $this->getTTL($ttl));
61
	}
62
63
	/** @inheritdoc */
64
	public function delete($key):bool{
65
		$this->checkKey($key);
66
67
		return $this->memcached->delete($key);
68
	}
69
70
	/** @inheritdoc */
71
	public function clear():bool{
72
		return $this->memcached->flush();
73
	}
74
75
	/** @inheritdoc */
76
	public function getMultiple($keys, $default = null):array{
77
		$keys = $this->getData($keys);
78
79
		$this->checkKeyArray($keys);
80
81
		$values = $this->memcached->getMulti($keys);
82
		$return = [];
83
84
		foreach($keys as $key){
85
			$return[$key] = $values[$key] ?? $default;
86
		}
87
88
		return $return;
89
	}
90
91
	/** @inheritdoc */
92
	public function setMultiple($values, $ttl = null):bool{
93
		$values = $this->getData($values);
94
95
		$this->checkKeyArray(array_keys($values));
96
97
		return $this->memcached->setMulti($values, $this->getTTL($ttl));
98
	}
99
100
	/** @inheritdoc */
101
	public function deleteMultiple($keys):bool{
102
		$keys = $this->getData($keys);
103
104
		$this->checkKeyArray($keys);
105
106
		return $this->memcached->deleteMulti($keys);
107
	}
108
109
}
110