Response.php 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace Illuminate\Http;
  3. use ArrayObject;
  4. use JsonSerializable;
  5. use Illuminate\Support\Traits\Macroable;
  6. use Illuminate\Contracts\Support\Jsonable;
  7. use Illuminate\Contracts\Support\Arrayable;
  8. use Illuminate\Contracts\Support\Renderable;
  9. use Symfony\Component\HttpFoundation\Response as BaseResponse;
  10. class Response extends BaseResponse
  11. {
  12. use ResponseTrait, Macroable {
  13. Macroable::__call as macroCall;
  14. }
  15. /**
  16. * Set the content on the response.
  17. *
  18. * @param mixed $content
  19. * @return $this
  20. */
  21. public function setContent($content)
  22. {
  23. $this->original = $content;
  24. // If the content is "JSONable" we will set the appropriate header and convert
  25. // the content to JSON. This is useful when returning something like models
  26. // from routes that will be automatically transformed to their JSON form.
  27. if ($this->shouldBeJson($content)) {
  28. $this->header('Content-Type', 'application/json');
  29. $content = $this->morphToJson($content);
  30. }
  31. // If this content implements the "Renderable" interface then we will call the
  32. // render method on the object so we will avoid any "__toString" exceptions
  33. // that might be thrown and have their errors obscured by PHP's handling.
  34. elseif ($content instanceof Renderable) {
  35. $content = $content->render();
  36. }
  37. parent::setContent($content);
  38. return $this;
  39. }
  40. /**
  41. * Determine if the given content should be turned into JSON.
  42. *
  43. * @param mixed $content
  44. * @return bool
  45. */
  46. protected function shouldBeJson($content)
  47. {
  48. return $content instanceof Arrayable ||
  49. $content instanceof Jsonable ||
  50. $content instanceof ArrayObject ||
  51. $content instanceof JsonSerializable ||
  52. is_array($content);
  53. }
  54. /**
  55. * Morph the given content into JSON.
  56. *
  57. * @param mixed $content
  58. * @return string
  59. */
  60. protected function morphToJson($content)
  61. {
  62. if ($content instanceof Jsonable) {
  63. return $content->toJson();
  64. } elseif ($content instanceof Arrayable) {
  65. return json_encode($content->toArray());
  66. }
  67. return json_encode($content);
  68. }
  69. }