| 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\HttpClient\Exception; |
| 13 |
|
| 14 |
use Symfony\Contracts\HttpClient\ResponseInterface; |
| 15 |
|
| 16 |
/** |
| 17 |
* @author Nicolas Grekas <[email protected]> |
| 18 |
* |
| 19 |
* @internal |
| 20 |
*/ |
| 21 |
trait HttpExceptionTrait |
| 22 |
{ |
| 23 |
private $response; |
| 24 |
|
| 25 |
public function __construct(ResponseInterface $response) |
| 26 |
{ |
| 27 |
$this->response = $response; |
| 28 |
$code = $response->getInfo('http_code'); |
| 29 |
$url = $response->getInfo('url'); |
| 30 |
$message = sprintf('HTTP %d returned for "%s".', $code, $url); |
| 31 |
|
| 32 |
$httpCodeFound = false; |
| 33 |
$isJson = false; |
| 34 |
foreach (array_reverse($response->getInfo('response_headers')) as $h) { |
| 35 |
if (str_starts_with($h, 'HTTP/')) { |
| 36 |
if ($httpCodeFound) { |
| 37 |
break; |
| 38 |
} |
| 39 |
|
| 40 |
$message = sprintf('%s returned for "%s".', $h, $url); |
| 41 |
$httpCodeFound = true; |
| 42 |
} |
| 43 |
|
| 44 |
if (0 === stripos($h, 'content-type:')) { |
| 45 |
if (preg_match('/\bjson\b/i', $h)) { |
| 46 |
$isJson = true; |
| 47 |
} |
| 48 |
|
| 49 |
if ($httpCodeFound) { |
| 50 |
break; |
| 51 |
} |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
// Try to guess a better error message using common API error formats |
| 56 |
// The MIME type isn't explicitly checked because some formats inherit from others |
| 57 |
// Ex: JSON:API follows RFC 7807 semantics, Hydra can be used in any JSON-LD-compatible format |
| 58 |
if ($isJson && $body = json_decode($response->getContent(false), true)) { |
| 59 |
if (isset($body['hydra:title']) || isset($body['hydra:description'])) { |
| 60 |
// see http://www.hydra-cg.com/spec/latest/core/#description-of-http-status-codes-and-errors |
| 61 |
$separator = isset($body['hydra:title'], $body['hydra:description']) ? "\n\n" : ''; |
| 62 |
$message = ($body['hydra:title'] ?? '').$separator.($body['hydra:description'] ?? ''); |
| 63 |
} elseif ((isset($body['title']) || isset($body['detail'])) |
| 64 |
&& (\is_scalar($body['title'] ?? '') && \is_scalar($body['detail'] ?? ''))) { |
| 65 |
// see RFC 7807 and https://jsonapi.org/format/#error-objects |
| 66 |
$separator = isset($body['title'], $body['detail']) ? "\n\n" : ''; |
| 67 |
$message = ($body['title'] ?? '').$separator.($body['detail'] ?? ''); |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
parent::__construct($message, $code); |
| 72 |
} |
| 73 |
|
| 74 |
public function getResponse(): ResponseInterface |
| 75 |
{ |
| 76 |
return $this->response; |
| 77 |
} |
| 78 |
} |
| 79 |
|