commercetools-8.x-1.2-alpha1/src/PsrCacheAdapter.php
src/PsrCacheAdapter.php
<?php
namespace Drupal\commercetools;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Cache\CacheBackendInterface;
use Psr\SimpleCache\CacheInterface;
/**
* Adapter to bridge Drupal's cache system to PSR-16 Simple Cache.
*/
class PsrCacheAdapter implements CacheInterface {
/**
* The cache backend interface.
*
* @var \Drupal\Core\Cache\CacheBackendInterface
*/
protected CacheBackendInterface $cacheBackend;
/**
* The time service.
*
* @var \Drupal\Component\Datetime\TimeInterface
*/
protected TimeInterface $time;
/**
* Constructs a new SimpleCacheAdapter object.
*
* @param \Drupal\Core\Cache\CacheBackendInterface $cacheBackend
* The cache backend.
* @param \Drupal\Component\Datetime\TimeInterface $time
* The time service.
*/
public function __construct(CacheBackendInterface $cacheBackend, TimeInterface $time) {
$this->cacheBackend = $cacheBackend;
$this->time = $time;
}
/**
* {@inheritdoc}
*/
public function get(string $key, mixed $default = NULL): mixed {
$cache_item = $this->cacheBackend->get($key);
return $cache_item ? $cache_item->data : $default;
}
/**
* {@inheritdoc}
*/
public function set(string $key, mixed $value, int|\DateInterval|null $ttl = NULL): bool {
$this->cacheBackend->set($key, $value, $this->convertTtlToExpire($ttl));
return TRUE;
}
/**
* {@inheritdoc}
*/
public function delete(string $key): bool {
$this->cacheBackend->delete($key);
return TRUE;
}
/**
* {@inheritdoc}
*/
public function clear(): bool {
$this->cacheBackend->deleteAll();
return TRUE;
}
/**
* {@inheritdoc}
*/
public function getMultiple(iterable $keys, mixed $default = NULL): iterable {
$results = [];
foreach ($keys as $key) {
$results[$key] = $this->get($key, $default);
}
return $results;
}
/**
* {@inheritdoc}
*/
public function setMultiple(iterable $values, int|\DateInterval|null $ttl = NULL): bool {
foreach ($values as $key => $value) {
$this->set($key, $value, $ttl);
}
return TRUE;
}
/**
* {@inheritdoc}
*/
public function deleteMultiple(iterable $keys): bool {
foreach ($keys as $key) {
$this->delete($key);
}
return TRUE;
}
/**
* {@inheritdoc}
*/
public function has(string $key): bool {
return (bool) $this->cacheBackend->get($key);
}
/**
* Converts a TTL value into an expiration timestamp.
*
* @param int|\DateInterval|null $ttl
* The TTL value. Can be a number of seconds, a DateInterval object,
* or NULL for an infinite duration.
*
* @return int|null
* A Unix timestamp for when the cache item should expire, or NULL for
* permanent cache.
*/
protected function convertTtlToExpire(int|\DateInterval|null $ttl): ?int {
if (is_null($ttl)) {
return CacheBackendInterface::CACHE_PERMANENT;
}
elseif ($ttl instanceof \DateInterval) {
$expireTimestamp = (new \DateTime())->add($ttl)->getTimestamp();
return $expireTimestamp - $this->time->getRequestTime();
}
else {
return $this->time->getRequestTime() + $ttl;
}
}
}
