<?php
namespace Cake\Cache\Engine;
use Cake\Cache\CacheEngine;
use InvalidArgumentException;
use Memcached;
class MemcachedEngine extends CacheEngine
{
protected $_Memcached;
protected $_defaultConfig = [
'compress' => false,
'duration' => 3600,
'groups' => [],
'host' => null,
'username' => null,
'password' => null,
'persistent' => false,
'port' => null,
'prefix' => 'cake_',
'probability' => 100,
'serialize' => 'php',
'servers' => ['127.0.0.1'],
'options' => [],
];
protected $_serializers = [];
protected $_compiledGroupNames = [];
public function init(array $config = [])
{
if (!extension_loaded('memcached')) {
return false;
}
$this->_serializers = [
'igbinary' => Memcached::SERIALIZER_IGBINARY,
'json' => Memcached::SERIALIZER_JSON,
'php' => Memcached::SERIALIZER_PHP
];
if (defined('Memcached::HAVE_MSGPACK') && Memcached::HAVE_MSGPACK) {
$this->_serializers['msgpack'] = Memcached::SERIALIZER_MSGPACK;
}
parent::init($config);
if (!empty($config['host'])) {
if (empty($config['port'])) {
$config['servers'] = [$config['host']];
} else {
$config['servers'] = [sprintf('%s:%d', $config['host'], $config['port'])];
}
}
if (isset($config['servers'])) {
$this->setConfig('servers', $config['servers'], false);
}
if (!is_array($this->_config['servers'])) {
$this->_config['servers'] = [$this->_config['servers']];
}
if (isset($this->_Memcached)) {
return true;
}
if ($this->_config['persistent']) {
$this->_Memcached = new Memcached((string)$this->_config['persistent']);
} else {
$this->_Memcached = new Memcached();
}
$this->_setOptions();
if (count($this->_Memcached->getServerList())) {
return true;
}
$servers = [];
foreach ($this->_config['servers'] as $server) {
$servers[] = $this->parseServerString($server);
}
if (!$this->_Memcached->addServers($servers)) {
return false;
}
if (is_array($this->_config['options'])) {
foreach ($this->_config['options'] as $opt => $value) {
$this->_Memcached->setOption($opt, $value);
}
}
if (empty($this->_config['username']) && !empty($this->_config['login'])) {
throw new InvalidArgumentException(
'Please pass "username" instead of "login" for connecting to Memcached'
);
}
if ($this->_config['username'] !== null && $this->_config['password'] !== null) {
if (!method_exists($this->_Memcached, 'setSaslAuthData')) {
throw new InvalidArgumentException(
'Memcached extension is not built with SASL support'
);
}
$this->_Memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
$this->_Memcached->setSaslAuthData(
$this->_config['username'],
$this->_config['password']
);
}
return true;
}
protected function _setOptions()
{
$this->_Memcached->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
$serializer = strtolower($this->_config['serialize']);
if (!isset($this->_serializers[$serializer])) {
throw new InvalidArgumentException(
sprintf('%s is not a valid serializer engine for Memcached', $serializer)
);
}
if ($serializer !== 'php' &&
!constant('Memcached::HAVE_' . strtoupper($serializer))
) {
throw new InvalidArgumentException(
sprintf('Memcached extension is not compiled with %s support', $serializer)
);
}
$this->_Memcached->setOption(
Memcached::OPT_SERIALIZER,
$this->_serializers[$serializer]
);
if (defined('Memcached::OPT_CLIENT_MODE') &&
defined('Memcached::DYNAMIC_CLIENT_MODE')
) {
$this->_Memcached->setOption(
Memcached::OPT_CLIENT_MODE,
Memcached::DYNAMIC_CLIENT_MODE
);
}
$this->_Memcached->setOption(
Memcached::OPT_COMPRESSION,
(bool)$this->_config['compress']
);
}
public function parseServerString($server)
{
$socketTransport = 'unix://';
if (strpos($server, $socketTransport) === 0) {
return [substr($server, strlen($socketTransport)), 0];
}
if (substr($server, 0, 1) === '[') {
$position = strpos($server, ']:');
if ($position !== false) {
$position++;
}
} else {
$position = strpos($server, ':');
}
$port = 11211;
$host = $server;
if ($position !== false) {
$host = substr($server, 0, $position);
$port = substr($server, $position + 1);
}
return [$host, (int)$port];
}
protected function _parseServerString($server)
{
return $this->parseServerString($server);
}
public function getOption($name)
{
return $this->_Memcached->getOption($name);
}
public function write($key, $value)
{
$duration = $this->_config['duration'];
if ($duration > 30 * DAY) {
$duration = 0;
}
$key = $this->_key($key);
return $this->_Memcached->set($key, $value, $duration);
}
public function writeMany($data)
{
$cacheData = [];
foreach ($data as $key => $value) {
$cacheData[$this->_key($key)] = $value;
}
$success = $this->_Memcached->setMulti($cacheData);
$return = [];
foreach (array_keys($data) as $key) {
$return[$key] = $success;
}
return $return;
}
public function read($key)
{
$key = $this->_key($key);
return $this->_Memcached->get($key);
}
public function readMany($keys)
{
$cacheKeys = [];
foreach ($keys as $key) {
$cacheKeys[] = $this->_key($key);
}
$values = $this->_Memcached->getMulti($cacheKeys);
$return = [];
foreach ($keys as &$key) {
$return[$key] = array_key_exists($this->_key($key), $values) ?
$values[$this->_key($key)] : false;
}
return $return;
}
public function increment($key, $offset = 1)
{
$key = $this->_key($key);
return $this->_Memcached->increment($key, $offset);
}
public function decrement($key, $offset = 1)
{
$key = $this->_key($key);
return $this->_Memcached->decrement($key, $offset);
}
public function delete($key)
{
$key = $this->_key($key);
return $this->_Memcached->delete($key);
}
public function deleteMany($keys)
{
$cacheKeys = [];
foreach ($keys as $key) {
$cacheKeys[] = $this->_key($key);
}
$success = $this->_Memcached->deleteMulti($cacheKeys);
$return = [];
foreach ($keys as $key) {
$return[$key] = $success;
}
return $return;
}
public function clear($check)
{
if ($check) {
return true;
}
$keys = $this->_Memcached->getAllKeys();
if ($keys === false) {
return false;
}
foreach ($keys as $key) {
if (strpos($key, $this->_config['prefix']) === 0) {
$this->_Memcached->delete($key);
}
}
return true;
}
public function add($key, $value)
{
$duration = $this->_config['duration'];
if ($duration > 30 * DAY) {
$duration = 0;
}
$key = $this->_key($key);
return $this->_Memcached->add($key, $value, $duration);
}
public function groups()
{
if (empty($this->_compiledGroupNames)) {
foreach ($this->_config['groups'] as $group) {
$this->_compiledGroupNames[] = $this->_config['prefix'] . $group;
}
}
$groups = $this->_Memcached->getMulti($this->_compiledGroupNames) ?: [];
if (count($groups) !== count($this->_config['groups'])) {
foreach ($this->_compiledGroupNames as $group) {
if (!isset($groups[$group])) {
$this->_Memcached->set($group, 1, 0);
$groups[$group] = 1;
}
}
ksort($groups);
}
$result = [];
$groups = array_values($groups);
foreach ($this->_config['groups'] as $i => $group) {
$result[] = $group . $groups[$i];
}
return $result;
}
public function clearGroup($group)
{
return (bool)$this->_Memcached->increment($this->_config['prefix'] . $group);
}
}