ResourceObjectNormalizerCacherTest.php in Drupal 9
File
core/modules/jsonapi/tests/src/Kernel/EventSubscriber/ResourceObjectNormalizerCacherTest.php
View source
<?php
namespace Drupal\Tests\jsonapi\Kernel\EventSubscriber;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\jsonapi\EventSubscriber\ResourceObjectNormalizationCacher;
use Drupal\jsonapi\JsonApiResource\ResourceObject;
use Drupal\jsonapi\Normalizer\Value\CacheableNormalization;
use Drupal\KernelTests\KernelTestBase;
use Drupal\user\Entity\User;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
class ResourceObjectNormalizerCacherTest extends KernelTestBase {
protected static $modules = [
'system',
'serialization',
'jsonapi',
'user',
];
protected $resourceTypeRepository;
protected $serializer;
protected $cacher;
protected function setUp() : void {
parent::setUp();
$this
->installEntitySchema('user');
$this
->installSchema('system', [
'sequences',
]);
$this
->installSchema('user', [
'users_data',
]);
$this->resourceTypeRepository = $this->container
->get('jsonapi.resource_type.repository');
$this->serializer = $this->container
->get('jsonapi.serializer');
$this->cacher = $this->container
->get('jsonapi.normalization_cacher');
}
public function testLinkNormalizationCacheability() {
$user = User::create([
'name' => $this
->randomMachineName(),
'pass' => $this
->randomString(),
]);
$user
->save();
$resource_type = $this->resourceTypeRepository
->get($user
->getEntityTypeId(), $user
->bundle());
$resource_object = ResourceObject::createFromEntity($resource_type, $user);
$cache_tag_to_invalidate = 'link_normalization';
$normalized_links = $this->serializer
->normalize($resource_object
->getLinks(), 'api_json')
->withCacheableDependency((new CacheableMetadata())
->addCacheTags([
$cache_tag_to_invalidate,
]));
assert($normalized_links instanceof CacheableNormalization);
$normalization_parts = [
ResourceObjectNormalizationCacher::RESOURCE_CACHE_SUBSET_BASE => [
'type' => CacheableNormalization::permanent($resource_object
->getTypeName()),
'id' => CacheableNormalization::permanent($resource_object
->getId()),
'links' => $normalized_links,
],
ResourceObjectNormalizationCacher::RESOURCE_CACHE_SUBSET_FIELDS => [],
];
$this->cacher
->saveOnTerminate($resource_object, $normalization_parts);
$event = $this
->prophesize(TerminateEvent::class);
$this->cacher
->onTerminate($event
->reveal());
$this
->assertNotFalse((bool) $this->cacher
->get($resource_object));
Cache::invalidateTags([
$cache_tag_to_invalidate,
]);
$this
->assertFalse((bool) $this->cacher
->get($resource_object));
}
}