HttpExceptionTrait.php 2.8 KB

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