HttpExceptionTrait.php 2.7 KB

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