From 201f3e86acfb249664cc778b7f029a8540b8ea74 Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Sun, 21 May 2023 14:00:00 +0100 Subject: [PATCH] Use symfony code style --- .php-cs-fixer.dist.php | 78 ++----------- src/Client.php | 34 +++--- src/Cookie/CookieJar.php | 26 +++-- src/Cookie/CookieJarInterface.php | 2 +- src/Cookie/SessionCookieJar.php | 2 +- src/Cookie/SetCookie.php | 30 ++--- src/Handler/CurlFactory.php | 47 ++++---- src/Handler/CurlMultiHandler.php | 3 +- src/Handler/EasyHandle.php | 2 +- src/Handler/HeaderProcessor.php | 4 +- src/Handler/MockHandler.php | 3 +- src/Handler/StreamHandler.php | 45 ++++---- src/HandlerStack.php | 12 +- src/MessageFormatter.php | 15 +-- src/Middleware.php | 20 +++- src/PrepareBodyMiddleware.php | 1 + src/RedirectMiddleware.php | 8 +- src/RequestOptions.php | 2 +- src/RetryMiddleware.php | 7 +- src/Utils.php | 22 ++-- src/functions.php | 8 +- src/functions_include.php | 2 +- tests/ClientTest.php | 82 ++++++------- tests/Cookie/CookieJarTest.php | 120 ++++++++++---------- tests/Cookie/FileCookieJarTest.php | 26 ++--- tests/Cookie/SessionCookieJarTest.php | 24 ++-- tests/Cookie/SetCookieTest.php | 40 +++---- tests/Exception/RequestExceptionTest.php | 2 +- tests/Handler/CurlFactoryTest.php | 71 ++++++------ tests/Handler/CurlMultiHandlerTest.php | 4 +- tests/Handler/EasyHandleTest.php | 2 +- tests/Handler/MockHandlerTest.php | 4 +- tests/Handler/Network/StreamHandlerTest.php | 8 +- tests/Handler/StreamHandlerTest.php | 58 +++++----- tests/HandlerStackTest.php | 23 ++-- tests/MessageFormatterTest.php | 8 +- tests/MiddlewareTest.php | 16 +-- tests/PoolTest.php | 18 +-- tests/PrepareBodyMiddlewareTest.php | 27 +++-- tests/RedirectMiddlewareTest.php | 64 ++++++----- tests/RetryMiddlewareTest.php | 5 +- tests/Server.php | 30 ++--- tests/TestLogger.php | 8 +- tests/UtilsTest.php | 2 +- tests/bootstrap.php | 7 +- 45 files changed, 515 insertions(+), 507 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 024fb0a55..7acf9b590 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -3,77 +3,17 @@ $config = (new PhpCsFixer\Config()) ->setRiskyAllowed(true) ->setRules([ - '@PSR2' => true, - 'array_syntax' => ['syntax' => 'short'], - 'binary_operator_spaces' => ['operators' => ['=>' => null]], - 'blank_line_after_opening_tag' => true, - 'class_attributes_separation' => ['elements' => ['method' => 'one']], - 'compact_nullable_typehint' => true, - 'concat_space' => ['spacing' => 'one'], - 'declare_equal_normalize' => ['space' => 'none'], + '@PHP71Migration:risky' => true, + '@PHPUnit75Migration:risky' => true, + '@Symfony' => true, 'declare_strict_types' => false, - 'dir_constant' => true, - 'fully_qualified_strict_types' => true, - 'function_to_constant' => true, - 'function_typehint_space' => true, - 'header_comment' => false, - 'list_syntax' => ['syntax' => 'short'], - 'lowercase_cast' => true, - 'magic_method_casing' => true, - 'modernize_types_casting' => true, - 'multiline_comment_opening_closing' => true, - 'native_constant_invocation' => true, - 'no_alias_functions' => true, - 'no_alternative_syntax' => true, - 'no_blank_lines_after_phpdoc' => true, - 'no_empty_comment' => true, - 'no_empty_phpdoc' => true, - 'no_extra_blank_lines' => true, - 'no_leading_import_slash' => true, - 'no_leading_namespace_whitespace' => true, - 'no_spaces_around_offset' => true, - 'no_superfluous_phpdoc_tags' => ['allow_mixed' => true], - 'no_trailing_comma_in_singleline_array' => true, - 'no_unneeded_control_parentheses' => true, - 'no_unset_cast' => true, - 'no_unused_imports' => true, - 'no_useless_else' => true, - 'no_useless_return' => true, - 'no_whitespace_in_blank_line' => true, - 'normalize_index_brace' => true, - 'ordered_imports' => true, - 'php_unit_construct' => true, - 'php_unit_dedicate_assert' => ['target' => 'newest'], - 'php_unit_dedicate_assert_internal_type' => ['target' => 'newest'], - 'php_unit_expectation' => ['target' => 'newest'], - 'php_unit_mock' => ['target' => 'newest'], - 'php_unit_mock_short_will_return' => true, - 'php_unit_no_expectation_annotation' => ['target' => 'newest'], - 'php_unit_test_annotation' => ['style' => 'prefix'], - 'php_unit_test_case_static_method_calls' => ['call_type' => 'self'], - 'phpdoc_align' => ['align' => 'vertical'], - 'phpdoc_line_span' => ['method' => 'multi', 'property' => 'multi'], - 'phpdoc_no_package' => true, - 'phpdoc_no_useless_inheritdoc' => true, - 'phpdoc_scalar' => true, - 'phpdoc_separation' => true, - 'phpdoc_single_line_var_spacing' => true, - 'phpdoc_trim' => true, - 'phpdoc_trim_consecutive_blank_line_separation' => true, - 'phpdoc_types' => true, - 'phpdoc_types_order' => ['null_adjustment' => 'always_last', 'sort_algorithm' => 'none'], - 'phpdoc_var_without_name' => true, - 'return_assignment' => true, - 'self_static_accessor' => true, - 'short_scalar_cast' => true, - 'single_trait_insert_per_statement' => true, - 'standardize_not_equals' => true, - 'static_lambda' => true, - 'ternary_to_null_coalescing' => true, - 'trim_array_spaces' => true, - 'visibility_required' => true, + 'global_namespace_import' => false, + 'phpdoc_annotation_without_dot' => false, + 'phpdoc_summary' => false, + 'phpdoc_to_comment' => false, + 'single_line_throw' => false, + 'void_return' => false, 'yoda_style' => false, - // 'native_function_invocation' => true, ]) ->setFinder( PhpCsFixer\Finder::create() diff --git a/src/Client.php b/src/Client.php index c21fcb6e4..9b0d71070 100644 --- a/src/Client.php +++ b/src/Client.php @@ -120,13 +120,14 @@ public function sendAsync(RequestInterface $request, array $options = []): Promi public function send(RequestInterface $request, array $options = []): ResponseInterface { $options[RequestOptions::SYNCHRONOUS] = true; + return $this->sendAsync($request, $options)->wait(); } /** * The HttpClient PSR (PSR-18) specify this method. * - * @inheritDoc + * {@inheritDoc} */ public function sendRequest(RequestInterface $request): ResponseInterface { @@ -184,6 +185,7 @@ public function requestAsync(string $method, $uri = '', array $options = []): Pr public function request(string $method, $uri = '', array $options = []): ResponseInterface { $options[RequestOptions::SYNCHRONOUS] = true; + return $this->requestAsync($method, $uri, $options)->wait(); } @@ -228,11 +230,11 @@ private function configureDefaults(array $config): void { $defaults = [ 'allow_redirects' => RedirectMiddleware::$defaultSettings, - 'http_errors' => true, - 'decode_content' => true, - 'verify' => true, - 'cookies' => false, - 'idn_conversion' => false, + 'http_errors' => true, + 'decode_content' => true, + 'verify' => true, + 'cookies' => false, + 'idn_conversion' => false, ]; // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set. @@ -354,10 +356,10 @@ private function applyOptions(RequestInterface $request, array &$options): Reque if (isset($options['form_params'])) { if (isset($options['multipart'])) { throw new InvalidArgumentException('You cannot use ' - . 'form_params and multipart at the same time. Use the ' - . 'form_params option if you want to send application/' - . 'x-www-form-urlencoded requests, and the multipart ' - . 'option to send multipart/form-data requests.'); + .'form_params and multipart at the same time. Use the ' + .'form_params option if you want to send application/' + .'x-www-form-urlencoded requests, and the multipart ' + .'option to send multipart/form-data requests.'); } $options['body'] = \http_build_query($options['form_params'], '', '&'); unset($options['form_params']); @@ -403,7 +405,7 @@ private function applyOptions(RequestInterface $request, array &$options): Reque // Ensure that we don't have the header in different case and set the new value. $modify['set_headers'] = Psr7\Utils::caselessRemove(['Authorization'], $modify['set_headers']); $modify['set_headers']['Authorization'] = 'Basic ' - . \base64_encode("$value[0]:$value[1]"); + .\base64_encode("$value[0]:$value[1]"); break; case 'digest': // @todo: Do not rely on curl @@ -447,7 +449,7 @@ private function applyOptions(RequestInterface $request, array &$options): Reque // Ensure that we don't have the header in different case and set the new value. $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary=' - . $request->getBody()->getBoundary(); + .$request->getBody()->getBoundary(); } // Merge in conditional headers if they are not present. @@ -473,9 +475,9 @@ private function applyOptions(RequestInterface $request, array &$options): Reque private function invalidBody(): InvalidArgumentException { return new InvalidArgumentException('Passing in the "body" request ' - . 'option as an array to send a request is not supported. ' - . 'Please use the "form_params" request option to send a ' - . 'application/x-www-form-urlencoded request, or the "multipart" ' - . 'request option to send a multipart/form-data request.'); + .'option as an array to send a request is not supported. ' + .'Please use the "form_params" request option to send a ' + .'application/x-www-form-urlencoded request, or the "multipart" ' + .'request option to send a multipart/form-data request.'); } } diff --git a/src/Cookie/CookieJar.php b/src/Cookie/CookieJar.php index 9985a9814..b4ced5a1a 100644 --- a/src/Cookie/CookieJar.php +++ b/src/Cookie/CookieJar.php @@ -50,10 +50,10 @@ public static function fromArray(array $cookies, string $domain): self $cookieJar = new self(); foreach ($cookies as $name => $value) { $cookieJar->setCookie(new SetCookie([ - 'Domain' => $domain, - 'Name' => $name, - 'Value' => $value, - 'Discard' => true + 'Domain' => $domain, + 'Name' => $name, + 'Value' => $value, + 'Discard' => true, ])); } @@ -97,7 +97,7 @@ public function getCookieByName(string $name): ?SetCookie } /** - * @inheritDoc + * {@inheritDoc} */ public function toArray(): array { @@ -107,12 +107,13 @@ public function toArray(): array } /** - * @inheritDoc + * {@inheritDoc} */ public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void { if (!$domain) { $this->cookies = []; + return; } elseif (!$path) { $this->cookies = \array_filter( @@ -142,7 +143,7 @@ static function (SetCookie $cookie) use ($path, $domain, $name) { } /** - * @inheritDoc + * {@inheritDoc} */ public function clearSessionCookies(): void { @@ -155,7 +156,7 @@ static function (SetCookie $cookie): bool { } /** - * @inheritDoc + * {@inheritDoc} */ public function setCookie(SetCookie $cookie): bool { @@ -170,9 +171,10 @@ public function setCookie(SetCookie $cookie): bool $result = $cookie->validate(); if ($result !== true) { if ($this->strictMode) { - throw new \RuntimeException('Invalid cookie: ' . $result); + throw new \RuntimeException('Invalid cookie: '.$result); } $this->removeCookieIfEmpty($cookie); + return false; } @@ -253,7 +255,7 @@ public function extractCookies(RequestInterface $request, ResponseInterface $res /** * Computes cookie path following RFC 6265 section 5.1.4 * - * @link https://tools.ietf.org/html/rfc6265#section-5.1.4 + * @see https://tools.ietf.org/html/rfc6265#section-5.1.4 */ private function getCookiePathFromRequest(RequestInterface $request): string { @@ -289,8 +291,8 @@ public function withCookieHeader(RequestInterface $request): RequestInterface !$cookie->isExpired() && (!$cookie->getSecure() || $scheme === 'https') ) { - $values[] = $cookie->getName() . '=' - . $cookie->getValue(); + $values[] = $cookie->getName().'=' + .$cookie->getValue(); } } diff --git a/src/Cookie/CookieJarInterface.php b/src/Cookie/CookieJarInterface.php index 7df374b5b..50bc36398 100644 --- a/src/Cookie/CookieJarInterface.php +++ b/src/Cookie/CookieJarInterface.php @@ -13,7 +13,7 @@ * necessary. Subclasses are also responsible for storing and retrieving * cookies from a file, database, etc. * - * @link https://docs.python.org/2/library/cookielib.html Inspiration + * @see https://docs.python.org/2/library/cookielib.html Inspiration * @extends \IteratorAggregate */ interface CookieJarInterface extends \Countable, \IteratorAggregate diff --git a/src/Cookie/SessionCookieJar.php b/src/Cookie/SessionCookieJar.php index 5d51ca982..cb3e67c6a 100644 --- a/src/Cookie/SessionCookieJar.php +++ b/src/Cookie/SessionCookieJar.php @@ -71,7 +71,7 @@ protected function load(): void $this->setCookie(new SetCookie($cookie)); } } elseif (\strlen($data)) { - throw new \RuntimeException("Invalid cookie data"); + throw new \RuntimeException('Invalid cookie data'); } } } diff --git a/src/Cookie/SetCookie.php b/src/Cookie/SetCookie.php index 3f04e307f..d74915bed 100644 --- a/src/Cookie/SetCookie.php +++ b/src/Cookie/SetCookie.php @@ -11,15 +11,15 @@ class SetCookie * @var array */ private static $defaults = [ - 'Name' => null, - 'Value' => null, - 'Domain' => null, - 'Path' => '/', - 'Max-Age' => null, - 'Expires' => null, - 'Secure' => false, - 'Discard' => false, - 'HttpOnly' => false + 'Name' => null, + 'Value' => null, + 'Domain' => null, + 'Path' => '/', + 'Max-Age' => null, + 'Expires' => null, + 'Secure' => false, + 'Discard' => false, + 'HttpOnly' => false, ]; /** @@ -134,13 +134,13 @@ public function __construct(array $data = []) public function __toString() { - $str = $this->data['Name'] . '=' . ($this->data['Value'] ?? '') . '; '; + $str = $this->data['Name'].'='.($this->data['Value'] ?? '').'; '; foreach ($this->data as $k => $v) { if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) { if ($k === 'Expires') { - $str .= 'Expires=' . \gmdate('D, d M Y H:i:s \G\M\T', $v) . '; '; + $str .= 'Expires='.\gmdate('D, d M Y H:i:s \G\M\T', $v).'; '; } else { - $str .= ($v === true ? $k : "{$k}={$v}") . '; '; + $str .= ($v === true ? $k : "{$k}={$v}").'; '; } } } @@ -436,7 +436,7 @@ public function matchesDomain(string $domain): bool return false; } - return (bool) \preg_match('/\.' . \preg_quote($cookieDomain, '/') . '$/', $domain); + return (bool) \preg_match('/\.'.\preg_quote($cookieDomain, '/').'$/', $domain); } /** @@ -465,8 +465,8 @@ public function validate() $name )) { return 'Cookie name must not contain invalid characters: ASCII ' - . 'Control characters (0-31;127), space, tab and the ' - . 'following characters: ()<>@,;:\"/?={}'; + .'Control characters (0-31;127), space, tab and the ' + .'following characters: ()<>@,;:\"/?={}'; } // Value must not be null. 0 and empty string are valid. Empty strings diff --git a/src/Handler/CurlFactory.php b/src/Handler/CurlFactory.php index 95375e30e..3a6a8db26 100644 --- a/src/Handler/CurlFactory.php +++ b/src/Handler/CurlFactory.php @@ -51,7 +51,7 @@ public function create(RequestInterface $request, array $options): EasyHandle unset($options['curl']['body_as_string']); } - $easy = new EasyHandle; + $easy = new EasyHandle(); $easy->request = $request; $easy->options = $options; $conf = $this->getDefaultConf($easy); @@ -161,11 +161,11 @@ private static function finishError(callable $handler, EasyHandle $easy, CurlFac private static function createRejection(EasyHandle $easy, array $ctx): PromiseInterface { static $connectionErrors = [ - \CURLE_OPERATION_TIMEOUTED => true, + \CURLE_OPERATION_TIMEOUTED => true, \CURLE_COULDNT_RESOLVE_HOST => true, - \CURLE_COULDNT_CONNECT => true, - \CURLE_SSL_CONNECT_ERROR => true, - \CURLE_GOT_NOTHING => true, + \CURLE_COULDNT_CONNECT => true, + \CURLE_SSL_CONNECT_ERROR => true, + \CURLE_GOT_NOTHING => true, ]; if ($easy->createResponseException) { @@ -219,11 +219,11 @@ private static function createRejection(EasyHandle $easy, array $ctx): PromiseIn private function getDefaultConf(EasyHandle $easy): array { $conf = [ - '_headers' => $easy->request->getHeaders(), - \CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(), - \CURLOPT_URL => (string) $easy->request->getUri()->withFragment(''), + '_headers' => $easy->request->getHeaders(), + \CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(), + \CURLOPT_URL => (string) $easy->request->getUri()->withFragment(''), \CURLOPT_RETURNTRANSFER => false, - \CURLOPT_HEADER => false, + \CURLOPT_HEADER => false, \CURLOPT_CONNECTTIMEOUT => 300, ]; @@ -250,6 +250,7 @@ private function applyMethod(EasyHandle $easy, array &$conf): void if ($size === null || $size > 0) { $this->applyBody($easy->request, $easy->options, $conf); + return; } @@ -341,6 +342,7 @@ private function removeHeader(string $name, array &$options): void foreach (\array_keys($options['_headers']) as $key) { if (!\strcasecmp($key, $name)) { unset($options['_headers'][$key]); + return; } } @@ -487,8 +489,8 @@ private function applyHandlerOptions(EasyHandle $easy, array &$conf): void if (!\file_exists($cert)) { throw new \InvalidArgumentException("SSL certificate not found: {$cert}"); } - # OpenSSL (versions 0.9.3 and later) also support "P12" for PKCS#12-encoded files. - # see https://curl.se/libcurl/c/CURLOPT_SSLCERTTYPE.html + // OpenSSL (versions 0.9.3 and later) also support "P12" for PKCS#12-encoded files. + // see https://curl.se/libcurl/c/CURLOPT_SSLCERTTYPE.html $ext = pathinfo($cert, \PATHINFO_EXTENSION); if (preg_match('#^(der|p12)$#i', $ext)) { $conf[\CURLOPT_SSLCERTTYPE] = strtoupper($ext); @@ -551,9 +553,10 @@ private static function retryFailedRewind(callable $handler, EasyHandle $easy, a } } catch (\RuntimeException $e) { $ctx['error'] = 'The connection unexpectedly failed without ' - . 'providing an error. The request would have been retried, ' - . 'but attempting to rewind the request body failed. ' - . 'Exception: ' . $e; + .'providing an error. The request would have been retried, ' + .'but attempting to rewind the request body failed. ' + .'Exception: '.$e; + return self::createRejection($easy, $ctx); } @@ -562,14 +565,15 @@ private static function retryFailedRewind(callable $handler, EasyHandle $easy, a $easy->options['_curl_retries'] = 1; } elseif ($easy->options['_curl_retries'] == 2) { $ctx['error'] = 'The cURL request was retried 3 times ' - . 'and did not succeed. The most likely reason for the failure ' - . 'is that cURL was unable to rewind the body of the request ' - . 'and subsequent retries resulted in the same error. Turn on ' - . 'the debug option to see what went wrong. See ' - . 'https://bugs.php.net/bug.php?id=47204 for more information.'; + .'and did not succeed. The most likely reason for the failure ' + .'is that cURL was unable to rewind the body of the request ' + .'and subsequent retries resulted in the same error. Turn on ' + .'the debug option to see what went wrong. See ' + .'https://bugs.php.net/bug.php?id=47204 for more information.'; + return self::createRejection($easy, $ctx); } else { - $easy->options['_curl_retries']++; + ++$easy->options['_curl_retries']; } return $handler($easy->request, $easy->options); @@ -599,6 +603,7 @@ private function createHeaderFn(EasyHandle $easy): callable $easy->createResponse(); } catch (\Exception $e) { $easy->createResponseException = $e; + return -1; } if ($onHeaders !== null) { @@ -608,6 +613,7 @@ private function createHeaderFn(EasyHandle $easy): callable // Associate the exception with the handle and trigger // a curl header write error by returning 0. $easy->onHeadersException = $e; + return -1; } } @@ -617,6 +623,7 @@ private function createHeaderFn(EasyHandle $easy): callable } else { $easy->headers[] = $value; } + return \strlen($h); }; } diff --git a/src/Handler/CurlMultiHandler.php b/src/Handler/CurlMultiHandler.php index 4356d0247..f0acde145 100644 --- a/src/Handler/CurlMultiHandler.php +++ b/src/Handler/CurlMultiHandler.php @@ -164,7 +164,8 @@ public function tick(): void \usleep(250); } - while (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM); + while (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM) { + } $this->processMessages(); } diff --git a/src/Handler/EasyHandle.php b/src/Handler/EasyHandle.php index 224344d7c..1bc39f4b4 100644 --- a/src/Handler/EasyHandle.php +++ b/src/Handler/EasyHandle.php @@ -106,7 +106,7 @@ public function createResponse(): void */ public function __get($name) { - $msg = $name === 'handle' ? 'The EasyHandle has been released' : 'Invalid property: ' . $name; + $msg = $name === 'handle' ? 'The EasyHandle has been released' : 'Invalid property: '.$name; throw new \BadMethodCallException($msg); } } diff --git a/src/Handler/HeaderProcessor.php b/src/Handler/HeaderProcessor.php index a0988845f..5554b8fa9 100644 --- a/src/Handler/HeaderProcessor.php +++ b/src/Handler/HeaderProcessor.php @@ -14,9 +14,9 @@ final class HeaderProcessor * * @param string[] $headers * - * @throws \RuntimeException - * * @return array{0:string, 1:int, 2:?string, 3:array} + * + * @throws \RuntimeException */ public static function parseHeaders(array $headers): array { diff --git a/src/Handler/MockHandler.php b/src/Handler/MockHandler.php index 79664e279..77ffed521 100644 --- a/src/Handler/MockHandler.php +++ b/src/Handler/MockHandler.php @@ -138,6 +138,7 @@ function ($reason) use ($request, $options) { if ($this->onRejected) { ($this->onRejected)($reason); } + return P\Create::rejectionFor($reason); } ); @@ -159,7 +160,7 @@ public function append(...$values): void ) { $this->queue[] = $value; } else { - throw new \TypeError('Expected a Response, Promise, Throwable or callable. Found ' . Utils::describeType($value)); + throw new \TypeError('Expected a Response, Promise, Throwable or callable. Found '.Utils::describeType($value)); } } } diff --git a/src/Handler/StreamHandler.php b/src/Handler/StreamHandler.php index 310987c20..61632f564 100644 --- a/src/Handler/StreamHandler.php +++ b/src/Handler/StreamHandler.php @@ -67,7 +67,7 @@ public function __invoke(RequestInterface $request, array $options): PromiseInte if (false !== \strpos($message, 'getaddrinfo') // DNS lookup failed || false !== \strpos($message, 'Connection refused') || false !== \strpos($message, "couldn't connect to host") // error on HHVM - || false !== \strpos($message, "connection attempt failed") + || false !== \strpos($message, 'connection attempt failed') ) { $e = new ConnectException($e->getMessage(), $request, $e); } else { @@ -231,9 +231,10 @@ private function createResource(callable $callback) \set_error_handler(static function ($_, $msg, $file, $line) use (&$errors): bool { $errors[] = [ 'message' => $msg, - 'file' => $file, - 'line' => $line + 'file' => $file, + 'line' => $line, ]; + return true; }); @@ -247,7 +248,7 @@ private function createResource(callable $callback) $message = 'Error creating resource: '; foreach ($errors as $err) { foreach ($err as $key => $value) { - $message .= "[$key] $value" . \PHP_EOL; + $message .= "[$key] $value".\PHP_EOL; } } throw new \RuntimeException(\trim($message)); @@ -350,6 +351,7 @@ private function resolveHost(RequestInterface $request, array $options): UriInte if (false === $records || !isset($records[0]['ip'])) { throw new ConnectException(\sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request); } + return $uri->withHost($records[0]['ip']); } if ('v6' === $options['force_ip_resolve']) { @@ -357,7 +359,8 @@ private function resolveHost(RequestInterface $request, array $options): UriInte if (false === $records || !isset($records[0]['ipv6'])) { throw new ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request); } - return $uri->withHost('[' . $records[0]['ipv6'] . ']'); + + return $uri->withHost('['.$records[0]['ipv6'].']'); } } @@ -375,11 +378,11 @@ private function getDefaultContext(RequestInterface $request): array $context = [ 'http' => [ - 'method' => $request->getMethod(), - 'header' => $headers, + 'method' => $request->getMethod(), + 'header' => $headers, 'protocol_version' => $request->getProtocolVersion(), - 'ignore_errors' => true, - 'follow_location' => 0, + 'ignore_errors' => true, + 'follow_location' => 0, ], 'ssl' => [ 'peer_name' => $request->getUri()->getHost(), @@ -561,27 +564,27 @@ private function add_debug(RequestInterface $request, array &$options, $value, a } static $map = [ - \STREAM_NOTIFY_CONNECT => 'CONNECT', + \STREAM_NOTIFY_CONNECT => 'CONNECT', \STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED', - \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT', - \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS', - \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS', - \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED', - \STREAM_NOTIFY_PROGRESS => 'PROGRESS', - \STREAM_NOTIFY_FAILURE => 'FAILURE', - \STREAM_NOTIFY_COMPLETED => 'COMPLETED', - \STREAM_NOTIFY_RESOLVE => 'RESOLVE', + \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT', + \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS', + \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS', + \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED', + \STREAM_NOTIFY_PROGRESS => 'PROGRESS', + \STREAM_NOTIFY_FAILURE => 'FAILURE', + \STREAM_NOTIFY_COMPLETED => 'COMPLETED', + \STREAM_NOTIFY_RESOLVE => 'RESOLVE', ]; static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max']; $value = Utils::debugResource($value); - $ident = $request->getMethod() . ' ' . $request->getUri()->withFragment(''); + $ident = $request->getMethod().' '.$request->getUri()->withFragment(''); self::addNotification( $params, static function (int $code, ...$passed) use ($ident, $value, $map, $args): void { \fprintf($value, '<%s> [%s] ', $ident, $map[$code]); foreach (\array_filter($passed) as $i => $v) { - \fwrite($value, $args[$i] . ': "' . $v . '" '); + \fwrite($value, $args[$i].': "'.$v.'" '); } \fwrite($value, "\n"); } @@ -596,7 +599,7 @@ private static function addNotification(array &$params, callable $notify): void } else { $params['notification'] = self::callArray([ $params['notification'], - $notify + $notify, ]); } } diff --git a/src/HandlerStack.php b/src/HandlerStack.php index e0a1d1191..1ce9c4b19 100644 --- a/src/HandlerStack.php +++ b/src/HandlerStack.php @@ -86,14 +86,14 @@ public function __toString() $stack = []; if ($this->handler !== null) { - $stack[] = "0) Handler: " . $this->debugCallable($this->handler); + $stack[] = '0) Handler: '.$this->debugCallable($this->handler); } $result = ''; foreach (\array_reverse($this->stack) as $tuple) { - $depth++; + ++$depth; $str = "{$depth}) Name: '{$tuple[1]}', "; - $str .= "Function: " . $this->debugCallable($tuple[0]); + $str .= 'Function: '.$this->debugCallable($tuple[0]); $result = "> {$str}\n{$result}"; $stack[] = $str; } @@ -122,7 +122,7 @@ public function setHandler(callable $handler): void */ public function hasHandler(): bool { - return $this->handler !== null ; + return $this->handler !== null; } /** @@ -266,10 +266,10 @@ private function debugCallable($fn): string if (\is_array($fn)) { return \is_string($fn[0]) ? "callable({$fn[0]}::{$fn[1]})" - : "callable(['" . \get_class($fn[0]) . "', '{$fn[1]}'])"; + : "callable(['".\get_class($fn[0])."', '{$fn[1]}'])"; } /** @var object $fn */ - return 'callable(' . \spl_object_hash($fn) . ')'; + return 'callable('.\spl_object_hash($fn).')'; } } diff --git a/src/MessageFormatter.php b/src/MessageFormatter.php index da499547f..9b77eee83 100644 --- a/src/MessageFormatter.php +++ b/src/MessageFormatter.php @@ -40,11 +40,11 @@ class MessageFormatter implements MessageFormatterInterface /** * Apache Common Log Format. * - * @link https://httpd.apache.org/docs/2.4/logs.html#common + * @see https://httpd.apache.org/docs/2.4/logs.html#common * * @var string */ - public const CLF = "{hostname} {req_header_User-Agent} - [{date_common_log}] \"{method} {target} HTTP/{version}\" {code} {res_header_Content-Length}"; + public const CLF = '{hostname} {req_header_User-Agent} - [{date_common_log}] "{method} {target} HTTP/{version}" {code} {res_header_Content-Length}'; public const DEBUG = ">>>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{error}"; public const SHORT = '[{ts}] "{method} {target} HTTP/{version}" {code}'; @@ -90,9 +90,9 @@ function (array $matches) use ($request, $response, $error, &$cache) { break; case 'req_headers': $result = \trim($request->getMethod() - . ' ' . $request->getRequestTarget()) - . ' HTTP/' . $request->getProtocolVersion() . "\r\n" - . $this->headers($request); + .' '.$request->getRequestTarget()) + .' HTTP/'.$request->getProtocolVersion()."\r\n" + .$this->headers($request); break; case 'res_headers': $result = $response ? @@ -101,7 +101,7 @@ function (array $matches) use ($request, $response, $error, &$cache) { $response->getProtocolVersion(), $response->getStatusCode(), $response->getReasonPhrase() - ) . "\r\n" . $this->headers($response) + )."\r\n".$this->headers($response) : 'NULL'; break; case 'req_body': @@ -177,6 +177,7 @@ function (array $matches) use ($request, $response, $error, &$cache) { } $cache[$matches[1]] = $result; + return $result; }, $this->template @@ -190,7 +191,7 @@ private function headers(MessageInterface $message): string { $result = ''; foreach ($message->getHeaders() as $name => $values) { - $result .= $name . ': ' . \implode(', ', $values) . "\r\n"; + $result .= $name.': '.\implode(', ', $values)."\r\n"; } return \trim($result); diff --git a/src/Middleware.php b/src/Middleware.php index 7035c77ff..7e3eb6b3a 100644 --- a/src/Middleware.php +++ b/src/Middleware.php @@ -34,10 +34,12 @@ public static function cookies(): callable } $cookieJar = $options['cookies']; $request = $cookieJar->withCookieHeader($request); + return $handler($request, $options) ->then( static function (ResponseInterface $response) use ($cookieJar, $request): ResponseInterface { $cookieJar->extractCookies($request, $response); + return $response; } ); @@ -60,6 +62,7 @@ public static function httpErrors(BodySummarizerInterface $bodySummarizer = null if (empty($options['http_errors'])) { return $handler($request, $options); } + return $handler($request, $options)->then( static function (ResponseInterface $response) use ($request, $bodySummarizer) { $code = $response->getStatusCode(); @@ -93,20 +96,22 @@ public static function history(&$container): callable return $handler($request, $options)->then( static function ($value) use ($request, &$container, $options) { $container[] = [ - 'request' => $request, + 'request' => $request, 'response' => $value, - 'error' => null, - 'options' => $options + 'error' => null, + 'options' => $options, ]; + return $value; }, static function ($reason) use ($request, &$container, $options) { $container[] = [ - 'request' => $request, + 'request' => $request, 'response' => null, - 'error' => $reason, - 'options' => $options + 'error' => $reason, + 'options' => $options, ]; + return P\Create::rejectionFor($reason); } ); @@ -138,6 +143,7 @@ public static function tap(callable $before = null, callable $after = null): cal if ($after) { $after($request, $options, $response); } + return $response; }; }; @@ -202,12 +208,14 @@ public static function log(LoggerInterface $logger, $formatter, string $logLevel static function ($response) use ($logger, $request, $formatter, $logLevel): ResponseInterface { $message = $formatter->format($request, $response); $logger->log($logLevel, $message); + return $response; }, static function ($reason) use ($logger, $request, $formatter): PromiseInterface { $response = $reason instanceof RequestException ? $reason->getResponse() : null; $message = $formatter->format($request, $response, P\Create::exceptionFor($reason)); $logger->error($message); + return P\Create::rejectionFor($reason); } ); diff --git a/src/PrepareBodyMiddleware.php b/src/PrepareBodyMiddleware.php index 7ca628338..0a8de8128 100644 --- a/src/PrepareBodyMiddleware.php +++ b/src/PrepareBodyMiddleware.php @@ -84,6 +84,7 @@ private function addExpectHeader(RequestInterface $request, array $options, arra // The expect header is unconditionally enabled if ($expect === true) { $modify['set_headers']['Expect'] = '100-Continue'; + return; } diff --git a/src/RedirectMiddleware.php b/src/RedirectMiddleware.php index f67d448be..f32808a75 100644 --- a/src/RedirectMiddleware.php +++ b/src/RedirectMiddleware.php @@ -27,10 +27,10 @@ class RedirectMiddleware * @var array */ public static $defaultSettings = [ - 'max' => 5, - 'protocols' => ['http', 'https'], - 'strict' => false, - 'referer' => false, + 'max' => 5, + 'protocols' => ['http', 'https'], + 'strict' => false, + 'referer' => false, 'track_redirects' => false, ]; diff --git a/src/RequestOptions.php b/src/RequestOptions.php index 542cd72c0..bf3b02b6b 100644 --- a/src/RequestOptions.php +++ b/src/RequestOptions.php @@ -7,7 +7,7 @@ * * More documentation for each option can be found at http://guzzlephp.org/. * - * @link http://docs.guzzlephp.org/en/v6/request-options.html + * @see http://docs.guzzlephp.org/en/v6/request-options.html */ final class RequestOptions { diff --git a/src/RetryMiddleware.php b/src/RetryMiddleware.php index 0236a9d54..8f4d93ac4 100644 --- a/src/RetryMiddleware.php +++ b/src/RetryMiddleware.php @@ -44,7 +44,7 @@ public function __construct(callable $decider, callable $nextHandler, callable $ { $this->decider = $decider; $this->nextHandler = $nextHandler; - $this->delay = $delay ?: __CLASS__ . '::exponentialDelay'; + $this->delay = $delay ?: __CLASS__.'::exponentialDelay'; } /** @@ -54,7 +54,7 @@ public function __construct(callable $decider, callable $nextHandler, callable $ */ public static function exponentialDelay(int $retries): int { - return (int) \pow(2, $retries - 1) * 1000; + return (int) 2 ** ($retries - 1) * 1000; } public function __invoke(RequestInterface $request, array $options): PromiseInterface @@ -64,6 +64,7 @@ public function __invoke(RequestInterface $request, array $options): PromiseInte } $fn = $this->nextHandler; + return $fn($request, $options) ->then( $this->onFulfilled($request, $options), @@ -85,6 +86,7 @@ private function onFulfilled(RequestInterface $request, array $options): callabl )) { return $value; } + return $this->doRetry($request, $options, $value); }; } @@ -103,6 +105,7 @@ private function onRejected(RequestInterface $req, array $options): callable )) { return P\Create::rejectionFor($reason); } + return $this->doRetry($req, $options); }; } diff --git a/src/Utils.php b/src/Utils.php index e355f3212..fcf571d6b 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -23,9 +23,9 @@ public static function describeType($input): string { switch (\gettype($input)) { case 'object': - return 'object(' . \get_class($input) . ')'; + return 'object('.\get_class($input).')'; case 'array': - return 'array(' . \count($input) . ')'; + return 'array('.\count($input).')'; default: \ob_start(); \var_dump($input); @@ -79,9 +79,9 @@ public static function debugResource($value = null) * * The returned handler is not wrapped by any default middlewares. * - * @throws \RuntimeException if no viable Handler is available. - * * @return callable(\Psr\Http\Message\RequestInterface, array): \GuzzleHttp\Promise\PromiseInterface Returns the best handler for the given system. + * + * @throws \RuntimeException if no viable Handler is available. */ public static function chooseHandler(): callable { @@ -247,8 +247,8 @@ public static function isHostInNoProxy(string $host, array $noProxyArray): bool } // Special match if the area when prefixed with ".". Remove any // existing leading "." and add a new leading ".". - $area = '.' . \ltrim($area, '.'); - if (\substr($host, -(\strlen($area))) === $area) { + $area = '.'.\ltrim($area, '.'); + if (\substr($host, -\strlen($area)) === $area) { return true; } } @@ -269,13 +269,13 @@ public static function isHostInNoProxy(string $host, array $noProxyArray): bool * * @throws InvalidArgumentException if the JSON cannot be decoded. * - * @link https://www.php.net/manual/en/function.json-decode.php + * @see https://www.php.net/manual/en/function.json-decode.php */ public static function jsonDecode(string $json, bool $assoc = false, int $depth = 512, int $options = 0) { $data = \json_decode($json, $assoc, $depth, $options); if (\JSON_ERROR_NONE !== \json_last_error()) { - throw new InvalidArgumentException('json_decode error: ' . \json_last_error_msg()); + throw new InvalidArgumentException('json_decode error: '.\json_last_error_msg()); } return $data; @@ -290,13 +290,13 @@ public static function jsonDecode(string $json, bool $assoc = false, int $depth * * @throws InvalidArgumentException if the JSON cannot be encoded. * - * @link https://www.php.net/manual/en/function.json-encode.php + * @see https://www.php.net/manual/en/function.json-encode.php */ public static function jsonEncode($value, int $options = 0, int $depth = 512): string { $json = \json_encode($value, $options, $depth); if (\JSON_ERROR_NONE !== \json_last_error()) { - throw new InvalidArgumentException('json_encode error: ' . \json_last_error_msg()); + throw new InvalidArgumentException('json_encode error: '.\json_last_error_msg()); } /** @var string */ @@ -341,7 +341,7 @@ public static function idnUriConvert(UriInterface $uri, int $options = 0): UriIn $errorMessage = 'IDN conversion failed'; if ($errors) { - $errorMessage .= ' (errors: ' . implode(', ', $errors) . ')'; + $errorMessage .= ' (errors: '.implode(', ', $errors).')'; } throw new InvalidArgumentException($errorMessage); diff --git a/src/functions.php b/src/functions.php index a70d2cbf3..5edc66ab1 100644 --- a/src/functions.php +++ b/src/functions.php @@ -50,10 +50,10 @@ function debug_resource($value = null) * * The returned handler is not wrapped by any default middlewares. * - * @throws \RuntimeException if no viable Handler is available. - * * @return callable(\Psr\Http\Message\RequestInterface, array): \GuzzleHttp\Promise\PromiseInterface Returns the best handler for the given system. * + * @throws \RuntimeException if no viable Handler is available. + * * @deprecated choose_handler will be removed in guzzlehttp/guzzle:8.0. Use Utils::chooseHandler instead. */ function choose_handler(): callable @@ -141,7 +141,7 @@ function is_host_in_noproxy(string $host, array $noProxyArray): bool * * @throws Exception\InvalidArgumentException if the JSON cannot be decoded. * - * @link https://www.php.net/manual/en/function.json-decode.php + * @see https://www.php.net/manual/en/function.json-decode.php * @deprecated json_decode will be removed in guzzlehttp/guzzle:8.0. Use Utils::jsonDecode instead. */ function json_decode(string $json, bool $assoc = false, int $depth = 512, int $options = 0) @@ -158,7 +158,7 @@ function json_decode(string $json, bool $assoc = false, int $depth = 512, int $o * * @throws Exception\InvalidArgumentException if the JSON cannot be encoded. * - * @link https://www.php.net/manual/en/function.json-encode.php + * @see https://www.php.net/manual/en/function.json-encode.php * @deprecated json_encode will be removed in guzzlehttp/guzzle:8.0. Use Utils::jsonEncode instead. */ function json_encode($value, int $options = 0, int $depth = 512): string diff --git a/src/functions_include.php b/src/functions_include.php index 6636a4224..394f95347 100644 --- a/src/functions_include.php +++ b/src/functions_include.php @@ -2,5 +2,5 @@ // Don't redefine the functions if included multiple times. if (!\function_exists('GuzzleHttp\describe_type')) { - require __DIR__ . '/functions.php'; + require __DIR__.'/functions.php'; } diff --git a/tests/ClientTest.php b/tests/ClientTest.php index e330679ed..39d4829a6 100644 --- a/tests/ClientTest.php +++ b/tests/ClientTest.php @@ -61,9 +61,9 @@ public function testClientHasOptions() { $client = new Client([ 'base_uri' => 'http://foo.com', - 'timeout' => 2, - 'headers' => ['bar' => 'baz'], - 'handler' => new MockHandler() + 'timeout' => 2, + 'headers' => ['bar' => 'baz'], + 'handler' => new MockHandler(), ]); $config = Helpers::readObjectAttribute($client, 'config'); self::assertArrayHasKey('base_uri', $config); @@ -80,12 +80,12 @@ public function testCanMergeOnBaseUri() $mock = new MockHandler([new Response()]); $client = new Client([ 'base_uri' => 'http://foo.com/bar/', - 'handler' => $mock + 'handler' => $mock, ]); $client->get('baz'); self::assertSame( 'http://foo.com/bar/baz', - (string)$mock->getLastRequest()->getUri() + (string) $mock->getLastRequest()->getUri() ); } @@ -93,8 +93,8 @@ public function testCanMergeOnBaseUriWithRequest() { $mock = new MockHandler([new Response(), new Response()]); $client = new Client([ - 'handler' => $mock, - 'base_uri' => 'http://foo.com/bar/' + 'handler' => $mock, + 'base_uri' => 'http://foo.com/bar/', ]); $client->request('GET', new Uri('baz')); self::assertSame( @@ -114,8 +114,8 @@ public function testCanUseRelativeUriWithSend() { $mock = new MockHandler([new Response()]); $client = new Client([ - 'handler' => $mock, - 'base_uri' => 'http://bar.com' + 'handler' => $mock, + 'base_uri' => 'http://bar.com', ]); $config = Helpers::readObjectAttribute($client, 'config'); self::assertSame('http://bar.com', (string) $config['base_uri']); @@ -143,7 +143,7 @@ public function testDoesNotOverwriteHeaderWithDefault() $mock = new MockHandler([new Response()]); $c = new Client([ 'headers' => ['User-agent' => 'foo'], - 'handler' => $mock + 'handler' => $mock, ]); $c->get('http://example.com', ['headers' => ['User-Agent' => 'bar']]); self::assertSame('bar', $mock->getLastRequest()->getHeaderLine('User-Agent')); @@ -154,7 +154,7 @@ public function testDoesNotOverwriteHeaderWithDefaultInRequest() $mock = new MockHandler([new Response()]); $c = new Client([ 'headers' => ['User-agent' => 'foo'], - 'handler' => $mock + 'handler' => $mock, ]); $request = new Request('GET', Server::$url, ['User-Agent' => 'bar']); $c->send($request); @@ -166,7 +166,7 @@ public function testDoesOverwriteHeaderWithSetRequestOption() $mock = new MockHandler([new Response()]); $c = new Client([ 'headers' => ['User-agent' => 'foo'], - 'handler' => $mock + 'handler' => $mock, ]); $request = new Request('GET', Server::$url, ['User-Agent' => 'bar']); $c->send($request, ['headers' => ['User-Agent' => 'YO']]); @@ -178,7 +178,7 @@ public function testCanUnsetRequestOptionWithNull() $mock = new MockHandler([new Response()]); $c = new Client([ 'headers' => ['foo' => 'bar'], - 'handler' => $mock + 'handler' => $mock, ]); $c->get('http://example.com', ['headers' => null]); self::assertFalse($mock->getLastRequest()->hasHeader('foo')); @@ -229,7 +229,7 @@ public function testSetCookieToTrueUsesSharedJar() { $mock = new MockHandler([ new Response(200, ['Set-Cookie' => 'foo=bar']), - new Response() + new Response(), ]); $handler = HandlerStack::create($mock); $client = new Client(['handler' => $handler, 'cookies' => true]); @@ -242,7 +242,7 @@ public function testSetCookieToJar() { $mock = new MockHandler([ new Response(200, ['Set-Cookie' => 'foo=bar']), - new Response() + new Response(), ]); $handler = HandlerStack::create($mock); $client = new Client(['handler' => $handler]); @@ -352,7 +352,7 @@ public function testCanAddJsonDataWithoutOverwritingContentType() $request = new Request('PUT', 'http://foo.com'); $client->send($request, [ 'headers' => ['content-type' => 'foo'], - 'json' => 'a' + 'json' => 'a', ]); $last = $mock->getLastRequest(); self::assertSame('"a"', (string) $mock->getLastRequest()->getBody()); @@ -366,7 +366,7 @@ public function testCanAddJsonDataWithNullHeader() $request = new Request('PUT', 'http://foo.com'); $client->send($request, [ 'headers' => null, - 'json' => 'a' + 'json' => 'a', ]); $last = $mock->getLastRequest(); self::assertSame('"a"', (string) $mock->getLastRequest()->getBody()); @@ -399,7 +399,7 @@ public function testAuthCanBeArrayForDigestAuth() $last = $mock->getLastOptions(); self::assertSame([ \CURLOPT_HTTPAUTH => 2, - \CURLOPT_USERPWD => 'a:b' + \CURLOPT_USERPWD => 'a:b', ], $last['curl']); } @@ -411,7 +411,7 @@ public function testAuthCanBeArrayForNtlmAuth() $last = $mock->getLastOptions(); self::assertSame([ \CURLOPT_HTTPAUTH => 8, - \CURLOPT_USERPWD => 'a:b' + \CURLOPT_USERPWD => 'a:b', ], $last['curl']); } @@ -431,8 +431,8 @@ public function testCanAddFormParams() $client->post('http://foo.com', [ 'form_params' => [ 'foo' => 'bar bam', - 'baz' => ['boo' => 'qux'] - ] + 'baz' => ['boo' => 'qux'], + ], ]); $last = $mock->getLastRequest(); self::assertSame( @@ -454,8 +454,8 @@ public function testFormParamsEncodedProperly() $client->post('http://foo.com', [ 'form_params' => [ 'foo' => 'bar bam', - 'baz' => ['boo' => 'qux'] - ] + 'baz' => ['boo' => 'qux'], + ], ]); $last = $mock->getLastRequest(); self::assertSame( @@ -474,7 +474,7 @@ public function testEnsuresThatFormParamsAndMultipartAreExclusive() $this->expectException(\InvalidArgumentException::class); $client->post('http://foo.com', [ 'form_params' => ['foo' => 'bar bam'], - 'multipart' => [] + 'multipart' => [], ]); } @@ -485,14 +485,14 @@ public function testCanSendMultipart() $client->post('http://foo.com', [ 'multipart' => [ [ - 'name' => 'foo', - 'contents' => 'bar' + 'name' => 'foo', + 'contents' => 'bar', ], [ - 'name' => 'test', - 'contents' => \fopen(__FILE__, 'r') - ] - ] + 'name' => 'test', + 'contents' => \fopen(__FILE__, 'r'), + ], + ], ]); $last = $mock->getLastRequest(); @@ -508,7 +508,7 @@ public function testCanSendMultipart() self::assertStringContainsString('bar', (string) $last->getBody()); self::assertStringContainsString( - 'Content-Disposition: form-data; name="foo"' . "\r\n", + 'Content-Disposition: form-data; name="foo"'."\r\n", (string) $last->getBody() ); self::assertStringContainsString( @@ -554,7 +554,7 @@ public function testCanSendMultipartWithExplicitBody() self::assertStringContainsString('bar', (string) $last->getBody()); self::assertStringContainsString( - 'Content-Disposition: form-data; name="foo"' . "\r\n", + 'Content-Disposition: form-data; name="foo"'."\r\n", (string) $last->getBody() ); self::assertStringContainsString( @@ -587,7 +587,7 @@ public function testUsesProxyEnvironmentVariables() $config = Helpers::readObjectAttribute($client, 'config'); self::assertArrayHasKey('proxy', $config); self::assertSame( - ['http' => '127.0.0.1', 'https' => '127.0.0.2', 'no' => ['127.0.0.3','127.0.0.4']], + ['http' => '127.0.0.1', 'https' => '127.0.0.2', 'no' => ['127.0.0.3', '127.0.0.4']], $config['proxy'] ); } finally { @@ -620,7 +620,7 @@ public function testSendWithInvalidHeader() $request = new Request('GET', 'http://foo.com'); $this->expectException(\GuzzleHttp\Exception\InvalidArgumentException::class); - $client->send($request, ['headers'=>['X-Foo: Bar']]); + $client->send($request, ['headers' => ['X-Foo: Bar']]); } public function testSendWithInvalidHeaders() @@ -630,7 +630,7 @@ public function testSendWithInvalidHeaders() $request = new Request('GET', 'http://foo.com'); $this->expectException(\GuzzleHttp\Exception\InvalidArgumentException::class); - $client->send($request, ['headers'=>['X-Foo: Bar', 'X-Test: Fail']]); + $client->send($request, ['headers' => ['X-Foo: Bar', 'X-Test: Fail']]); } public function testCanSetCustomHandler() @@ -641,7 +641,7 @@ public function testCanSetCustomHandler() self::assertSame( 200, $client->send(new Request('GET', 'http://foo.com'), [ - 'handler' => $mock2 + 'handler' => $mock2, ])->getStatusCode() ); } @@ -711,7 +711,7 @@ public function testOnlyAddSchemeWhenHostIsPresent() public function testThatVersionIsOverwrittenWhenSendingARequest() { $mockHandler = new MockHandler([new Response(), new Response()]); - $client = new Client(['handler' => $mockHandler]); + $client = new Client(['handler' => $mockHandler]); $request = new Request('get', '/bar', [], null, '1.1'); $client->send($request, [RequestOptions::VERSION => '1.0']); @@ -817,7 +817,7 @@ public function testIdnBaseUri() { $mock = new MockHandler([new Response()]); $client = new Client([ - 'handler' => $mock, + 'handler' => $mock, 'base_uri' => 'http://яндекс.рф', 'idn_conversion' => true, ]); @@ -836,7 +836,7 @@ public function testIdnWithRedirect() { $mockHandler = new MockHandler([ new Response(302, ['Location' => 'http://www.tést.com/whatever']), - new Response() + new Response(), ]); $handler = HandlerStack::create($mockHandler); $requests = []; @@ -846,9 +846,9 @@ public function testIdnWithRedirect() $client->request('GET', 'https://яндекс.рф/images', [ RequestOptions::ALLOW_REDIRECTS => [ 'referer' => true, - 'track_redirects' => true + 'track_redirects' => true, ], - 'idn_conversion' => true + 'idn_conversion' => true, ]); $request = $mockHandler->getLastRequest(); diff --git a/tests/Cookie/CookieJarTest.php b/tests/Cookie/CookieJarTest.php index 5cf2dec69..87d95bd9c 100644 --- a/tests/Cookie/CookieJarTest.php +++ b/tests/Cookie/CookieJarTest.php @@ -31,7 +31,7 @@ protected function getTestCookies() return [ new SetCookie(['Name' => 'foo', 'Value' => 'bar', 'Domain' => 'foo.com', 'Path' => '/', 'Discard' => true]), new SetCookie(['Name' => 'test', 'Value' => '123', 'Domain' => 'baz.com', 'Path' => '/foo', 'Expires' => 2]), - new SetCookie(['Name' => 'you', 'Value' => '123', 'Domain' => 'bar.com', 'Path' => '/boo', 'Expires' => \time() + 1000]) + new SetCookie(['Name' => 'you', 'Value' => '123', 'Domain' => 'bar.com', 'Path' => '/boo', 'Expires' => \time() + 1000]), ]; } @@ -39,7 +39,7 @@ public function testCreatesFromArray() { $jar = CookieJar::fromArray([ 'foo' => 'bar', - 'baz' => 'bam' + 'baz' => 'bam', ], 'example.com'); self::assertCount(2, $jar); } @@ -58,8 +58,8 @@ public function testGetsCookiesByName() $testCookie = $cookies[0]; self::assertEquals($testCookie, $this->jar->getCookieByName($testCookie->getName())); - self::assertNull($this->jar->getCookieByName("doesnotexist")); - self::assertNull($this->jar->getCookieByName("")); + self::assertNull($this->jar->getCookieByName('doesnotexist')); + self::assertNull($this->jar->getCookieByName('')); } /** @@ -151,7 +151,7 @@ public static function providesIncompleteCookies(): array ], [ [ - 'Name' => 'foo', + 'Name' => 'foo', 'Domain' => 'foo.com', ], ], @@ -171,16 +171,16 @@ public static function providesEmptyCookies(): array return [ [ [ - 'Name' => '', + 'Name' => '', 'Domain' => 'foo.com', - 'Value' => 0, + 'Value' => 0, ], ], [ [ - 'Name' => null, + 'Name' => null, 'Domain' => 'foo.com', - 'Value' => 0, + 'Value' => 0, ], ], ]; @@ -199,30 +199,30 @@ public static function providesValidCookies(): array return [ [ [ - 'Name' => '0', + 'Name' => '0', 'Domain' => 'foo.com', - 'Value' => 0, + 'Value' => 0, ], ], [ [ - 'Name' => 'foo', + 'Name' => 'foo', 'Domain' => 'foo.com', - 'Value' => 0, + 'Value' => 0, ], ], [ [ - 'Name' => 'foo', + 'Name' => 'foo', 'Domain' => 'foo.com', - 'Value' => 0.0, + 'Value' => 0.0, ], ], [ [ - 'Name' => 'foo', + 'Name' => 'foo', 'Domain' => 'foo.com', - 'Value' => '0', + 'Value' => '0', ], ], ]; @@ -240,14 +240,14 @@ public function testOverwritesCookiesThatAreOlderOrDiscardable() { $t = \time() + 1000; $data = [ - 'Name' => 'foo', - 'Value' => 'bar', - 'Domain' => '.example.com', - 'Path' => '/', + 'Name' => 'foo', + 'Value' => 'bar', + 'Domain' => '.example.com', + 'Path' => '/', 'Max-Age' => '86400', - 'Secure' => true, + 'Secure' => true, 'Discard' => true, - 'Expires' => $t + 'Expires' => $t, ]; // Make sure that the discard cookie is overridden with the non-discard @@ -277,14 +277,14 @@ public function testOverwritesCookiesThatHaveChanged() { $t = \time() + 1000; $data = [ - 'Name' => 'foo', - 'Value' => 'bar', - 'Domain' => '.example.com', - 'Path' => '/', + 'Name' => 'foo', + 'Value' => 'bar', + 'Domain' => '.example.com', + 'Path' => '/', 'Max-Age' => '86400', - 'Secure' => true, + 'Secure' => true, 'Discard' => true, - 'Expires' => $t + 'Expires' => $t, ]; // Make sure that the discard cookie is overridden with the non-discard @@ -307,7 +307,7 @@ public function testOverwritesCookiesThatHaveChanged() public function testAddsCookiesFromResponseWithRequest() { $response = new Response(200, [ - 'Set-Cookie' => "fpc=d=.Hm.yh4.1XmJWjJfs4orLQzKzPImxklQoxXSHOZATHUSEFciRueW_7704iYUtsXNEXq0M92Px2glMdWypmJ7HIQl6XIUvrZimWjQ3vIdeuRbI.FNQMAfcxu_XN1zSx7l.AcPdKL6guHc2V7hIQFhnjRW0rxm2oHY1P4bGQxFNz7f.tHm12ZD3DbdMDiDy7TBXsuP4DM-&v=2; expires=Fri, 02-Mar-2019 02:17:40 GMT;" + 'Set-Cookie' => 'fpc=d=.Hm.yh4.1XmJWjJfs4orLQzKzPImxklQoxXSHOZATHUSEFciRueW_7704iYUtsXNEXq0M92Px2glMdWypmJ7HIQl6XIUvrZimWjQ3vIdeuRbI.FNQMAfcxu_XN1zSx7l.AcPdKL6guHc2V7hIQFhnjRW0rxm2oHY1P4bGQxFNz7f.tHm12ZD3DbdMDiDy7TBXsuP4DM-&v=2; expires=Fri, 02-Mar-2019 02:17:40 GMT;', ]); $request = new Request('GET', 'http://www.example.com'); $this->jar->extractCookies($request, $response); @@ -321,7 +321,7 @@ public function getMatchingCookiesDataProvider() ['http://example.com', ''], ['https://example.com:8912', 'foo=bar; baz=foobar'], ['https://foo.example.com', 'foo=bar; baz=foobar'], - ['http://foo.example.com/test/acme/', 'googoo=gaga'] + ['http://foo.example.com/test/acme/', 'googoo=gaga'], ]; } @@ -332,42 +332,42 @@ public function testReturnsCookiesMatchingRequests(string $url, string $cookies) { $bag = [ new SetCookie([ - 'Name' => 'foo', - 'Value' => 'bar', - 'Domain' => 'example.com', - 'Path' => '/', + 'Name' => 'foo', + 'Value' => 'bar', + 'Domain' => 'example.com', + 'Path' => '/', 'Max-Age' => '86400', - 'Secure' => true + 'Secure' => true, ]), new SetCookie([ - 'Name' => 'baz', - 'Value' => 'foobar', - 'Domain' => 'example.com', - 'Path' => '/', + 'Name' => 'baz', + 'Value' => 'foobar', + 'Domain' => 'example.com', + 'Path' => '/', 'Max-Age' => '86400', - 'Secure' => true + 'Secure' => true, ]), new SetCookie([ - 'Name' => 'test', - 'Value' => '123', - 'Domain' => 'www.foobar.com', - 'Path' => '/path/', - 'Discard' => true + 'Name' => 'test', + 'Value' => '123', + 'Domain' => 'www.foobar.com', + 'Path' => '/path/', + 'Discard' => true, ]), new SetCookie([ - 'Name' => 'muppet', - 'Value' => 'cookie_monster', - 'Domain' => '.y.example.com', - 'Path' => '/acme/', - 'Expires' => \time() + 86400 + 'Name' => 'muppet', + 'Value' => 'cookie_monster', + 'Domain' => '.y.example.com', + 'Path' => '/acme/', + 'Expires' => \time() + 86400, ]), new SetCookie([ - 'Name' => 'googoo', - 'Value' => 'gaga', - 'Domain' => '.example.com', - 'Path' => '/test/acme/', - 'Max-Age' => 1500 - ]) + 'Name' => 'googoo', + 'Value' => 'gaga', + 'Domain' => '.example.com', + 'Path' => '/test/acme/', + 'Max-Age' => 1500, + ]), ]; foreach ($bag as $cookie) { @@ -395,7 +395,7 @@ public function testDeletesCookiesByName() 'Value' => '123', 'Domain' => 'bar.com', 'Path' => '/boo', - 'Expires' => \time() + 1000 + 'Expires' => \time() + 1000, ]); $jar = new CookieJar(); foreach ($cookies as $cookie) { @@ -427,7 +427,7 @@ public function testCanConvertToAndLoadFromArray() public function testAddsCookiesWithEmptyPathFromResponse() { $response = new Response(200, [ - 'Set-Cookie' => "fpc=foobar; expires={$this->futureExpirationDate()}; path=;" + 'Set-Cookie' => "fpc=foobar; expires={$this->futureExpirationDate()}; path=;", ]); $request = new Request('GET', 'http://www.example.com'); $this->jar->extractCookies($request, $response); @@ -502,6 +502,6 @@ public function testIgnoresCookiesForMismatchingDomains(string $requestHost, str private function futureExpirationDate() { - return (new DateTimeImmutable)->add(new DateInterval('P1D'))->format(DateTime::COOKIE); + return (new DateTimeImmutable())->add(new DateInterval('P1D'))->format(DateTime::COOKIE); } } diff --git a/tests/Cookie/FileCookieJarTest.php b/tests/Cookie/FileCookieJarTest.php index a57945a09..6955dee63 100644 --- a/tests/Cookie/FileCookieJarTest.php +++ b/tests/Cookie/FileCookieJarTest.php @@ -43,21 +43,21 @@ public function testPersistsToFile($testSaveSessionCookie = false) { $jar = new FileCookieJar($this->file, $testSaveSessionCookie); $jar->setCookie(new SetCookie([ - 'Name' => 'foo', - 'Value' => 'bar', - 'Domain' => 'foo.com', - 'Expires' => \time() + 1000 + 'Name' => 'foo', + 'Value' => 'bar', + 'Domain' => 'foo.com', + 'Expires' => \time() + 1000, ])); $jar->setCookie(new SetCookie([ - 'Name' => 'baz', - 'Value' => 'bar', - 'Domain' => 'foo.com', - 'Expires' => \time() + 1000 + 'Name' => 'baz', + 'Value' => 'bar', + 'Domain' => 'foo.com', + 'Expires' => \time() + 1000, ])); $jar->setCookie(new SetCookie([ - 'Name' => 'boo', - 'Value' => 'bar', - 'Domain' => 'foo.com', + 'Name' => 'boo', + 'Value' => 'bar', + 'Domain' => 'foo.com', ])); self::assertCount(3, $jar); @@ -85,7 +85,7 @@ public function providerPersistsToFileFileParameters() { return [ [false], - [true] + [true], ]; } @@ -93,7 +93,7 @@ public function invalidCookieJarContent(): array { return [ [true], - ['invalid-data'] + ['invalid-data'], ]; } } diff --git a/tests/Cookie/SessionCookieJarTest.php b/tests/Cookie/SessionCookieJarTest.php index 9d7e70c8b..30a4b1017 100644 --- a/tests/Cookie/SessionCookieJarTest.php +++ b/tests/Cookie/SessionCookieJarTest.php @@ -44,21 +44,21 @@ public function testPersistsToSession($testSaveSessionCookie = false) { $jar = new SessionCookieJar($this->sessionVar, $testSaveSessionCookie); $jar->setCookie(new SetCookie([ - 'Name' => 'foo', - 'Value' => 'bar', - 'Domain' => 'foo.com', - 'Expires' => \time() + 1000 + 'Name' => 'foo', + 'Value' => 'bar', + 'Domain' => 'foo.com', + 'Expires' => \time() + 1000, ])); $jar->setCookie(new SetCookie([ - 'Name' => 'baz', - 'Value' => 'bar', - 'Domain' => 'foo.com', - 'Expires' => \time() + 1000 + 'Name' => 'baz', + 'Value' => 'bar', + 'Domain' => 'foo.com', + 'Expires' => \time() + 1000, ])); $jar->setCookie(new SetCookie([ - 'Name' => 'boo', - 'Value' => 'bar', - 'Domain' => 'foo.com', + 'Name' => 'boo', + 'Value' => 'bar', + 'Domain' => 'foo.com', ])); self::assertCount(3, $jar); @@ -86,7 +86,7 @@ public function providerPersistsToSessionParameters() { return [ [false], - [true] + [true], ]; } } diff --git a/tests/Cookie/SetCookieTest.php b/tests/Cookie/SetCookieTest.php index 02d9af262..55d4e7fc3 100644 --- a/tests/Cookie/SetCookieTest.php +++ b/tests/Cookie/SetCookieTest.php @@ -33,17 +33,17 @@ public function testHoldsValues() { $t = \time(); $data = [ - 'Name' => 'foo', - 'Value' => 'baz', - 'Path' => '/bar', - 'Domain' => 'baz.com', - 'Expires' => $t, - 'Max-Age' => 100, - 'Secure' => true, - 'Discard' => true, + 'Name' => 'foo', + 'Value' => 'baz', + 'Path' => '/bar', + 'Domain' => 'baz.com', + 'Expires' => $t, + 'Max-Age' => 100, + 'Secure' => true, + 'Discard' => true, 'HttpOnly' => true, - 'foo' => 'baz', - 'bar' => 'bam' + 'foo' => 'baz', + 'bar' => 'bam', ]; $cookie = new SetCookie($data); @@ -173,8 +173,8 @@ public function cookieValidateProvider() public function testValidatesCookies($name, $value, $domain, $result) { $cookie = new SetCookie([ - 'Name' => $name, - 'Value' => $value, + 'Name' => $name, + 'Value' => $value, 'Domain' => $domain, ]); self::assertSame($result, $cookie->validate()); @@ -196,7 +196,7 @@ public function testConvertsToString() 'Expires' => $t, 'Path' => '/abc', 'HttpOnly' => true, - 'Secure' => true + 'Secure' => true, ]); self::assertSame( 'test=123; Domain=foo.com; Path=/abc; Expires=Sun, 27 Oct 2013 23:20:08 GMT; Secure; HttpOnly', @@ -246,7 +246,7 @@ public function cookieParserDataProvider() ], // Test setting a blank value for a cookie [[ - 'foo=', 'foo =', 'foo =;', 'foo= ;', 'foo =', 'foo= '], + 'foo=', 'foo =', 'foo =;', 'foo= ;', 'foo =', 'foo= ', ], [ 'Name' => 'foo', 'Value' => '', @@ -261,7 +261,7 @@ public function cookieParserDataProvider() ], // Test setting a value and removing quotes [[ - 'foo=1', 'foo =1', 'foo =1;', 'foo=1 ;', 'foo =1', 'foo= 1', 'foo = 1 ;'], + 'foo=1', 'foo =1', 'foo =1;', 'foo=1 ;', 'foo =1', 'foo= 1', 'foo = 1 ;', ], [ 'Name' => 'foo', 'Value' => '1', @@ -420,17 +420,17 @@ public function testParseCookie($cookie, $parsed) if (isset($p['Expires'])) { $delta = 40; $parsedExpires = \is_numeric($parsed['Expires']) ? $parsed['Expires'] : \strtotime($parsed['Expires']); - self::assertLessThan($delta, \abs($p['Expires'] - $parsedExpires), 'Comparing Expires ' . \var_export($p['Expires'], true) . ' : ' . \var_export($parsed, true) . ' | ' . \var_export($p, true)); + self::assertLessThan($delta, \abs($p['Expires'] - $parsedExpires), 'Comparing Expires '.\var_export($p['Expires'], true).' : '.\var_export($parsed, true).' | '.\var_export($p, true)); unset($p['Expires']); unset($parsed['Expires']); } if (!empty($parsed)) { foreach ($parsed as $key => $value) { - self::assertEquals($parsed[$key], $p[$key], 'Comparing ' . $key . ' ' . \var_export($value, true) . ' : ' . \var_export($parsed, true) . ' | ' . \var_export($p, true)); + self::assertEquals($parsed[$key], $p[$key], 'Comparing '.$key.' '.\var_export($value, true).' : '.\var_export($parsed, true).' | '.\var_export($p, true)); } foreach ($p as $key => $value) { - self::assertEquals($p[$key], $parsed[$key], 'Comparing ' . $key . ' ' . \var_export($value, true) . ' : ' . \var_export($parsed, true) . ' | ' . \var_export($p, true)); + self::assertEquals($p[$key], $parsed[$key], 'Comparing '.$key.' '.\var_export($value, true).' : '.\var_export($parsed, true).' | '.\var_export($p, true)); } } else { self::assertSame([ @@ -465,11 +465,11 @@ public function isExpiredProvider() true, ], [ - 'FOO=bar; expires=' . \date(\DateTime::RFC1123, \time() + 10) . ';', + 'FOO=bar; expires='.\date(\DateTime::RFC1123, \time() + 10).';', false, ], [ - 'FOO=bar; expires=' . \date(\DateTime::RFC1123, \time() - 10) . ';', + 'FOO=bar; expires='.\date(\DateTime::RFC1123, \time() - 10).';', true, ], [ diff --git a/tests/Exception/RequestExceptionTest.php b/tests/Exception/RequestExceptionTest.php index 35521ad4a..a17ff7fab 100644 --- a/tests/Exception/RequestExceptionTest.php +++ b/tests/Exception/RequestExceptionTest.php @@ -122,7 +122,7 @@ public function testCreatesExceptionWithTruncatedSummary() $content = \str_repeat('+', 121); $response = new Response(500, [], $content); $e = RequestException::create(new Request('GET', '/'), $response); - $expected = \str_repeat('+', 120) . ' (truncated...)'; + $expected = \str_repeat('+', 120).' (truncated...)'; self::assertStringContainsString($expected, $e->getMessage()); } diff --git a/tests/Handler/CurlFactoryTest.php b/tests/Handler/CurlFactoryTest.php index 5c8095e6e..ec787e6ff 100644 --- a/tests/Handler/CurlFactoryTest.php +++ b/tests/Handler/CurlFactoryTest.php @@ -39,12 +39,12 @@ public function testCreatesCurlHandle() 'Foo' => 'Bar', 'Baz' => 'bam', 'Content-Length' => 2, - ], 'hi') + ], 'hi'), ]); $stream = Psr7\Utils::streamFor(); $request = new Psr7\Request('PUT', Server::$url, [ - 'Hi' => ' 123', - 'Content-Length' => '7' + 'Hi' => ' 123', + 'Content-Length' => '7', ], 'testing'); $f = new Handler\CurlFactory(3); $result = $f->create($request, ['sink' => $stream]); @@ -188,7 +188,7 @@ private function checkNoProxyForHost($url, $noProxy, $assertUseProxy) 'proxy' => [ 'http' => 'http://bar.com', 'https' => 'https://t', - 'no' => $noProxy + 'no' => $noProxy, ], ]); if ($assertUseProxy) { @@ -206,13 +206,13 @@ public function testUsesProxy() 'Foo' => 'Bar', 'Baz' => 'bam', 'Content-Length' => 2, - ], 'hi') + ], 'hi'), ]); $handler = new Handler\CurlMultiHandler(); $request = new Psr7\Request('GET', 'http://www.example.com', [], null, '1.0'); $promise = $handler($request, [ - 'proxy' => Server::$url + 'proxy' => Server::$url, ]); $response = $promise->wait(); self::assertSame(200, $response->getStatusCode()); @@ -319,7 +319,7 @@ public function testAddsCertWithPassword() public function testAddsDerCert() { - $certFile = tempnam(sys_get_temp_dir(), "mock_test_cert"); + $certFile = tempnam(sys_get_temp_dir(), 'mock_test_cert'); rename($certFile, $certFile .= '.der'); try { $f = new Handler\CurlFactory(3); @@ -333,7 +333,7 @@ public function testAddsDerCert() public function testAddsP12Cert() { - $certFile = tempnam(sys_get_temp_dir(), "mock_test_cert"); + $certFile = tempnam(sys_get_temp_dir(), 'mock_test_cert'); rename($certFile, $certFile .= '.p12'); try { $f = new Handler\CurlFactory(3); @@ -364,8 +364,8 @@ public function testEmitsDebugInfoToStream() $response->wait(); \rewind($res); $output = \str_replace("\r", '', \stream_get_contents($res)); - self::assertStringContainsString("> HEAD / HTTP/1.1", $output); - self::assertStringContainsString("< HTTP/1.1 200", $output); + self::assertStringContainsString('> HEAD / HTTP/1.1', $output); + self::assertStringContainsString('< HTTP/1.1 200', $output); \fclose($res); } @@ -398,6 +398,7 @@ private function addDecodeResponse($withEncoding = true) $response = new Psr7\Response(200, $headers, $content); Server::flush(); Server::enqueue([$response]); + return $content; } @@ -500,7 +501,7 @@ public function testSavesToStream() $request = new Psr7\Request('GET', Server::$url); $response = $handler($request, [ 'decode_content' => true, - 'sink' => $stream, + 'sink' => $stream, ]); $response->wait(); \rewind($stream); @@ -515,7 +516,7 @@ public function testSavesToGuzzleStream() $request = new Psr7\Request('GET', Server::$url); $response = $handler($request, [ 'decode_content' => true, - 'sink' => $stream, + 'sink' => $stream, ]); $response->wait(); self::assertEquals('test', (string) $stream); @@ -529,7 +530,7 @@ public function testSavesToFileOnDisk() $request = new Psr7\Request('GET', Server::$url); $response = $handler($request, [ 'decode_content' => true, - 'sink' => $tmpfile, + 'sink' => $tmpfile, ]); $response->wait(); self::assertStringEqualsFile($tmpfile, 'test'); @@ -572,6 +573,7 @@ public function testFailsWhenCannotRewindRetryAfterNoResponse() $request = new Psr7\Request('PUT', Server::$url, [], $stream); $fn = static function ($request, $options) use (&$fn, $factory) { $easy = $factory->create($request, $options); + return Handler\CurlFactory::finish($fn, $easy, $factory); }; @@ -586,16 +588,17 @@ public function testRetriesWhenBodyCanBeRewound() $fn = static function ($r, $options) use (&$callHandler) { $callHandler = true; + return P\Create::promiseFor(new Psr7\Response()); }; $bd = Psr7\FnStream::decorate(Psr7\Utils::streamFor('test'), [ - 'tell' => static function () { + 'tell' => static function () { return 1; }, 'rewind' => static function () use (&$called) { $called = true; - } + }, ]); $factory = new Handler\CurlFactory(1); @@ -613,8 +616,9 @@ public function testFailsWhenRetryMoreThanThreeTimes() $factory = new Handler\CurlFactory(1); $call = 0; $fn = static function ($request, $options) use (&$mock, &$call, $factory) { - $call++; + ++$call; $easy = $factory->create($request, $options); + return Handler\CurlFactory::finish($mock, $easy, $factory); }; $mock = new Handler\MockHandler([$fn, $fn, $fn]); @@ -634,7 +638,7 @@ public function testHandles100Continue() new Psr7\Response(200, ['Test' => 'Hello', 'Content-Length' => 4], 'test'), ]); $request = new Psr7\Request('PUT', Server::$url, [ - 'Expect' => '100-Continue' + 'Expect' => '100-Continue', ], 'test'); $handler = new Handler\CurlMultiHandler(); $response = $handler($request, [])->wait(); @@ -668,8 +672,8 @@ public function testAddsTimeouts() { $f = new Handler\CurlFactory(3); $f->create(new Psr7\Request('GET', Server::$url), [ - 'timeout' => 0.1, - 'connect_timeout' => 0.2 + 'timeout' => 0.1, + 'connect_timeout' => 0.2, ]); self::assertEquals(100, $_SERVER['_curl'][\CURLOPT_TIMEOUT_MS]); self::assertEquals(200, $_SERVER['_curl'][\CURLOPT_CONNECTTIMEOUT_MS]); @@ -681,7 +685,7 @@ public function testAddsStreamingBody() $bd = Psr7\FnStream::decorate(Psr7\Utils::streamFor('foo'), [ 'getSize' => static function () { return null; - } + }, ]); $request = new Psr7\Request('PUT', Server::$url, [], $bd); $f->create($request, []); @@ -696,7 +700,7 @@ public function testEnsuresDirExistsBeforeThrowingWarning() $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Directory /does/not/exist/so does not exist for sink value of /does/not/exist/so/error.txt'); $f->create(new Psr7\Request('GET', Server::$url), [ - 'sink' => '/does/not/exist/so/error.txt' + 'sink' => '/does/not/exist/so/error.txt', ]); } @@ -726,7 +730,7 @@ public function testClosesIdleHandles() public function testRejectsPromiseWhenCreateResponseFails() { Server::flush(); - Server::enqueueRaw(999, "Incorrect", ['X-Foo' => 'bar'], 'abc 123'); + Server::enqueueRaw(999, 'Incorrect', ['X-Foo' => 'bar'], 'abc 123'); $req = new Psr7\Request('GET', Server::$url); $handler = new Handler\CurlHandler(); @@ -750,14 +754,14 @@ public function testRejectsPromiseWhenOnHeadersFails() { Server::flush(); Server::enqueue([ - new Psr7\Response(200, ['X-Foo' => 'bar'], 'abc 123') + new Psr7\Response(200, ['X-Foo' => 'bar'], 'abc 123'), ]); $req = new Psr7\Request('GET', Server::$url); $handler = new Handler\CurlHandler(); $promise = $handler($req, [ 'on_headers' => static function () { throw new \Exception('test'); - } + }, ]); $this->expectException(RequestException::class); @@ -769,7 +773,7 @@ public function testSuccessfullyCallsOnHeadersBeforeWritingToSink() { Server::flush(); Server::enqueue([ - new Psr7\Response(200, ['X-Foo' => 'bar'], 'abc 123') + new Psr7\Response(200, ['X-Foo' => 'bar'], 'abc 123'), ]); $req = new Psr7\Request('GET', Server::$url); $got = null; @@ -778,17 +782,18 @@ public function testSuccessfullyCallsOnHeadersBeforeWritingToSink() $stream = Psr7\FnStream::decorate($stream, [ 'write' => static function ($data) use ($stream, &$got) { self::assertNotNull($got); + return $stream->write($data); - } + }, ]); $handler = new Handler\CurlHandler(); $promise = $handler($req, [ - 'sink' => $stream, + 'sink' => $stream, 'on_headers' => static function (ResponseInterface $res) use (&$got) { $got = $res; self::assertEquals('bar', $res->getHeaderLine('X-Foo')); - } + }, ]); $response = $promise->wait(); @@ -807,7 +812,7 @@ public function testInvokesOnStatsOnSuccess() $promise = $handler($req, [ 'on_stats' => static function (TransferStats $stats) use (&$gotStats) { $gotStats = $stats; - } + }, ]); $response = $promise->wait(); self::assertSame(200, $response->getStatusCode()); @@ -834,7 +839,7 @@ public function testInvokesOnStatsOnError() 'timeout' => 0.001, 'on_stats' => static function (TransferStats $stats) use (&$gotStats) { $gotStats = $stats; - } + }, ]); $promise->wait(false); self::assertFalse($gotStats->hasResponse()); @@ -902,7 +907,7 @@ public function testBodyEofOnWindows() Server::enqueue([ new Psr7\Response(200, [ 'Content-Length' => $expectedLength, - ], \str_repeat('x', $expectedLength)) + ], \str_repeat('x', $expectedLength)), ]); $handler = new Handler\CurlMultiHandler(); @@ -926,7 +931,7 @@ public function testHandlesGarbageHttpServerGracefully() $this->expectException(RequestException::class); $this->expectExceptionMessage('cURL error 1: Received HTTP/0.9 when not allowed'); - $a(new Psr7\Request('GET', Server::$url . 'guzzle-server/garbage'), [])->wait(); + $a(new Psr7\Request('GET', Server::$url.'guzzle-server/garbage'), [])->wait(); } public function testHandlesInvalidStatusCodeGracefully() @@ -936,6 +941,6 @@ public function testHandlesInvalidStatusCodeGracefully() $this->expectException(RequestException::class); $this->expectExceptionMessage('An error was encountered while creating the response'); - $a(new Psr7\Request('GET', Server::$url . 'guzzle-server/bad-status'), [])->wait(); + $a(new Psr7\Request('GET', Server::$url.'guzzle-server/bad-status'), [])->wait(); } } diff --git a/tests/Handler/CurlMultiHandlerTest.php b/tests/Handler/CurlMultiHandlerTest.php index 3e9438060..e829af272 100644 --- a/tests/Handler/CurlMultiHandlerTest.php +++ b/tests/Handler/CurlMultiHandlerTest.php @@ -68,7 +68,7 @@ public function testCanCancel() Server::enqueue(\array_fill_keys(\range(0, 10), $response)); $a = new CurlMultiHandler(); $responses = []; - for ($i = 0; $i < 10; $i++) { + for ($i = 0; $i < 10; ++$i) { $response = $a(new Request('GET', Server::$url), []); $response->cancel(); $responses[] = $response; @@ -111,7 +111,7 @@ public function testUsesTimeoutEnvironmentVariables() // Default if no options are given and no environment variable is set self::assertEquals(1, Helpers::readObjectAttribute($a, 'selectTimeout')); - \putenv("GUZZLE_CURL_SELECT_TIMEOUT=3"); + \putenv('GUZZLE_CURL_SELECT_TIMEOUT=3'); $a = new CurlMultiHandler(); // Handler reads from the environment if no options are given self::assertEquals(3, Helpers::readObjectAttribute($a, 'selectTimeout')); diff --git a/tests/Handler/EasyHandleTest.php b/tests/Handler/EasyHandleTest.php index b2fda82d8..e9ad4e90f 100644 --- a/tests/Handler/EasyHandleTest.php +++ b/tests/Handler/EasyHandleTest.php @@ -12,7 +12,7 @@ class EasyHandleTest extends TestCase { public function testEnsuresHandleExists() { - $easy = new EasyHandle; + $easy = new EasyHandle(); unset($easy->handle); $this->expectException(\BadMethodCallException::class); diff --git a/tests/Handler/MockHandlerTest.php b/tests/Handler/MockHandlerTest.php index 538e2d9d6..842c68021 100644 --- a/tests/Handler/MockHandlerTest.php +++ b/tests/Handler/MockHandlerTest.php @@ -76,7 +76,7 @@ public function testCanGetLastRequestAndOptions() public function testSinkFilename() { - $filename = \sys_get_temp_dir() . '/mock_test_' . \uniqid(); + $filename = \sys_get_temp_dir().'/mock_test_'.\uniqid(); $res = new Response(200, [], 'TEST CONTENT'); $mock = new MockHandler([$res]); $request = new Request('GET', '/'); @@ -146,7 +146,7 @@ public function testRejectsPromiseWhenOnHeadersFails() $promise = $mock($request, [ 'on_headers' => static function () { throw new \Exception('test'); - } + }, ]); $this->expectException(RequestException::class); diff --git a/tests/Handler/Network/StreamHandlerTest.php b/tests/Handler/Network/StreamHandlerTest.php index 6c92bc860..c3fc11753 100644 --- a/tests/Handler/Network/StreamHandlerTest.php +++ b/tests/Handler/Network/StreamHandlerTest.php @@ -17,7 +17,7 @@ class StreamHandlerTest extends TestCase public function setUp(): void { if (!($_SERVER['GUZZLE_TEST_ALLOW_NETWORK'] ?? false)) { - self::markTestSkipped("This test requires the GUZZLE_TEST_ALLOW_NETWORK environment variable."); + self::markTestSkipped('This test requires the GUZZLE_TEST_ALLOW_NETWORK environment variable.'); } } @@ -33,7 +33,7 @@ public function testSslRequestWorks() )->wait(); self::assertSame(200, $response->getStatusCode()); - self::assertStringContainsString('

Example Domain

', (string)$response->getBody()); + self::assertStringContainsString('

Example Domain

', (string) $response->getBody()); } public function testSslRequestWorksWithForceIpResolve() @@ -49,7 +49,7 @@ public function testSslRequestWorksWithForceIpResolve() )->wait(); self::assertSame(200, $response->getStatusCode()); - self::assertStringContainsString('

Example Domain

', (string)$response->getBody()); + self::assertStringContainsString('

Example Domain

', (string) $response->getBody()); } public function testSslRequestWorksWithForceIpResolveAfterRedirect() @@ -66,6 +66,6 @@ public function testSslRequestWorksWithForceIpResolveAfterRedirect() ); self::assertSame(200, $response->getStatusCode()); - self::assertStringContainsString('jobsjob_idstepsrun', (string)$response->getBody()); + self::assertStringContainsString('jobsjob_idstepsrun', (string) $response->getBody()); } } diff --git a/tests/Handler/StreamHandlerTest.php b/tests/Handler/StreamHandlerTest.php index 135308391..2d02b5ec5 100644 --- a/tests/Handler/StreamHandlerTest.php +++ b/tests/Handler/StreamHandlerTest.php @@ -28,7 +28,7 @@ private function queueRes() new Response(200, [ 'Foo' => 'Bar', 'Content-Length' => 8, - ], 'hi there') + ], 'hi there'), ]); } @@ -69,7 +69,7 @@ public function testStreamAttributeKeepsStreamOpen() $handler = new StreamHandler(); $request = new Request( 'PUT', - Server::$url . 'foo?baz=bar', + Server::$url.'foo?baz=bar', ['Foo' => 'Bar'], 'test' ); @@ -153,7 +153,7 @@ public function testDrainsResponseAndReadsOnlyContentLengthBytes() new Response(200, [ 'Foo' => 'Bar', 'Content-Length' => 8, - ], 'hi there... This has way too much data!') + ], 'hi there... This has way too much data!'), ]); $handler = new StreamHandler(); $request = new Request('GET', Server::$url); @@ -172,7 +172,7 @@ public function testDoesNotDrainWhenHeadRequest() new Response(200, [ 'Foo' => 'Bar', 'Content-Length' => 8, - ], '') + ], ''), ]); $handler = new StreamHandler(); $request = new Request('HEAD', Server::$url); @@ -190,8 +190,8 @@ public function testAutomaticallyDecompressGzip() Server::enqueue([ new Response(200, [ 'Content-Encoding' => 'gzip', - 'Content-Length' => \strlen($content), - ], $content) + 'Content-Length' => \strlen($content), + ], $content), ]); $handler = new StreamHandler(); $request = new Request('GET', Server::$url); @@ -208,8 +208,8 @@ public function testAutomaticallyDecompressGzipHead() Server::enqueue([ new Response(200, [ 'Content-Encoding' => 'gzip', - 'Content-Length' => \strlen($content), - ], $content) + 'Content-Length' => \strlen($content), + ], $content), ]); $handler = new StreamHandler(); $request = new Request('HEAD', Server::$url); @@ -226,8 +226,8 @@ public function testReportsOriginalSizeAndContentEncodingAfterDecoding() Server::enqueue([ new Response(200, [ 'Content-Encoding' => 'gzip', - 'Content-Length' => \strlen($content), - ], $content) + 'Content-Length' => \strlen($content), + ], $content), ]); $handler = new StreamHandler(); $request = new Request('GET', Server::$url); @@ -250,8 +250,8 @@ public function testDoesNotForceGzipDecode() Server::enqueue([ new Response(200, [ 'Content-Encoding' => 'gzip', - 'Content-Length' => \strlen($content), - ], $content) + 'Content-Length' => \strlen($content), + ], $content), ]); $handler = new StreamHandler(); $request = new Request('GET', Server::$url); @@ -276,6 +276,7 @@ protected function getSendResult(array $opts) $handler = new StreamHandler(); $opts['stream'] = true; $request = new Request('GET', Server::$url); + return $handler($request, $opts)->wait(); } @@ -303,7 +304,7 @@ public function testAddsProxyButHonorsNoProxy() $url = Server::$url; $res = $this->getSendResult(['proxy' => [ 'http' => $url, - 'no' => ['*'] + 'no' => ['*'], ]]); $opts = \stream_context_get_options($res->getBody()->detach()); self::assertArrayNotHasKey('proxy', $opts['http']); @@ -315,7 +316,7 @@ public function testUsesProxy() $handler = new StreamHandler(); $request = new Request('GET', 'http://www.example.com', [], null, '1.0'); $response = $handler($request, [ - 'proxy' => Server::$url + 'proxy' => Server::$url, ])->wait(); self::assertSame(200, $response->getStatusCode()); self::assertSame('OK', $response->getReasonPhrase()); @@ -478,7 +479,7 @@ public function testEmitsProgressInformationAndDebugInformation() $this->queueRes(); $buffer = \fopen('php://memory', 'w+'); $this->getSendResult([ - 'debug' => $buffer, + 'debug' => $buffer, 'progress' => static function (...$args) use (&$called) { $called[] = $args; }, @@ -591,14 +592,14 @@ public function testRejectsPromiseWhenOnHeadersFails() { Server::flush(); Server::enqueue([ - new Response(200, ['X-Foo' => 'bar'], 'abc 123') + new Response(200, ['X-Foo' => 'bar'], 'abc 123'), ]); $req = new Request('GET', Server::$url); $handler = new StreamHandler(); $promise = $handler($req, [ 'on_headers' => static function () { throw new \Exception('test'); - } + }, ]); $this->expectException(RequestException::class); @@ -610,7 +611,7 @@ public function testSuccessfullyCallsOnHeadersBeforeWritingToSink() { Server::flush(); Server::enqueue([ - new Response(200, ['X-Foo' => 'bar'], 'abc 123') + new Response(200, ['X-Foo' => 'bar'], 'abc 123'), ]); $req = new Request('GET', Server::$url); $got = null; @@ -619,17 +620,18 @@ public function testSuccessfullyCallsOnHeadersBeforeWritingToSink() $stream = FnStream::decorate($stream, [ 'write' => static function ($data) use ($stream, &$got) { self::assertNotNull($got); + return $stream->write($data); - } + }, ]); $handler = new StreamHandler(); $promise = $handler($req, [ - 'sink' => $stream, + 'sink' => $stream, 'on_headers' => static function (ResponseInterface $res) use (&$got) { $got = $res; self::assertSame('bar', $res->getHeaderLine('X-Foo')); - } + }, ]); $response = $promise->wait(); @@ -648,7 +650,7 @@ public function testInvokesOnStatsOnSuccess() $promise = $handler($req, [ 'on_stats' => static function (TransferStats $stats) use (&$gotStats) { $gotStats = $stats; - } + }, ]); $response = $promise->wait(); self::assertSame(200, $response->getStatusCode()); @@ -674,7 +676,7 @@ public function testInvokesOnStatsOnError() 'timeout' => 0.001, 'on_stats' => static function (TransferStats $stats) use (&$gotStats) { $gotStats = $stats; - } + }, ]); $promise->wait(false); self::assertFalse($gotStats->hasResponse()); @@ -702,7 +704,7 @@ public function testStreamIgnoresZeroTimeout() $handler = new StreamHandler(); $promise = $handler($req, [ 'connect_timeout' => 10, - 'timeout' => 0 + 'timeout' => 0, ]); $response = $promise->wait(); self::assertSame(200, $response->getStatusCode()); @@ -715,7 +717,7 @@ public function testDrainsResponseAndReadsAllContentWhenContentLengthIsZero() new Response(200, [ 'Foo' => 'Bar', 'Content-Length' => '0', - ], 'hi there... This has a lot of data!') + ], 'hi there... This has a lot of data!'), ]); $handler = new StreamHandler(); $request = new Request('GET', Server::$url); @@ -731,7 +733,7 @@ public function testHonorsReadTimeout() Server::flush(); $handler = new StreamHandler(); $response = $handler( - new Request('GET', Server::$url . 'guzzle-server/read-timeout'), + new Request('GET', Server::$url.'guzzle-server/read-timeout'), [ RequestOptions::READ_TIMEOUT => 1, RequestOptions::STREAM => true, @@ -756,7 +758,7 @@ public function testHandlesGarbageHttpServerGracefully() $this->expectExceptionMessage('An error was encountered while creating the response'); $handler( - new Request('GET', Server::$url . 'guzzle-server/garbage'), + new Request('GET', Server::$url.'guzzle-server/garbage'), [ RequestOptions::STREAM => true, ] @@ -771,7 +773,7 @@ public function testHandlesInvalidStatusCodeGracefully() $this->expectExceptionMessage('An error was encountered while creating the response'); $handler( - new Request('GET', Server::$url . 'guzzle-server/bad-status'), + new Request('GET', Server::$url.'guzzle-server/bad-status'), [ RequestOptions::STREAM => true, ] diff --git a/tests/HandlerStackTest.php b/tests/HandlerStackTest.php index 99f07a870..6ed3ee977 100644 --- a/tests/HandlerStackTest.php +++ b/tests/HandlerStackTest.php @@ -96,13 +96,13 @@ public function testCanPrintMiddleware() $builder->push($meths[2], 'a'); $builder->push([__CLASS__, 'foo']); $builder->push([$this, 'bar']); - $builder->push(__CLASS__ . '::' . 'foo'); + $builder->push(__CLASS__.'::'.'foo'); $lines = \explode("\n", (string) $builder); self::assertStringContainsString("> 4) Name: 'a', Function: callable(", $lines[0]); self::assertStringContainsString("> 3) Name: '', Function: callable(GuzzleHttp\\Tests\\HandlerStackTest::foo)", $lines[1]); self::assertStringContainsString("> 2) Name: '', Function: callable(['GuzzleHttp\\Tests\\HandlerStackTest', 'bar'])", $lines[2]); self::assertStringContainsString("> 1) Name: '', Function: callable(GuzzleHttp\\Tests\\HandlerStackTest::foo)", $lines[3]); - self::assertStringContainsString("< 0) Handler: callable(", $lines[4]); + self::assertStringContainsString('< 0) Handler: callable(', $lines[4]); self::assertStringContainsString("< 1) Name: '', Function: callable(GuzzleHttp\\Tests\\HandlerStackTest::foo)", $lines[5]); self::assertStringContainsString("< 2) Name: '', Function: callable(['GuzzleHttp\\Tests\\HandlerStackTest', 'bar'])", $lines[6]); self::assertStringContainsString("< 3) Name: '', Function: callable(GuzzleHttp\\Tests\\HandlerStackTest::foo)", $lines[7]); @@ -154,17 +154,17 @@ public function testPicksUpCookiesFromRedirects() { $mock = new MockHandler([ new Response(301, [ - 'Location' => 'http://foo.com/baz', - 'Set-Cookie' => 'foo=bar; Domain=foo.com' + 'Location' => 'http://foo.com/baz', + 'Set-Cookie' => 'foo=bar; Domain=foo.com', ]), - new Response(200) + new Response(200), ]); $handler = HandlerStack::create($mock); $request = new Request('GET', 'http://foo.com/bar'); $jar = new CookieJar(); $response = $handler($request, [ 'allow_redirects' => true, - 'cookies' => $jar + 'cookies' => $jar, ])->wait(); self::assertSame(200, $response->getStatusCode()); $lastRequest = $mock->getLastRequest(); @@ -179,26 +179,29 @@ private function getFunctions() $a = static function (callable $next) use (&$calls) { return static function ($v) use ($next, &$calls) { $calls[] = ['a', $v]; - return $next($v . '1'); + + return $next($v.'1'); }; }; $b = static function (callable $next) use (&$calls) { return static function ($v) use ($next, &$calls) { $calls[] = ['b', $v]; - return $next($v . '2'); + + return $next($v.'2'); }; }; $c = static function (callable $next) use (&$calls) { return static function ($v) use ($next, &$calls) { $calls[] = ['c', $v]; - return $next($v . '3'); + + return $next($v.'3'); }; }; $handler = static function ($v) { - return 'Hello - ' . $v; + return 'Hello - '.$v; }; return [&$calls, $handler, $a, $b, $c]; diff --git a/tests/MessageFormatterTest.php b/tests/MessageFormatterTest.php index 41181e170..4304d4e90 100644 --- a/tests/MessageFormatterTest.php +++ b/tests/MessageFormatterTest.php @@ -27,7 +27,7 @@ public function dateProvider() return [ ['{ts}', '/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}/'], ['{date_iso_8601}', '/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}/'], - ['{date_common_log}', '/^\d\d\/[A-Z][a-z]{2}\/[0-9]{4}/'] + ['{date_common_log}', '/^\d\d\/[A-Z][a-z]{2}\/[0-9]{4}/'], ]; } @@ -57,9 +57,9 @@ public function formatProvider() return [ ['{request}', [$request], Psr7\Message::toString($request)], ['{response}', [$request, $response], Psr7\Message::toString($response)], - ['{request} {response}', [$request, $response], Psr7\Message::toString($request) . ' ' . Psr7\Message::toString($response)], + ['{request} {response}', [$request, $response], Psr7\Message::toString($request).' '.Psr7\Message::toString($response)], // Empty response yields no value - ['{request} {response}', [$request], Psr7\Message::toString($request) . ' '], + ['{request} {response}', [$request], Psr7\Message::toString($request).' '], ['{req_headers}', [$request], "PUT / HTTP/1.1\r\nx-test: abc"], ['{res_headers}', [$request, $response], "HTTP/1.1 200 OK\r\nX-Baz: Bar"], ['{res_headers}', [$request], 'NULL'], @@ -74,7 +74,7 @@ public function formatProvider() ['{res_version}', [$request], 'NULL'], ['{host}', [$request], $request->getHeaderLine('Host')], ['{hostname}', [$request, $response], \gethostname()], - ['{hostname}{hostname}', [$request, $response], \gethostname() . \gethostname()], + ['{hostname}{hostname}', [$request, $response], \gethostname().\gethostname()], ['{code}', [$request, $response], $response->getStatusCode()], ['{code}', [$request], 'NULL'], ['{phrase}', [$request, $response], $response->getReasonPhrase()], diff --git a/tests/MiddlewareTest.php b/tests/MiddlewareTest.php index dc4c03336..cad9ff33f 100644 --- a/tests/MiddlewareTest.php +++ b/tests/MiddlewareTest.php @@ -31,12 +31,12 @@ public function testAddsCookiesToRequests() static function (RequestInterface $request) { return new Response(200, [ 'Set-Cookie' => (string) new SetCookie([ - 'Name' => 'name', - 'Value' => 'value', - 'Domain' => 'foo.com' - ]) + 'Name' => 'name', + 'Value' => 'value', + 'Domain' => 'foo.com', + ]), ]); - } + }, ] ); $f = $m($h); @@ -119,7 +119,7 @@ public function getHistoryUseCases() { return [ [[]], // 1. Container is an array - [new \ArrayObject()] // 2. Container is an ArrayObject + [new \ArrayObject()], // 2. Container is an ArrayObject ]; } @@ -142,6 +142,7 @@ public function testTapsBeforeAndAfter() $m = static function ($handler) use (&$calls) { return static function ($request, $options) use ($handler, &$calls) { $calls[] = '2'; + return $handler($request, $options); }; }; @@ -171,8 +172,9 @@ public function testMapsRequest() $h = new MockHandler([ static function (RequestInterface $request, array $options) { self::assertSame('foo', $request->getHeaderLine('Bar')); + return new Response(200); - } + }, ]); $stack = new HandlerStack($h); $stack->push(Middleware::mapRequest(static function (RequestInterface $request) { diff --git a/tests/PoolTest.php b/tests/PoolTest.php index ec6dc610c..054482e00 100644 --- a/tests/PoolTest.php +++ b/tests/PoolTest.php @@ -73,8 +73,9 @@ public function testUsesRequestOptions() $handler = new MockHandler([ static function (RequestInterface $request) use (&$h) { $h[] = $request; + return new Response(); - } + }, ]); $c = new Client(['handler' => $handler]); $opts = ['options' => ['headers' => ['x-foo' => 'bar']]]; @@ -90,13 +91,15 @@ public function testCanProvideCallablesThatReturnResponses() $handler = new MockHandler([ static function (RequestInterface $request) use (&$h) { $h[] = $request; + return new Response(); - } + }, ]); $c = new Client(['handler' => $handler]); $optHistory = []; $fn = static function (array $opts) use (&$optHistory, $c) { $optHistory = $opts; + return $c->request('GET', 'http://example.com', $opts); }; $opts = ['options' => ['headers' => ['x-foo' => 'bar']]]; @@ -133,18 +136,18 @@ public function testBatchesResultsWithCallbacks() { $requests = [ new Request('GET', 'http://foo.com/200'), - new Request('GET', 'http://foo.com/201') + new Request('GET', 'http://foo.com/201'), ]; $mock = new MockHandler([ static function (RequestInterface $request) { return new Response(\substr($request->getUri()->getPath(), 1)); - } + }, ]); $client = new Client(['handler' => $mock]); $results = Pool::batch($client, $requests, [ 'fulfilled' => static function ($value) use (&$called) { $called = true; - } + }, ]); self::assertCount(2, $results); self::assertTrue($called); @@ -173,7 +176,7 @@ public function testUsesYieldedKeyInFulfilledCallback() 'pool_size' => 2, 'fulfilled' => static function ($res, $index) use (&$keys) { $keys[] = $index; - } + }, ]); $p->promise()->wait(); self::assertCount(3, $keys); @@ -183,10 +186,11 @@ public function testUsesYieldedKeyInFulfilledCallback() private function getClient($total = 1) { $queue = []; - for ($i = 0; $i < $total; $i++) { + for ($i = 0; $i < $total; ++$i) { $queue[] = new Response(); } $handler = new MockHandler($queue); + return new Client(['handler' => $handler]); } } diff --git a/tests/PrepareBodyMiddlewareTest.php b/tests/PrepareBodyMiddlewareTest.php index b0cb992a2..5dcec8264 100644 --- a/tests/PrepareBodyMiddlewareTest.php +++ b/tests/PrepareBodyMiddlewareTest.php @@ -39,8 +39,9 @@ static function (RequestInterface $request) use ($body) { } else { self::assertFalse($request->hasHeader('Content-Length')); } + return new Response(200); - } + }, ]); $m = Middleware::prepareBody(); $stack = new HandlerStack($h); @@ -57,14 +58,15 @@ public function testAddsTransferEncodingWhenNoContentLength() $body = FnStream::decorate(Psr7\Utils::streamFor('foo'), [ 'getSize' => static function () { return null; - } + }, ]); $h = new MockHandler([ static function (RequestInterface $request) { self::assertFalse($request->hasHeader('Content-Length')); self::assertSame('chunked', $request->getHeaderLine('Transfer-Encoding')); + return new Response(200); - } + }, ]); $m = Middleware::prepareBody(); $stack = new HandlerStack($h); @@ -78,13 +80,14 @@ static function (RequestInterface $request) { public function testAddsContentTypeWhenMissingAndPossible() { - $bd = Psr7\Utils::streamFor(\fopen(__DIR__ . '/../composer.json', 'r')); + $bd = Psr7\Utils::streamFor(\fopen(__DIR__.'/../composer.json', 'r')); $h = new MockHandler([ static function (RequestInterface $request) { self::assertSame('application/json', $request->getHeaderLine('Content-Type')); self::assertTrue($request->hasHeader('Content-Length')); + return new Response(200); - } + }, ]); $m = Middleware::prepareBody(); $stack = new HandlerStack($h); @@ -102,7 +105,7 @@ public function expectProvider() [true, ['100-Continue']], [false, []], [10, ['100-Continue']], - [500000, []] + [500000, []], ]; } @@ -111,13 +114,14 @@ public function expectProvider() */ public function testAddsExpect($value, $result) { - $bd = Psr7\Utils::streamFor(\fopen(__DIR__ . '/../composer.json', 'r')); + $bd = Psr7\Utils::streamFor(\fopen(__DIR__.'/../composer.json', 'r')); $h = new MockHandler([ static function (RequestInterface $request) use ($result) { self::assertSame($result, $request->getHeader('Expect')); + return new Response(200); - } + }, ]); $m = Middleware::prepareBody(); @@ -125,7 +129,7 @@ static function (RequestInterface $request) use ($result) { $stack->push($m); $comp = $stack->resolve(); $p = $comp(new Request('PUT', 'http://www.google.com', [], $bd), [ - 'expect' => $value + 'expect' => $value, ]); self::assertInstanceOf(PromiseInterface::class, $p); $response = $p->wait(); @@ -134,12 +138,13 @@ static function (RequestInterface $request) use ($result) { public function testIgnoresIfExpectIsPresent() { - $bd = Psr7\Utils::streamFor(\fopen(__DIR__ . '/../composer.json', 'r')); + $bd = Psr7\Utils::streamFor(\fopen(__DIR__.'/../composer.json', 'r')); $h = new MockHandler([ static function (RequestInterface $request) { self::assertSame(['Foo'], $request->getHeader('Expect')); + return new Response(200); - } + }, ]); $m = Middleware::prepareBody(); diff --git a/tests/RedirectMiddlewareTest.php b/tests/RedirectMiddlewareTest.php index 5ca36ccb7..2bd355fb0 100644 --- a/tests/RedirectMiddlewareTest.php +++ b/tests/RedirectMiddlewareTest.php @@ -47,36 +47,36 @@ public function testRedirectsWithAbsoluteUri() { $mock = new MockHandler([ new Response(302, ['Location' => 'http://test.com']), - new Response(200) + new Response(200), ]); $stack = new HandlerStack($mock); $stack->push(Middleware::redirect()); $handler = $stack->resolve(); $request = new Request('GET', 'http://example.com?a=b'); $promise = $handler($request, [ - 'allow_redirects' => ['max' => 2] + 'allow_redirects' => ['max' => 2], ]); $response = $promise->wait(); self::assertSame(200, $response->getStatusCode()); - self::assertSame('http://test.com', (string)$mock->getLastRequest()->getUri()); + self::assertSame('http://test.com', (string) $mock->getLastRequest()->getUri()); } public function testRedirectsWithRelativeUri() { $mock = new MockHandler([ new Response(302, ['Location' => '/foo']), - new Response(200) + new Response(200), ]); $stack = new HandlerStack($mock); $stack->push(Middleware::redirect()); $handler = $stack->resolve(); $request = new Request('GET', 'http://example.com?a=b'); $promise = $handler($request, [ - 'allow_redirects' => ['max' => 2] + 'allow_redirects' => ['max' => 2], ]); $response = $promise->wait(); self::assertSame(200, $response->getStatusCode()); - self::assertSame('http://example.com/foo', (string)$mock->getLastRequest()->getUri()); + self::assertSame('http://example.com/foo', (string) $mock->getLastRequest()->getUri()); } public function testLimitsToMaxRedirects() @@ -85,7 +85,7 @@ public function testLimitsToMaxRedirects() new Response(301, ['Location' => 'http://test.com']), new Response(302, ['Location' => 'http://test.com']), new Response(303, ['Location' => 'http://test.com']), - new Response(304, ['Location' => 'http://test.com']) + new Response(304, ['Location' => 'http://test.com']), ]); $stack = new HandlerStack($mock); $stack->push(Middleware::redirect()); @@ -102,7 +102,7 @@ public function testTooManyRedirectsExceptionHasResponse() { $mock = new MockHandler([ new Response(301, ['Location' => 'http://test.com']), - new Response(302, ['Location' => 'http://test.com']) + new Response(302, ['Location' => 'http://test.com']), ]); $stack = new HandlerStack($mock); $stack->push(Middleware::redirect()); @@ -121,7 +121,7 @@ public function testTooManyRedirectsExceptionHasResponse() public function testEnsuresProtocolIsValid() { $mock = new MockHandler([ - new Response(301, ['Location' => 'ftp://test.com']) + new Response(301, ['Location' => 'ftp://test.com']), ]); $stack = new HandlerStack($mock); $stack->push(Middleware::redirect()); @@ -137,14 +137,14 @@ public function testAddsRefererHeader() { $mock = new MockHandler([ new Response(302, ['Location' => 'http://test.com']), - new Response(200) + new Response(200), ]); $stack = new HandlerStack($mock); $stack->push(Middleware::redirect()); $handler = $stack->resolve(); $request = new Request('GET', 'http://example.com?a=b'); $promise = $handler($request, [ - 'allow_redirects' => ['max' => 2, 'referer' => true] + 'allow_redirects' => ['max' => 2, 'referer' => true], ]); $promise->wait(); self::assertSame( @@ -157,14 +157,14 @@ public function testAddsRefererHeaderButClearsUserInfo() { $mock = new MockHandler([ new Response(302, ['Location' => 'http://test.com']), - new Response(200) + new Response(200), ]); $stack = new HandlerStack($mock); $stack->push(Middleware::redirect()); $handler = $stack->resolve(); $request = new Request('GET', 'http://foo:bar@example.com?a=b'); $promise = $handler($request, [ - 'allow_redirects' => ['max' => 2, 'referer' => true] + 'allow_redirects' => ['max' => 2, 'referer' => true], ]); $promise->wait(); self::assertSame( @@ -179,7 +179,7 @@ public function testAddsGuzzleRedirectHeader() new Response(302, ['Location' => 'http://example.com']), new Response(302, ['Location' => 'http://example.com/foo']), new Response(302, ['Location' => 'http://example.com/bar']), - new Response(200) + new Response(200), ]); $stack = new HandlerStack($mock); @@ -187,7 +187,7 @@ public function testAddsGuzzleRedirectHeader() $handler = $stack->resolve(); $request = new Request('GET', 'http://example.com?a=b'); $promise = $handler($request, [ - 'allow_redirects' => ['track_redirects' => true] + 'allow_redirects' => ['track_redirects' => true], ]); $response = $promise->wait(true); self::assertSame( @@ -207,7 +207,7 @@ public function testAddsGuzzleRedirectStatusHeader() new Response(302, ['Location' => 'http://example.com/foo']), new Response(301, ['Location' => 'http://example.com/bar']), new Response(302, ['Location' => 'http://example.com/baz']), - new Response(200) + new Response(200), ]); $stack = new HandlerStack($mock); @@ -215,7 +215,7 @@ public function testAddsGuzzleRedirectStatusHeader() $handler = $stack->resolve(); $request = new Request('GET', 'http://example.com?a=b'); $promise = $handler($request, [ - 'allow_redirects' => ['track_redirects' => true] + 'allow_redirects' => ['track_redirects' => true], ]); $response = $promise->wait(true); self::assertSame( @@ -233,14 +233,14 @@ public function testDoesNotAddRefererWhenGoingFromHttpsToHttp() { $mock = new MockHandler([ new Response(302, ['Location' => 'http://test.com']), - new Response(200) + new Response(200), ]); $stack = new HandlerStack($mock); $stack->push(Middleware::redirect()); $handler = $stack->resolve(); $request = new Request('GET', 'https://example.com?a=b'); $promise = $handler($request, [ - 'allow_redirects' => ['max' => 2, 'referer' => true] + 'allow_redirects' => ['max' => 2, 'referer' => true], ]); $promise->wait(); self::assertFalse($mock->getLastRequest()->hasHeader('Referer')); @@ -250,7 +250,7 @@ public function testInvokesOnRedirectForRedirects() { $mock = new MockHandler([ new Response(302, ['Location' => 'http://test.com']), - new Response(200) + new Response(200), ]); $stack = new HandlerStack($mock); $stack->push(Middleware::redirect()); @@ -265,8 +265,8 @@ public function testInvokesOnRedirectForRedirects() self::assertSame('GET', $request->getMethod()); self::assertSame('http://test.com', (string) $uri); $call = true; - } - ] + }, + ], ]); $promise->wait(); self::assertTrue($call); @@ -293,8 +293,9 @@ static function (RequestInterface $request, $options) { isset($options['curl'][\CURLOPT_USERPWD]), 'curl options still contain CURLOPT_USERPWD entry' ); + return new Response(200); - } + }, ]); $handler = HandlerStack::create($mock); $client = new Client(['handler' => $handler]); @@ -322,8 +323,9 @@ static function (RequestInterface $request, $options) { isset($options['curl'][\CURLOPT_USERPWD]), 'curl options still contain CURLOPT_USERPWD entry' ); + return new Response(200); - } + }, ]); $handler = HandlerStack::create($mock); $client = new Client(['handler' => $handler]); @@ -351,8 +353,9 @@ static function (RequestInterface $request, $options) { isset($options['curl'][\CURLOPT_USERPWD]), 'curl options still contain CURLOPT_USERPWD entry' ); + return new Response(200); - } + }, ]); $handler = HandlerStack::create($mock); $client = new Client(['handler' => $handler]); @@ -380,8 +383,9 @@ static function (RequestInterface $request, $options) { isset($options['curl'][\CURLOPT_USERPWD]), 'curl options still contain CURLOPT_USERPWD entry' ); + return new Response(200); - } + }, ]); $handler = HandlerStack::create($mock); $client = new Client(['handler' => $handler]); @@ -409,8 +413,9 @@ static function (RequestInterface $request, $options) { isset($options['curl'][\CURLOPT_USERPWD]), 'curl options does not contain expected CURLOPT_USERPWD entry' ); + return new Response(200); - } + }, ]); $handler = HandlerStack::create($mock); $client = new Client(['handler' => $handler]); @@ -451,7 +456,7 @@ static function (RequestInterface $request) use ($isCrossOrigin) { self::assertSame(!$isCrossOrigin, $request->hasHeader('Cookie')); return new Response(200); - } + }, ]); $handler = HandlerStack::create($mock); $client = new Client(['handler' => $handler]); @@ -464,8 +469,9 @@ public function testNotRemoveAuthorizationHeaderOnRedirect() new Response(302, ['Location' => 'http://example.com/2']), static function (RequestInterface $request) { self::assertTrue($request->hasHeader('Authorization')); + return new Response(200); - } + }, ]); $handler = HandlerStack::create($mock); $client = new Client(['handler' => $handler]); diff --git a/tests/RetryMiddlewareTest.php b/tests/RetryMiddlewareTest.php index b3408fcb7..090f3019b 100644 --- a/tests/RetryMiddlewareTest.php +++ b/tests/RetryMiddlewareTest.php @@ -18,13 +18,15 @@ public function testRetriesWhenDeciderReturnsTrue() $calls = []; $decider = static function (...$args) use (&$calls) { $calls[] = $args; + return \count($calls) < 3; }; $delay = static function ($retries, $response, $request) use (&$delayCalls) { - $delayCalls++; + ++$delayCalls; self::assertSame($retries, $delayCalls); self::assertInstanceOf(Response::class, $response); self::assertInstanceOf(Request::class, $request); + return 1; }; $m = Middleware::retry($decider, $delay); @@ -55,6 +57,7 @@ public function testCanRetryExceptions() $calls = []; $decider = static function (...$args) use (&$calls) { $calls[] = $args; + return $args[3] instanceof \Exception; }; $m = Middleware::retry($decider); diff --git a/tests/Server.php b/tests/Server.php index b49caef95..04062fae0 100644 --- a/tests/Server.php +++ b/tests/Server.php @@ -63,15 +63,15 @@ public static function enqueue($responses) }, $response->getHeaders()); $data[] = [ - 'status' => (string) $response->getStatusCode(), - 'reason' => $response->getReasonPhrase(), + 'status' => (string) $response->getStatusCode(), + 'reason' => $response->getReasonPhrase(), 'headers' => $headers, - 'body' => \base64_encode((string) $response->getBody()) + 'body' => \base64_encode((string) $response->getBody()), ]; } self::getClient()->request('PUT', 'guzzle-server/responses', [ - 'json' => $data + 'json' => $data, ]); } @@ -89,15 +89,15 @@ public static function enqueueRaw($statusCode, $reasonPhrase, $headers, $body) { $data = [ [ - 'status' => (string) $statusCode, - 'reason' => $reasonPhrase, + 'status' => (string) $statusCode, + 'reason' => $reasonPhrase, 'headers' => $headers, - 'body' => \base64_encode((string) $body) - ] + 'body' => \base64_encode((string) $body), + ], ]; self::getClient()->request('PUT', 'guzzle-server/responses', [ - 'json' => $data + 'json' => $data, ]); } @@ -121,7 +121,7 @@ public static function received() static function ($message) { $uri = $message['uri']; if (isset($message['query_string'])) { - $uri .= '?' . $message['query_string']; + $uri .= '?'.$message['query_string']; } $response = new Psr7\Request( $message['http_method'], @@ -130,6 +130,7 @@ static function ($message) { $message['body'], $message['version'] ); + return $response->withUri( $response->getUri() ->withScheme('http') @@ -171,8 +172,8 @@ public static function start() } if (!self::isListening()) { - \exec('node ' . __DIR__ . '/server.js ' - . self::$port . ' >> /tmp/server.log 2>&1 &'); + \exec('node '.__DIR__.'/server.js ' + .self::$port.' >> /tmp/server.log 2>&1 &'); self::wait(); } @@ -184,8 +185,9 @@ private static function isListening() try { self::getClient()->request('GET', 'guzzle-server/perf', [ 'connect_timeout' => 5, - 'timeout' => 5 + 'timeout' => 5, ]); + return true; } catch (\Exception $e) { return false; @@ -197,7 +199,7 @@ private static function getClient() if (!self::$client) { self::$client = new Client([ 'base_uri' => self::$url, - 'sync' => true, + 'sync' => true, ]); } diff --git a/tests/TestLogger.php b/tests/TestLogger.php index 9a263341b..9d4d1b5af 100644 --- a/tests/TestLogger.php +++ b/tests/TestLogger.php @@ -36,6 +36,7 @@ public function hasRecord($record, $level) if (is_string($record)) { $record = ['message' => $record]; } + return $this->hasRecordThatPasses(static function ($rec) use ($record) { if ($rec['message'] !== $record['message']) { return false; @@ -43,6 +44,7 @@ public function hasRecord($record, $level) if (isset($record['context']) && $rec['context'] !== $record['context']) { return false; } + return true; }, $level); } @@ -71,20 +73,22 @@ public function hasRecordThatPasses(callable $predicate, $level) return true; } } + return false; } public function __call($method, $args) { if (preg_match('/(.*)(Debug|Info|Notice|Warning|Error|Critical|Alert|Emergency)(.*)/', $method, $matches) > 0) { - $genericMethod = $matches[1] . ('Records' !== $matches[3] ? 'Record' : '') . $matches[3]; + $genericMethod = $matches[1].('Records' !== $matches[3] ? 'Record' : '').$matches[3]; $level = strtolower($matches[2]); if (method_exists($this, $genericMethod)) { $args[] = $level; + return call_user_func_array([$this, $genericMethod], $args); } } - throw new \BadMethodCallException('Call to undefined method ' . static::class . '::' . $method . '()'); + throw new \BadMethodCallException('Call to undefined method '.static::class.'::'.$method.'()'); } public function reset() diff --git a/tests/UtilsTest.php b/tests/UtilsTest.php index 04eb89df4..9eb50320a 100644 --- a/tests/UtilsTest.php +++ b/tests/UtilsTest.php @@ -22,7 +22,7 @@ public function typeProvider() [10, 'int(10)'], [1.0, 'float(1)'], [new StrClass(), 'object(GuzzleHttp\Test\StrClass)'], - [['foo'], 'array(1)'] + [['foo'], 'array(1)'], ]; } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index a52fca245..12b8fa766 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -6,8 +6,8 @@ } namespace GuzzleHttp\Test { - require __DIR__ . '/../vendor/autoload.php'; - require __DIR__ . '/Server.php'; + require __DIR__.'/../vendor/autoload.php'; + require __DIR__.'/Server.php'; use GuzzleHttp\Tests\Server; Server::start(); @@ -17,6 +17,7 @@ } // Override curl_setopt_array() and curl_multi_setopt() to get the last set curl options + namespace GuzzleHttp\Handler { function curl_setopt_array($handle, array $options) { @@ -25,6 +26,7 @@ function curl_setopt_array($handle, array $options) } else { unset($_SERVER['_curl']); } + return \curl_setopt_array($handle, $options); } @@ -35,6 +37,7 @@ function curl_multi_setopt($handle, $option, $value) } else { unset($_SERVER['_curl_multi']); } + return \curl_multi_setopt($handle, $option, $value); } }