From 590fe4a3a1bf87e70fd5988e484ca3b1f4715d62 Mon Sep 17 00:00:00 2001 From: Inhere Date: Tue, 7 Dec 2021 22:53:45 +0800 Subject: [PATCH] update: migrate syntax to php 8.0+ --- composer.json | 4 +- example/refer-file_get_contents.php | 29 ++++++ example/refer-file_get_contents1.php | 18 ++++ example/refer-fopen.php | 22 +++++ example/refer-fopen2.php | 32 +++++++ example/refer.php | 93 ------------------- example/{coreq.php => swoole-coreq.php} | 0 src/AbstractClient.php | 118 ++++++++++++------------ src/Client.php | 6 +- src/ClientInterface.php | 90 +++++++++--------- src/ClientUtil.php | 50 +--------- src/Curl/CurlClient.php | 37 ++++---- src/Curl/CurlClientInterface.php | 2 +- src/Curl/CurlMulti.php | 46 ++++----- src/Exception/NetworkException.php | 2 +- src/Exception/RequestException.php | 4 +- src/FOpenClient.php | 8 +- src/FSockClient.php | 13 +-- src/FileClient.php | 4 +- src/StreamClient.php | 15 +-- src/Swoole/CoClient.php | 23 ++--- src/Swoole/CoClient2.php | 13 +-- src/Traits/BuildRawHttpRequestTrait.php | 2 +- src/Traits/ParseRawResponseTrait.php | 4 +- src/Traits/StreamContextBuildTrait.php | 7 +- test/bootstrap.php | 2 +- 26 files changed, 311 insertions(+), 333 deletions(-) create mode 100644 example/refer-file_get_contents.php create mode 100644 example/refer-file_get_contents1.php create mode 100644 example/refer-fopen.php create mode 100644 example/refer-fopen2.php delete mode 100644 example/refer.php rename example/{coreq.php => swoole-coreq.php} (100%) diff --git a/composer.json b/composer.json index 05dfe83..f3114de 100644 --- a/composer.json +++ b/composer.json @@ -19,9 +19,9 @@ } ], "require": { - "php": ">7.2.0", + "php": ">8.0.0", "psr/http-client": "^1.0", - "toolkit/stdlib": "^1.0" + "toolkit/stdlib": "^2.0" }, "autoload": { "psr-4": { diff --git a/example/refer-file_get_contents.php b/example/refer-file_get_contents.php new file mode 100644 index 0000000..6761aa7 --- /dev/null +++ b/example/refer-file_get_contents.php @@ -0,0 +1,29 @@ + 'some content', + 'var2' => 'doh' + ] +); + +$opts = [ + 'http' => + [ + 'method' => 'POST', + 'header' => 'Content-type: application/x-www-form-urlencoded', + 'content' => $postdata + ] +]; + +$context = stream_context_create($opts); +$result = file_get_contents('http://example.com/submit.php', false, $context); + diff --git a/example/refer-file_get_contents1.php b/example/refer-file_get_contents1.php new file mode 100644 index 0000000..14bc899 --- /dev/null +++ b/example/refer-file_get_contents1.php @@ -0,0 +1,18 @@ + [ + 'protocol_version' => 1.1, + 'header' => [ + 'Connection: close', + ], + ], +])); + diff --git a/example/refer-fopen.php b/example/refer-fopen.php new file mode 100644 index 0000000..f279a56 --- /dev/null +++ b/example/refer-fopen.php @@ -0,0 +1,22 @@ + [ + 'method' => 'GET', + 'timeout' => 20, + 'header' => 'User-agent: Myagent', + 'proxy' => 'tcp://my-proxy.localnet:3128', + 'request_fulluri' => true /* without this option we get an HTTP error! */ + ] +]); + +if ($fp = fopen('http://example.com', 'rb', false, $stream)) { + print 'well done'; +} + diff --git a/example/refer-fopen2.php b/example/refer-fopen2.php new file mode 100644 index 0000000..4232b7c --- /dev/null +++ b/example/refer-fopen2.php @@ -0,0 +1,32 @@ + + [ + 'method' => 'GET', + 'max_redirects' => '0', + 'ignore_errors' => '1' + ] +]; + +$context = stream_context_create($opts); +$stream = fopen($url, 'rb', false, $context); + +// header information as well as meta data +// about the stream +vdump(stream_get_meta_data($stream)); + +// actual data at $url +vdump(stream_get_contents($stream)); +fclose($stream); + diff --git a/example/refer.php b/example/refer.php deleted file mode 100644 index 8fb4160..0000000 --- a/example/refer.php +++ /dev/null @@ -1,93 +0,0 @@ - 'some content', - 'var2' => 'doh' - ] -); - -$opts = [ - 'http' => - [ - 'method' => 'POST', - 'header' => 'Content-type: application/x-www-form-urlencoded', - 'content' => $postdata - ] -]; - -$context = stream_context_create($opts); -$result = file_get_contents('http://example.com/submit.php', false, $context); - -?> - - - [ - 'method' => 'GET', - 'max_redirects' => '0', - 'ignore_errors' => '1' - ] -]; - -$context = stream_context_create($opts); -$stream = fopen($url, 'r', false, $context); - -// header information as well as meta data -// about the stream -var_dump(stream_get_meta_data($stream)); - -// actual data at $url -var_dump(stream_get_contents($stream)); -fclose($stream); -?> - - [ - 'protocol_version' => 1.1, - 'header' => [ - 'Connection: close', - ], - ], -])); -?> - - [ - 'method' => 'GET', - 'timeout' => 20, - 'header' => 'User-agent: Myagent', - 'proxy' => 'tcp://my-proxy.localnet:3128', - 'request_fulluri' => true /* without this option we get an HTTP error! */ - ] -]); - -if ($fp = fopen('http://example.com', 'r', false, $stream)) { - print 'well done'; -} -?> diff --git a/example/coreq.php b/example/swoole-coreq.php similarity index 100% rename from example/coreq.php rename to example/swoole-coreq.php diff --git a/src/AbstractClient.php b/src/AbstractClient.php index 1158731..e38eecc 100644 --- a/src/AbstractClient.php +++ b/src/AbstractClient.php @@ -42,15 +42,15 @@ abstract class AbstractClient implements ClientInterface /** * for create psr7 ResponseInterface instance * - * @var Closure function(): ResponseInterface {..} - * @psalm-var Closure(): ResponseInterface + * @var callable(): ResponseInterface + * @psalm-var callable(): ResponseInterface */ protected $responseCreator; /** * @var array Default options data */ - protected $defaultOptions = [ + protected array $defaultOptions = [ // open debug mode 'debug' => false, // retry times, when an error occurred. @@ -93,7 +93,7 @@ abstract class AbstractClient implements ClientInterface * @see AbstractClient::$defaultOptions * @var array */ - protected $options; + protected array $options; /************************************************************************** * request data. @@ -104,7 +104,7 @@ abstract class AbstractClient implements ClientInterface * * @var string */ - protected $baseUrl = ''; + protected string $baseUrl = ''; /** * setting headers for curl @@ -114,13 +114,13 @@ abstract class AbstractClient implements ClientInterface * @var array * @psalm-var array */ - protected $headers = []; + protected array $headers = []; /** * @var array * @psalm-var array */ - protected $cookies = []; + protected array $cookies = []; /************************************************************************** * response data @@ -129,27 +129,27 @@ abstract class AbstractClient implements ClientInterface /** * @var int */ - protected $errNo = 0; + protected int $errNo = 0; /** * @var string */ - protected $error = ''; + protected string $error = ''; /** * @var int response status code. eg. 200 404 */ - protected $statusCode = 0; + protected int $statusCode = 0; /** * @var string body string, it's parsed from $_response */ - protected $responseBody = ''; + protected string $responseBody = ''; /** * @var string[] headers data, it's parsed from $_response */ - protected $responseHeaders = []; + protected array $responseHeaders = []; /** * @param array $options @@ -157,7 +157,7 @@ abstract class AbstractClient implements ClientInterface * @return static * @throws RuntimeException */ - public static function new(array $options = []): ClientInterface + public static function new(array $options = []): static { return new static($options); } @@ -168,7 +168,7 @@ public static function new(array $options = []): ClientInterface * @return static * @throws RuntimeException */ - public static function create(array $options = []): ClientInterface + public static function create(array $options = []): static { return new static($options); } @@ -228,7 +228,7 @@ public static function getSupportedMethods(): array /** * {@inheritDoc} */ - public function get(string $url, $params = null, array $headers = [], array $options = []): ClientInterface + public function get(string $url, $params = null, array $headers = [], array $options = []): static { return $this->request($url, $params, self::GET, $headers, $options); } @@ -236,7 +236,7 @@ public function get(string $url, $params = null, array $headers = [], array $opt /** * {@inheritDoc} */ - public function post(string $url, $data = null, array $headers = [], array $options = []): ClientInterface + public function post(string $url, mixed $data = null, array $headers = [], array $options = []): static { return $this->request($url, $data, self::POST, $headers, $options); } @@ -244,7 +244,7 @@ public function post(string $url, $data = null, array $headers = [], array $opti /** * {@inheritDoc} */ - public function put(string $url, $data = null, array $headers = [], array $options = []): ClientInterface + public function put(string $url, mixed $data = null, array $headers = [], array $options = []): static { return $this->request($url, $data, self::PUT, $headers, $options); } @@ -252,7 +252,7 @@ public function put(string $url, $data = null, array $headers = [], array $optio /** * {@inheritDoc} */ - public function patch(string $url, $data = null, array $headers = [], array $options = []): ClientInterface + public function patch(string $url, mixed $data = null, array $headers = [], array $options = []): static { return $this->request($url, $data, self::PATCH, $headers, $options); } @@ -260,7 +260,7 @@ public function patch(string $url, $data = null, array $headers = [], array $opt /** * {@inheritDoc} */ - public function delete(string $url, $params = null, array $headers = [], array $options = []): ClientInterface + public function delete(string $url, $params = null, array $headers = [], array $options = []): static { return $this->request($url, $params, self::DELETE, $headers, $options); } @@ -268,7 +268,7 @@ public function delete(string $url, $params = null, array $headers = [], array $ /** * {@inheritDoc} */ - public function options(string $url, $params = null, array $headers = [], array $options = []): ClientInterface + public function options(string $url, $params = null, array $headers = [], array $options = []): static { return $this->request($url, $params, self::OPTIONS, $headers, $options); } @@ -276,7 +276,7 @@ public function options(string $url, $params = null, array $headers = [], array /** * {@inheritDoc} */ - public function head(string $url, $params = null, array $headers = [], array $options = []): ClientInterface + public function head(string $url, $params = null, array $headers = [], array $options = []): static { return $this->request($url, $params, self::HEAD, $headers, $options); } @@ -287,9 +287,9 @@ public function head(string $url, $params = null, array $headers = [], array $op * @param array $headers * @param array $options * - * @return ClientInterface + * @return static */ - public function trace(string $url, $params = null, array $headers = [], array $options = []): ClientInterface + public function trace(string $url, $params = null, array $headers = [], array $options = []): static { return $this->request($url, $params, self::TRACE, $headers, $options); } @@ -315,13 +315,13 @@ public function sendRequest(RequestInterface $request): ResponseInterface /** * @param string $url - * @param mixed $data + * @param mixed|null $data * @param array $headers * @param array $options * * @return ClientInterface */ - public function json(string $url, $data = null, array $headers = [], array $options = []): ClientInterface + public function json(string $url, mixed $data = null, array $headers = [], array $options = []): static { if (!isset($options['method'])) { $options['method'] = 'POST'; @@ -395,11 +395,11 @@ public function SSLVerify(bool $enable): self * Set contents of HTTP Cookie header. * * @param string $key The name of the cookie - * @param string $value The value for the provided cookie name + * @param int|string $value The value for the provided cookie name * * @return $this */ - public function setCookie(string $key, $value): ClientInterface + public function setCookie(string $key, int|string $value): static { $this->cookies[$key] = (string)$value; return $this; @@ -430,8 +430,10 @@ public function setCookies(array $cookies): AbstractClient /** * accept Gzip + * + * @return static */ - public function acceptGzip() + public function acceptGzip(): static { return $this->addHeaders([ 'Expect' => '', // 首次速度非常慢 解决 @@ -486,7 +488,7 @@ public function withAjax(): self * * @return $this */ - public function setUserAgent(string $userAgent): ClientInterface + public function setUserAgent(string $userAgent): static { $this->setHeader('User-Agent', $userAgent); return $this; @@ -521,7 +523,7 @@ public function setUserAuth(string $user, string $pwd = '', int $authType = self * * @return $this */ - public function setProxy(string $host, int $port): ClientInterface + public function setProxy(string $host, int $port): static { $this->options['proxy'] = [ 'host' => $host, @@ -546,7 +548,7 @@ public function getHeaders(): array * * @inheritdoc */ - public function setHeaders(array $headers): ClientInterface + public function setHeaders(array $headers): static { $this->headers = []; // clear old. @@ -563,7 +565,7 @@ public function setHeaders(array $headers): ClientInterface * * @return $this */ - public function addHeaders(array $headers, bool $override = true): ClientInterface + public function addHeaders(array $headers, bool $override = true): static { foreach ($headers as $name => $value) { $this->setHeader($name, $value, $override); @@ -579,7 +581,7 @@ public function addHeaders(array $headers, bool $override = true): ClientInterfa * * @return $this */ - public function setHeader(string $name, string $value, bool $override = false): ClientInterface + public function setHeader(string $name, string $value, bool $override = false): static { $name = ucwords($name); @@ -591,11 +593,11 @@ public function setHeader(string $name, string $value, bool $override = false): } /** - * @param string|array $names + * @param array|string $names * * @return $this */ - public function delHeader($names): ClientInterface + public function delHeader(array|string $names): static { foreach ((array)$names as $name) { $name = ucwords($name); @@ -614,11 +616,11 @@ public function delHeader($names): ClientInterface /** * @param string $url - * @param mixed $data + * @param mixed|null $data * * @return string */ - protected function buildFullUrl(string $url, $data = null): string + protected function buildFullUrl(string $url, mixed $data = null): string { $url = trim($url); @@ -680,7 +682,7 @@ public function getPsr7Response(): ResponseInterface * * @return $this */ - protected function resetOptions(): ClientInterface + protected function resetOptions(): static { $this->options = $this->defaultOptions; return $this; @@ -689,7 +691,7 @@ protected function resetOptions(): ClientInterface /** * @return $this */ - public function resetRequest(): ClientInterface + public function resetRequest(): static { $this->headers = []; $this->cookies = []; @@ -699,7 +701,7 @@ public function resetRequest(): ClientInterface /** * @return $this */ - public function resetHeaders(): ClientInterface + public function resetHeaders(): static { $this->headers = []; return $this; @@ -708,7 +710,7 @@ public function resetHeaders(): ClientInterface /** * @return $this */ - public function resetCookies(): ClientInterface + public function resetCookies(): static { $this->cookies = []; return $this; @@ -717,7 +719,7 @@ public function resetCookies(): ClientInterface /** * @return $this */ - public function resetResponse(): ClientInterface + public function resetResponse(): static { $this->responseBody = ''; $this->responseHeaders = []; @@ -729,7 +731,7 @@ public function resetResponse(): ClientInterface * * @return $this */ - public function reset(): ClientInterface + public function reset(): static { $this->resetOptions(); @@ -749,11 +751,11 @@ public function getResponseCreator(): Closure } /** - * @param Closure $responseCreator + * @param callable $responseCreator * - * @return AbstractClient + * @return static */ - public function setResponseCreator(Closure $responseCreator): ClientInterface + public function setResponseCreator(callable $responseCreator): static { $this->responseCreator = $responseCreator; return $this; @@ -764,7 +766,7 @@ public function setResponseCreator(Closure $responseCreator): ClientInterface * * @return $this */ - public function setBaseUrl(string $url): ClientInterface + public function setBaseUrl(string $url): static { $this->baseUrl = trim($url); return $this; @@ -780,11 +782,11 @@ public function getBaseUrl(): string /** * @param int|string $name - * @param null|mixed $default + * @param mixed|null $default * * @return mixed */ - public function getOption($name, $default = null) + public function getOption(int|string $name, mixed $default = null): mixed { return $this->options[$name] ?? $default; } @@ -802,7 +804,7 @@ public function getOptions(): array * * @return ClientInterface */ - public function setOptions(array $options): ClientInterface + public function setOptions(array $options): static { $this->options = array_merge($this->options, $options); return $this; @@ -814,7 +816,7 @@ public function setOptions(array $options): ClientInterface * * @return ClientInterface */ - public function setOption(string $key, $value): ClientInterface + public function setOption(string $key, mixed $value): static { $this->options[$key] = $value; return $this; @@ -833,7 +835,7 @@ public function isDebug(): bool * * @return $this */ - public function setDebug($debug): ClientInterface + public function setDebug(mixed $debug): static { $this->options['debug'] = (bool)$debug; return $this; @@ -844,7 +846,7 @@ public function setDebug($debug): ClientInterface * * @return $this */ - public function setRetry(int $retry): ClientInterface + public function setRetry(int $retry): static { $this->options['retry'] = $retry; return $this; @@ -875,7 +877,7 @@ public function getJsonArray(): array return []; } - $data = json_decode($body, true); + $data = json_decode($body, true, 512, JSON_THROW_ON_ERROR); if (json_last_error() > 0) { return []; } @@ -886,13 +888,13 @@ public function getJsonArray(): array /** * @return bool|stdClass */ - public function getJsonObject() + public function getJsonObject(): bool|stdClass { if (!$body = $this->getResponseBody()) { return false; } - $data = json_decode($body, false); + $data = json_decode($body, false, 512, JSON_THROW_ON_ERROR); if (json_last_error() > 0) { return false; } @@ -926,11 +928,11 @@ public function getResponseHeaders(): array /** * @param string $name - * @param null $default + * @param string $default * * @return string */ - public function getResponseHeader(string $name, $default = null): ?string + public function getResponseHeader(string $name, string $default = ''): string { $name = ucwords($name); return $this->responseHeaders[$name] ?? $default; diff --git a/src/Client.php b/src/Client.php index 38dbadf..8676620 100644 --- a/src/Client.php +++ b/src/Client.php @@ -37,7 +37,7 @@ class Client * * @var ClientInterface[] */ - private static $drivers = [ + private static array $drivers = [ 'curl' => CurlClient::class, 'stream' => StreamClient::class, 'fsock' => FSockClient::class, @@ -50,14 +50,14 @@ class Client /** * @var ClientInterface */ - private static $defaultDriver; + private static ClientInterface $defaultDriver; /** * config data for $defaultDriver * * @var array */ - private static $defaultConfig = []; + private static array $defaultConfig = []; /** * Quick create an client diff --git a/src/ClientInterface.php b/src/ClientInterface.php index 1b03cda..948bfc9 100644 --- a/src/ClientInterface.php +++ b/src/ClientInterface.php @@ -9,8 +9,6 @@ namespace PhpPkg\Http\Client; -use Closure; - /** * Interface ClientInterface * @@ -62,16 +60,16 @@ interface ClientInterface extends \Psr\Http\Client\ClientInterface /** * @param array $options * - * @return ClientInterface + * @return static */ - public static function new(array $options): ClientInterface; + public static function new(array $options): static; /** * @param array $options * - * @return ClientInterface + * @return static */ - public static function create(array $options): ClientInterface; + public static function create(array $options): static; /** * @return string @@ -96,45 +94,45 @@ public function __toString(): string; * @param array $headers * @param array $options * - * @return ClientInterface + * @return static */ - public function get(string $url, $params = null, array $headers = [], array $options = []): ClientInterface; + public function get(string $url, $params = null, array $headers = [], array $options = []): static; /** * POST * * @param string $url - * @param mixed $data + * @param mixed|null $data * @param array $headers * @param array $options * - * @return ClientInterface + * @return static */ - public function post(string $url, $data = null, array $headers = [], array $options = []): ClientInterface; + public function post(string $url, mixed $data = null, array $headers = [], array $options = []): static; /** * PUT * * @param string $url - * @param mixed $data + * @param mixed|null $data * @param array $headers * @param array $options * - * @return ClientInterface + * @return static */ - public function put(string $url, $data = null, array $headers = [], array $options = []): ClientInterface; + public function put(string $url, mixed $data = null, array $headers = [], array $options = []): static; /** * PATCH * * @param string $url - * @param mixed $data + * @param mixed|null $data * @param array $headers * @param array $options * - * @return ClientInterface + * @return static */ - public function patch(string $url, $data = null, array $headers = [], array $options = []): ClientInterface; + public function patch(string $url, mixed $data = null, array $headers = [], array $options = []): static; /** * DELETE @@ -144,9 +142,9 @@ public function patch(string $url, $data = null, array $headers = [], array $opt * @param array $headers * @param array $options * - * @return ClientInterface + * @return static */ - public function delete(string $url, $params = null, array $headers = [], array $options = []): ClientInterface; + public function delete(string $url, $params = null, array $headers = [], array $options = []): static; /** * OPTIONS @@ -156,9 +154,9 @@ public function delete(string $url, $params = null, array $headers = [], array $ * @param array $headers * @param array $options * - * @return ClientInterface + * @return static */ - public function options(string $url, $params = null, array $headers = [], array $options = []): ClientInterface; + public function options(string $url, $params = null, array $headers = [], array $options = []): static; /** * HEAD @@ -168,9 +166,9 @@ public function options(string $url, $params = null, array $headers = [], array * @param array $headers * @param array $options * - * @return ClientInterface + * @return static */ - public function head(string $url, array $params = [], array $headers = [], array $options = []): ClientInterface; + public function head(string $url, array $params = [], array $headers = [], array $options = []): static; /** * TRACE @@ -180,9 +178,9 @@ public function head(string $url, array $params = [], array $headers = [], array * @param array $headers * @param array $options * - * @return ClientInterface + * @return static */ - public function trace(string $url, array $params = [], array $headers = [], array $options = []): ClientInterface; + public function trace(string $url, array $params = [], array $headers = [], array $options = []): static; /** * Send request to remote URL @@ -193,43 +191,43 @@ public function trace(string $url, array $params = [], array $headers = [], arra * @param array $headers * @param array $options All options please {@see AbstractClient::$defaultOptions} * - * @return ClientInterface + * @return static */ public function request( string $url, - $data = null, + array|string $data = null, string $method = '', array $headers = [], array $options = [] - ): ClientInterface; + ): static; /** - * @param Closure $responseCreator + * @param callable $responseCreator * * @return self */ - public function setResponseCreator(Closure $responseCreator): ClientInterface; + public function setResponseCreator(callable $responseCreator): static; /** * reset options, request headers, cookies, response data... * * @return self */ - public function reset(): ClientInterface; + public function reset(): static; /** * Reset request data * * @return self */ - public function resetRequest(): ClientInterface; + public function resetRequest(): static; /** * Reset response data * * @return self */ - public function resetResponse(): ClientInterface; + public function resetResponse(): static; /************************************************************************** * config client @@ -241,29 +239,29 @@ public function resetResponse(): ClientInterface; * * @return $this */ - public function setProxy(string $host, int $port): ClientInterface; + public function setProxy(string $host, int $port): static; /** * @param string $userAgent * * @return $this */ - public function setUserAgent(string $userAgent): ClientInterface; + public function setUserAgent(string $userAgent): static; /** * @param array $options * - * @return ClientInterface + * @return static */ - public function setOptions(array $options): ClientInterface; + public function setOptions(array $options): static; /** * @param string $key * @param mixed $value * - * @return ClientInterface + * @return static */ - public function setOption(string $key, $value): ClientInterface; + public function setOption(string $key, mixed $value): static; /** * @return bool @@ -275,7 +273,7 @@ public function isDebug(): bool; * * @return $this */ - public function setDebug($debug): ClientInterface; + public function setDebug(mixed $debug): static; /************************************************************************** * request cookies @@ -292,7 +290,7 @@ public function setDebug($debug): ClientInterface; * * @return $this */ - public function setHeaders(array $headers): self; + public function setHeaders(array $headers): static; /** * add headers @@ -302,14 +300,14 @@ public function setHeaders(array $headers): self; * * @return mixed */ - public function addHeaders(array $headers, bool $override = true): self; + public function addHeaders(array $headers, bool $override = true): static; /** - * @param string|array $names + * @param array|string $names * * @return $this */ - public function delHeader($names): self; + public function delHeader(array|string $names): static; /** * @return mixed @@ -322,11 +320,11 @@ public function getHeaders(): array; /** * @param string $key - * @param string|int $value + * @param int|string $value * * @return self */ - public function setCookie(string $key, $value): self; + public function setCookie(string $key, int|string $value): self; /************************************************************************** * response info diff --git a/src/ClientUtil.php b/src/ClientUtil.php index 576ac0b..7900313 100644 --- a/src/ClientUtil.php +++ b/src/ClientUtil.php @@ -10,23 +10,14 @@ namespace PhpPkg\Http\Client; use InvalidArgumentException; -use PhpPkg\Http\Client\Exception\ClientException; -use Toolkit\Stdlib\Arr\ArrayHelper; use Toolkit\Stdlib\Helper\JsonHelper; use Toolkit\Stdlib\Str\UrlHelper; -use function array_merge; use function http_build_query; use function is_scalar; -use function mb_convert_encoding; -use function parse_url; -use function rawurlencode; -use function str_replace; use function stripos; use function strpos; use function strtoupper; -use function trim; use function ucwords; -use function urldecode; /** * Class ClientUtil @@ -35,18 +26,6 @@ */ class ClientUtil { - /** - * @param array $src - * @param array $append - * - * @return array - * @deprecated please use ArrayHelper::quickMerge($append, $src) - */ - public static function mergeArray(array $src, array $append): array - { - return ArrayHelper::quickMerge($append, $src); - } - /** * @param array $arr * @@ -74,29 +53,7 @@ public static function isFullURL(string $url): bool /** * @param string $url - * - * @return array - * @deprecated please use UrlHelper::parse2($url); - */ - public static function parseUrl(string $url): array - { - $info = parse_url($url); - if ($info === false) { - throw new ClientException('invalid request url: ' . $url); - } - - return array_merge([ - 'scheme' => 'http', - 'host' => '', - 'port' => 80, - 'path' => '/', - 'query' => '', - ], $info); - } - - /** - * @param string $url - * @param null $data + * @param null $data * * @return string */ @@ -122,11 +79,12 @@ public static function encodeURL(string $url): string /** * @param array $headers - * @param string|array|object $data body data + * @param object|array|string $data body data * * @return string + * @throws \JsonException */ - public static function buildBodyByContentType(array &$headers, $data): string + public static function buildBodyByContentType(array &$headers, object|array|string $data): string { $defContentType = 'application/x-www-form-urlencoded'; diff --git a/src/Curl/CurlClient.php b/src/Curl/CurlClient.php index ddfc0ed..fab9cbd 100644 --- a/src/Curl/CurlClient.php +++ b/src/Curl/CurlClient.php @@ -9,6 +9,7 @@ namespace PhpPkg\Http\Client\Curl; +use CurlHandle; use InvalidArgumentException; use PhpPkg\Http\Client\AbstractClient; use PhpPkg\Http\Client\ClientConst; @@ -17,6 +18,7 @@ use PhpPkg\Http\Client\Exception\ClientException; use PhpPkg\Http\Client\Traits\ParseRawResponseTrait; use Toolkit\Stdlib\Arr\ArrayHelper; +use Toolkit\Stdlib\Helper\Assert; use Toolkit\Stdlib\Str\UrlHelper; use function array_merge; use function curl_close; @@ -114,7 +116,7 @@ class CurlClient extends AbstractClient implements CurlClientInterface * * @var array */ - private static $canRetryErrorCodes = [ + private static array $canRetryErrorCodes = [ CURLE_COULDNT_RESOLVE_HOST, CURLE_COULDNT_CONNECT, CURLE_HTTP_NOT_FOUND, @@ -133,7 +135,7 @@ class CurlClient extends AbstractClient implements CurlClientInterface * * @var array */ - private $_curlOptions = [ + private array $_curlOptions = [ // TRUE 将 curl_exec() 获取的信息以字符串返回,而不是直接输出 CURLOPT_RETURNTRANSFER => true, @@ -185,7 +187,7 @@ class CurlClient extends AbstractClient implements CurlClientInterface * "starttransfer_time" * "redirect_time" */ - private $_responseInfo = []; + private array $_responseInfo = []; /** * {@inheritDoc} @@ -221,13 +223,13 @@ public function __construct(array $options = []) * @param string $mimeType The post file mime type * param string $postFilename The post file name * - * @return ClientInterface + * @return static */ - public function upload(string $url, string $field, string $filePath, string $mimeType = ''): ClientInterface + public function upload(string $url, string $field, string $filePath, string $mimeType = ''): static { if (!$mimeType) { $fInfo = finfo_open(FILEINFO_MIME); // 返回 mime 类型 - $mimeType = finfo_file($fInfo, $filePath) ?: 'application/octet-stream'; + $mimeType = (string)finfo_file($fInfo, $filePath) ?: 'application/octet-stream'; } // create file @@ -261,7 +263,7 @@ public function downloadImage(string $imgUrl, string $saveDir, string $rename = $last = trim(strrchr($real, '/'), '/'); // special url e.g http://img.blog.csdn.net/20150929103749499 - if (false === strpos($last, '.')) { + if (!str_contains($last, '.')) { $suffix = 'jpg'; $name = $rename ?: $last; } else { @@ -290,14 +292,14 @@ public function downloadImage(string $imgUrl, string $saveDir, string $rename = * Send request * * @param string $url - * @param mixed $data + * @param array|string|null $data * @param string $method * @param array $headers * @param array $options * * @return $this */ - public function request(string $url, $data = null, string $method = 'GET', array $headers = [], array $options = []): ClientInterface + public function request(string $url, array|string $data = null, string $method = 'GET', array $headers = [], array $options = []): static { if ($method) { $options['method'] = strtoupper($method); @@ -355,9 +357,9 @@ public function request(string $url, $data = null, string $method = 'GET', array * @param array $headers * @param array $options * - * @return resource + * @return CurlHandle */ - protected function prepareRequest(string $url, $data, array $headers, array $options = []) + protected function prepareRequest(string $url, mixed $data, array $headers, array $options = []): CurlHandle { $this->resetResponse(); @@ -377,6 +379,7 @@ protected function prepareRequest(string $url, $data, array $headers, array $opt // init curl $ch = curl_init(); + Assert::notEmpty($ch, 'init an curl handle failed'); // add send data if ($data) { @@ -456,7 +459,7 @@ public function getTotalTime(): int /** * @return $this */ - public function resetOptions(): ClientInterface + public function resetOptions(): static { // $this->_curlOptions = []; @@ -467,7 +470,7 @@ public function resetOptions(): ClientInterface /** * @return $this */ - public function resetResponse(): ClientInterface + public function resetResponse(): static { $this->rawResponse = ''; $this->responseParsed = false; @@ -485,7 +488,7 @@ public function resetResponse(): ClientInterface * * @return $this */ - public function setUserAgent(string $userAgent): ClientInterface + public function setUserAgent(string $userAgent): static { $this->_curlOptions[CURLOPT_USERAGENT] = $userAgent; return $this; @@ -600,7 +603,7 @@ public function enableSSLVerify(): self /** * @inheritdoc */ - public function setCurlOptions(array $options) + public function setCurlOptions(array $options): static { $this->_curlOptions = array_merge($this->_curlOptions, $options); return $this; @@ -612,7 +615,7 @@ public function setCurlOptions(array $options) * * @return $this */ - public function setCurlOption($name, $value): self + public function setCurlOption(int $name, $value): self { $this->_curlOptions[$name] = $value; return $this; @@ -632,7 +635,7 @@ public function getCurlOptions(): array * * @return mixed */ - public function getCurlOption($name, $default = null) + public function getCurlOption(int|string $name, $default = null): mixed { return $this->_curlOptions[$name] ?? $default; } diff --git a/src/Curl/CurlClientInterface.php b/src/Curl/CurlClientInterface.php index 5c5a4a9..618fc4f 100644 --- a/src/Curl/CurlClientInterface.php +++ b/src/Curl/CurlClientInterface.php @@ -21,7 +21,7 @@ interface CurlClientInterface * * @param array $options */ - public function setCurlOptions(array $options); + public function setCurlOptions(array $options): static; /** * @return array diff --git a/src/Curl/CurlMulti.php b/src/Curl/CurlMulti.php index 5a93f90..7c4d489 100644 --- a/src/Curl/CurlMulti.php +++ b/src/Curl/CurlMulti.php @@ -9,9 +9,12 @@ namespace PhpPkg\Http\Client\Curl; +use CurlHandle; +use CurlMultiHandle; use PhpPkg\Http\Client\ClientUtil; use RuntimeException; use Toolkit\Stdlib\Arr\ArrayHelper; +use Toolkit\Stdlib\Helper\Assert; use Toolkit\Stdlib\Str\UrlHelper; use function array_merge; use function curl_errno; @@ -57,29 +60,29 @@ class CurlMulti // extends CurlLite /** * @var array */ - private $errors = []; + private array $errors = []; /** - * @var array + * @var CurlHandle[] */ - private $chMap = []; + private array $chMap = []; /** - * @var resource + * @var CurlMultiHandle|null */ - private $mh; + private ?CurlMultiHandle $mh = null; /** * base Url * * @var string */ - protected $baseUrl = ''; + protected string $baseUrl = ''; /** * @var array */ - protected $defaultOptions = [ + protected array $defaultOptions = [ 'uri' => '', 'method' => 'GET', // 'POST' 'retry' => 3, @@ -101,7 +104,7 @@ class CurlMulti // extends CurlLite /** * @var array */ - private $options; + private array $options; /** * @param array $options @@ -148,13 +151,13 @@ public function build(array $data): self /** * @param string $url - * @param mixed $data + * @param mixed|null $data * @param array $headers * @param array $options * * @return $this */ - public function append(string $url, $data = null, array $headers = [], array $options = []): self + public function append(string $url, mixed $data = null, array $headers = [], array $options = []): self { $options = array_merge($this->options, $options); // append @@ -170,11 +173,11 @@ public function append(string $url, $data = null, array $headers = [], array $op * * @link https://secure.php.net/manual/zh/function.curl-multi-select.php * - * @param null|resource $mh + * @param null|CurlMultiHandle $mh * * @return bool|array */ - public function execute($mh = null) + public function execute(CurlMultiHandle $mh = null): bool|array { if (!($mh = $mh ?: $this->mh)) { return false; @@ -216,15 +219,16 @@ public function execute($mh = null) /** * @param string $url - * @param mixed $data + * @param mixed|null $data * @param array $headers * @param array $opts * - * @return resource + * @return CurlHandle */ - public function createResource(string $url, $data = null, array $headers = [], array $opts = []) + public function createResource(string $url, mixed $data = null, array $headers = [], array $opts = []): CurlHandle { $ch = curl_init(); + Assert::notEmpty($ch, 'init an curl handle failed'); $curlOptions = [ // 设置超时 @@ -303,11 +307,11 @@ public function createResource(string $url, $data = null, array $headers = [], a /** * @param string $url - * @param mixed $data + * @param mixed|null $data * * @return string */ - protected function buildUrl(string $url, $data = null): string + protected function buildUrl(string $url, mixed $data = null): string { $url = trim($url); @@ -386,17 +390,17 @@ public function setChMap(array $chMap): void } /** - * @return resource + * @return CurlMultiHandle|null */ - public function getMh() + public function getMh(): ?CurlMultiHandle { return $this->mh; } /** - * @param resource $mh + * @param CurlMultiHandle $mh */ - public function setMh($mh): void + public function setMh(CurlMultiHandle $mh): void { $this->mh = $mh; } diff --git a/src/Exception/NetworkException.php b/src/Exception/NetworkException.php index 8b8ddff..f2a74be 100644 --- a/src/Exception/NetworkException.php +++ b/src/Exception/NetworkException.php @@ -24,7 +24,7 @@ class NetworkException extends RuntimeException implements NetworkExceptionInter /** * @var RequestInterface */ - private $request; + private ?RequestInterface $request; /** * NetworkException constructor. diff --git a/src/Exception/RequestException.php b/src/Exception/RequestException.php index 56aa2ae..2a0b12c 100644 --- a/src/Exception/RequestException.php +++ b/src/Exception/RequestException.php @@ -22,9 +22,9 @@ class RequestException extends RuntimeException implements RequestExceptionInterface { /** - * @var RequestInterface + * @var RequestInterface|null */ - private $request; + private ?RequestInterface $request; /** * NetworkException constructor. diff --git a/src/FOpenClient.php b/src/FOpenClient.php index 9d1d4a8..c2fa7e6 100644 --- a/src/FOpenClient.php +++ b/src/FOpenClient.php @@ -60,7 +60,7 @@ class FOpenClient extends AbstractClient * 'uri' => string(20) "http://www.baidu.com" * ] */ - private $responseInfo = []; + private array $responseInfo = []; /** * @return bool @@ -74,7 +74,7 @@ public static function isAvailable(): bool * Send request to remote URL * * @param string $url - * @param null $data + * @param array|string|null $data * @param string $method * @param array $headers * @param array $options @@ -83,11 +83,11 @@ public static function isAvailable(): bool */ public function request( string $url, - $data = null, + array|string $data = null, string $method = self::GET, array $headers = [], array $options = [] - ): ClientInterface { + ): static { if ($method) { $options['method'] = strtoupper($method); } diff --git a/src/FSockClient.php b/src/FSockClient.php index 844e577..373a093 100644 --- a/src/FSockClient.php +++ b/src/FSockClient.php @@ -13,6 +13,7 @@ use PhpPkg\Http\Client\Exception\RequestException; use PhpPkg\Http\Client\Traits\BuildRawHttpRequestTrait; use PhpPkg\Http\Client\Traits\ParseRawResponseTrait; +use Toolkit\Stdlib\Str\UrlHelper; use function array_merge; use function fclose; use function feof; @@ -49,7 +50,7 @@ class FSockClient extends AbstractClient * 'seekable' => bool(false) * ] */ - private $responseInfo = []; + private array $responseInfo = []; /** * @return bool @@ -63,7 +64,7 @@ public static function isAvailable(): bool * Send request to remote URL * * @param string $url - * @param null $data + * @param array|string|null $data * @param string $method * @param array $headers * @param array $options @@ -72,17 +73,17 @@ public static function isAvailable(): bool */ public function request( string $url, - $data = null, + array|string $data = null, string $method = self::GET, array $headers = [], array $options = [] - ): ClientInterface { + ): static { if ($method) { $options['method'] = strtoupper($method); } // get request url info - $info = ClientUtil::parseUrl($this->buildFullUrl($url)); + $info = UrlHelper::parse2($this->buildFullUrl($url)); // merge global options data. $options = array_merge($this->options, $options); @@ -129,7 +130,7 @@ public function request( /** * @return $this */ - public function resetResponse(): ClientInterface + public function resetResponse(): static { $this->rawResponse = ''; $this->responseParsed = false; diff --git a/src/FileClient.php b/src/FileClient.php index 0558908..fd0b0f8 100644 --- a/src/FileClient.php +++ b/src/FileClient.php @@ -41,11 +41,11 @@ public static function isAvailable(): bool */ public function request( string $url, - $data = null, + array|string $data = null, string $method = self::GET, array $headers = [], array $options = [] - ): ClientInterface { + ): static { if ($method) { $options['method'] = strtoupper($method); } diff --git a/src/StreamClient.php b/src/StreamClient.php index a9d9a63..bc4fdd2 100644 --- a/src/StreamClient.php +++ b/src/StreamClient.php @@ -14,6 +14,7 @@ use PhpPkg\Http\Client\Exception\RequestException; use PhpPkg\Http\Client\Traits\BuildRawHttpRequestTrait; use PhpPkg\Http\Client\Traits\ParseRawResponseTrait; +use Toolkit\Stdlib\Str\UrlHelper; use function array_merge; use function fclose; use function feof; @@ -53,7 +54,7 @@ class StreamClient extends AbstractClient * 'seekable' => bool(false) * ] */ - private $responseInfo = []; + private array $responseInfo = []; /** * @return bool @@ -70,7 +71,7 @@ public static function isAvailable(): bool * * @return mixed|resource */ - protected function buildStreamContext(array $opts) + protected function buildStreamContext(array $opts): mixed { if (isset($opts['streamContext'])) { $context = $opts['streamContext']; @@ -110,7 +111,7 @@ protected function buildStreamContext(array $opts) * Send request to remote URL * * @param string $url - * @param null $data + * @param array|string|null $data * @param string $method * @param array $headers * @param array $options @@ -119,11 +120,11 @@ protected function buildStreamContext(array $opts) */ public function request( string $url, - $data = null, + array|string $data = null, string $method = self::GET, array $headers = [], array $options = [] - ): ClientInterface { + ): static { if ($method) { $options['method'] = strtoupper($method); } @@ -132,7 +133,7 @@ public function request( $options = array_merge($this->options, $options); // get request url info - $info = ClientUtil::parseUrl($this->buildFullUrl($url)); + $info = UrlHelper::parse2($this->buildFullUrl($url)); $ctx = $this->buildStreamContext($options); $timeout = (int)$options['timeout']; @@ -182,7 +183,7 @@ public function request( /** * @return $this */ - public function resetResponse(): ClientInterface + public function resetResponse(): static { $this->rawResponse = ''; $this->responseParsed = false; diff --git a/src/Swoole/CoClient.php b/src/Swoole/CoClient.php index 1ed76f8..5472080 100644 --- a/src/Swoole/CoClient.php +++ b/src/Swoole/CoClient.php @@ -14,6 +14,7 @@ use PhpPkg\Http\Client\ClientUtil; use PhpPkg\Http\Client\Exception\ClientException; use Swoole\Coroutine\Http\Client; +use Toolkit\Stdlib\Str\UrlHelper; use function array_merge; use function class_exists; use function socket_strerror; @@ -29,14 +30,14 @@ class CoClient extends AbstractClient { /** - * @var Client + * @var Client|null */ - private $client; + private ?Client $client = null; /** * @var bool */ - private $defer = false; + private bool $defer = false; /** * @return bool @@ -57,7 +58,7 @@ public static function isAvailable(): bool public function download(string $url, string $saveAs): bool { // get request url info - $info = ClientUtil::parseUrl($this->buildFullUrl($url)); + $info = UrlHelper::parse2($this->buildFullUrl($url)); $uri = $info['path']; if ($info['query']) { @@ -74,7 +75,7 @@ public function download(string $url, string $saveAs): bool * Send request to remote URL * * @param string $url - * @param mixed $data + * @param array|string|null $data * @param string $method * @param array $headers * @param array $options @@ -83,11 +84,11 @@ public function download(string $url, string $saveAs): bool */ public function request( string $url, - $data = null, + array|string $data = null, string $method = self::GET, array $headers = [], array $options = [] - ): ClientInterface { + ): static { // not in coroutine env if (\Swoole\Coroutine::getCid() < 0) { \Swoole\Coroutine\run(function () use ($url, $data, $method, $headers, $options) { @@ -103,14 +104,14 @@ public function request( /** * @param string $url - * @param null|mixed $data + * @param mixed|null $data * @param string $method * @param array $headers * @param array $options */ protected function doRequest( string $url, - $data = null, + mixed $data = null, string $method = self::GET, array $headers = [], array $options = [] @@ -121,7 +122,7 @@ protected function doRequest( } // get request url info - $info = ClientUtil::parseUrl($this->buildFullUrl($url)); + $info = UrlHelper::parse2($this->buildFullUrl($url)); // create co client $client = $this->newSwooleClient($info); @@ -277,7 +278,7 @@ public function isDefer(): bool * * @return CoClient */ - public function setDefer(bool $defer = true): ClientInterface + public function setDefer(bool $defer = true): static { $this->defer = $defer; return $this; diff --git a/src/Swoole/CoClient2.php b/src/Swoole/CoClient2.php index 4b28da0..608e594 100644 --- a/src/Swoole/CoClient2.php +++ b/src/Swoole/CoClient2.php @@ -14,6 +14,7 @@ use PhpPkg\Http\Client\ClientUtil; use Swoole\Coroutine\Http2\Client; use Swoole\Coroutine\Http2\Request; +use Toolkit\Stdlib\Str\UrlHelper; use function array_merge; use function class_exists; use function strtoupper; @@ -27,9 +28,9 @@ class CoClient2 extends AbstractClient { /** - * @var Client + * @var Client|null */ - private $client; + private ?Client $client = null; /** * @return bool @@ -43,7 +44,7 @@ public static function isAvailable(): bool * Send request to remote URL * * @param string $url - * @param array|null $data + * @param array|string|null $data * @param string $method * @param array $headers * @param array $options @@ -52,17 +53,17 @@ public static function isAvailable(): bool */ public function request( string $url, - $data = null, + array|string $data = null, string $method = self::GET, array $headers = [], array $options = [] - ): ClientInterface { + ): static { if ($method) { $options['method'] = strtoupper($method); } // get request url info - $info = ClientUtil::parseUrl($this->buildFullUrl($url)); + $info = UrlHelper::parse2($this->buildFullUrl($url)); // enable SSL verify // options: 'sslVerify' => false/true, diff --git a/src/Traits/BuildRawHttpRequestTrait.php b/src/Traits/BuildRawHttpRequestTrait.php index 4824e60..2f5d47e 100644 --- a/src/Traits/BuildRawHttpRequestTrait.php +++ b/src/Traits/BuildRawHttpRequestTrait.php @@ -33,7 +33,7 @@ trait BuildRawHttpRequestTrait * * @return string */ - protected function buildRawHttpData(array $info, array $headers, array $opts, $data): string + protected function buildRawHttpData(array $info, array $headers, array $opts, mixed $data): string { $uri = $info['path']; if ($info['query']) { diff --git a/src/Traits/ParseRawResponseTrait.php b/src/Traits/ParseRawResponseTrait.php index 1e080a8..03bbb01 100644 --- a/src/Traits/ParseRawResponseTrait.php +++ b/src/Traits/ParseRawResponseTrait.php @@ -29,12 +29,12 @@ trait ParseRawResponseTrait * * @var string */ - private $rawResponse = ''; + private string $rawResponse = ''; /** * @var bool */ - private $responseParsed = false; + private bool $responseParsed = false; /** * parse response data string. diff --git a/src/Traits/StreamContextBuildTrait.php b/src/Traits/StreamContextBuildTrait.php index dc36670..f69413a 100644 --- a/src/Traits/StreamContextBuildTrait.php +++ b/src/Traits/StreamContextBuildTrait.php @@ -12,6 +12,7 @@ use InvalidArgumentException; use PhpPkg\Http\Client\ClientUtil; use PhpPkg\Http\Client\StreamContext; +use Toolkit\Stdlib\Str\UrlHelper; use function array_merge; use function http_build_query; use function is_resource; @@ -28,7 +29,7 @@ trait StreamContextBuildTrait /** * @var string */ - protected $fullUrl = ''; + protected string $fullUrl = ''; /** * build stream context. it's create by stream_context_create() @@ -40,7 +41,7 @@ trait StreamContextBuildTrait * * @return resource */ - protected function buildStreamContext(string $fullUrl, array $headers, array $opts, $data = null) + protected function buildStreamContext(string $fullUrl, array $headers, array $opts, mixed $data = null) { if (isset($opts['streamContext'])) { $context = $opts['streamContext']; @@ -59,7 +60,7 @@ protected function buildStreamContext(string $fullUrl, array $headers, array $op $headers['Cookie'] = http_build_query($cookies, '', '; '); } - $info = ClientUtil::parseUrl($fullUrl); + $info = UrlHelper::parse2($fullUrl); $headers = array_merge($this->headers, $opts['headers'], $headers); $headers = ClientUtil::ucwordArrayKeys($headers); diff --git a/test/bootstrap.php b/test/bootstrap.php index 29af687..a36eee7 100644 --- a/test/bootstrap.php +++ b/test/bootstrap.php @@ -17,7 +17,7 @@ spl_autoload_register(static function ($class) use ($namespaces): void { foreach ($namespaces as $np => $dir) { - if (0 === strpos($class, $np)) { + if (str_starts_with($class, $np)) { $path = str_replace('\\', '/', substr($class, strlen($np))); $file = $dir . "/$path.php";