<?php
namespace Customize\Entity;
use Eccube\Common\Constant;
use Symfony\Component\Cache\Adapter\AbstractAdapter;
use Symfony\Component\Cache\CacheItem;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Component\Cache\Adapter\MemcachedAdapter;
trait CacheTrait
{
/**
* @var bool
*/
protected $cacheEnabled = true;
/**
* @return MemcachedAdapter
* @throws \ErrorException
*/
private function getConfigCache()
{
$host = env('CACHE_HOST', '127.0.0.1');
$port = env('CACHE_PORT', '11211');
$cacheConnection = 'memcached://' . $host . ':' . $port;
$client = MemcachedAdapter::createConnection($cacheConnection);
if ($adapter = new MemcachedAdapter($client, $namespace = '', $defaultLifetime = Constant::ONE_HOUR)) {
// backofficeのキャッシュクリア/生成管理の仕様と合わせる
$adapter->enableVersioning(false);
}
return $adapter;
}
/***
* @param string $cacheKey
* @param callable $callback
* @param int $ttl
* @return mixed|null
* @throws \Psr\Cache\InvalidArgumentException
*/
public function getCacheByKey(string $cacheKey, callable $callback, int $ttl = Constant::ONE_HOUR)
{
if (!$this->isCacheEnabled()) {
//
return $callback();
}
if (empty($cacheKey) || empty($callback)) return null;
$cache = self::getConfigCache();
return $cache->get($cacheKey, function (ItemInterface $item) use ($callback, $ttl) {
$data = call_user_func($callback);
$item->expiresAfter($ttl);
return $data;
});
}
/**
* @return bool
*/
protected function isCacheEnabled()
{
return $this->cacheEnabled;
}
protected function enableCache()
{
$this->cacheEnabled = true;
}
protected function disableCache()
{
$this->cacheEnabled = false;
}
/**
* @param callable|string $masterCacheKey
* @param string $device
* @param string[] $cacheKeys
* @return AbstractAdapter
* @throws \ErrorException
* @throws \Psr\Cache\InvalidArgumentException
*/
protected function handleMasterCache($masterCacheKey, $device, $cacheKeys)
{
//
$masterCache = $this->getConfigCache();
//
if (is_callable($masterCacheKey)) {
//
$masterCacheKey = $masterCacheKey();
}
/**
* @var CacheItem $masterCacheItem
*/
if ($masterCacheItem = $masterCache->getItem($masterCacheKey)) {
//
$masterCacheData = unserialize(base64_decode($masterCacheItem->get()));
} else {
//
$masterCacheData = [];
}
//
if (!isset($masterCacheData[$device])) {
//
$masterCacheData[$device] = [];
}
//
foreach ($cacheKeys as $cacheKey) {
//
if (!in_array($cacheKey, $masterCacheData[$device])) {
//
$masterCacheData[$device][] = $cacheKey;
}
}
//
$masterCache->save($masterCacheItem->set(base64_encode(serialize($masterCacheData))));
//
return $masterCache;
}
}