Response.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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\BrowserKit;
  11. /**
  12. * @author Fabien Potencier <fabien@symfony.com>
  13. */
  14. final class Response
  15. {
  16. private $content;
  17. private $status;
  18. private $headers;
  19. /**
  20. * The headers array is a set of key/value pairs. If a header is present multiple times
  21. * then the value is an array of all the values.
  22. *
  23. * @param string $content The content of the response
  24. * @param int $status The response status code
  25. * @param array $headers An array of headers
  26. */
  27. public function __construct(string $content = '', int $status = 200, array $headers = [])
  28. {
  29. $this->content = $content;
  30. $this->status = $status;
  31. $this->headers = $headers;
  32. }
  33. /**
  34. * Converts the response object to string containing all headers and the response content.
  35. *
  36. * @return string The response with headers and content
  37. */
  38. public function __toString(): string
  39. {
  40. $headers = '';
  41. foreach ($this->headers as $name => $value) {
  42. if (\is_string($value)) {
  43. $headers .= sprintf("%s: %s\n", $name, $value);
  44. } else {
  45. foreach ($value as $headerValue) {
  46. $headers .= sprintf("%s: %s\n", $name, $headerValue);
  47. }
  48. }
  49. }
  50. return $headers."\n".$this->content;
  51. }
  52. /**
  53. * Gets the response content.
  54. *
  55. * @return string The response content
  56. */
  57. public function getContent(): string
  58. {
  59. return $this->content;
  60. }
  61. public function getStatusCode(): int
  62. {
  63. return $this->status;
  64. }
  65. /**
  66. * Gets the response headers.
  67. *
  68. * @return array The response headers
  69. */
  70. public function getHeaders(): array
  71. {
  72. return $this->headers;
  73. }
  74. /**
  75. * Gets a response header.
  76. *
  77. * @return string|array The first header value if $first is true, an array of values otherwise
  78. */
  79. public function getHeader(string $header, bool $first = true)
  80. {
  81. $normalizedHeader = str_replace('-', '_', strtolower($header));
  82. foreach ($this->headers as $key => $value) {
  83. if (str_replace('-', '_', strtolower($key)) === $normalizedHeader) {
  84. if ($first) {
  85. return \is_array($value) ? (\count($value) ? $value[0] : '') : $value;
  86. }
  87. return \is_array($value) ? $value : [$value];
  88. }
  89. }
  90. return $first ? null : [];
  91. }
  92. }