[CORE][HTTPClient] Add some shortcut functions inspired by pre-v3

This commit is contained in:
Diogo Peralta Cordeiro 2021-10-27 04:20:22 +01:00
parent 3227e1f919
commit 3cdaf6671a
No known key found for this signature in database
GPG Key ID: 18D2D35001FBFAB0

View File

@ -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'])) {