From 3cdaf6671a280dad7527d86d9e4bbcd9ed4cceec Mon Sep 17 00:00:00 2001 From: Diogo Peralta Cordeiro Date: Wed, 27 Oct 2021 04:20:22 +0100 Subject: [PATCH] [CORE][HTTPClient] Add some shortcut functions inspired by pre-v3 --- src/Core/HTTPClient.php | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/Core/HTTPClient.php b/src/Core/HTTPClient.php index 09fb00218a..d68d40955a 100644 --- a/src/Core/HTTPClient.php +++ b/src/Core/HTTPClient.php @@ -21,6 +21,9 @@ declare(strict_types = 1); namespace App\Core; +use InvalidArgumentException; +use Symfony\Component\HttpClient\Exception\ClientException as HTTPClientException; +use Symfony\Component\HttpClient\Exception\TransportException; use Symfony\Contracts\HttpClient\HttpClientInterface; use Symfony\Contracts\HttpClient\ResponseInterface; @@ -46,6 +49,28 @@ abstract class HTTPClient self::$client = $client; } + public static function statusCodeIsOkay(int|ResponseInterface $status): bool + { + if (!\is_int($status)) { + $status = $status->getStatusCode(); + } + return $status >= 200 && $status < 300; + } + + public static function getEffectiveUrl(ResponseInterface $head): string + { + try { + // This must come before getInfo given that Symfony HTTPClient is lazy (thus forcing curl exec) + $head->getHeaders(); + // @codeCoverageIgnoreStart + } catch (HTTPClientException|TransportException $e) { + throw new InvalidArgumentException(previous: $e); + // @codeCoverageIgnoreEnd + } + // The last effective url (after getHeaders, so it follows redirects) + return $head->getInfo('url'); + } + public static function __callStatic(string $name, array $args) { if (\in_array(mb_strtoupper($name), ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH'])) {