HtmlResponsePlaceholderStrategySubscriber.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace Drupal\Core\EventSubscriber;
  3. use Drupal\Core\Render\HtmlResponse;
  4. use Drupal\Core\Render\Placeholder\PlaceholderStrategyInterface;
  5. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. /**
  9. * HTML response subscriber to allow for different placeholder strategies.
  10. *
  11. * This allows core and contrib to coordinate how to render placeholders;
  12. * e.g. an EsiRenderStrategy could replace the placeholders with ESI tags,
  13. * while e.g. a BigPipeRenderStrategy could store the placeholders in a
  14. * BigPipe service and render them after the main content has been sent to
  15. * the client.
  16. */
  17. class HtmlResponsePlaceholderStrategySubscriber implements EventSubscriberInterface {
  18. /**
  19. * The placeholder strategy to use.
  20. *
  21. * @var \Drupal\Core\Render\Placeholder\PlaceholderStrategyInterface
  22. */
  23. protected $placeholderStrategy;
  24. /**
  25. * Constructs a HtmlResponsePlaceholderStrategySubscriber object.
  26. *
  27. * @param \Drupal\Core\Render\Placeholder\PlaceholderStrategyInterface $placeholder_strategy
  28. * The placeholder strategy to use.
  29. */
  30. public function __construct(PlaceholderStrategyInterface $placeholder_strategy) {
  31. $this->placeholderStrategy = $placeholder_strategy;
  32. }
  33. /**
  34. * Processes placeholders for HTML responses.
  35. *
  36. * @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
  37. * The event to process.
  38. */
  39. public function onRespond(FilterResponseEvent $event) {
  40. $response = $event->getResponse();
  41. if (!$response instanceof HtmlResponse) {
  42. return;
  43. }
  44. $attachments = $response->getAttachments();
  45. if (empty($attachments['placeholders'])) {
  46. return;
  47. }
  48. $attachments['placeholders'] = $this->placeholderStrategy->processPlaceholders($attachments['placeholders']);
  49. $response->setAttachments($attachments);
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public static function getSubscribedEvents() {
  55. // Run shortly before HtmlResponseSubscriber.
  56. $events[KernelEvents::RESPONSE][] = ['onRespond', 5];
  57. return $events;
  58. }
  59. }