Skip to content
Snippets Groups Projects

Resolve #3521173 "Process attachments cssjs"

Files
12
<?php
declare(strict_types=1);
namespace Drupal\Core\EventSubscriber;
use Drupal\Component\Utility\Html;
use Drupal\Core\Render\AttachmentsResponseProcessorInterface;
use Drupal\Core\Render\HtmlResponse;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Adds assets on responses to HTMX requests.
*
* @see \Drupal\Core\Render\Hypermedia\HtmxResponseAttachmentsProcessor
*/
class HtmxResponseSubscriber implements EventSubscriberInterface {
/**
* Constructs a HtmxResponseSubscriber object.
*/
public function __construct(
protected readonly RequestStack $requestStack,
protected \Closure $attachmentsProcessor,
) {}
/**
* Add assemble and attachments add HTMX attributes.
*
* @see \Drupal\Core\EventSubscriber\HtmlResponseSubscriber::onRespond
*/
public function onRespond(ResponseEvent $event): void {
$response = $event->getResponse();
$requestHeaders = $this->requestStack->getCurrentRequest()->headers;
if (!($response instanceof HtmlResponse && $requestHeaders->has('HX-Request'))) {
// Only operate on HTML responses from an HTMX request.
return;
}
$processedResponse = $this->getAttachementsProcessor()->processAttachments($response);
if (!($processedResponse instanceof HtmlResponse)) {
throw new \TypeError("ResponseEvent::setResponse() requires an HtmlResponse object");
}
$event->setResponse($processedResponse);
}
protected function getAttachementsProcessor(): AttachmentsResponseProcessorInterface {
return ($this->attachmentsProcessor)();
}
/**
* Sets \Drupal\Component\Utility\Html::$isAjax to TRUE.
*
* @param \Symfony\Component\HttpKernel\Event\RequestEvent $event
* The request event, which contains the current request.
*/
public function onRequest(RequestEvent $event) {
$requestHeaders = $event->getRequest()->headers;
// Pass to the Html class that the current request is an Ajax request.
if ($requestHeaders->has('HX-Request')) {
Html::setIsAjax(TRUE);
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
return [
// Our method needs to run before the HtmlResponseSubscriber(weight 0).
KernelEvents::RESPONSE => ['onRespond', 100],
KernelEvents::REQUEST => ['onRequest', 50],
];
}
}
Loading