AjaxResponse.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace Drupal\Core\Ajax;
  3. use Drupal\Core\Render\BubbleableMetadata;
  4. use Drupal\Core\Render\AttachmentsInterface;
  5. use Drupal\Core\Render\AttachmentsTrait;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. /**
  8. * JSON response object for AJAX requests.
  9. *
  10. * @ingroup ajax
  11. */
  12. class AjaxResponse extends JsonResponse implements AttachmentsInterface {
  13. use AttachmentsTrait;
  14. /**
  15. * The array of ajax commands.
  16. *
  17. * @var array
  18. */
  19. protected $commands = [];
  20. /**
  21. * Add an AJAX command to the response.
  22. *
  23. * @param \Drupal\Core\Ajax\CommandInterface $command
  24. * An AJAX command object implementing CommandInterface.
  25. * @param bool $prepend
  26. * A boolean which determines whether the new command should be executed
  27. * before previously added commands. Defaults to FALSE.
  28. *
  29. * @return $this
  30. * The current AjaxResponse.
  31. */
  32. public function addCommand(CommandInterface $command, $prepend = FALSE) {
  33. if ($prepend) {
  34. array_unshift($this->commands, $command->render());
  35. }
  36. else {
  37. $this->commands[] = $command->render();
  38. }
  39. if ($command instanceof CommandWithAttachedAssetsInterface) {
  40. $assets = $command->getAttachedAssets();
  41. $attachments = [
  42. 'library' => $assets->getLibraries(),
  43. 'drupalSettings' => $assets->getSettings(),
  44. ];
  45. $attachments = BubbleableMetadata::mergeAttachments($this->getAttachments(), $attachments);
  46. $this->setAttachments($attachments);
  47. }
  48. return $this;
  49. }
  50. /**
  51. * Gets all AJAX commands.
  52. *
  53. * @return array
  54. * Returns render arrays for all previously added commands.
  55. */
  56. public function &getCommands() {
  57. return $this->commands;
  58. }
  59. }