1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
<?php
namespace Commercetools\Core\Cache;
use Cache\Adapter\Apcu\ApcuCachePool;
use Cache\Adapter\Doctrine\DoctrineCachePool;
use Cache\Adapter\Filesystem\FilesystemCachePool;
use Cache\Adapter\Redis\RedisCachePool;
use Doctrine\Common\Cache\Cache;
use Commercetools\Core\Error\Message;
use Commercetools\Core\Error\InvalidArgumentException;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use Psr\Cache\CacheItemPoolInterface;
use Psr\SimpleCache\CacheInterface;
class CacheAdapterFactory
{
private $cacheDir;
protected $callbacks = [];
public function __construct($cacheDir = null)
{
$this->cacheDir = !is_null($cacheDir) ? $cacheDir : realpath(__DIR__ . '/../..');
$this->registerCallback(
function ($cache) {
if ($cache instanceof Cache) {
return new DoctrineCachePool($cache);
}
return null;
}
)
->registerCallback(
function ($cache) {
if ($cache instanceof \Redis) {
return new RedisCachePool($cache);
}
return null;
}
);
}
public function registerCallback(callable $callback)
{
$this->callbacks[] = $callback;
return $this;
}
public function get($cache = null)
{
if (is_null($cache)) {
$cache = $this->getDefaultCache();
}
if ($cache instanceof CacheItemPoolInterface) {
return $cache;
}
if ($cache instanceof CacheInterface) {
return $cache;
}
foreach ($this->callbacks as $callBack) {
$result = call_user_func($callBack, $cache);
if ($result instanceof CacheItemPoolInterface) {
return $result;
}
if ($result instanceof CacheInterface) {
return $result;
}
}
throw new InvalidArgumentException(Message::INVALID_CACHE_ADAPTER);
}
protected function getDefaultCache()
{
if (extension_loaded('apcu')) {
return new ApcuCachePool();
}
if (class_exists('\Cache\Adapter\Filesystem\FilesystemCachePool')) {
$filesystemAdapter = new Local($this->cacheDir);
$filesystem = new Filesystem($filesystemAdapter);
return new FilesystemCachePool($filesystem);
}
return null;
}
}