sparql_entity_storage-8.x-1.0-alpha8/tests/src/Kernel/TestMemoryBackend.php
tests/src/Kernel/TestMemoryBackend.php
<?php
declare(strict_types=1);
namespace Drupal\Tests\sparql_entity_storage\Kernel;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\MemoryCache\MemoryCache;
use Drupal\Core\State\StateInterface;
/**
* A variant of the memory cache backend that allows to log called methods.
*/
class TestMemoryBackend extends MemoryCache {
/**
* The name of the state variable used to log the calls.
*/
const STATE_VARIABLE_NAME = 'views_test_memory_backend';
/**
* The state storage service.
*
* @var \Drupal\Core\State\StateInterface
*/
protected StateInterface $state;
/**
* Constructs a TestMemoryBackend object.
*
* @param \Drupal\Component\Datetime\TimeInterface $time
* The time service.
* @param \Drupal\Core\State\StateInterface $state
* The state storage service.
*/
public function __construct(TimeInterface $time, StateInterface $state) {
parent::__construct($time);
$this->state = $state;
}
/**
* Logs the calls to the state backend.
*
* @param string $method
* The method that was called.
* @param string $cid
* The CID related to the call.
* @param bool $has_return
* Whether the call had return values. Defaults to FALSE. Always false for
* set() calls.
*/
protected function log(string $method, string $cid, bool $has_return = FALSE): void {
$calls = $this->state->get(self::STATE_VARIABLE_NAME, []);
$calls[] = [
'method' => $method,
'cid' => $cid,
'has_return' => $has_return,
];
$this->state->set(self::STATE_VARIABLE_NAME, $calls);
}
/**
* {@inheritdoc}
*/
public function get($cid, $allow_invalid = FALSE) {
$return = parent::get($cid, $allow_invalid);
$this->log(__FUNCTION__, $cid, !empty($return));
return $return;
}
/**
* {@inheritdoc}
*/
public function set($cid, $data, $expire = Cache::PERMANENT, ?array $tags = []): void {
parent::set($cid, $data, $expire, $tags);
$this->log(__FUNCTION__, $cid);
}
}
