Prefix all sprintf() calls

This commit is contained in:
Alexander M. Turek
2024-06-20 17:52:34 +02:00
parent cb1de10f95
commit f53dab37bd
36 changed files with 126 additions and 126 deletions

View File

@@ -165,7 +165,7 @@ final class AmpHttpClient implements HttpClientInterface, LoggerAwareInterface,
foreach ($pushedResponses as [$pushedUrl, $pushDeferred]) {
$pushDeferred->fail(new CancelledException());
$this->logger?->debug(sprintf('Unused pushed response: "%s"', $pushedUrl));
$this->logger?->debug(\sprintf('Unused pushed response: "%s"', $pushedUrl));
}
}

View File

@@ -44,7 +44,7 @@ class CachingHttpClient implements HttpClientInterface, ResetInterface
array $defaultOptions = [],
) {
if (!class_exists(HttpClientKernel::class)) {
throw new \LogicException(sprintf('Using "%s" requires that the HttpKernel component version 4.3 or higher is installed, try running "composer require symfony/http-kernel:^5.4".', __CLASS__));
throw new \LogicException(\sprintf('Using "%s" requires that the HttpKernel component version 4.3 or higher is installed, try running "composer require symfony/http-kernel:^5.4".', __CLASS__));
}
$kernel = new HttpClientKernel($client);

View File

@@ -96,17 +96,17 @@ final class ServerSentEvent extends DataChunk implements ChunkInterface
}
if ('' === $this->data) {
throw new JsonException(sprintf('Server-Sent Event%s data is empty.', '' !== $this->id ? sprintf(' "%s"', $this->id) : ''));
throw new JsonException(\sprintf('Server-Sent Event%s data is empty.', '' !== $this->id ? \sprintf(' "%s"', $this->id) : ''));
}
try {
$jsonData = json_decode($this->data, true, 512, \JSON_BIGINT_AS_STRING | \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new JsonException(sprintf('Decoding Server-Sent Event%s failed: ', '' !== $this->id ? sprintf(' "%s"', $this->id) : '').$e->getMessage(), $e->getCode());
throw new JsonException(\sprintf('Decoding Server-Sent Event%s failed: ', '' !== $this->id ? \sprintf(' "%s"', $this->id) : '').$e->getMessage(), $e->getCode());
}
if (!\is_array($jsonData)) {
throw new JsonException(sprintf('JSON content was expected to decode to an array, "%s" returned in Server-Sent Event%s.', get_debug_type($jsonData), '' !== $this->id ? sprintf(' "%s"', $this->id) : ''));
throw new JsonException(\sprintf('JSON content was expected to decode to an array, "%s" returned in Server-Sent Event%s.', get_debug_type($jsonData), '' !== $this->id ? \sprintf(' "%s"', $this->id) : ''));
}
return $this->jsonData = $jsonData;

View File

@@ -152,14 +152,14 @@ final class CurlHttpClient implements HttpClientInterface, LoggerAwareInterface,
if (\is_array($options['auth_ntlm'])) {
$count = \count($options['auth_ntlm']);
if ($count <= 0 || $count > 2) {
throw new InvalidArgumentException(sprintf('Option "auth_ntlm" must contain 1 or 2 elements, %d given.', $count));
throw new InvalidArgumentException(\sprintf('Option "auth_ntlm" must contain 1 or 2 elements, %d given.', $count));
}
$options['auth_ntlm'] = implode(':', $options['auth_ntlm']);
}
if (!\is_string($options['auth_ntlm'])) {
throw new InvalidArgumentException(sprintf('Option "auth_ntlm" must be a string or an array, "%s" given.', get_debug_type($options['auth_ntlm'])));
throw new InvalidArgumentException(\sprintf('Option "auth_ntlm" must be a string or an array, "%s" given.', get_debug_type($options['auth_ntlm'])));
}
$curlopts[\CURLOPT_USERPWD] = $options['auth_ntlm'];
@@ -297,28 +297,28 @@ final class CurlHttpClient implements HttpClientInterface, LoggerAwareInterface,
unset($multi->pushedResponses[$url]);
if (self::acceptPushForRequest($method, $options, $pushedResponse)) {
$this->logger?->debug(sprintf('Accepting pushed response: "%s %s"', $method, $url));
$this->logger?->debug(\sprintf('Accepting pushed response: "%s %s"', $method, $url));
// Reinitialize the pushed response with request's options
$ch = $pushedResponse->handle;
$pushedResponse = $pushedResponse->response;
$pushedResponse->__construct($multi, $url, $options, $this->logger);
} else {
$this->logger?->debug(sprintf('Rejecting pushed response: "%s"', $url));
$this->logger?->debug(\sprintf('Rejecting pushed response: "%s"', $url));
$pushedResponse = null;
}
}
if (!$pushedResponse) {
$ch = curl_init();
$this->logger?->info(sprintf('Request: "%s %s"', $method, $url));
$this->logger?->info(\sprintf('Request: "%s %s"', $method, $url));
$curlopts += [\CURLOPT_SHARE => $multi->share];
}
foreach ($curlopts as $opt => $value) {
if (null !== $value && !curl_setopt($ch, $opt, $value) && \CURLOPT_CERTINFO !== $opt && (!\defined('CURLOPT_HEADEROPT') || \CURLOPT_HEADEROPT !== $opt)) {
$constantName = $this->findConstantName($opt);
throw new TransportException(sprintf('Curl option "%s" is not supported.', $constantName ?? $opt));
throw new TransportException(\sprintf('Curl option "%s" is not supported.', $constantName ?? $opt));
}
}
@@ -385,7 +385,7 @@ final class CurlHttpClient implements HttpClientInterface, LoggerAwareInterface,
{
if (!$eof && \strlen($buffer) < $length) {
if (!\is_string($data = $body($length))) {
throw new TransportException(sprintf('The return value of the "body" option callback must be a string, "%s" returned.', get_debug_type($data)));
throw new TransportException(\sprintf('The return value of the "body" option callback must be a string, "%s" returned.', get_debug_type($data)));
}
$buffer .= $data;
@@ -551,7 +551,7 @@ final class CurlHttpClient implements HttpClientInterface, LoggerAwareInterface,
foreach ($options as $opt => $optValue) {
if (isset($curloptsToConfig[$opt])) {
$constName = $this->findConstantName($opt) ?? $opt;
throw new InvalidArgumentException(sprintf('Cannot set "%s" with "extra.curl", use option "%s" instead.', $constName, $curloptsToConfig[$opt]));
throw new InvalidArgumentException(\sprintf('Cannot set "%s" with "extra.curl", use option "%s" instead.', $constName, $curloptsToConfig[$opt]));
}
if (\in_array($opt, $methodOpts, true)) {
@@ -560,7 +560,7 @@ final class CurlHttpClient implements HttpClientInterface, LoggerAwareInterface,
if (\in_array($opt, $curloptsToCheck, true)) {
$constName = $this->findConstantName($opt) ?? $opt;
throw new InvalidArgumentException(sprintf('Cannot set "%s" with "extra.curl".', $constName));
throw new InvalidArgumentException(\sprintf('Cannot set "%s" with "extra.curl".', $constName));
}
}
}

View File

@@ -233,8 +233,8 @@ final class HttpClientDataCollector extends DataCollector implements LateDataCol
}
if (preg_match('/^> ([A-Z]+)/', $line, $match)) {
$command[] = sprintf('--request %s', $match[1]);
$command[] = sprintf('--url %s', escapeshellarg($url));
$command[] = \sprintf('--request %s', $match[1]);
$command[] = \sprintf('--url %s', escapeshellarg($url));
continue;
}

View File

@@ -108,7 +108,7 @@ final class EventSourceHttpClient implements HttpClientInterface, ResetInterface
if (preg_match('/^text\/event-stream(;|$)/i', $context->getHeaders()['content-type'][0] ?? '')) {
$state->buffer = '';
} elseif (null !== $lastError || (null !== $state->buffer && 200 === $context->getStatusCode())) {
throw new EventSourceException(sprintf('Response content-type is "%s" while "text/event-stream" was expected for "%s".', $context->getHeaders()['content-type'][0] ?? '', $context->getInfo('url')));
throw new EventSourceException(\sprintf('Response content-type is "%s" while "text/event-stream" was expected for "%s".', $context->getHeaders()['content-type'][0] ?? '', $context->getInfo('url')));
} else {
$context->passthru();
}

View File

@@ -27,7 +27,7 @@ trait HttpExceptionTrait
$this->response = $response;
$code = $response->getInfo('http_code');
$url = $response->getInfo('url');
$message = sprintf('HTTP %d returned for "%s".', $code, $url);
$message = \sprintf('HTTP %d returned for "%s".', $code, $url);
$httpCodeFound = false;
$isJson = false;
@@ -37,7 +37,7 @@ trait HttpExceptionTrait
break;
}
$message = sprintf('%s returned for "%s".', $h, $url);
$message = \sprintf('%s returned for "%s".', $h, $url);
$httpCodeFound = true;
}

View File

@@ -45,7 +45,7 @@ trait HttpClientTrait
{
if (null !== $method) {
if (\strlen($method) !== strspn($method, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')) {
throw new InvalidArgumentException(sprintf('Invalid HTTP method "%s", only uppercase letters are accepted.', $method));
throw new InvalidArgumentException(\sprintf('Invalid HTTP method "%s", only uppercase letters are accepted.', $method));
}
if (!$method) {
throw new InvalidArgumentException('The HTTP method cannot be empty.');
@@ -60,11 +60,11 @@ trait HttpClientTrait
$options['buffer'] = static function (array $headers) use ($buffer) {
if (!\is_bool($buffer = $buffer($headers))) {
if (!\is_array($bufferInfo = @stream_get_meta_data($buffer))) {
throw new \LogicException(sprintf('The closure passed as option "buffer" must return bool or stream resource, got "%s".', get_debug_type($buffer)));
throw new \LogicException(\sprintf('The closure passed as option "buffer" must return bool or stream resource, got "%s".', get_debug_type($buffer)));
}
if (false === strpbrk($bufferInfo['mode'], 'acew+')) {
throw new \LogicException(sprintf('The stream returned by the closure passed as option "buffer" must be writeable, got mode "%s".', $bufferInfo['mode']));
throw new \LogicException(\sprintf('The stream returned by the closure passed as option "buffer" must be writeable, got mode "%s".', $bufferInfo['mode']));
}
}
@@ -72,11 +72,11 @@ trait HttpClientTrait
};
} elseif (!\is_bool($buffer)) {
if (!\is_array($bufferInfo = @stream_get_meta_data($buffer))) {
throw new InvalidArgumentException(sprintf('Option "buffer" must be bool, stream resource or Closure, "%s" given.', get_debug_type($buffer)));
throw new InvalidArgumentException(\sprintf('Option "buffer" must be bool, stream resource or Closure, "%s" given.', get_debug_type($buffer)));
}
if (false === strpbrk($bufferInfo['mode'], 'acew+')) {
throw new InvalidArgumentException(sprintf('The stream in option "buffer" must be writeable, mode "%s" given.', $bufferInfo['mode']));
throw new InvalidArgumentException(\sprintf('The stream in option "buffer" must be writeable, mode "%s" given.', $bufferInfo['mode']));
}
}
@@ -127,25 +127,25 @@ trait HttpClientTrait
// Validate on_progress
if (isset($options['on_progress']) && !\is_callable($onProgress = $options['on_progress'])) {
throw new InvalidArgumentException(sprintf('Option "on_progress" must be callable, "%s" given.', get_debug_type($onProgress)));
throw new InvalidArgumentException(\sprintf('Option "on_progress" must be callable, "%s" given.', get_debug_type($onProgress)));
}
if (\is_array($options['auth_basic'] ?? null)) {
$count = \count($options['auth_basic']);
if ($count <= 0 || $count > 2) {
throw new InvalidArgumentException(sprintf('Option "auth_basic" must contain 1 or 2 elements, "%s" given.', $count));
throw new InvalidArgumentException(\sprintf('Option "auth_basic" must contain 1 or 2 elements, "%s" given.', $count));
}
$options['auth_basic'] = implode(':', $options['auth_basic']);
}
if (!\is_string($options['auth_basic'] ?? '')) {
throw new InvalidArgumentException(sprintf('Option "auth_basic" must be string or an array, "%s" given.', get_debug_type($options['auth_basic'])));
throw new InvalidArgumentException(\sprintf('Option "auth_basic" must be string or an array, "%s" given.', get_debug_type($options['auth_basic'])));
}
if (isset($options['auth_bearer'])) {
if (!\is_string($options['auth_bearer'])) {
throw new InvalidArgumentException(sprintf('Option "auth_bearer" must be a string, "%s" given.', get_debug_type($options['auth_bearer'])));
throw new InvalidArgumentException(\sprintf('Option "auth_bearer" must be a string, "%s" given.', get_debug_type($options['auth_bearer'])));
}
if (preg_match('{[^\x21-\x7E]}', $options['auth_bearer'])) {
throw new InvalidArgumentException('Invalid character found in option "auth_bearer": '.json_encode($options['auth_bearer']).'.');
@@ -250,11 +250,11 @@ trait HttpClientTrait
$msg = 'try using "%s" instead.';
}
throw new InvalidArgumentException(sprintf('Option "auth_ntlm" is not supported by "%s", '.$msg, __CLASS__, CurlHttpClient::class));
throw new InvalidArgumentException(\sprintf('Option "auth_ntlm" is not supported by "%s", '.$msg, __CLASS__, CurlHttpClient::class));
}
if ('vars' === $name) {
throw new InvalidArgumentException(sprintf('Option "vars" is not supported by "%s", try using "%s" instead.', __CLASS__, UriTemplateHttpClient::class));
throw new InvalidArgumentException(\sprintf('Option "vars" is not supported by "%s", try using "%s" instead.', __CLASS__, UriTemplateHttpClient::class));
}
$alternatives = [];
@@ -265,7 +265,7 @@ trait HttpClientTrait
}
}
throw new InvalidArgumentException(sprintf('Unsupported option "%s" passed to "%s", did you mean "%s"?', $name, __CLASS__, implode('", "', $alternatives ?: array_keys($defaultOptions))));
throw new InvalidArgumentException(\sprintf('Unsupported option "%s" passed to "%s", did you mean "%s"?', $name, __CLASS__, implode('", "', $alternatives ?: array_keys($defaultOptions))));
}
return $options;
@@ -287,13 +287,13 @@ trait HttpClientTrait
if (\is_int($name)) {
if (!\is_string($values)) {
throw new InvalidArgumentException(sprintf('Invalid value for header "%s": expected string, "%s" given.', $name, get_debug_type($values)));
throw new InvalidArgumentException(\sprintf('Invalid value for header "%s": expected string, "%s" given.', $name, get_debug_type($values)));
}
[$name, $values] = explode(':', $values, 2);
$values = [ltrim($values)];
} elseif (!is_iterable($values)) {
if (\is_object($values)) {
throw new InvalidArgumentException(sprintf('Invalid value for header "%s": expected string, "%s" given.', $name, get_debug_type($values)));
throw new InvalidArgumentException(\sprintf('Invalid value for header "%s": expected string, "%s" given.', $name, get_debug_type($values)));
}
$values = (array) $values;
@@ -306,7 +306,7 @@ trait HttpClientTrait
$normalizedHeaders[$lcName][] = $value = $name.': '.$value;
if (\strlen($value) !== strcspn($value, "\r\n\0")) {
throw new InvalidArgumentException(sprintf('Invalid header: CR/LF/NUL found in "%s".', $value));
throw new InvalidArgumentException(\sprintf('Invalid header: CR/LF/NUL found in "%s".', $value));
}
}
}
@@ -377,10 +377,10 @@ trait HttpClientTrait
$v = $streams[$v];
if (!\is_array($m = @stream_get_meta_data($v))) {
throw new TransportException(sprintf('Invalid "%s" resource found in body part "%s".', get_resource_type($v), $k));
throw new TransportException(\sprintf('Invalid "%s" resource found in body part "%s".', get_resource_type($v), $k));
}
if (feof($v)) {
throw new TransportException(sprintf('Uploaded stream ended for body part "%s".', $k));
throw new TransportException(\sprintf('Uploaded stream ended for body part "%s".', $k));
}
$m += stream_context_get_options($v)['http'] ?? [];
@@ -436,7 +436,7 @@ trait HttpClientTrait
while (null !== $h && !feof($h)) {
if (false === $part = fread($h, $size)) {
throw new TransportException(sprintf('Error while reading uploaded stream for body part "%s".', $k));
throw new TransportException(\sprintf('Error while reading uploaded stream for body part "%s".', $k));
}
yield $part;
@@ -485,7 +485,7 @@ trait HttpClientTrait
}
if (!\is_array(@stream_get_meta_data($body))) {
throw new InvalidArgumentException(sprintf('Option "body" must be string, stream resource, iterable or callable, "%s" given.', get_debug_type($body)));
throw new InvalidArgumentException(\sprintf('Option "body" must be string, stream resource, iterable or callable, "%s" given.', get_debug_type($body)));
}
return $body;
@@ -518,14 +518,14 @@ trait HttpClientTrait
40 => ['sha1' => $fingerprint],
44 => ['pin-sha256' => [$fingerprint]],
64 => ['sha256' => $fingerprint],
default => throw new InvalidArgumentException(sprintf('Cannot auto-detect fingerprint algorithm for "%s".', $fingerprint)),
default => throw new InvalidArgumentException(\sprintf('Cannot auto-detect fingerprint algorithm for "%s".', $fingerprint)),
};
} elseif (\is_array($fingerprint)) {
foreach ($fingerprint as $algo => $hash) {
$fingerprint[$algo] = 'pin-sha256' === $algo ? (array) $hash : str_replace(':', '', $hash);
}
} else {
throw new InvalidArgumentException(sprintf('Option "peer_fingerprint" must be string or array, "%s" given.', get_debug_type($fingerprint)));
throw new InvalidArgumentException(\sprintf('Option "peer_fingerprint" must be string or array, "%s" given.', get_debug_type($fingerprint)));
}
return $fingerprint;
@@ -557,15 +557,15 @@ trait HttpClientTrait
private static function resolveUrl(array $url, ?array $base, array $queryDefaults = []): array
{
if (null !== $base && '' === ($base['scheme'] ?? '').($base['authority'] ?? '')) {
throw new InvalidArgumentException(sprintf('Invalid "base_uri" option: host or scheme is missing in "%s".', implode('', $base)));
throw new InvalidArgumentException(\sprintf('Invalid "base_uri" option: host or scheme is missing in "%s".', implode('', $base)));
}
if (null === $url['scheme'] && (null === $base || null === $base['scheme'])) {
throw new InvalidArgumentException(sprintf('Invalid URL: scheme is missing in "%s". Did you forget to add "http(s)://"?', implode('', $base ?? $url)));
throw new InvalidArgumentException(\sprintf('Invalid URL: scheme is missing in "%s". Did you forget to add "http(s)://"?', implode('', $base ?? $url)));
}
if (null === $base && '' === $url['scheme'].$url['authority']) {
throw new InvalidArgumentException(sprintf('Invalid URL: no "base_uri" option was provided and host or scheme is missing in "%s".', implode('', $url)));
throw new InvalidArgumentException(\sprintf('Invalid URL: no "base_uri" option was provided and host or scheme is missing in "%s".', implode('', $url)));
}
if (null !== $url['scheme']) {
@@ -620,7 +620,7 @@ trait HttpClientTrait
private static function parseUrl(string $url, array $query = [], array $allowedSchemes = ['http' => 80, 'https' => 443]): array
{
if (false === $parts = parse_url($url)) {
throw new InvalidArgumentException(sprintf('Malformed URL "%s".', $url));
throw new InvalidArgumentException(\sprintf('Malformed URL "%s".', $url));
}
if ($query) {
@@ -631,7 +631,7 @@ trait HttpClientTrait
if (null !== $scheme = $parts['scheme'] ?? null) {
if (!isset($allowedSchemes[$scheme = strtolower($scheme)])) {
throw new InvalidArgumentException(sprintf('Unsupported scheme in "%s".', $url));
throw new InvalidArgumentException(\sprintf('Unsupported scheme in "%s".', $url));
}
$port = $allowedSchemes[$scheme] === $port ? 0 : $port;
@@ -640,7 +640,7 @@ trait HttpClientTrait
if (null !== $host = $parts['host'] ?? null) {
if (!\defined('INTL_IDNA_VARIANT_UTS46') && preg_match('/[\x80-\xFF]/', $host)) {
throw new InvalidArgumentException(sprintf('Unsupported IDN "%s", try enabling the "intl" PHP extension or running "composer require symfony/polyfill-intl-idn".', $host));
throw new InvalidArgumentException(\sprintf('Unsupported IDN "%s", try enabling the "intl" PHP extension or running "composer require symfony/polyfill-intl-idn".', $host));
}
$host = \defined('INTL_IDNA_VARIANT_UTS46') ? idn_to_ascii($host, \IDNA_DEFAULT | \IDNA_USE_STD3_RULES | \IDNA_CHECK_BIDI | \IDNA_CHECK_CONTEXTJ | \IDNA_NONTRANSITIONAL_TO_ASCII, \INTL_IDNA_VARIANT_UTS46) ?: strtolower($host) : strtolower($host);
@@ -777,7 +777,7 @@ trait HttpClientTrait
} elseif ('https' === $proxy['scheme']) {
$proxyUrl = 'ssl://'.$proxy['host'].':'.($proxy['port'] ?? '443');
} else {
throw new TransportException(sprintf('Unsupported proxy scheme "%s": "http" or "https" expected.', $proxy['scheme']));
throw new TransportException(\sprintf('Unsupported proxy scheme "%s": "http" or "https" expected.', $proxy['scheme']));
}
$noProxy ??= $_SERVER['no_proxy'] ?? $_SERVER['NO_PROXY'] ?? '';

View File

@@ -113,7 +113,7 @@ final class HttplugClient implements ClientInterface, HttpAsyncClient, RequestFa
public function sendAsyncRequest(RequestInterface $request): HttplugPromise
{
if (!$promisePool = $this->promisePool) {
throw new \LogicException(sprintf('You cannot use "%s()" as the "guzzlehttp/promises" package is not installed. Try running "composer require guzzlehttp/promises".', __METHOD__));
throw new \LogicException(\sprintf('You cannot use "%s()" as the "guzzlehttp/promises" package is not installed. Try running "composer require guzzlehttp/promises".', __METHOD__));
}
try {
@@ -160,7 +160,7 @@ final class HttplugClient implements ClientInterface, HttpAsyncClient, RequestFa
} elseif (class_exists(Request::class)) {
$request = new Request($method, $uri);
} else {
throw new \LogicException(sprintf('You cannot use "%s()" as no PSR-17 factories have been found. Try running "composer require php-http/discovery psr/http-factory-implementation:*".', __METHOD__));
throw new \LogicException(\sprintf('You cannot use "%s()" as no PSR-17 factories have been found. Try running "composer require php-http/discovery psr/http-factory-implementation:*".', __METHOD__));
}
return $request;
@@ -195,7 +195,7 @@ final class HttplugClient implements ClientInterface, HttpAsyncClient, RequestFa
return new Uri($uri);
}
throw new \LogicException(sprintf('You cannot use "%s()" as no PSR-17 factories have been found. Try running "composer require php-http/discovery psr/http-factory-implementation:*".', __METHOD__));
throw new \LogicException(\sprintf('You cannot use "%s()" as no PSR-17 factories have been found. Try running "composer require php-http/discovery psr/http-factory-implementation:*".', __METHOD__));
}
public function __sleep(): array

View File

@@ -140,7 +140,7 @@ class AmpBody implements RequestBody, InputStream
}
if (!\is_string($data)) {
throw new TransportException(sprintf('Return value of the "body" option callback must be string, "%s" returned.', get_debug_type($data)));
throw new TransportException(\sprintf('Return value of the "body" option callback must be string, "%s" returned.', get_debug_type($data)));
}
return new Success($data);

View File

@@ -198,11 +198,11 @@ final class AmpClientState extends ClientState
if ($this->maxPendingPushes <= \count($this->pushedResponses[$authority] ?? [])) {
$fifoUrl = key($this->pushedResponses[$authority]);
unset($this->pushedResponses[$authority][$fifoUrl]);
$this->logger?->debug(sprintf('Evicting oldest pushed response: "%s"', $fifoUrl));
$this->logger?->debug(\sprintf('Evicting oldest pushed response: "%s"', $fifoUrl));
}
$url = (string) $request->getUri();
$this->logger?->debug(sprintf('Queueing pushed response: "%s"', $url));
$this->logger?->debug(\sprintf('Queueing pushed response: "%s"', $url));
$this->pushedResponses[$authority][] = [$url, $deferred, $request, $response, [
'proxy' => $options['proxy'],
'bindto' => $options['bindto'],

View File

@@ -89,7 +89,7 @@ class AmpListener implements EventListener
$this->info['primary_ip'] = $host;
$this->info['primary_port'] = $stream->getRemoteAddress()->getPort();
$this->info['pretransfer_time'] = microtime(true) - $this->info['start_time'];
$this->info['debug'] .= sprintf("* Connected to %s (%s) port %d\n", $request->getUri()->getHost(), $host, $this->info['primary_port']);
$this->info['debug'] .= \sprintf("* Connected to %s (%s) port %d\n", $request->getUri()->getHost(), $host, $this->info['primary_port']);
if ((isset($this->info['peer_certificate_chain']) || $this->pinSha256) && null !== $tlsInfo = $stream->getTlsInfo()) {
foreach ($tlsInfo->getPeerCertificates() as $cert) {
@@ -104,7 +104,7 @@ class AmpListener implements EventListener
$pin = base64_encode(hash('sha256', $pin, true));
if (!\in_array($pin, $this->pinSha256, true)) {
throw new TransportException(sprintf('SSL public key does not match pinned public key for "%s".', $this->info['url']));
throw new TransportException(\sprintf('SSL public key does not match pinned public key for "%s".', $this->info['url']));
}
}
}
@@ -121,7 +121,7 @@ class AmpListener implements EventListener
$requestUri = $uri->getHost().': '.($uri->getPort() ?? ('https' === $uri->getScheme() ? 443 : 80));
}
$this->info['debug'] .= sprintf("> %s %s HTTP/%s \r\n", $method, $requestUri, $request->getProtocolVersions()[0]);
$this->info['debug'] .= \sprintf("> %s %s HTTP/%s \r\n", $method, $requestUri, $request->getProtocolVersions()[0]);
foreach ($request->getRawHeaders() as [$name, $value]) {
$this->info['debug'] .= $name.': '.$value."\r\n";

View File

@@ -81,7 +81,7 @@ final class CurlClientState extends ClientState
public function reset(): void
{
foreach ($this->pushedResponses as $url => $response) {
$this->logger?->debug(sprintf('Unused pushed response: "%s"', $url));
$this->logger?->debug(\sprintf('Unused pushed response: "%s"', $url));
curl_multi_remove_handle($this->handle, $response->handle);
curl_close($response->handle);
}
@@ -112,7 +112,7 @@ final class CurlClientState extends ClientState
}
if (!isset($headers[':method']) || !isset($headers[':scheme']) || !isset($headers[':authority']) || !isset($headers[':path'])) {
$this->logger?->debug(sprintf('Rejecting pushed response from "%s": pushed headers are invalid', $origin));
$this->logger?->debug(\sprintf('Rejecting pushed response from "%s": pushed headers are invalid', $origin));
return \CURL_PUSH_DENY;
}
@@ -123,7 +123,7 @@ final class CurlClientState extends ClientState
// but this is a MUST in the HTTP/2 RFC; let's restrict pushes to the original host,
// ignoring domains mentioned as alt-name in the certificate for now (same as curl).
if (!str_starts_with($origin, $url.'/')) {
$this->logger?->debug(sprintf('Rejecting pushed response from "%s": server is not authoritative for "%s"', $origin, $url));
$this->logger?->debug(\sprintf('Rejecting pushed response from "%s": server is not authoritative for "%s"', $origin, $url));
return \CURL_PUSH_DENY;
}
@@ -131,11 +131,11 @@ final class CurlClientState extends ClientState
if ($maxPendingPushes <= \count($this->pushedResponses)) {
$fifoUrl = key($this->pushedResponses);
unset($this->pushedResponses[$fifoUrl]);
$this->logger?->debug(sprintf('Evicting oldest pushed response: "%s"', $fifoUrl));
$this->logger?->debug(\sprintf('Evicting oldest pushed response: "%s"', $fifoUrl));
}
$url .= $headers[':path'][0];
$this->logger?->debug(sprintf('Queueing pushed response: "%s"', $url));
$this->logger?->debug(\sprintf('Queueing pushed response: "%s"', $url));
$this->pushedResponses[$url] = new PushedResponse(new CurlResponse($this, $pushed), $headers, $this->openHandles[(int) $parent][1] ?? [], $pushed);

View File

@@ -78,7 +78,7 @@ class MockHttpClient implements HttpClientInterface, ResetInterface
++$this->requestsCount;
if (!$response instanceof ResponseInterface) {
throw new TransportException(sprintf('The response factory passed to MockHttpClient must return/yield an instance of ResponseInterface, "%s" given.', get_debug_type($response)));
throw new TransportException(\sprintf('The response factory passed to MockHttpClient must return/yield an instance of ResponseInterface, "%s" given.', get_debug_type($response)));
}
return MockResponse::fromRequest($method, $url, $options, $response);

View File

@@ -139,7 +139,7 @@ final class NativeHttpClient implements HttpClientInterface, LoggerAwareInterfac
$maxDuration = 0 < $options['max_duration'] ? $options['max_duration'] : \INF;
$onProgress = static function (...$progress) use ($onProgress, &$info, $maxDuration) {
if ($info['total_time'] >= $maxDuration) {
throw new TransportException(sprintf('Max duration was reached for "%s".', implode('', $info['url'])));
throw new TransportException(\sprintf('Max duration was reached for "%s".', implode('', $info['url'])));
}
$progressInfo = $info;
@@ -162,7 +162,7 @@ final class NativeHttpClient implements HttpClientInterface, LoggerAwareInterfac
$maxDuration = $options['max_duration'];
$onProgress = static function () use (&$info, $maxDuration): void {
if ($info['total_time'] >= $maxDuration) {
throw new TransportException(sprintf('Max duration was reached for "%s".', implode('', $info['url'])));
throw new TransportException(\sprintf('Max duration was reached for "%s".', implode('', $info['url'])));
}
};
}
@@ -192,7 +192,7 @@ final class NativeHttpClient implements HttpClientInterface, LoggerAwareInterfac
$this->multi->dnsCache = $options['resolve'] + $this->multi->dnsCache;
}
$this->logger?->info(sprintf('Request: "%s %s"', $method, implode('', $url)));
$this->logger?->info(\sprintf('Request: "%s %s"', $method, implode('', $url)));
if (!isset($options['normalized_headers']['user-agent'])) {
$options['headers'][] = 'User-Agent: Symfony HttpClient (Native)';
@@ -297,7 +297,7 @@ final class NativeHttpClient implements HttpClientInterface, LoggerAwareInterfac
while ('' !== $data = $body(self::$CHUNK_SIZE)) {
if (!\is_string($data)) {
throw new TransportException(sprintf('Return value of the "body" option callback must be string, "%s" returned.', get_debug_type($data)));
throw new TransportException(\sprintf('Return value of the "body" option callback must be string, "%s" returned.', get_debug_type($data)));
}
$result .= $data;
@@ -331,7 +331,7 @@ final class NativeHttpClient implements HttpClientInterface, LoggerAwareInterfac
$now = microtime(true);
if (!$ip = gethostbynamel($host)) {
throw new TransportException(sprintf('Could not resolve host "%s".', $host));
throw new TransportException(\sprintf('Could not resolve host "%s".', $host));
}
$info['namelookup_time'] = microtime(true) - ($info['start_time'] ?: $now);

View File

@@ -39,7 +39,7 @@ final class NoPrivateNetworkHttpClient implements HttpClientInterface, LoggerAwa
private string|array|null $subnets = null,
) {
if (!class_exists(IpUtils::class)) {
throw new \LogicException(sprintf('You cannot use "%s" if the HttpFoundation component is not installed. Try running "composer require symfony/http-foundation".', __CLASS__));
throw new \LogicException(\sprintf('You cannot use "%s" if the HttpFoundation component is not installed. Try running "composer require symfony/http-foundation".', __CLASS__));
}
}
@@ -47,7 +47,7 @@ final class NoPrivateNetworkHttpClient implements HttpClientInterface, LoggerAwa
{
$onProgress = $options['on_progress'] ?? null;
if (null !== $onProgress && !\is_callable($onProgress)) {
throw new InvalidArgumentException(sprintf('Option "on_progress" must be callable, "%s" given.', get_debug_type($onProgress)));
throw new InvalidArgumentException(\sprintf('Option "on_progress" must be callable, "%s" given.', get_debug_type($onProgress)));
}
$subnets = $this->subnets;
@@ -56,7 +56,7 @@ final class NoPrivateNetworkHttpClient implements HttpClientInterface, LoggerAwa
static $lastPrimaryIp = '';
if ($info['primary_ip'] !== $lastPrimaryIp) {
if ($info['primary_ip'] && IpUtils::checkIp($info['primary_ip'], $subnets ?? IpUtils::PRIVATE_SUBNETS)) {
throw new TransportException(sprintf('IP "%s" is blocked for "%s".', $info['primary_ip'], $info['url']));
throw new TransportException(\sprintf('IP "%s" is blocked for "%s".', $info['primary_ip'], $info['url']));
}
$lastPrimaryIp = $info['primary_ip'];

View File

@@ -128,7 +128,7 @@ final class Psr18Client implements ClientInterface, RequestFactoryInterface, Str
return new Request($method, $uri);
}
throw new \LogicException(sprintf('You cannot use "%s()" as no PSR-17 factories have been found. Try running "composer require php-http/discovery psr/http-factory-implementation:*".', __METHOD__));
throw new \LogicException(\sprintf('You cannot use "%s()" as no PSR-17 factories have been found. Try running "composer require php-http/discovery psr/http-factory-implementation:*".', __METHOD__));
}
public function createStream(string $content = ''): StreamInterface
@@ -166,7 +166,7 @@ final class Psr18Client implements ClientInterface, RequestFactoryInterface, Str
return new Uri($uri);
}
throw new \LogicException(sprintf('You cannot use "%s()" as no PSR-17 factories have been found. Try running "composer require php-http/discovery psr/http-factory-implementation:*".', __METHOD__));
throw new \LogicException(\sprintf('You cannot use "%s()" as no PSR-17 factories have been found. Try running "composer require php-http/discovery psr/http-factory-implementation:*".', __METHOD__));
}
public function reset(): void

View File

@@ -228,7 +228,7 @@ final class AmpResponse implements ResponseInterface, StreamableInterface
try {
/* @var Response $response */
if (null === $response = yield from self::getPushedResponse($request, $multi, $info, $headers, $options, $logger)) {
$logger?->info(sprintf('Request: "%s %s"', $info['http_method'], $info['url']));
$logger?->info(\sprintf('Request: "%s %s"', $info['http_method'], $info['url']));
$response = yield from self::followRedirects($request, $multi, $info, $headers, $canceller, $options, $onProgress, $handle, $logger, $pause);
}
@@ -312,7 +312,7 @@ final class AmpResponse implements ResponseInterface, StreamableInterface
return $response;
}
$logger?->info(sprintf('Redirecting: "%s %s"', $status, $info['url']));
$logger?->info(\sprintf('Redirecting: "%s %s"', $status, $info['url']));
try {
// Discard body of redirects
@@ -373,7 +373,7 @@ final class AmpResponse implements ResponseInterface, StreamableInterface
$headers = [];
}
$h = sprintf('HTTP/%s %s %s', $response->getProtocolVersion(), $response->getStatus(), $response->getReason());
$h = \sprintf('HTTP/%s %s %s', $response->getProtocolVersion(), $response->getStatus(), $response->getReason());
$info['debug'] .= "< {$h}\r\n";
$info['response_headers'][] = $h;
@@ -420,14 +420,14 @@ final class AmpResponse implements ResponseInterface, StreamableInterface
foreach ($response->getHeaderArray('vary') as $vary) {
foreach (preg_split('/\s*+,\s*+/', $vary) as $v) {
if ('*' === $v || ($pushedRequest->getHeaderArray($v) !== $request->getHeaderArray($v) && 'accept-encoding' !== strtolower($v))) {
$logger?->debug(sprintf('Skipping pushed response: "%s"', $info['url']));
$logger?->debug(\sprintf('Skipping pushed response: "%s"', $info['url']));
continue 3;
}
}
}
$pushDeferred->resolve();
$logger?->debug(sprintf('Accepting pushed response: "%s %s"', $info['http_method'], $info['url']));
$logger?->debug(\sprintf('Accepting pushed response: "%s %s"', $info['http_method'], $info['url']));
self::addResponseHeaders($response, $info, $headers);
unset($multi->pushedResponses[$authority][$i]);

View File

@@ -166,7 +166,7 @@ final class AsyncContext
}
if (0 < ($info['max_duration'] ?? 0) && 0 < ($info['total_time'] ?? 0)) {
if (0 >= $options['max_duration'] = $info['max_duration'] - $info['total_time']) {
throw new TransportException(sprintf('Max duration was reached for "%s".', $info['url']));
throw new TransportException(\sprintf('Max duration was reached for "%s".', $info['url']));
}
}

View File

@@ -217,7 +217,7 @@ class AsyncResponse implements ResponseInterface, StreamableInterface
foreach ($responses as $r) {
if (!$r instanceof self) {
throw new \TypeError(sprintf('"%s::stream()" expects parameter 1 to be an iterable of AsyncResponse objects, "%s" given.', $class ?? static::class, get_debug_type($r)));
throw new \TypeError(\sprintf('"%s::stream()" expects parameter 1 to be an iterable of AsyncResponse objects, "%s" given.', $class ?? static::class, get_debug_type($r)));
}
if (null !== $e = $r->info['error'] ?? null) {
@@ -269,7 +269,7 @@ class AsyncResponse implements ResponseInterface, StreamableInterface
if (null !== $chunk->getError() || $chunk->isLast()) {
unset($asyncMap[$response]);
} elseif (null !== $r->content && '' !== ($content = $chunk->getContent()) && \strlen($content) !== fwrite($r->content, $content)) {
$chunk = new ErrorChunk($r->offset, new TransportException(sprintf('Failed writing %d bytes to the response buffer.', \strlen($content))));
$chunk = new ErrorChunk($r->offset, new TransportException(\sprintf('Failed writing %d bytes to the response buffer.', \strlen($content))));
$r->info['error'] = $chunk->getError();
$r->response->cancel();
}
@@ -283,7 +283,7 @@ class AsyncResponse implements ResponseInterface, StreamableInterface
} elseif ($chunk->isFirst()) {
$r->yieldedState = self::FIRST_CHUNK_YIELDED;
} elseif (self::FIRST_CHUNK_YIELDED !== $r->yieldedState && null === $chunk->getInformationalStatus()) {
throw new \LogicException(sprintf('Instance of "%s" is already consumed and cannot be managed by "%s". A decorated client should not call any of the response\'s methods in its "request()" method.', get_debug_type($response), $class ?? static::class));
throw new \LogicException(\sprintf('Instance of "%s" is already consumed and cannot be managed by "%s". A decorated client should not call any of the response\'s methods in its "request()" method.', get_debug_type($response), $class ?? static::class));
}
foreach (self::passthru($r->client, $r, $chunk, $asyncMap) as $chunk) {
@@ -330,7 +330,7 @@ class AsyncResponse implements ResponseInterface, StreamableInterface
}
if (!$stream instanceof \Iterator) {
throw new \LogicException(sprintf('A chunk passthru must return an "Iterator", "%s" returned.', get_debug_type($stream)));
throw new \LogicException(\sprintf('A chunk passthru must return an "Iterator", "%s" returned.', get_debug_type($stream)));
}
$r->stream = $stream;
@@ -366,7 +366,7 @@ class AsyncResponse implements ResponseInterface, StreamableInterface
$chunk = $r->stream->current();
if (!$chunk instanceof ChunkInterface) {
throw new \LogicException(sprintf('A chunk passthru must yield instances of "%s", "%s" yielded.', ChunkInterface::class, get_debug_type($chunk)));
throw new \LogicException(\sprintf('A chunk passthru must yield instances of "%s", "%s" yielded.', ChunkInterface::class, get_debug_type($chunk)));
}
if (null !== $chunk->getError()) {
@@ -393,7 +393,7 @@ class AsyncResponse implements ResponseInterface, StreamableInterface
}
if (null !== $r->content && \strlen($content) !== fwrite($r->content, $content)) {
$chunk = new ErrorChunk($r->offset, new TransportException(sprintf('Failed writing %d bytes to the response buffer.', \strlen($content))));
$chunk = new ErrorChunk($r->offset, new TransportException(\sprintf('Failed writing %d bytes to the response buffer.', \strlen($content))));
$r->info['error'] = $chunk->getError();
$r->response->cancel();
}

View File

@@ -87,11 +87,11 @@ trait CommonResponseTrait
try {
$content = json_decode($content, true, 512, \JSON_BIGINT_AS_STRING | \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new JsonException($e->getMessage().sprintf(' for "%s".', $this->getInfo('url')), $e->getCode());
throw new JsonException($e->getMessage().\sprintf(' for "%s".', $this->getInfo('url')), $e->getCode());
}
if (!\is_array($content)) {
throw new JsonException(sprintf('JSON content was expected to decode to an array, "%s" returned for "%s".', get_debug_type($content), $this->getInfo('url')));
throw new JsonException(\sprintf('JSON content was expected to decode to an array, "%s" returned for "%s".', get_debug_type($content), $this->getInfo('url')));
}
if (null !== $this->content) {

View File

@@ -143,7 +143,7 @@ final class CurlResponse implements ResponseInterface, StreamableInterface
curl_setopt($ch, \CURLOPT_WRITEFUNCTION, static function ($ch, string $data) use ($multi, $id): int {
if ('H' === (curl_getinfo($ch, \CURLINFO_PRIVATE)[0] ?? null)) {
$multi->handlesActivity[$id][] = null;
$multi->handlesActivity[$id][] = new TransportException(sprintf('Unsupported protocol for "%s"', curl_getinfo($ch, \CURLINFO_EFFECTIVE_URL)));
$multi->handlesActivity[$id][] = new TransportException(\sprintf('Unsupported protocol for "%s"', curl_getinfo($ch, \CURLINFO_EFFECTIVE_URL)));
return 0;
}
@@ -275,7 +275,7 @@ final class CurlResponse implements ResponseInterface, StreamableInterface
if ($responses) {
$response = current($responses);
$multi->handlesActivity[(int) $response->handle][] = null;
$multi->handlesActivity[(int) $response->handle][] = new TransportException(sprintf('Userland callback cannot use the client nor the response while processing "%s".', curl_getinfo($response->handle, \CURLINFO_EFFECTIVE_URL)));
$multi->handlesActivity[(int) $response->handle][] = new TransportException(\sprintf('Userland callback cannot use the client nor the response while processing "%s".', curl_getinfo($response->handle, \CURLINFO_EFFECTIVE_URL)));
}
return;
@@ -316,7 +316,7 @@ final class CurlResponse implements ResponseInterface, StreamableInterface
}
$multi->handlesActivity[$id][] = null;
$multi->handlesActivity[$id][] = \in_array($result, [\CURLE_OK, \CURLE_TOO_MANY_REDIRECTS], true) || '_0' === $waitFor || curl_getinfo($ch, \CURLINFO_SIZE_DOWNLOAD) === curl_getinfo($ch, \CURLINFO_CONTENT_LENGTH_DOWNLOAD) ? null : new TransportException(ucfirst(curl_error($ch) ?: curl_strerror($result)).sprintf(' for "%s".', curl_getinfo($ch, \CURLINFO_EFFECTIVE_URL)));
$multi->handlesActivity[$id][] = \in_array($result, [\CURLE_OK, \CURLE_TOO_MANY_REDIRECTS], true) || '_0' === $waitFor || curl_getinfo($ch, \CURLINFO_SIZE_DOWNLOAD) === curl_getinfo($ch, \CURLINFO_CONTENT_LENGTH_DOWNLOAD) ? null : new TransportException(ucfirst(curl_error($ch) ?: curl_strerror($result)).\sprintf(' for "%s".', curl_getinfo($ch, \CURLINFO_EFFECTIVE_URL)));
}
} finally {
$multi->performing = false;
@@ -451,7 +451,7 @@ final class CurlResponse implements ResponseInterface, StreamableInterface
curl_setopt($ch, \CURLOPT_PRIVATE, $waitFor);
} elseif (null !== $info['redirect_url'] && $logger) {
$logger->info(sprintf('Redirecting: "%s %s"', $info['http_code'], $info['redirect_url']));
$logger->info(\sprintf('Redirecting: "%s %s"', $info['http_code'], $info['redirect_url']));
}
$location = null;

View File

@@ -34,12 +34,12 @@ class JsonMockResponse extends MockResponse
public static function fromFile(string $path, array $info = []): static
{
if (!is_file($path)) {
throw new InvalidArgumentException(sprintf('File not found: "%s".', $path));
throw new InvalidArgumentException(\sprintf('File not found: "%s".', $path));
}
$json = file_get_contents($path);
if (!json_validate($json)) {
throw new \InvalidArgumentException(sprintf('File "%s" does not contain valid JSON.', $path));
throw new \InvalidArgumentException(\sprintf('File "%s" does not contain valid JSON.', $path));
}
return new static(json_decode($json, true, flags: \JSON_THROW_ON_ERROR), $info);

View File

@@ -67,7 +67,7 @@ class MockResponse implements ResponseInterface, StreamableInterface
public static function fromFile(string $path, array $info = []): static
{
if (!is_file($path)) {
throw new \InvalidArgumentException(sprintf('File not found: "%s".', $path));
throw new \InvalidArgumentException(\sprintf('File not found: "%s".', $path));
}
return new static(file_get_contents($path), $info);
@@ -252,7 +252,7 @@ class MockResponse implements ResponseInterface, StreamableInterface
} elseif ($body instanceof \Closure) {
while ('' !== $data = $body(16372)) {
if (!\is_string($data)) {
throw new TransportException(sprintf('Return value of the "body" option callback must be string, "%s" returned.', get_debug_type($data)));
throw new TransportException(\sprintf('Return value of the "body" option callback must be string, "%s" returned.', get_debug_type($data)));
}
// "notify" upload progress
@@ -308,7 +308,7 @@ class MockResponse implements ResponseInterface, StreamableInterface
if ('' === $chunk = (string) $chunk) {
// simulate an idle timeout
$response->body[] = new ErrorChunk($offset, sprintf('Idle timeout reached for "%s".', $response->info['url']));
$response->body[] = new ErrorChunk($offset, \sprintf('Idle timeout reached for "%s".', $response->info['url']));
} else {
$response->body[] = $chunk;
$offset += \strlen($chunk);
@@ -332,7 +332,7 @@ class MockResponse implements ResponseInterface, StreamableInterface
$onProgress($offset, $dlSize, $response->info);
if ($dlSize && $offset !== $dlSize) {
throw new TransportException(sprintf('Transfer closed with %d bytes remaining to read.', $dlSize - $offset));
throw new TransportException(\sprintf('Transfer closed with %d bytes remaining to read.', $dlSize - $offset));
}
}
}

View File

@@ -123,7 +123,7 @@ final class NativeResponse implements ResponseInterface, StreamableInterface
throw new TransportException($msg);
}
$this->logger?->info(sprintf('%s for "%s".', $msg, $url ?? $this->url));
$this->logger?->info(\sprintf('%s for "%s".', $msg, $url ?? $this->url));
});
try {
@@ -142,7 +142,7 @@ final class NativeResponse implements ResponseInterface, StreamableInterface
$this->info['request_header'] = $this->info['url']['path'].$this->info['url']['query'];
}
$this->info['request_header'] = sprintf("> %s %s HTTP/%s \r\n", $context['http']['method'], $this->info['request_header'], $context['http']['protocol_version']);
$this->info['request_header'] = \sprintf("> %s %s HTTP/%s \r\n", $context['http']['method'], $this->info['request_header'], $context['http']['protocol_version']);
$this->info['request_header'] .= implode("\r\n", $context['http']['header'])."\r\n\r\n";
if (\array_key_exists('peer_name', $context['ssl']) && null === $context['ssl']['peer_name']) {
@@ -159,7 +159,7 @@ final class NativeResponse implements ResponseInterface, StreamableInterface
break;
}
$this->logger?->info(sprintf('Redirecting: "%s %s"', $this->info['http_code'], $url ?? $this->url));
$this->logger?->info(\sprintf('Redirecting: "%s %s"', $this->info['http_code'], $url ?? $this->url));
}
} catch (\Throwable $e) {
$this->close();
@@ -294,7 +294,7 @@ final class NativeResponse implements ResponseInterface, StreamableInterface
if (null === $e) {
if (0 < $remaining) {
$e = new TransportException(sprintf('Transfer closed with %s bytes remaining to read.', $remaining));
$e = new TransportException(\sprintf('Transfer closed with %s bytes remaining to read.', $remaining));
} elseif (-1 === $remaining && fwrite($buffer, '-') && '' !== stream_get_contents($buffer, -1, 0)) {
$e = new TransportException('Transfer closed with outstanding data remaining from chunked response.');
}

View File

@@ -56,7 +56,7 @@ class StreamWrapper
}
if (null === $client && !method_exists($response, 'stream')) {
throw new \InvalidArgumentException(sprintf('Providing a client to "%s()" is required when the response doesn\'t have any "stream()" method.', __CLASS__));
throw new \InvalidArgumentException(\sprintf('Providing a client to "%s()" is required when the response doesn\'t have any "stream()" method.', __CLASS__));
}
static $registered = false;
@@ -94,7 +94,7 @@ class StreamWrapper
{
if ('r' !== $mode) {
if ($options & \STREAM_REPORT_ERRORS) {
trigger_error(sprintf('Invalid mode "%s": only "r" is supported.', $mode), \E_USER_WARNING);
trigger_error(\sprintf('Invalid mode "%s": only "r" is supported.', $mode), \E_USER_WARNING);
}
return false;

View File

@@ -168,7 +168,7 @@ class TraceableResponse implements ResponseInterface, StreamableInterface
foreach ($responses as $r) {
if (!$r instanceof self) {
throw new \TypeError(sprintf('"%s::stream()" expects parameter 1 to be an iterable of TraceableResponse objects, "%s" given.', TraceableHttpClient::class, get_debug_type($r)));
throw new \TypeError(\sprintf('"%s::stream()" expects parameter 1 to be an iterable of TraceableResponse objects, "%s" given.', TraceableHttpClient::class, get_debug_type($r)));
}
$traceableMap[$r->response] = $r;

View File

@@ -181,7 +181,7 @@ trait TransportResponseTrait
unset($responses[$j]);
continue;
} elseif ($elapsedTimeout >= $timeoutMax) {
$multi->handlesActivity[$j] = [new ErrorChunk($response->offset, sprintf('Idle timeout reached for "%s".', $response->getInfo('url')))];
$multi->handlesActivity[$j] = [new ErrorChunk($response->offset, \sprintf('Idle timeout reached for "%s".', $response->getInfo('url')))];
$multi->lastTimeout ??= $lastActivity;
} else {
continue;
@@ -193,12 +193,12 @@ trait TransportResponseTrait
if (\is_string($chunk = array_shift($multi->handlesActivity[$j]))) {
if (null !== $response->inflate && false === $chunk = @inflate_add($response->inflate, $chunk)) {
$multi->handlesActivity[$j] = [null, new TransportException(sprintf('Error while processing content unencoding for "%s".', $response->getInfo('url')))];
$multi->handlesActivity[$j] = [null, new TransportException(\sprintf('Error while processing content unencoding for "%s".', $response->getInfo('url')))];
continue;
}
if ('' !== $chunk && null !== $response->content && \strlen($chunk) !== fwrite($response->content, $chunk)) {
$multi->handlesActivity[$j] = [null, new TransportException(sprintf('Failed writing %d bytes to the response buffer.', \strlen($chunk)))];
$multi->handlesActivity[$j] = [null, new TransportException(\sprintf('Failed writing %d bytes to the response buffer.', \strlen($chunk)))];
continue;
}
@@ -231,7 +231,7 @@ trait TransportResponseTrait
} elseif ($chunk instanceof FirstChunk) {
if ($response->logger) {
$info = $response->getInfo();
$response->logger->info(sprintf('Response: "%s %s"', $info['http_code'], $info['url']));
$response->logger->info(\sprintf('Response: "%s %s"', $info['http_code'], $info['url']));
}
$response->inflate = \extension_loaded('zlib') && $response->inflate && 'gzip' === ($response->headers['content-encoding'][0] ?? null) ? inflate_init(\ZLIB_ENCODING_GZIP) : null;

View File

@@ -51,19 +51,19 @@ class GenericRetryStrategy implements RetryStrategyInterface
private float $jitter = 0.1,
) {
if ($delayMs < 0) {
throw new InvalidArgumentException(sprintf('Delay must be greater than or equal to zero: "%s" given.', $delayMs));
throw new InvalidArgumentException(\sprintf('Delay must be greater than or equal to zero: "%s" given.', $delayMs));
}
if ($multiplier < 1) {
throw new InvalidArgumentException(sprintf('Multiplier must be greater than or equal to one: "%s" given.', $multiplier));
throw new InvalidArgumentException(\sprintf('Multiplier must be greater than or equal to one: "%s" given.', $multiplier));
}
if ($maxDelayMs < 0) {
throw new InvalidArgumentException(sprintf('Max delay must be greater than or equal to zero: "%s" given.', $maxDelayMs));
throw new InvalidArgumentException(\sprintf('Max delay must be greater than or equal to zero: "%s" given.', $maxDelayMs));
}
if ($jitter < 0 || $jitter > 1) {
throw new InvalidArgumentException(sprintf('Jitter must be between 0 and 1: "%s" given.', $jitter));
throw new InvalidArgumentException(\sprintf('Jitter must be between 0 and 1: "%s" given.', $jitter));
}
}

View File

@@ -100,7 +100,7 @@ class RetryableHttpClient implements HttpClientInterface, ResetInterface
if ('' !== $context->getInfo('primary_ip')) {
$shouldRetry = $this->strategy->shouldRetry($context, null, $exception);
if (null === $shouldRetry) {
throw new \LogicException(sprintf('The "%s::shouldRetry()" method must not return null when called with an exception.', $this->strategy::class));
throw new \LogicException(\sprintf('The "%s::shouldRetry()" method must not return null when called with an exception.', $this->strategy::class));
}
if (false === $shouldRetry) {
@@ -131,7 +131,7 @@ class RetryableHttpClient implements HttpClientInterface, ResetInterface
}
if (null === $shouldRetry = $this->strategy->shouldRetry($context, $content, null)) {
throw new \LogicException(sprintf('The "%s::shouldRetry()" method must not return null when called with a body.', $this->strategy::class));
throw new \LogicException(\sprintf('The "%s::shouldRetry()" method must not return null when called with a body.', $this->strategy::class));
}
if (false === $shouldRetry) {

View File

@@ -34,7 +34,7 @@ class ScopingHttpClient implements HttpClientInterface, ResetInterface, LoggerAw
private ?string $defaultRegexp = null,
) {
if (null !== $defaultRegexp && !isset($defaultOptionsByRegexp[$defaultRegexp])) {
throw new InvalidArgumentException(sprintf('No options are mapped to the provided "%s" default regexp.', $defaultRegexp));
throw new InvalidArgumentException(\sprintf('No options are mapped to the provided "%s" default regexp.', $defaultRegexp));
}
}

View File

@@ -34,7 +34,7 @@ class HarFileResponseFactory
public function __invoke(string $method, string $url, array $options): ResponseInterface
{
if (!is_file($this->archiveFile)) {
throw new \InvalidArgumentException(sprintf('Invalid file path provided: "%s".', $this->archiveFile));
throw new \InvalidArgumentException(\sprintf('Invalid file path provided: "%s".', $this->archiveFile));
}
$json = json_decode(json: file_get_contents($this->archiveFile), associative: true, flags: \JSON_THROW_ON_ERROR);
@@ -77,7 +77,7 @@ class HarFileResponseFactory
return new MockResponse($body, $info);
}
throw new TransportException(sprintf('File "%s" does not contain a response for HTTP request "%s" "%s".', $this->archiveFile, $method, $url));
throw new TransportException(\sprintf('File "%s" does not contain a response for HTTP request "%s" "%s".', $this->archiveFile, $method, $url));
}
/**
@@ -91,7 +91,7 @@ class HarFileResponseFactory
return match ($encoding) {
'base64' => base64_decode($text),
null => $text,
default => throw new \InvalidArgumentException(sprintf('Unsupported encoding "%s", currently only base64 is supported.', $encoding)),
default => throw new \InvalidArgumentException(\sprintf('Unsupported encoding "%s", currently only base64 is supported.', $encoding)),
};
}
}

View File

@@ -182,7 +182,7 @@ class HttpClientDataCollectorTest extends TestCase
$curlCommand = $collectedData['http_client']['traces'][0]['curlCommand'];
$isWindows = '\\' === \DIRECTORY_SEPARATOR;
self::assertEquals(sprintf($expectedCurlCommand, $isWindows ? '"' : "'", $isWindows ? '' : "'"), $curlCommand);
self::assertEquals(\sprintf($expectedCurlCommand, $isWindows ? '"' : "'", $isWindows ? '' : "'"), $curlCommand);
}
public static function provideCurlRequests(): iterable
@@ -363,7 +363,7 @@ class HttpClientDataCollectorTest extends TestCase
$collectedData = $sut->getClients();
self::assertCount(1, $collectedData['http_client']['traces']);
$curlCommand = $collectedData['http_client']['traces'][0]['curlCommand'];
self::assertEquals(sprintf('curl \\
self::assertEquals(\sprintf('curl \\
--compressed \\
--request GET \\
--url %1$shttp://localhost:8057/301%1$s \\

View File

@@ -68,11 +68,11 @@ class NoPrivateNetworkHttpClientTest extends TestCase
public function testExclude(string $ipAddr, $subnets, bool $mustThrow)
{
$content = 'foo';
$url = sprintf('http://%s/', 0 < substr_count($ipAddr, ':') ? sprintf('[%s]', $ipAddr) : $ipAddr);
$url = \sprintf('http://%s/', 0 < substr_count($ipAddr, ':') ? \sprintf('[%s]', $ipAddr) : $ipAddr);
if ($mustThrow) {
$this->expectException(TransportException::class);
$this->expectExceptionMessage(sprintf('IP "%s" is blocked for "%s".', $ipAddr, $url));
$this->expectExceptionMessage(\sprintf('IP "%s" is blocked for "%s".', $ipAddr, $url));
}
$previousHttpClient = $this->getHttpClientMock($url, $ipAddr, $content);
@@ -88,7 +88,7 @@ class NoPrivateNetworkHttpClientTest extends TestCase
public function testCustomOnProgressCallback()
{
$ipAddr = '104.26.14.6';
$url = sprintf('http://%s/', $ipAddr);
$url = \sprintf('http://%s/', $ipAddr);
$content = 'foo';
$executionCount = 0;
@@ -108,9 +108,9 @@ class NoPrivateNetworkHttpClientTest extends TestCase
public function testNonCallableOnProgressCallback()
{
$ipAddr = '104.26.14.6';
$url = sprintf('http://%s/', $ipAddr);
$url = \sprintf('http://%s/', $ipAddr);
$content = 'bar';
$customCallback = sprintf('cb_%s', microtime(true));
$customCallback = \sprintf('cb_%s', microtime(true));
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Option "on_progress" must be callable, "string" given.');

View File

@@ -118,7 +118,7 @@ final class JsonMockResponseTest extends TestCase
$path = __DIR__.'/Fixtures/invalid_json.json';
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(sprintf('File "%s" does not contain valid JSON.', $path));
$this->expectExceptionMessage(\sprintf('File "%s" does not contain valid JSON.', $path));
JsonMockResponse::fromFile($path);
}

View File

@@ -23,7 +23,7 @@ class ThrottlingHttpClientTest extends TestCase
public function testThrottling()
{
$failPauseHandler = static function (float $duration) {
self::fail(sprintf('The pause handler should\'t have been called, but it was called with %f.', $duration));
self::fail(\sprintf('The pause handler should\'t have been called, but it was called with %f.', $duration));
};
$pauseHandler = static fn (float $expectedDuration) => function (float $duration) use ($expectedDuration) {