HtmlResponse.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. namespace Drupal\Core\Render;
  3. use Drupal\Core\Cache\CacheableMetadata;
  4. use Drupal\Core\Cache\CacheableResponseInterface;
  5. use Drupal\Core\Cache\CacheableResponseTrait;
  6. use Symfony\Component\HttpFoundation\Response;
  7. /**
  8. * A response that contains and can expose cacheability metadata and attachments.
  9. *
  10. * Supports Drupal's caching concepts: cache tags for invalidation and cache
  11. * contexts for variations.
  12. *
  13. * Supports Drupal's idea of #attached metadata: libraries, settings, http_header and html_head.
  14. *
  15. * @see \Drupal\Core\Cache\CacheableResponse
  16. * @see \Drupal\Core\Render\AttachmentsInterface
  17. * @see \Drupal\Core\Render\AttachmentsTrait
  18. */
  19. class HtmlResponse extends Response implements CacheableResponseInterface, AttachmentsInterface {
  20. use CacheableResponseTrait;
  21. use AttachmentsTrait;
  22. /**
  23. * {@inheritdoc}
  24. */
  25. public function setContent($content) {
  26. // A render array can automatically be converted to a string and set the
  27. // necessary metadata.
  28. if (is_array($content) && (isset($content['#markup']))) {
  29. $content += [
  30. '#attached' => [
  31. 'html_response_attachment_placeholders' => [],
  32. 'placeholders' => [],
  33. ],
  34. ];
  35. $this->addCacheableDependency(CacheableMetadata::createFromRenderArray($content));
  36. $this->setAttachments($content['#attached']);
  37. $content = $content['#markup'];
  38. }
  39. return parent::setContent($content);
  40. }
  41. }