summaryrefslogtreecommitdiffstatshomepage
path: root/core/lib/Drupal/Core/EventSubscriber/HtmlResponsePlaceholderStrategySubscriber.php
blob: 8b9ab1d016382a13304facca26952c4efda88826 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php

namespace Drupal\Core\EventSubscriber;

use Drupal\Core\Render\HtmlResponse;
use Drupal\Core\Render\Placeholder\PlaceholderStrategyInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * HTML response subscriber to allow for different placeholder strategies.
 *
 * This allows core and contrib to coordinate how to render placeholders;
 * e.g. an EsiRenderStrategy could replace the placeholders with ESI tags,
 * while e.g. a BigPipeRenderStrategy could store the placeholders in a
 * BigPipe service and render them after the main content has been sent to
 * the client.
 */
class HtmlResponsePlaceholderStrategySubscriber implements EventSubscriberInterface {

  /**
   * The placeholder strategy to use.
   *
   * @var \Drupal\Core\Render\Placeholder\PlaceholderStrategyInterface
   */
  protected $placeholderStrategy;

  /**
   * Constructs a HtmlResponsePlaceholderStrategySubscriber object.
   *
   * @param \Drupal\Core\Render\Placeholder\PlaceholderStrategyInterface $placeholder_strategy
   *   The placeholder strategy to use.
   */
  public function __construct(PlaceholderStrategyInterface $placeholder_strategy) {
    $this->placeholderStrategy = $placeholder_strategy;
  }

  /**
   * Processes placeholders for HTML responses.
   *
   * @param \Symfony\Component\HttpKernel\Event\ResponseEvent $event
   *   The event to process.
   */
  public function onRespond(ResponseEvent $event) {
    $response = $event->getResponse();
    if (!$response instanceof HtmlResponse) {
      return;
    }

    $attachments = $response->getAttachments();
    if (empty($attachments['placeholders'])) {
      return;
    }

    $attachments['placeholders'] = $this->placeholderStrategy->processPlaceholders($attachments['placeholders']);

    $response->setAttachments($attachments);
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    // Run shortly before HtmlResponseSubscriber.
    $events[KernelEvents::RESPONSE][] = ['onRespond', 5];
    return $events;
  }

}