<?php
namespace Cake\Cache\Engine;
use APCuIterator;
use Cake\Cache\CacheEngine;
class ApcuEngine extends CacheEngine
{
protected $_compiledGroupNames = [];
public function init(array $config = [])
{
if (!extension_loaded('apcu')) {
return false;
}
return parent::init($config);
}
public function write($key, $value)
{
$key = $this->_key($key);
$duration = $this->_config['duration'];
return apcu_store($key, $value, $duration);
}
public function read($key)
{
$key = $this->_key($key);
return apcu_fetch($key);
}
public function increment($key, $offset = 1)
{
$key = $this->_key($key);
return apcu_inc($key, $offset);
}
public function decrement($key, $offset = 1)
{
$key = $this->_key($key);
return apcu_dec($key, $offset);
}
public function delete($key)
{
$key = $this->_key($key);
return apcu_delete($key);
}
public function clear($check)
{
if ($check) {
return true;
}
if (class_exists('APCuIterator', false)) {
$iterator = new APCuIterator(
'/^' . preg_quote($this->_config['prefix'], '/') . '/',
APC_ITER_NONE
);
apcu_delete($iterator);
return true;
}
$cache = apcu_cache_info(); foreach ($cache['cache_list'] as $key) {
if (strpos($key['info'], $this->_config['prefix']) === 0) {
apcu_delete($key['info']);
}
}
return true;
}
public function add($key, $value)
{
$key = $this->_key($key);
$duration = $this->_config['duration'];
return apcu_add($key, $value, $duration);
}
public function groups()
{
if (empty($this->_compiledGroupNames)) {
foreach ($this->_config['groups'] as $group) {
$this->_compiledGroupNames[] = $this->_config['prefix'] . $group;
}
}
$success = false;
$groups = apcu_fetch($this->_compiledGroupNames, $success);
if ($success && count($groups) !== count($this->_config['groups'])) {
foreach ($this->_compiledGroupNames as $group) {
if (!isset($groups[$group])) {
$value = 1;
if (apcu_store($group, $value) === false) {
$this->warning(
sprintf('Failed to store key "%s" with value "%s" into APCu cache.', $group, $value)
);
}
$groups[$group] = $value;
}
}
ksort($groups);
}
$result = [];
$groups = array_values($groups);
foreach ($this->_config['groups'] as $i => $group) {
$result[] = $group . $groups[$i];
}
return $result;
}
public function clearGroup($group)
{
$success = false;
apcu_inc($this->_config['prefix'] . $group, 1, $success);
return $success;
}
}