JsonResponse.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation;
  11. /**
  12. * Response represents an HTTP response in JSON format.
  13. *
  14. * @author Igor Wiedler <igor@wiedler.ch>
  15. */
  16. class JsonResponse extends Response
  17. {
  18. /**
  19. * Constructor.
  20. *
  21. * @param mixed $data The response data
  22. * @param integer $status The response status code
  23. * @param array $headers An array of response headers
  24. */
  25. public function __construct($data = array(), $status = 200, $headers = array())
  26. {
  27. // root should be JSON object, not array
  28. if (is_array($data) && 0 === count($data)) {
  29. $data = new \ArrayObject();
  30. }
  31. parent::__construct(
  32. json_encode($data),
  33. $status,
  34. array_merge(array('Content-Type' => 'application/json'), $headers)
  35. );
  36. }
  37. /**
  38. * {@inheritDoc}
  39. */
  40. static public function create($data = array(), $status = 200, $headers = array())
  41. {
  42. return new static($data, $status, $headers);
  43. }
  44. }