external_entity-1.0.x-dev/src/Controller/ExternalEntityAPICacheController.php
src/Controller/ExternalEntityAPICacheController.php
<?php
declare(strict_types=1);
namespace Drupal\external_entity\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Cache\CacheBackendInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
/**
* Define the external entity API cache controller.
*/
class ExternalEntityAPICacheController extends ControllerBase {
/**
* @var \Symfony\Component\HttpFoundation\Request|null
*/
protected $request;
/**
* @var \Drupal\Core\Cache\CacheBackendInterface
*/
protected $externalEntityCache;
/**
* Define the controller constructor.
*/
public function __construct(
RequestStack $request_stack,
CacheBackendInterface $external_entity_cache,
) {
$this->request = $request_stack->getCurrentRequest();
$this->externalEntityCache = $external_entity_cache;
}
/**
* {@inheritDoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('request_stack'),
$container->get('cache.external_entity')
);
}
/**
* Invalidate the consumer external entity cache.
*
* @return array|\Symfony\Component\HttpFoundation\Response
* The JSON response object
*/
public function invalidateCache(): Response {
$data = [
'status' => 'error',
];
$request = $this->request;
if ($request->headers->get('Content-Type') === 'application/json') {
$contents = json_decode($request->getContent(), TRUE);
if ($contents === FALSE) {
throw new BadRequestHttpException('Unable to parse request contents.');
}
if (!isset($contents['action'], $contents['cache_tags'])) {
throw new BadRequestHttpException(
'Invalid request. The following data need to exist in the request body:
action, cache_tags.'
);
}
$action = $contents['action'];
$backend_cache = $this->externalEntityCache;
if (
($action === 'update')
&& $backend_cache instanceof CacheTagsInvalidatorInterface
) {
$data['status'] = 'successful';
$backend_cache->invalidateTags($contents['cache_tags']);
}
}
return new JsonResponse($data);
}
}
