JsonResponse.php 1.08 KB
Newer Older
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
<?php

namespace Drupal\bootstrap;

use Drupal\Component\Serialization\Json;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class JsonResponse.
 */
class JsonResponse extends Response {

  /**
   * The decoded JSON array.
   *
   * @var array
   */
  protected $json;

  /**
   * {@inheritdoc}
   */
  public function __construct($content = '', $status = 200, array $headers = []) {
    parent::__construct($content, $status, $headers);
    $this->json = Json::decode($content ?: '[]') ?: [];
  }

  /**
   * Creates a new JsonResponse object from a Symfony Response object.
   *
   * @param \Symfony\Component\HttpFoundation\Response $response
   *   A Symfony Response object.
   *
   * @return \Drupal\bootstrap\JsonResponse
   *   A JsonResponse object.
   */
  public static function createFromResponse(Response $response) {
    return new static($response->getContent(), $response->getStatusCode(), $response->headers->all());
  }

  /**
   * Retrieves the JSON array.
   *
   * @return array
   *   The JSON array.
   */
  public function getJson(): array {
    return $this->json;
  }

}