| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace Symfony\Component\HttpClient\Exception; |
| 13 |
|
| 14 |
use Symfony\Contracts\HttpClient\ResponseInterface; |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
trait HttpExceptionTrait |
| 22 |
{ |
| 23 |
public function __construct( |
| 24 |
private ResponseInterface $response, |
| 25 |
) { |
| 26 |
$code = $response->getInfo('http_code'); |
| 27 |
$url = $response->getInfo('url'); |
| 28 |
$message = \sprintf('HTTP %d returned for "%s".', $code, $url); |
| 29 |
|
| 30 |
$httpCodeFound = false; |
| 31 |
$isJson = false; |
| 32 |
foreach (array_reverse($response->getInfo('response_headers')) as $h) { |
| 33 |
if (str_starts_with($h, 'HTTP/')) { |
| 34 |
if ($httpCodeFound) { |
| 35 |
break; |
| 36 |
} |
| 37 |
|
| 38 |
$message = \sprintf('%s returned for "%s".', $h, $url); |
| 39 |
$httpCodeFound = true; |
| 40 |
} |
| 41 |
|
| 42 |
if (0 === stripos($h, 'content-type:')) { |
| 43 |
if (preg_match('/\bjson\b/i', $h)) { |
| 44 |
$isJson = true; |
| 45 |
} |
| 46 |
|
| 47 |
if ($httpCodeFound) { |
| 48 |
break; |
| 49 |
} |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
if ($isJson && $body = json_decode($response->getContent(false), true)) { |
| 57 |
if (isset($body['hydra:title']) || isset($body['hydra:description'])) { |
| 58 |
|
| 59 |
$separator = isset($body['hydra:title'], $body['hydra:description']) ? "\n\n" : ''; |
| 60 |
$message = ($body['hydra:title'] ?? '').$separator.($body['hydra:description'] ?? ''); |
| 61 |
} elseif ((isset($body['title']) || isset($body['detail'])) |
| 62 |
&& (\is_scalar($body['title'] ?? '') && \is_scalar($body['detail'] ?? ''))) { |
| 63 |
|
| 64 |
$separator = isset($body['title'], $body['detail']) ? "\n\n" : ''; |
| 65 |
$message = ($body['title'] ?? '').$separator.($body['detail'] ?? ''); |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
parent::__construct($message, $code); |
| 70 |
} |
| 71 |
|
| 72 |
public function getResponse(): ResponseInterface |
| 73 |
{ |
| 74 |
return $this->response; |
| 75 |
} |
| 76 |
} |