| 1 |
<?php |
| 2 |
|
| 3 |
/* |
| 4 |
* This file is part of the Symfony package. |
| 5 |
* |
| 6 |
* (c) Fabien Potencier <[email protected]> |
| 7 |
* |
| 8 |
* For the full copyright and license information, please view the LICENSE |
| 9 |
* file that was distributed with this source code. |
| 10 |
*/ |
| 11 |
|
| 12 |
namespace Symfony\Component\BrowserKit; |
| 13 |
|
| 14 |
/** |
| 15 |
* @author Fabien Potencier <[email protected]> |
| 16 |
*/ |
| 17 |
final class Response |
| 18 |
{ |
| 19 |
private $content; |
| 20 |
private $status; |
| 21 |
private $headers; |
| 22 |
|
| 23 |
/** |
| 24 |
* The headers array is a set of key/value pairs. If a header is present multiple times |
| 25 |
* then the value is an array of all the values. |
| 26 |
* |
| 27 |
* @param string $content The content of the response |
| 28 |
* @param int $status The response status code |
| 29 |
* @param array $headers An array of headers |
| 30 |
*/ |
| 31 |
public function __construct(string $content = '', int $status = 200, array $headers = []) |
| 32 |
{ |
| 33 |
$this->content = $content; |
| 34 |
$this->status = $status; |
| 35 |
$this->headers = $headers; |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Converts the response object to string containing all headers and the response content. |
| 40 |
*/ |
| 41 |
public function __toString(): string |
| 42 |
{ |
| 43 |
$headers = ''; |
| 44 |
foreach ($this->headers as $name => $value) { |
| 45 |
if (\is_string($value)) { |
| 46 |
$headers .= sprintf("%s: %s\n", $name, $value); |
| 47 |
} else { |
| 48 |
foreach ($value as $headerValue) { |
| 49 |
$headers .= sprintf("%s: %s\n", $name, $headerValue); |
| 50 |
} |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
return $headers."\n".$this->content; |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* Gets the response content. |
| 59 |
*/ |
| 60 |
public function getContent(): string |
| 61 |
{ |
| 62 |
return $this->content; |
| 63 |
} |
| 64 |
|
| 65 |
public function getStatusCode(): int |
| 66 |
{ |
| 67 |
return $this->status; |
| 68 |
} |
| 69 |
|
| 70 |
/** |
| 71 |
* Gets the response headers. |
| 72 |
*/ |
| 73 |
public function getHeaders(): array |
| 74 |
{ |
| 75 |
return $this->headers; |
| 76 |
} |
| 77 |
|
| 78 |
/** |
| 79 |
* Gets a response header. |
| 80 |
* |
| 81 |
* @return string|array|null The first header value if $first is true, an array of values otherwise |
| 82 |
*/ |
| 83 |
public function getHeader(string $header, bool $first = true) |
| 84 |
{ |
| 85 |
$normalizedHeader = str_replace('-', '_', strtolower($header)); |
| 86 |
foreach ($this->headers as $key => $value) { |
| 87 |
if (str_replace('-', '_', strtolower($key)) === $normalizedHeader) { |
| 88 |
if ($first) { |
| 89 |
return \is_array($value) ? (\count($value) ? $value[0] : '') : $value; |
| 90 |
} |
| 91 |
|
| 92 |
return \is_array($value) ? $value : [$value]; |
| 93 |
} |
| 94 |
} |
| 95 |
|
| 96 |
return $first ? null : []; |
| 97 |
} |
| 98 |
} |
| 99 |
|