Debian Codegraph @

lib/3rdParty/composer/symfony/http-client/Exception/HttpExceptionTrait.php

raw symbols SCIP
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 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 // Try to guess a better error message using common API error formats
54 // The MIME type isn't explicitly checked because some formats inherit from others
55 // Ex: JSON:API follows RFC 7807 semantics, Hydra can be used in any JSON-LD-compatible format
56 if ($isJson && $body = json_decode($response->getContent(false), true)) {
57 if (isset($body['hydra:title']) || isset($body['hydra:description'])) {
58 // see http://www.hydra-cg.com/spec/latest/core/#description-of-http-status-codes-and-errors
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 // see RFC 7807 and https://jsonapi.org/format/#error-objects
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 }