From 486b23772bc94b4905bdac774e9e52c47d3fe491 Mon Sep 17 00:00:00 2001 From: Yurun Date: Fri, 13 Oct 2023 15:51:48 +0800 Subject: [PATCH 01/12] =?UTF-8?q?=E5=8D=87=E7=BA=A7=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/phpcs.yml | 2 +- .github/workflows/phpstan.yml | 2 +- .php_cs.dist | 44 --- composer.json | 4 +- examples/http2Client.php | 18 +- examples/pool-curl.php | 3 +- examples/pool-swoole.php | 6 +- examples/psr7Ex.php | 2 +- examples/websocket.php | 3 +- src/HttpRequest.php | 94 ++--- src/YurunHttp.php | 70 ++-- src/YurunHttp/Attributes.php | 84 ++--- src/YurunHttp/Co/Batch.php | 30 +- src/YurunHttp/ConnectionPool.php | 27 +- src/YurunHttp/Cookie/CookieItem.php | 27 +- src/YurunHttp/Cookie/CookieJar.php | 6 +- src/YurunHttp/Cookie/CookieManager.php | 98 ++--- src/YurunHttp/FormDataBuilder.php | 9 +- src/YurunHttp/Handler/Curl.php | 279 +++++---------- .../Handler/Curl/CurlConnectionPool.php | 18 +- .../Curl/CurlHttpConnectionManager.php | 15 +- src/YurunHttp/Handler/Swoole.php | 334 ++++++------------ .../Swoole/SwooleHttp2ConnectionManager.php | 15 +- .../Swoole/SwooleHttp2ConnectionPool.php | 27 +- .../Swoole/SwooleHttpConnectionManager.php | 15 +- .../Swoole/SwooleHttpConnectionPool.php | 12 +- src/YurunHttp/HandlerOptions.php | 6 +- src/YurunHttp/Http/Psr7/AbstractMessage.php | 88 ++--- src/YurunHttp/Http/Psr7/Consts/MediaType.php | 56 ++- .../Http/Psr7/Consts/RequestHeader.php | 64 ++-- .../Http/Psr7/Consts/RequestMethod.php | 16 +- .../Http/Psr7/Consts/ResponseHeader.php | 74 ++-- src/YurunHttp/Http/Psr7/Consts/StatusCode.php | 122 +++---- src/YurunHttp/Http/Psr7/Request.php | 21 +- src/YurunHttp/Http/Psr7/Response.php | 12 +- src/YurunHttp/Http/Psr7/ServerRequest.php | 61 ++-- src/YurunHttp/Http/Psr7/UploadedFile.php | 38 +- src/YurunHttp/Http/Psr7/Uri.php | 62 ++-- src/YurunHttp/Http/Response.php | 21 +- src/YurunHttp/Http2/SwooleClient.php | 81 ++--- .../Pool/Traits/TConnectionPoolConfigs.php | 12 +- src/YurunHttp/Random.php | 3 +- src/YurunHttp/Stream/FileStream.php | 82 ++--- src/YurunHttp/Stream/MemoryStream.php | 40 +-- src/YurunHttp/Stream/StreamMode.php | 16 +- src/YurunHttp/Traits/TCookieManager.php | 6 +- src/YurunHttp/Traits/THandler.php | 29 +- src/YurunHttp/Traits/TLogger.php | 18 +- src/YurunHttp/WebSocket/Swoole.php | 6 +- tests/bootstrap.php | 45 +-- tests/server/Http/WorkermanHttp.php | 117 +++--- tests/server/Http/server.php | 14 +- tests/server/Http2/http2-server.php | 3 +- tests/server/WebSocket/ws-server.php | 6 +- tests/unit/BaseTest.php | 2 +- tests/unit/DefaultHandlerTest.php | 12 +- tests/unit/Http2/SwooleHttp2Test.php | 38 +- tests/unit/HttpRequestTest/CurlPoolTest.php | 8 +- .../unit/HttpRequestTest/HttpRequestTest.php | 125 +++---- tests/unit/HttpRequestTest/SwoolePoolTest.php | 8 +- tests/unit/Traits/TSwooleHandlerTest.php | 27 +- tests/unit/WebSocketTest/WebSocketTest.php | 9 +- 62 files changed, 978 insertions(+), 1614 deletions(-) delete mode 100644 .php_cs.dist diff --git a/.github/workflows/phpcs.yml b/.github/workflows/phpcs.yml index 57561cd..584d2c5 100644 --- a/.github/workflows/phpcs.yml +++ b/.github/workflows/phpcs.yml @@ -20,7 +20,7 @@ jobs: - name: Prepare run: | ./.github/prepare-test.sh swoole - docker exec swoole composer require friendsofphp/php-cs-fixer:^2.19 --dev + docker exec swoole composer require php-cs-fixer/shim:~3.35.0 --dev - name: Test run: docker exec swoole ./vendor/bin/php-cs-fixer fix --dry-run --diff diff --git a/.github/workflows/phpstan.yml b/.github/workflows/phpstan.yml index 2972c06..a15b7c5 100644 --- a/.github/workflows/phpstan.yml +++ b/.github/workflows/phpstan.yml @@ -20,7 +20,7 @@ jobs: - name: Prepare run: | ./.github/prepare-test.sh swoole - docker exec swoole composer require phpstan/phpstan:^0.12.91 --dev + docker exec swoole composer require phpstan/phpstan:~1.10.0 --dev - name: Test run: docker exec swoole ./vendor/bin/phpstan analyse --memory-limit 1G diff --git a/.php_cs.dist b/.php_cs.dist deleted file mode 100644 index efd7022..0000000 --- a/.php_cs.dist +++ /dev/null @@ -1,44 +0,0 @@ -setRules([ - '@Symfony' => true, - '@Symfony:risky' => true, - 'php_unit_dedicate_assert' => ['target' => '5.6'], - 'array_syntax' => ['syntax' => 'short'], - 'array_indentation' => true, - 'binary_operator_spaces' => [ - 'operators' => [ - '=>' => 'align_single_space', - ], - ], - 'concat_space' => [ - 'spacing' => 'one', - ], - 'fopen_flags' => false, - 'protected_to_private' => false, - 'native_constant_invocation' => true, - 'single_quote' => true, - 'braces' => [ - 'position_after_control_structures' => 'next', - ], - 'no_superfluous_phpdoc_tags' => false, - 'single_line_comment_style' => false, - 'combine_nested_dirname' => false, - 'backtick_to_shell_exec' => false, - ]) - ->setRiskyAllowed(true) - ->setFinder( - PhpCsFixer\Finder::create() - ->exclude(__DIR__ . '/vendor') - ->in(__DIR__ . '/src') - ->in(__DIR__ . '/examples') - ->in(__DIR__ . '/tests') - ->append([__FILE__]) - ) -; diff --git a/composer.json b/composer.json index 0307b73..4ce2fed 100644 --- a/composer.json +++ b/composer.json @@ -2,8 +2,8 @@ "name": "yurunsoft/yurun-http", "description": "YurunHttp 是开源的 PHP HTTP 类库,支持链式操作,简单易用。支持 Curl、Swoole,支持 Http、Http2、WebSocket!", "require": { - "php": ">=5.5.0", - "psr/http-message": "~1.0", + "php": ">=7.0", + "psr/http-message": "~1.0|~2.0", "psr/log": "~1.0|~2.0|~3.0" }, "require-dev": { diff --git a/examples/http2Client.php b/examples/http2Client.php index 5eb1d56..595bbb6 100644 --- a/examples/http2Client.php +++ b/examples/http2Client.php @@ -19,11 +19,11 @@ // 接收服务端主动推送 $client->setServerPushQueueLength(16); // 接收服务端推送的队列长度 go(function () use ($client) { - do - { + do { $response = $client->recv(); var_dump($response->body()); - } while ($response->success); + } + while ($response->success); }); // 客户端请求和响应获取 @@ -31,8 +31,7 @@ $count = 10; $channel = new Channel($count); - for ($i = 0; $i < $count; ++$i) - { + for ($i = 0; $i < $count; ++$i) { go(function () use ($i, $client, $channel, $httpRequest, $uri) { $request = $httpRequest->header('aaa', 'bbb')->buildRequest($uri, [ 'date' => $i, @@ -46,13 +45,12 @@ }); } $returnCount = 0; - do - { - if ($channel->pop()) - { + do { + if ($channel->pop()) { ++$returnCount; } - } while ($returnCount < $count); + } + while ($returnCount < $count); $client->close(); }); diff --git a/examples/pool-curl.php b/examples/pool-curl.php index a74eb47..1cac794 100644 --- a/examples/pool-curl.php +++ b/examples/pool-curl.php @@ -8,8 +8,7 @@ function dumpPoolInfo() { - foreach (CurlHttpConnectionManager::getInstance()->getConnectionPools() as $pool) - { + foreach (CurlHttpConnectionManager::getInstance()->getConnectionPools() as $pool) { var_dump($pool->getConfig()->getUrl() . ': Count=' . $pool->getCount() . ', Free=' . $pool->getFree() . ', Used=' . $pool->getUsed()); } } diff --git a/examples/pool-swoole.php b/examples/pool-swoole.php index fe75adb..33e986e 100644 --- a/examples/pool-swoole.php +++ b/examples/pool-swoole.php @@ -9,8 +9,7 @@ function dumpPoolInfo() { - foreach (SwooleHttpConnectionManager::getInstance()->getConnectionPools() as $pool) - { + foreach (SwooleHttpConnectionManager::getInstance()->getConnectionPools() as $pool) { var_dump($pool->getConfig()->getUrl() . ': Count=' . $pool->getCount() . ', Free=' . $pool->getFree() . ', Used=' . $pool->getUsed()); } } @@ -30,8 +29,7 @@ function dumpPoolInfo() }); $wg = new \Swoole\Coroutine\WaitGroup(); - for ($i = 0; $i < 10; ++$i) - { + for ($i = 0; $i < 10; ++$i) { $wg->add(); go(function () use ($wg) { $http = new HttpRequest(); diff --git a/examples/psr7Ex.php b/examples/psr7Ex.php index 4130495..5579f95 100644 --- a/examples/psr7Ex.php +++ b/examples/psr7Ex.php @@ -77,7 +77,7 @@ function test() ->withAttribute(Attributes::DOWNLOAD_SPEED, 30000) // 上传限速,单位:字节,仅Curl有效 ->withAttribute(Attributes::UPLOAD_SPEED, 30000) - ; + ; $response = YurunHttp::send($request); var_dump($response); } diff --git a/examples/websocket.php b/examples/websocket.php index 65f3d54..01564c8 100644 --- a/examples/websocket.php +++ b/examples/websocket.php @@ -12,8 +12,7 @@ $http = new HttpRequest(); $http->header('Origin', 'http://coolaf.com'); $client = $http->websocket($url); - if (!$client->isConnected()) - { + if (!$client->isConnected()) { throw new \RuntimeException('Connect failed'); } $time = time() . ''; diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 4908fea..713b329 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -63,7 +63,7 @@ class HttpRequest * * @var callable|null */ - public $retryCallback = null; + public $retryCallback; /** * 是否使用代理,默认false. @@ -175,7 +175,7 @@ class HttpRequest * * @var string */ - public $certPassword = null; + public $certPassword; /** * certType规定的私钥的加密类型,支持的密钥类型为"PEM"(默认值)、"DER"和"ENG". @@ -196,7 +196,7 @@ class HttpRequest * * @var string */ - public $keyPassword = null; + public $keyPassword; /** * 请求方法. @@ -217,7 +217,7 @@ class HttpRequest * * @var bool|null */ - public $connectionPool = null; + public $connectionPool; /** * 代理认证方式. @@ -236,12 +236,12 @@ class HttpRequest /** * 自动扩展名标志. */ - const AUTO_EXT_FLAG = '.*'; + public const AUTO_EXT_FLAG = '.*'; /** * 自动扩展名用的临时文件名. */ - const AUTO_EXT_TEMP_EXT = '.tmp'; + public const AUTO_EXT_TEMP_EXT = '.tmp'; /** * 构造方法. @@ -300,8 +300,7 @@ public function open($options = []) */ public function close() { - if ($this->handler) - { + if ($this->handler) { $handler = $this->handler; $this->handler = null; $handler->close(); @@ -390,8 +389,7 @@ public function requestBody($requestBody) public function options($options) { $thisOptions = &$this->options; - foreach ($options as $key => $value) - { + foreach ($options as $key => $value) { $thisOptions[$key] = $value; } @@ -453,8 +451,7 @@ public function header($header, $value) public function rawHeaders($headers) { $thisHeaders = &$this->headers; - foreach ($headers as $header) - { + foreach ($headers as $header) { $list = explode(':', $header, 2); $thisHeaders[trim($list[0])] = trim($list[1]); } @@ -654,7 +651,7 @@ public function ua($userAgent) */ public function retry($retry, $callback = null) { - $this->retry = $retry < 0 ? 0 : $retry; //至少请求1次,即重试0次 + $this->retry = $retry < 0 ? 0 : $retry; // 至少请求1次,即重试0次 $this->retryCallback = $callback; return $this; @@ -709,12 +706,10 @@ public function proxyAuth($username, $password) */ public function timeout($timeout = null, $connectTimeout = null) { - if (null !== $timeout) - { + if (null !== $timeout) { $this->timeout = $timeout; } - if (null !== $connectTimeout) - { + if (null !== $connectTimeout) { $this->connectTimeout = $connectTimeout; } @@ -793,12 +788,10 @@ public function getSavePath() public function sslCert($path, $type = null, $password = null) { $this->certPath = $path; - if (null !== $type) - { + if (null !== $type) { $this->certType = $type; } - if (null !== $password) - { + if (null !== $password) { $this->certPassword = $password; } @@ -817,12 +810,10 @@ public function sslCert($path, $type = null, $password = null) public function sslKey($path, $type = null, $password = null) { $this->keyPath = $path; - if (null !== $type) - { + if (null !== $type) { $this->keyType = $type; } - if (null !== $password) - { + if (null !== $password) { $this->keyPassword = $password; } @@ -868,35 +859,28 @@ public function connectionPool($connectionPool) protected function parseRequestBody($requestBody, $contentType) { $body = $files = []; - if (\is_string($requestBody)) - { + if (\is_string($requestBody)) { $body = $requestBody; } - elseif (\is_array($requestBody) || \is_object($requestBody)) - { - switch ($contentType) - { + elseif (\is_array($requestBody) || \is_object($requestBody)) { + switch ($contentType) { case 'json': $body = json_encode($requestBody); $this->header('Content-Type', MediaType::APPLICATION_JSON); break; default: - foreach ($requestBody as $k => $v) - { - if ($v instanceof UploadedFile) - { + foreach ($requestBody as $k => $v) { + if ($v instanceof UploadedFile) { $files[$k] = $v; } - else - { + else { $body[$k] = $v; } } $body = http_build_query($body, '', '&'); } } - else - { + else { throw new \InvalidArgumentException('$requestBody only can be string or array'); } @@ -915,12 +899,10 @@ protected function parseRequestBody($requestBody, $contentType) */ public function buildRequest($url = null, $requestBody = null, $method = null, $contentType = null) { - if (null === $url) - { + if (null === $url) { $url = $this->url; } - if (null === $method) - { + if (null === $method) { $method = $this->method; } list($body, $files) = $this->parseRequestBody(null === $requestBody ? $this->content : $requestBody, $contentType); @@ -951,9 +933,8 @@ public function buildRequest($url = null, $requestBody = null, $method = null, $ ->withAttribute(Attributes::RETRY, $this->retry) ->withAttribute(Attributes::RETRY_CALLBACK, $this->retryCallback) ->withProtocolVersion($this->protocolVersion) - ; - foreach ($this->proxy as $name => $value) - { + ; + foreach ($this->proxy as $name => $value) { $request = $request->withAttribute('proxy.' . $name, $value); } @@ -1006,14 +987,11 @@ public function sendHttp2WithoutRecv($url = null, $requestBody = null, $method = */ public function get($url = null, $requestBody = null) { - if (!empty($requestBody)) - { - if (strpos($url, '?')) - { + if (!empty($requestBody)) { + if (strpos($url, '?')) { $url .= '&'; } - else - { + else { $url .= '?'; } $url .= http_build_query($requestBody, '', '&'); @@ -1105,8 +1083,7 @@ public function download($fileName, $url = null, $requestBody = null, $method = { $isAutoExt = self::checkDownloadIsAutoExt($fileName, $fileName); $result = $this->saveFile($fileName)->send($url, $requestBody, $method); - if ($isAutoExt) - { + if ($isAutoExt) { self::parseDownloadAutoExt($result, $fileName); } $this->saveFileOption = []; @@ -1139,8 +1116,7 @@ public function websocket($url = null) public static function checkDownloadIsAutoExt($fileName, &$tempFileName) { $flagLength = \strlen(self::AUTO_EXT_FLAG); - if (self::AUTO_EXT_FLAG !== substr($fileName, -$flagLength)) - { + if (self::AUTO_EXT_FLAG !== substr($fileName, -$flagLength)) { return false; } $tempFileName = substr($fileName, 0, -$flagLength) . self::AUTO_EXT_TEMP_EXT; @@ -1159,8 +1135,7 @@ public static function checkDownloadIsAutoExt($fileName, &$tempFileName) public static function parseDownloadAutoExt(&$response, $tempFileName) { $ext = MediaType::getExt($response->getHeaderLine('Content-Type')); - if (null === $ext) - { + if (null === $ext) { $ext = 'file'; } $savedFileName = substr($tempFileName, 0, -\strlen(self::AUTO_EXT_TEMP_EXT)) . '.' . $ext; @@ -1169,8 +1144,7 @@ public static function parseDownloadAutoExt(&$response, $tempFileName) } } -if (\extension_loaded('curl')) -{ +if (\extension_loaded('curl')) { // 代理认证方式 HttpRequest::$proxyAuths = [ 'basic' => \CURLAUTH_BASIC, diff --git a/src/YurunHttp.php b/src/YurunHttp.php index cda4a0c..7144831 100644 --- a/src/YurunHttp.php +++ b/src/YurunHttp.php @@ -12,7 +12,7 @@ abstract class YurunHttp * * @var string|null */ - private static $defaultHandler = null; + private static $defaultHandler; /** * 属性. @@ -24,7 +24,7 @@ abstract class YurunHttp /** * 版本号. */ - const VERSION = '4.3'; + public const VERSION = '4.3'; /** * 设置默认处理器类. @@ -35,7 +35,7 @@ abstract class YurunHttp */ public static function setDefaultHandler($class) { - static::$defaultHandler = $class; + self::$defaultHandler = $class; } /** @@ -45,7 +45,7 @@ public static function setDefaultHandler($class) */ public static function getDefaultHandler() { - return static::$defaultHandler; + return self::$defaultHandler; } /** @@ -57,21 +57,17 @@ public static function getDefaultHandler() */ public static function getHandler($options = []) { - if (static::$defaultHandler) - { - $class = static::$defaultHandler; + if (self::$defaultHandler) { + $class = self::$defaultHandler; // @phpstan-ignore-next-line - if (!is_subclass_of($class, IHandler::class)) - { + if (!is_subclass_of($class, IHandler::class)) { throw new \RuntimeException(sprintf('Class %s does not implement %s', $class, IHandler::class)); } } - elseif (\defined('SWOOLE_VERSION') && Coroutine::getuid() > -1) - { + elseif (\defined('SWOOLE_VERSION') && Coroutine::getuid() > -1) { $class = \Yurun\Util\YurunHttp\Handler\Swoole::class; } - else - { + else { $class = \Yurun\Util\YurunHttp\Handler\Curl::class; } @@ -89,35 +85,28 @@ public static function getHandler($options = []) */ public static function send($request, $handlerClass = null, $options = []) { - if ($handlerClass instanceof IHandler) - { + if ($handlerClass instanceof IHandler) { $handler = $handlerClass; $needClose = false; } - else - { + else { $needClose = true; - if (null === $handlerClass) - { + if (null === $handlerClass) { $handler = static::getHandler($options); } - else - { + else { /** @var IHandler $handler */ $handler = new $handlerClass(); } } - foreach (static::$attributes as $name => $value) - { - if (null === $request->getAttribute($name)) - { + foreach (self::$attributes as $name => $value) { + if (null === $request->getAttribute($name)) { $request = $request->withAttribute($name, $value); } } $handler->send($request); $response = $handler->recv(); - if ($needClose) - { + if ($needClose) { $handler->close(); } @@ -135,22 +124,17 @@ public static function send($request, $handlerClass = null, $options = []) */ public static function websocket($request, $handlerClass = null, $options = []) { - if ($handlerClass instanceof IHandler) - { + if ($handlerClass instanceof IHandler) { $handler = $handlerClass; } - elseif (null === $handlerClass) - { + elseif (null === $handlerClass) { $handler = static::getHandler($options); } - else - { + else { $handler = new $handlerClass(); } - foreach (static::$attributes as $name => $value) - { - if (null === $request->getAttribute($name)) - { + foreach (self::$attributes as $name => $value) { + if (null === $request->getAttribute($name)) { $request = $request->withAttribute($name, $value); } } @@ -165,7 +149,7 @@ public static function websocket($request, $handlerClass = null, $options = []) */ public static function getAttributes() { - return static::$attributes; + return self::$attributes; } /** @@ -178,12 +162,10 @@ public static function getAttributes() */ public static function getAttribute($name, $default = null) { - if (\array_key_exists($name, static::$attributes)) - { - return static::$attributes[$name]; + if (\array_key_exists($name, self::$attributes)) { + return self::$attributes[$name]; } - else - { + else { return $default; } } @@ -198,6 +180,6 @@ public static function getAttribute($name, $default = null) */ public static function setAttribute($name, $value) { - static::$attributes[$name] = $value; + self::$attributes[$name] = $value; } } diff --git a/src/YurunHttp/Attributes.php b/src/YurunHttp/Attributes.php index cac9a3d..9ed4c65 100644 --- a/src/YurunHttp/Attributes.php +++ b/src/YurunHttp/Attributes.php @@ -12,210 +12,210 @@ abstract class Attributes /** * 客户端参数. */ - const OPTIONS = 'options'; + public const OPTIONS = 'options'; /** * 全局默认 UserAgent. */ - const USER_AGENT = 'userAgent'; + public const USER_AGENT = 'userAgent'; /** * 重试次数. */ - const RETRY = 'retry'; + public const RETRY = 'retry'; /** * 重试回调. */ - const RETRY_CALLBACK = 'retry_callback'; + public const RETRY_CALLBACK = 'retry_callback'; /** * 下载文件保存路径. */ - const SAVE_FILE_PATH = 'saveFilePath'; + public const SAVE_FILE_PATH = 'saveFilePath'; /** * 保存文件的模型. */ - const SAVE_FILE_MODE = 'saveFileMode'; + public const SAVE_FILE_MODE = 'saveFileMode'; /** * 允许重定向. */ - const FOLLOW_LOCATION = 'followLocation'; + public const FOLLOW_LOCATION = 'followLocation'; /** * 最大允许重定向次数. */ - const MAX_REDIRECTS = 'maxRedirects'; + public const MAX_REDIRECTS = 'maxRedirects'; /** * 是否验证 CA 证书. */ - const IS_VERIFY_CA = 'isVerifyCA'; + public const IS_VERIFY_CA = 'isVerifyCA'; /** * CA 证书. */ - const CA_CERT = 'caCert'; + public const CA_CERT = 'caCert'; /** * SSL 证书类型. */ - const CERT_TYPE = 'certType'; + public const CERT_TYPE = 'certType'; /** * SSL 证书路径. */ - const CERT_PATH = 'certPath'; + public const CERT_PATH = 'certPath'; /** * SSL 证书密码 */ - const CERT_PASSWORD = 'certPassword'; + public const CERT_PASSWORD = 'certPassword'; /** * SSL 密钥类型. */ - const KEY_TYPE = 'keyType'; + public const KEY_TYPE = 'keyType'; /** * SSL 密钥路径. */ - const KEY_PATH = 'keyPath'; + public const KEY_PATH = 'keyPath'; /** * SSL 密钥密码 */ - const KEY_PASSWORD = 'keyPassword'; + public const KEY_PASSWORD = 'keyPassword'; /** * 使用代理. */ - const USE_PROXY = 'useProxy'; + public const USE_PROXY = 'useProxy'; /** * 代理类型. */ - const PROXY_TYPE = 'proxy.type'; + public const PROXY_TYPE = 'proxy.type'; /** * 代理服务器地址 */ - const PROXY_SERVER = 'proxy.server'; + public const PROXY_SERVER = 'proxy.server'; /** * 代理服务器端口. */ - const PROXY_PORT = 'proxy.port'; + public const PROXY_PORT = 'proxy.port'; /** * 代理用户名. */ - const PROXY_USERNAME = 'proxy.username'; + public const PROXY_USERNAME = 'proxy.username'; /** * 代理密码 */ - const PROXY_PASSWORD = 'proxy.password'; + public const PROXY_PASSWORD = 'proxy.password'; /** * 代理的 Basic 认证配置. */ - const PROXY_AUTH = 'proxy.auth'; + public const PROXY_AUTH = 'proxy.auth'; /** * 认证用户名. */ - const USERNAME = 'username'; + public const USERNAME = 'username'; /** * 认证密码 */ - const PASSWORD = 'password'; + public const PASSWORD = 'password'; /** * 超时时间. */ - const TIMEOUT = 'timeout'; + public const TIMEOUT = 'timeout'; /** * 连接超时. */ - const CONNECT_TIMEOUT = 'connectTimeout'; + public const CONNECT_TIMEOUT = 'connectTimeout'; /** * 保持长连接. */ - const KEEP_ALIVE = 'keep_alive'; + public const KEEP_ALIVE = 'keep_alive'; /** * 下载限速 */ - const DOWNLOAD_SPEED = 'downloadSpeed'; + public const DOWNLOAD_SPEED = 'downloadSpeed'; /** * 上传限速 */ - const UPLOAD_SPEED = 'uploadSpeed'; + public const UPLOAD_SPEED = 'uploadSpeed'; /** * 使用自定义重定向操作. */ - const CUSTOM_LOCATION = 'customLocation'; + public const CUSTOM_LOCATION = 'customLocation'; /** * http2 请求不调用 recv(). */ - const HTTP2_NOT_RECV = 'http2_not_recv'; + public const HTTP2_NOT_RECV = 'http2_not_recv'; /** * 启用 Http2 pipeline. */ - const HTTP2_PIPELINE = 'http2_pipeline'; + public const HTTP2_PIPELINE = 'http2_pipeline'; /** * 启用连接池. */ - const CONNECTION_POOL = 'connection_pool'; + public const CONNECTION_POOL = 'connection_pool'; /** * 重试计数. */ - const PRIVATE_RETRY_COUNT = '__retryCount'; + public const PRIVATE_RETRY_COUNT = '__retryCount'; /** * 重定向计数. */ - const PRIVATE_REDIRECT_COUNT = '__redirectCount'; + public const PRIVATE_REDIRECT_COUNT = '__redirectCount'; /** * WebSocket 请求 */ - const PRIVATE_WEBSOCKET = '__websocket'; + public const PRIVATE_WEBSOCKET = '__websocket'; /** * Http2 流ID. */ - const PRIVATE_HTTP2_STREAM_ID = '__http2StreamId'; + public const PRIVATE_HTTP2_STREAM_ID = '__http2StreamId'; /** * 是否为 Http2. */ - const PRIVATE_IS_HTTP2 = '__isHttp2'; + public const PRIVATE_IS_HTTP2 = '__isHttp2'; /** * 是否为 WebSocket. */ - const PRIVATE_IS_WEBSOCKET = '__isWebSocket'; + public const PRIVATE_IS_WEBSOCKET = '__isWebSocket'; /** * 连接对象 */ - const PRIVATE_CONNECTION = '__connection'; + public const PRIVATE_CONNECTION = '__connection'; /** * 连接池的键. */ - const PRIVATE_POOL_KEY = '__poolKey'; + public const PRIVATE_POOL_KEY = '__poolKey'; } diff --git a/src/YurunHttp/Co/Batch.php b/src/YurunHttp/Co/Batch.php index 185205d..b7a4ef5 100644 --- a/src/YurunHttp/Co/Batch.php +++ b/src/YurunHttp/Co/Batch.php @@ -22,45 +22,35 @@ public static function run($requests, $timeout = null, $handlerClass = null, $op { $batchRequests = []; $downloadAutoExt = []; - foreach ($requests as $i => $request) - { - if ($request instanceof HttpRequest) - { + foreach ($requests as $i => $request) { + if ($request instanceof HttpRequest) { $savePath = $request->getSavePath(); - if (null !== $savePath && HttpRequest::checkDownloadIsAutoExt($savePath, $savePath)) - { + if (null !== $savePath && HttpRequest::checkDownloadIsAutoExt($savePath, $savePath)) { $request->saveFileOption['filePath'] = $savePath; $downloadAutoExt[] = $i; } $batchRequests[$i] = $request->buildRequest(); } - elseif (!$request instanceof \Yurun\Util\YurunHttp\Http\Request) - { + elseif (!$request instanceof \Yurun\Util\YurunHttp\Http\Request) { throw new \InvalidArgumentException('Request must be instance of \Yurun\Util\YurunHttp\Http\Request or \Yurun\Util\HttpRequest'); } } - if (null === $handlerClass) - { + if (null === $handlerClass) { $handler = YurunHttp::getHandler($options); } - else - { + else { $handler = new $handlerClass(); } /** @var \Yurun\Util\YurunHttp\Handler\IHandler $handler */ $result = $handler->coBatch($batchRequests, $timeout); - foreach ($downloadAutoExt as $i) - { - if (isset($result[$i])) - { + foreach ($downloadAutoExt as $i) { + if (isset($result[$i])) { $response = &$result[$i]; } - else - { + else { $response = null; } - if ($response) - { + if ($response) { HttpRequest::parseDownloadAutoExt($response, $response->getRequest()->getAttribute(Attributes::SAVE_FILE_PATH)); } unset($response); diff --git a/src/YurunHttp/ConnectionPool.php b/src/YurunHttp/ConnectionPool.php index c1bd526..50316e9 100644 --- a/src/YurunHttp/ConnectionPool.php +++ b/src/YurunHttp/ConnectionPool.php @@ -80,28 +80,23 @@ public static function disable() */ public static function setConfig($url, $maxConnections = 0, $waitTimeout = 30) { - if (isset(self::$connectionPoolConfigs[$url])) - { + if (isset(self::$connectionPoolConfigs[$url])) { $config = self::$connectionPoolConfigs[$url]; $config->setMaxConnections($maxConnections); $config->setWaitTimeout($waitTimeout); } - else - { + else { self::$connectionPoolConfigs[$url] = $config = new PoolConfig($url, $maxConnections, $waitTimeout); } - foreach (self::$connectionManagers as $class) - { + foreach (self::$connectionManagers as $class) { /** @var IConnectionManager $connectionManager */ $connectionManager = $class::getInstance(); $connectionManagerConfig = $connectionManager->getConfig($url); - if ($connectionManagerConfig) - { + if ($connectionManagerConfig) { $connectionManagerConfig->setMaxConnections($maxConnections); $connectionManagerConfig->setWaitTimeout($waitTimeout); } - else - { + else { $connectionManager->setConfig($url, $maxConnections, $waitTimeout); } } @@ -116,12 +111,10 @@ public static function setConfig($url, $maxConnections = 0, $waitTimeout = 30) */ public static function getConfig($url) { - if (isset(self::$connectionPoolConfigs[$url])) - { + if (isset(self::$connectionPoolConfigs[$url])) { return self::$connectionPoolConfigs[$url]; } - else - { + else { return null; } } @@ -135,12 +128,10 @@ public static function getConfig($url) */ public static function getKey($url) { - if ($url instanceof UriInterface) - { + if ($url instanceof UriInterface) { return $url->getScheme() . '://' . Uri::getDomain($url); } - else - { + else { return $url; } } diff --git a/src/YurunHttp/Cookie/CookieItem.php b/src/YurunHttp/Cookie/CookieItem.php index 7f469d4..3675148 100644 --- a/src/YurunHttp/Cookie/CookieItem.php +++ b/src/YurunHttp/Cookie/CookieItem.php @@ -86,8 +86,7 @@ public function __construct($name, $value, $expires = 0, $path = '/', $domain = public static function newInstance($data) { $object = new static('', ''); - foreach ($data as $k => $v) - { + foreach ($data as $k => $v) { $object->$k = $v; } @@ -103,32 +102,25 @@ public static function newInstance($data) */ public static function fromSetCookie($setCookieContent) { - if (preg_match_all('/;?\s*((?P[^=;]+)=(?P[^;]+)|((?P[^=;]+)))/', $setCookieContent, $matches) > 0) - { + if (preg_match_all('/;?\s*((?P[^=;]+)=(?P[^;]+)|((?P[^=;]+)))/', $setCookieContent, $matches) > 0) { $name = $matches['name'][0]; $value = $matches['value'][0]; unset($matches['name'][0], $matches['value'][0]); $data = array_combine(array_map('strtolower', $matches['name']), $matches['value']); - if (isset($data[''])) - { + if (isset($data[''])) { unset($data['']); } - if (isset($data['max-age'])) - { + if (isset($data['max-age'])) { $expires = time() + $data['max-age']; } - elseif (isset($data['expires'])) - { + elseif (isset($data['expires'])) { $expires = strtotime($data['expires']); } - else - { + else { $expires = null; } - foreach ($matches['name2'] as $boolItemName) - { - if ('' !== $boolItemName) - { + foreach ($matches['name2'] as $boolItemName) { + if ('' !== $boolItemName) { $data[strtolower($boolItemName)] = true; } } @@ -136,8 +128,7 @@ public static function fromSetCookie($setCookieContent) return $object; } - else - { + else { return null; } } diff --git a/src/YurunHttp/Cookie/CookieJar.php b/src/YurunHttp/Cookie/CookieJar.php index 110f4fd..11c20e4 100644 --- a/src/YurunHttp/Cookie/CookieJar.php +++ b/src/YurunHttp/Cookie/CookieJar.php @@ -24,8 +24,7 @@ public function __construct($cookieManager) */ public function load($fileName) { - if (is_file($fileName)) - { + if (is_file($fileName)) { $data = json_decode(file_get_contents($fileName), true); $this->cookieManager->setCookieList($data); } @@ -39,8 +38,7 @@ public function load($fileName) public function save($fileName) { $data = []; - foreach ($this->cookieManager->getCookieList() as $cookieItem) - { + foreach ($this->cookieManager->getCookieList() as $cookieItem) { $data[] = (array) $cookieItem; } file_put_contents($fileName, json_encode($data, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE)); diff --git a/src/YurunHttp/Cookie/CookieManager.php b/src/YurunHttp/Cookie/CookieManager.php index 003ff26..9f2691a 100644 --- a/src/YurunHttp/Cookie/CookieManager.php +++ b/src/YurunHttp/Cookie/CookieManager.php @@ -50,8 +50,7 @@ public function setCookieList($cookieList) $this->autoIncrementId = 1; $this->cookieList = []; $this->relationMap = []; - foreach ($cookieList as $item) - { + foreach ($cookieList as $item) { $item = CookieItem::newInstance($item); $this->insertCookie($item); } @@ -77,12 +76,10 @@ public function getCookieList() public function addSetCookie($setCookie) { $item = CookieItem::fromSetCookie($setCookie); - if (($id = $this->findCookie($item)) > 0) - { + if (($id = $this->findCookie($item)) > 0) { $this->updateCookie($id, $item); } - else - { + else { $this->insertCookie($item); } @@ -105,12 +102,10 @@ public function addSetCookie($setCookie) public function setCookie($name, $value, $expires = 0, $path = '/', $domain = '', $secure = false, $httpOnly = false) { $item = new CookieItem($name, $value, $expires, $path, $domain, $secure, $httpOnly); - if (($id = $this->findCookie($item)) > 0) - { + if (($id = $this->findCookie($item)) > 0) { $this->updateCookie($id, $item); } - else - { + else { $this->insertCookie($item); } @@ -137,32 +132,24 @@ public function count() public function getRequestCookies($uri) { // @phpstan-ignore-next-line - if (\defined('SWOOLE_VERSION') && \SWOOLE_VERSION < 4.4) - { + if (\defined('SWOOLE_VERSION') && \SWOOLE_VERSION < 4.4) { // Fix bug: https://github.com/swoole/swoole-src/pull/2644 $result = json_decode('[]', true); } - else - { + else { $result = []; } $uriDomain = Uri::getDomain($uri); $uriPath = $uri->getPath(); $cookieList = &$this->cookieList; $time = time(); - foreach ($this->relationMap as $relationDomain => $list1) - { - if ('' === $relationDomain || $this->checkDomain($uriDomain, $relationDomain)) - { - foreach ($list1 as $path => $idList) - { - if ($this->checkPath($uriPath, $path)) - { - foreach ($idList as $id) - { + foreach ($this->relationMap as $relationDomain => $list1) { + if ('' === $relationDomain || $this->checkDomain($uriDomain, $relationDomain)) { + foreach ($list1 as $path => $idList) { + if ($this->checkPath($uriPath, $path)) { + foreach ($idList as $id) { $cookieItem = $cookieList[$id]; - if ((0 === $cookieItem->expires || $cookieItem->expires > $time) && (!$cookieItem->secure || 'https' === $uri->getScheme() || 'wss' === $uri->getScheme())) - { + if ((0 === $cookieItem->expires || $cookieItem->expires > $time) && (!$cookieItem->secure || 'https' === $uri->getScheme() || 'wss' === $uri->getScheme())) { $result[$cookieItem->name] = $cookieItem->value; } } @@ -184,8 +171,7 @@ public function getRequestCookies($uri) public function getRequestCookieString($uri) { $content = ''; - foreach ($this->getRequestCookies($uri) as $name => $value) - { + foreach ($this->getRequestCookies($uri) as $name => $value) { $content .= "{$name}={$value}; "; } @@ -203,8 +189,7 @@ public function getRequestCookieString($uri) */ public function getCookieItem($name, $domain = '', $path = '/') { - if (isset($this->relationMap[$domain][$path][$name])) - { + if (isset($this->relationMap[$domain][$path][$name])) { $id = $this->relationMap[$domain][$path][$name]; return $this->cookieList[$id]; @@ -220,16 +205,12 @@ public function getCookieItem($name, $domain = '', $path = '/') */ public function gc() { - if ($this->cookieList) - { + if ($this->cookieList) { $time = time(); - foreach ($this->cookieList as $id => $item) - { - if ($item->expires > 0 && $time >= $item->expires) - { + foreach ($this->cookieList as $id => $item) { + if ($item->expires > 0 && $time >= $item->expires) { unset($this->cookieList[$id]); - if (isset($this->relationMap[$item->domain][$item->path][$item->name]) && $id === $this->relationMap[$item->domain][$item->path][$item->name]) - { + if (isset($this->relationMap[$item->domain][$item->path][$item->name]) && $id === $this->relationMap[$item->domain][$item->path][$item->name]) { unset($this->relationMap[$item->domain][$item->path][$item->name]); } } @@ -249,7 +230,7 @@ private function checkDomain($uriDomain, $cookieDomain) { return ($uriDomain === $cookieDomain) || (isset($cookieDomain[0]) && '.' === $cookieDomain[0] && substr($uriDomain, -\strlen($cookieDomain) - 1) === '.' . $cookieDomain) - ; + ; } /** @@ -264,44 +245,35 @@ private function checkPath($uriPath, $cookiePath) { $uriPath = rtrim($uriPath, '/'); $cookiePath = rtrim($cookiePath, '/'); - if ($uriPath === $cookiePath) - { + if ($uriPath === $cookiePath) { return true; } $uriPathDSCount = substr_count($uriPath, '/'); $cookiePathDSCount = substr_count($cookiePath, '/'); - if ('' === $uriPath) - { + if ('' === $uriPath) { $uriPath = '/'; } - if ('' === $cookiePath) - { + if ('' === $cookiePath) { $cookiePath = '/'; } - if ($uriPathDSCount > $cookiePathDSCount) - { - if (version_compare(\PHP_VERSION, '7.0', '>=')) - { + if ($uriPathDSCount > $cookiePathDSCount) { + if (version_compare(\PHP_VERSION, '7.0', '>=')) { $path = \dirname($uriPath, $uriPathDSCount - $cookiePathDSCount); } - else - { + else { $count = $uriPathDSCount - $cookiePathDSCount; $path = $uriPath; - while ($count--) - { + while ($count--) { $path = \dirname($path); } } - if ('\\' === \DIRECTORY_SEPARATOR && false !== strpos($path, \DIRECTORY_SEPARATOR)) - { + if ('\\' === \DIRECTORY_SEPARATOR && str_contains($path, \DIRECTORY_SEPARATOR)) { $path = str_replace(\DIRECTORY_SEPARATOR, '/', $path); } return $path === $cookiePath; } - else - { + else { return false; } } @@ -316,12 +288,10 @@ private function checkPath($uriPath, $cookiePath) */ private function updateCookie($id, $item) { - if (isset($this->cookieList[$id])) - { + if (isset($this->cookieList[$id])) { $object = $this->cookieList[$id]; // @phpstan-ignore-next-line - foreach ($item as $k => $v) - { + foreach ($item as $k => $v) { $object->$k = $v; } } @@ -352,12 +322,10 @@ private function insertCookie($item) */ private function findCookie($item) { - if (isset($this->relationMap[$item->domain][$item->path][$item->name])) - { + if (isset($this->relationMap[$item->domain][$item->path][$item->name])) { return $this->relationMap[$item->domain][$item->path][$item->name]; } - else - { + else { return null; } } diff --git a/src/YurunHttp/FormDataBuilder.php b/src/YurunHttp/FormDataBuilder.php index 0321376..47accb8 100644 --- a/src/YurunHttp/FormDataBuilder.php +++ b/src/YurunHttp/FormDataBuilder.php @@ -16,17 +16,14 @@ abstract class FormDataBuilder public static function build($body, $files, &$boundary) { $result = ''; - if (!\is_array($body)) - { + if (!\is_array($body)) { parse_str($body, $body); } $boundary = Random::letter(8, 16); - foreach ($body as $k => $v) - { + foreach ($body as $k => $v) { $result .= sprintf("--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", $boundary, $k, $v); } - foreach ($files as $name => $file) - { + foreach ($files as $name => $file) { $result .= sprintf("--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n", $boundary, $name, basename($file->getClientFilename()), $file->getClientMediaType()) . $file->getStream()->getContents() . "\r\n"; } $result .= sprintf("--%s--\r\n", $boundary); diff --git a/src/YurunHttp/Handler/Curl.php b/src/YurunHttp/Handler/Curl.php index 1233fab..06871e4 100644 --- a/src/YurunHttp/Handler/Curl.php +++ b/src/YurunHttp/Handler/Curl.php @@ -98,10 +98,9 @@ class Curl implements IHandler public function __construct($options = []) { $this->options = $options; - if (null === static::$defaultUA) - { + if (null === self::$defaultUA) { $version = curl_version(); - static::$defaultUA = sprintf('Mozilla/5.0 YurunHttp/%s Curl/%s', YurunHttp::VERSION, isset($version['version']) ? $version['version'] : 'unknown'); + self::$defaultUA = sprintf('Mozilla/5.0 YurunHttp/%s Curl/%s', YurunHttp::VERSION, isset($version['version']) ? $version['version'] : 'unknown'); } $this->initCookieManager(); } @@ -113,14 +112,11 @@ public function __construct($options = []) */ public function close() { - if ($this->handler) - { - if ($this->poolIsEnabled) - { + if ($this->handler) { + if ($this->poolIsEnabled) { CurlHttpConnectionManager::getInstance()->release($this->poolKey, $this->handler); } - else - { + else { curl_close($this->handler); } $this->handler = null; @@ -137,43 +133,35 @@ public function close() public function send(&$request) { $this->poolIsEnabled = $poolIsEnabled = ConnectionPool::isEnabled() && false !== $request->getAttribute(Attributes::CONNECTION_POOL); - if ($poolIsEnabled) - { + if ($poolIsEnabled) { $httpConnectionManager = CurlHttpConnectionManager::getInstance(); } - try - { + try { $this->request = $request; $request = &$this->request; $handler = &$this->handler; - if ($handler) - { + if ($handler) { curl_reset($handler); } - else - { - if ($poolIsEnabled) - { + else { + if ($poolIsEnabled) { $this->poolKey = $poolKey = ConnectionPool::getKey($request->getUri()); $handler = $httpConnectionManager->getConnection($poolKey); curl_reset($handler); } - else - { + else { $handler = curl_init(); } } $files = $request->getUploadedFiles(); $body = (string) $request->getBody(); - if (!empty($files)) - { + if (!empty($files)) { $body = FormDataBuilder::build($body, $files, $boundary); $request = $request->withHeader('Content-Type', MediaType::MULTIPART_FORM_DATA . '; boundary=' . $boundary); } $this->buildCurlHandlerBase($request, $handler, $receiveHeaders, $saveFileFp); - if ([] !== ($queryParams = $request->getQueryParams())) - { + if ([] !== ($queryParams = $request->getQueryParams())) { $request = $request->withUri($request->getUri()->withQuery(http_build_query($queryParams, '', '&'))); } $uri = $request->getUri(); @@ -183,58 +171,45 @@ public function send(&$request) $retry = $request->getAttribute(Attributes::RETRY, 0); $retryCallback = $request->getAttribute(Attributes::RETRY_CALLBACK); $beginTime = microtime(true); - do - { + while (true) { // 请求方法 - if ($isLocation && \in_array($statusCode, [301, 302, 303])) - { + if ($isLocation && \in_array($statusCode, [301, 302, 303])) { $method = 'GET'; } - else - { + else { $method = $request->getMethod(); } - if ('GET' !== $method) - { + if ('GET' !== $method) { $bodyContent = $body; } - else - { + else { $bodyContent = false; } $this->buildCurlHandlerEx($request, $handler, $uri, $method, $bodyContent); $result = null; - for ($i = 0; $i <= $retry; ++$i) - { + for ($i = 0; $i <= $retry; ++$i) { $receiveHeaders = []; $curlResult = curl_exec($handler); $this->result = $this->getResponse($request, $handler, $curlResult, $receiveHeaders); $result = &$this->result; - if ($retryCallback) - { - if ($retryCallback($request, $result, $i)) - { + if ($retryCallback) { + if ($retryCallback($request, $result, $i)) { break; } } - else - { + else { $statusCode = $result->getStatusCode(); // 状态码为5XX或者0才需要重试 - if (!(0 === $statusCode || (5 === (int) ($statusCode / 100)))) - { + if (!(0 === $statusCode || (5 === (int) ($statusCode / 100)))) { break; } } } - if ($request->getAttribute(Attributes::FOLLOW_LOCATION, true) && ($statusCode >= 300 && $statusCode < 400) && $result && '' !== ($location = $result->getHeaderLine('location'))) - { + if ($request->getAttribute(Attributes::FOLLOW_LOCATION, true) && ($statusCode >= 300 && $statusCode < 400) && $result && '' !== ($location = $result->getHeaderLine('location'))) { $maxRedirects = $request->getAttribute(Attributes::MAX_REDIRECTS, 10); - if (++$redirectCount <= $maxRedirects) - { + if (++$redirectCount <= $maxRedirects) { // 重定向清除之前下载的文件 - if (null !== $saveFileFp) - { + if (null !== $saveFileFp) { ftruncate($saveFileFp, 0); fseek($saveFileFp, 0); } @@ -242,8 +217,7 @@ public function send(&$request) $uri = $this->parseRedirectLocation($location, $uri); continue; } - else - { + else { $result = $result->withErrno(-1) ->withError(sprintf('Maximum (%s) redirects followed', $maxRedirects)); } @@ -253,20 +227,17 @@ public function send(&$request) $this->cookieManager->gc(); $this->saveCookieJar(); break; - } while (true); + } + // 关闭保存至文件的句柄 - if (null !== $saveFileFp) - { + if (null !== $saveFileFp) { fclose($saveFileFp); $saveFileFp = null; } } - finally - { - if ($this->handler) - { - if ($poolIsEnabled) - { + finally { + if ($this->handler) { + if ($poolIsEnabled) { // @phpstan-ignore-next-line $httpConnectionManager->release($this->poolKey, $this->handler); $this->handler = null; @@ -289,34 +260,28 @@ private function buildCurlHandlerBase(&$request, $handler, &$headers = null, &$s { $options = $request->getAttribute(Attributes::OPTIONS, []); // 返回内容 - if (!isset($options[\CURLOPT_RETURNTRANSFER])) - { + if (!isset($options[\CURLOPT_RETURNTRANSFER])) { $options[\CURLOPT_RETURNTRANSFER] = true; } // 保存cookie - if (!isset($options[\CURLOPT_COOKIEJAR])) - { + if (!isset($options[\CURLOPT_COOKIEJAR])) { $options[\CURLOPT_COOKIEJAR] = 'php://memory'; } // 允许复用连接 - if (!isset($options[\CURLOPT_FORBID_REUSE])) - { + if (!isset($options[\CURLOPT_FORBID_REUSE])) { $options[\CURLOPT_FORBID_REUSE] = false; } // 自动重定向 - if (!isset($options[\CURLOPT_MAXREDIRS])) - { + if (!isset($options[\CURLOPT_MAXREDIRS])) { $options[\CURLOPT_MAXREDIRS] = $request->getAttribute(Attributes::MAX_REDIRECTS, 10); } // 自动解压缩支持 $acceptEncoding = $request->getHeaderLine('Accept-Encoding'); - if ('' !== $acceptEncoding) - { + if ('' !== $acceptEncoding) { $options[\CURLOPT_ENCODING] = $acceptEncoding; } - else - { + else { $options[\CURLOPT_ENCODING] = ''; } $this->parseOptions($request, $options, $headers, $saveFileFp); @@ -341,31 +306,25 @@ private function buildCurlHandlerBase(&$request, $handler, &$headers = null, &$s */ private function buildCurlHandlerEx(&$request, $handler, $uri = null, $method = null, $body = null) { - if (null === $uri) - { + if (null === $uri) { $uri = $request->getUri(); } - if (null === $method) - { + if (null === $method) { $method = $request->getMethod(); } - if (null === $body) - { + if (null === $body) { $body = (string) $request->getBody(); } - switch ($request->getProtocolVersion()) - { + switch ($request->getProtocolVersion()) { case '1.0': $httpVersion = \CURL_HTTP_VERSION_1_0; break; case '2.0': $ssl = 'https' === $uri->getScheme(); - if ($ssl) - { + if ($ssl) { $httpVersion = \CURL_HTTP_VERSION_2TLS; } - else - { + else { $httpVersion = \CURL_HTTP_VERSION_2; } break; @@ -377,13 +336,11 @@ private function buildCurlHandlerEx(&$request, $handler, $uri = null, $method = \CURLOPT_HTTP_VERSION => $httpVersion, ]; // 请求方法 - if ($body && 'GET' !== $method) - { + if ($body && 'GET' !== $method) { $requestOptions[\CURLOPT_POSTFIELDS] = $body; } $requestOptions[\CURLOPT_CUSTOMREQUEST] = $method; - if ('HEAD' === $method) - { + if ('HEAD' === $method) { $requestOptions[\CURLOPT_NOBODY] = true; } curl_setopt_array($handler, $requestOptions); @@ -412,8 +369,7 @@ public function recv() private function getResponse($request, $handler, $body, $receiveHeaders) { // PHP 7.0.0开始substr()的 string 字符串长度与 start 相同时将返回一个空字符串。在之前的版本中,这种情况将返回 FALSE 。 - if (false === $body) - { + if (false === $body) { $body = ''; } @@ -422,23 +378,20 @@ private function getResponse($request, $handler, $body, $receiveHeaders) // headers $headers = $this->parseHeaderOneRequest($receiveHeaders); - foreach ($headers as $name => $value) - { + foreach ($headers as $name => $value) { $result = $result->withAddedHeader($name, $value); } // cookies $cookies = []; $cookieManager = $this->cookieManager; - foreach ($result->getHeader('set-cookie') as $content) - { + foreach ($result->getHeader('set-cookie') as $content) { $cookieItem = $cookieManager->addSetCookie($content); $cookies[$cookieItem->name] = (array) $cookieItem; } // 下载文件名 - if ($savedFileName = $request->getAttribute(Attributes::SAVE_FILE_PATH)) - { + if ($savedFileName = $request->getAttribute(Attributes::SAVE_FILE_PATH)) { $result = $result->withSavedFileName($savedFileName); } @@ -459,25 +412,20 @@ private function parseHeaderOneRequest($headers) { $tmpHeaders = []; $count = \count($headers); - //从1开始,第0行包含了协议信息和状态信息,排除该行 - for ($i = 1; $i < $count; ++$i) - { + // 从1开始,第0行包含了协议信息和状态信息,排除该行 + for ($i = 1; $i < $count; ++$i) { $line = trim($headers[$i]); - if (empty($line) || false == strstr($line, ':')) - { + if (empty($line) || false == strstr($line, ':')) { continue; } list($key, $value) = explode(':', $line, 2); $key = trim($key); $value = trim($value); - if (isset($tmpHeaders[$key])) - { - if (\is_array($tmpHeaders[$key])) - { + if (isset($tmpHeaders[$key])) { + if (\is_array($tmpHeaders[$key])) { $tmpHeaders[$key][] = $value; } - else - { + else { $tmp = $tmpHeaders[$key]; $tmpHeaders[$key] = [ $tmp, @@ -485,8 +433,7 @@ private function parseHeaderOneRequest($headers) ]; } } - else - { + else { $tmpHeaders[$key] = $value; } } @@ -504,27 +451,23 @@ private function parseHeaderOneRequest($headers) */ private function parseSSL(&$request, &$options) { - if ($request->getAttribute(Attributes::IS_VERIFY_CA, false)) - { + if ($request->getAttribute(Attributes::IS_VERIFY_CA, false)) { $options[\CURLOPT_SSL_VERIFYPEER] = true; $options[\CURLOPT_CAINFO] = $request->getAttribute(Attributes::CA_CERT); $options[\CURLOPT_SSL_VERIFYHOST] = 2; } - else - { + else { $options[\CURLOPT_SSL_VERIFYPEER] = false; $options[\CURLOPT_SSL_VERIFYHOST] = 0; } $certPath = $request->getAttribute(Attributes::CERT_PATH, ''); - if ('' !== $certPath) - { + if ('' !== $certPath) { $options[\CURLOPT_SSLCERT] = $certPath; $options[\CURLOPT_SSLCERTPASSWD] = $request->getAttribute(Attributes::CERT_PASSWORD); $options[\CURLOPT_SSLCERTTYPE] = $request->getAttribute(Attributes::CERT_TYPE, 'pem'); } $keyPath = $request->getAttribute(Attributes::KEY_PATH, ''); - if ('' !== $keyPath) - { + if ('' !== $keyPath) { $options[\CURLOPT_SSLKEY] = $keyPath; $options[\CURLOPT_SSLKEYPASSWD] = $request->getAttribute(Attributes::KEY_PASSWORD); $options[\CURLOPT_SSLKEYTYPE] = $request->getAttribute(Attributes::KEY_TYPE, 'pem'); @@ -543,30 +486,25 @@ private function parseSSL(&$request, &$options) */ private function parseOptions(&$request, &$options, &$headers = null, &$saveFileFp = null) { - if (isset($options[\CURLOPT_HEADERFUNCTION])) - { + if (isset($options[\CURLOPT_HEADERFUNCTION])) { $headerCallable = $options[\CURLOPT_HEADERFUNCTION]; } - else - { + else { $headerCallable = null; } $headers = []; $options[\CURLOPT_HEADERFUNCTION] = function ($handler, $header) use ($headerCallable, &$headers) { $headers[] = $header; - if ($headerCallable) - { + if ($headerCallable) { $headerCallable($handler, $header); } return \strlen($header); }; // 请求结果保存为文件 - if (null !== ($saveFilePath = $request->getAttribute(Attributes::SAVE_FILE_PATH))) - { + if (null !== ($saveFilePath = $request->getAttribute(Attributes::SAVE_FILE_PATH))) { $last = substr($saveFilePath, -1, 1); - if ('/' === $last || '\\' === $last) - { + if ('/' === $last || '\\' === $last) { // 自动获取文件名 $saveFilePath .= basename($request->getUri()->__toString()); } @@ -587,8 +525,7 @@ private function parseOptions(&$request, &$options, &$headers = null, &$saveFile */ private function parseProxy(&$request, &$options) { - if ($request->getAttribute(Attributes::USE_PROXY, false)) - { + if ($request->getAttribute(Attributes::USE_PROXY, false)) { $type = $request->getAttribute(Attributes::PROXY_TYPE, 'http'); $options[\CURLOPT_PROXYAUTH] = self::$proxyAuths[$request->getAttribute(Attributes::PROXY_AUTH, 'basic')]; $options[\CURLOPT_PROXY] = $request->getAttribute(Attributes::PROXY_SERVER); @@ -608,12 +545,10 @@ private function parseProxy(&$request, &$options) */ private function parseHeaders(&$request, &$options) { - if (!$request->hasHeader('User-Agent')) - { - $request = $request->withHeader('User-Agent', $request->getAttribute(Attributes::USER_AGENT, static::$defaultUA)); + if (!$request->hasHeader('User-Agent')) { + $request = $request->withHeader('User-Agent', $request->getAttribute(Attributes::USER_AGENT, self::$defaultUA)); } - if (!$request->hasHeader('Connection') && $request->getProtocolVersion() >= 1.1) - { + if (!$request->hasHeader('Connection') && $request->getProtocolVersion() >= 1.1) { $request = $request->withHeader('Connection', 'Keep-Alive')->withHeader('Keep-Alive', '300'); } $options[\CURLOPT_HTTPHEADER] = $this->parseHeadersFormat($request); @@ -629,8 +564,7 @@ private function parseHeaders(&$request, &$options) private function parseHeadersFormat($request) { $headers = []; - foreach ($request->getHeaders() as $name => $value) - { + foreach ($request->getHeaders() as $name => $value) { $headers[] = $name . ': ' . implode(',', $value); } @@ -648,13 +582,11 @@ private function parseHeadersFormat($request) private function parseCookies(&$request, &$options) { $cookieManager = $this->cookieManager; - foreach ($request->getCookieParams() as $name => $value) - { + foreach ($request->getCookieParams() as $name => $value) { $cookieManager->setCookie($name, $value); } $cookie = $cookieManager->getRequestCookieString($request->getUri()); - if ('' !== $cookie) - { + if ('' !== $cookie) { $options[\CURLOPT_COOKIE] = $cookie; } } @@ -671,12 +603,10 @@ private function parseNetwork(&$request, &$options) { // 用户名密码处理 $username = $request->getAttribute(Attributes::USERNAME); - if (null != $username) - { + if (null != $username) { $userPwd = $username . ':' . $request->getAttribute(Attributes::PASSWORD, ''); } - else - { + else { $userPwd = ''; } // 连接超时 @@ -729,18 +659,15 @@ public function coBatch($requests, $timeout = null) $curlHandlers = $recvHeaders = $saveFileFps = []; $result = []; $needRedirectRequests = []; - try - { - foreach ($requests as $k => $request) - { + try { + foreach ($requests as $k => $request) { $result[$k] = null; $curlHandler = curl_init(); $recvHeaders[$k] = $saveFileFps[$k] = null; $this->buildCurlHandlerBase($request, $curlHandler, $recvHeaders[$k], $saveFileFps[$k]); $files = $request->getUploadedFiles(); $body = (string) $request->getBody(); - if (!empty($files)) - { + if (!empty($files)) { $body = FormDataBuilder::build($body, $files, $boundary); $request = $request->withHeader('Content-Type', MediaType::MULTIPART_FORM_DATA . '; boundary=' . $boundary); } @@ -751,24 +678,20 @@ public function coBatch($requests, $timeout = null) $running = null; $beginTime = microtime(true); // 执行批处理句柄 - do - { + while (true) { curl_multi_exec($mh, $running); - if ($running > 0) - { - if ($timeout && microtime(true) - $beginTime >= $timeout) - { + if ($running > 0) { + if ($timeout && microtime(true) - $beginTime >= $timeout) { break; } usleep(5000); // 每次延时 5 毫秒 } - else - { + else { break; } - } while (true); - foreach ($requests as $k => $request) - { + } + + foreach ($requests as $k => $request) { $handler = $curlHandlers[$k]; $receiveHeaders = $recvHeaders[$k]; $curlResult = curl_multi_getcontent($handler); @@ -777,22 +700,18 @@ public function coBatch($requests, $timeout = null) // 重定向处理 $statusCode = $response->getStatusCode(); $redirectCount = $request->getAttribute(Attributes::PRIVATE_REDIRECT_COUNT); - if ($request->getAttribute(Attributes::FOLLOW_LOCATION, true) && ($statusCode >= 300 && $statusCode < 400) && '' !== ($location = $response->getHeaderLine('location'))) - { + if ($request->getAttribute(Attributes::FOLLOW_LOCATION, true) && ($statusCode >= 300 && $statusCode < 400) && '' !== ($location = $response->getHeaderLine('location'))) { $maxRedirects = $request->getAttribute(Attributes::MAX_REDIRECTS, 10); - if (++$redirectCount <= $maxRedirects) - { + if (++$redirectCount <= $maxRedirects) { $request = $request->withAttribute(Attributes::PRIVATE_REDIRECT_COUNT, $redirectCount); - if (\in_array($statusCode, [301, 302, 303])) - { + if (\in_array($statusCode, [301, 302, 303])) { $request = $request->withMethod('GET')->withBody(new MemoryStream()); } $request = $request->withUri($this->parseRedirectLocation($location, $request->getUri())); $needRedirectRequests[$k] = $request; continue; } - else - { + else { $response = $response->withErrno(-1) ->withError(sprintf('Maximum (%s) redirects followed', $maxRedirects)); } @@ -804,27 +723,21 @@ public function coBatch($requests, $timeout = null) $this->cookieManager->gc(); $this->saveCookieJar(); } - finally - { - foreach ($saveFileFps as $fp) - { + finally { + foreach ($saveFileFps as $fp) { // @phpstan-ignore-next-line - if ($fp) - { + if ($fp) { fclose($fp); } } - foreach ($curlHandlers as $curlHandler) - { + foreach ($curlHandlers as $curlHandler) { curl_multi_remove_handle($mh, $curlHandler); curl_close($curlHandler); } curl_multi_close($mh); } - if ($needRedirectRequests) - { - foreach ($this->coBatch($needRedirectRequests, $timeout) as $k => $response) - { + if ($needRedirectRequests) { + foreach ($this->coBatch($needRedirectRequests, $timeout) as $k => $response) { $result[$k] = $response; } } diff --git a/src/YurunHttp/Handler/Curl/CurlConnectionPool.php b/src/YurunHttp/Handler/Curl/CurlConnectionPool.php index 7ca5ad8..e6b9ad8 100644 --- a/src/YurunHttp/Handler/Curl/CurlConnectionPool.php +++ b/src/YurunHttp/Handler/Curl/CurlConnectionPool.php @@ -39,8 +39,7 @@ public function close() $connections = $this->connections; $this->connections = []; $this->queue = new \SplQueue(); - foreach ($connections as $connection) - { + foreach ($connections as $connection) { curl_close($connection); } } @@ -62,19 +61,15 @@ public function createConnection() */ public function getConnection() { - if ($this->getFree() > 0) - { + if ($this->getFree() > 0) { return $this->queue->dequeue(); } - else - { + else { $maxConnections = $this->getConfig()->getMaxConnections(); - if (0 != $maxConnections && $this->getCount() >= $maxConnections) - { + if (0 != $maxConnections && $this->getCount() >= $maxConnections) { return false; } - else - { + else { return $this->connections[] = $this->createConnection(); } } @@ -89,8 +84,7 @@ public function getConnection() */ public function release($connection) { - if (\in_array($connection, $this->connections)) - { + if (\in_array($connection, $this->connections)) { $this->queue->enqueue($connection); } } diff --git a/src/YurunHttp/Handler/Curl/CurlHttpConnectionManager.php b/src/YurunHttp/Handler/Curl/CurlHttpConnectionManager.php index 9daeb5e..7fe4732 100644 --- a/src/YurunHttp/Handler/Curl/CurlHttpConnectionManager.php +++ b/src/YurunHttp/Handler/Curl/CurlHttpConnectionManager.php @@ -28,8 +28,7 @@ class CurlHttpConnectionManager implements IConnectionManager */ public static function getInstance() { - if (null === self::$instance) - { + if (null === self::$instance) { return self::$instance = new static(); } @@ -55,15 +54,12 @@ public function getConnectionPools() */ public function getConnectionPool($url) { - if (isset($this->connectionPools[$url])) - { + if (isset($this->connectionPools[$url])) { return $this->connectionPools[$url]; } - else - { + else { $config = ConnectionPool::getConfig($url); - if (null === $config) - { + if (null === $config) { ConnectionPool::setConfig($url); } $config = ConnectionPool::getConfig($url); @@ -135,8 +131,7 @@ public function close() { $connectionPools = $this->connectionPools; $this->connectionPools = []; - foreach ($connectionPools as $connectionPool) - { + foreach ($connectionPools as $connectionPool) { $connectionPool->close(); } } diff --git a/src/YurunHttp/Handler/Swoole.php b/src/YurunHttp/Handler/Swoole.php index 1caf32a..598dcda 100644 --- a/src/YurunHttp/Handler/Swoole.php +++ b/src/YurunHttp/Handler/Swoole.php @@ -43,13 +43,6 @@ class Swoole implements IHandler */ private $result; - /** - * 连接池键. - * - * @var string - */ - private $poolKey; - /** * 连接池是否启用. * @@ -77,9 +70,8 @@ class Swoole implements IHandler public function __construct($options = []) { $this->options = $options; - if (null === static::$defaultUA) - { - static::$defaultUA = sprintf('Mozilla/5.0 YurunHttp/%s Swoole/%s', YurunHttp::VERSION, \defined('SWOOLE_VERSION') ? \SWOOLE_VERSION : 'unknown'); + if (null === self::$defaultUA) { + self::$defaultUA = sprintf('Mozilla/5.0 YurunHttp/%s Swoole/%s', YurunHttp::VERSION, \defined('SWOOLE_VERSION') ? \SWOOLE_VERSION : 'unknown'); } $this->initCookieManager(); $this->httpConnectionManager = new SwooleHttpConnectionManager(); @@ -108,22 +100,18 @@ public function close() */ public function buildRequest($request, $connection, &$http2Request) { - if ($isHttp2 = '2.0' === $request->getProtocolVersion()) - { + if ($isHttp2 = '2.0' === $request->getProtocolVersion()) { $http2Request = new Http2Request(); } - else - { + else { $http2Request = null; } $uri = $request->getUri(); // method - if ($isHttp2) - { + if ($isHttp2) { $http2Request->method = $request->getMethod(); } - else - { + else { $connection->setMethod($request->getMethod()); } // cookie @@ -131,29 +119,23 @@ public function buildRequest($request, $connection, &$http2Request) // body $hasFile = false; $redirectCount = $request->getAttribute(Attributes::PRIVATE_REDIRECT_COUNT, 0); - if ($redirectCount <= 0) - { + if ($redirectCount <= 0) { $files = $request->getUploadedFiles(); $body = (string) $request->getBody(); - if (!empty($files)) - { - if ($isHttp2) - { + if (!empty($files)) { + if ($isHttp2) { throw new \RuntimeException('Http2 swoole handler does not support upload file'); } $hasFile = true; - foreach ($files as $name => $file) - { + foreach ($files as $name => $file) { $connection->addFile($file->getTempFileName(), $name, $file->getClientMediaType(), basename($file->getClientFilename())); } parse_str($body, $body); } - if ($isHttp2) - { + if ($isHttp2) { $http2Request->data = $body; } - else - { + else { $connection->setData($body); } } @@ -163,46 +145,37 @@ public function buildRequest($request, $connection, &$http2Request) $this->parseNetwork($request); // 设置客户端参数 $settings = $request->getAttribute(Attributes::OPTIONS, []); - if ($settings) - { + if ($settings) { $connection->set($settings); } // headers - if (!$request->hasHeader('Host')) - { + if (!$request->hasHeader('Host')) { $request = $request->withHeader('Host', Uri::getDomain($uri)); } - if (!$hasFile && !$request->hasHeader('Content-Type')) - { + if (!$hasFile && !$request->hasHeader('Content-Type')) { $request = $request->withHeader('Content-Type', MediaType::APPLICATION_FORM_URLENCODED); } - if (!$request->hasHeader('User-Agent')) - { - $request = $request->withHeader('User-Agent', $request->getAttribute(Attributes::USER_AGENT, static::$defaultUA)); + if (!$request->hasHeader('User-Agent')) { + $request = $request->withHeader('User-Agent', $request->getAttribute(Attributes::USER_AGENT, self::$defaultUA)); } $headers = []; - foreach ($request->getHeaders() as $name => $value) - { + foreach ($request->getHeaders() as $name => $value) { $headers[$name] = implode(',', $value); } - if ($isHttp2) - { + if ($isHttp2) { $http2Request->headers = $headers; $http2Request->pipeline = $request->getAttribute(Attributes::HTTP2_PIPELINE, false); $path = $uri->getPath(); - if ('' === $path) - { + if ('' === $path) { $path = '/'; } $query = $uri->getQuery(); - if ('' !== $query) - { + if ('' !== $query) { $path .= '?' . $query; } $http2Request->path = $path; } - else - { + else { $connection->setHeaders($headers); } } @@ -219,8 +192,7 @@ public function send(&$request) $this->poolIsEnabled = ConnectionPool::isEnabled() && false !== $request->getAttribute(Attributes::CONNECTION_POOL); $beginTime = microtime(true); $request = $this->sendDefer($request); - if ($request->getAttribute(Attributes::PRIVATE_IS_HTTP2) && $request->getAttribute(Attributes::HTTP2_NOT_RECV)) - { + if ($request->getAttribute(Attributes::PRIVATE_IS_HTTP2) && $request->getAttribute(Attributes::HTTP2_NOT_RECV)) { return true; } @@ -240,43 +212,33 @@ public function send(&$request) public function sendDefer($request) { $isHttp2 = '2.0' === $request->getProtocolVersion(); - if ($poolIsEnabled = $this->poolIsEnabled) - { - if ($isHttp2) - { + if ($poolIsEnabled = $this->poolIsEnabled) { + if ($isHttp2) { $http2ConnectionManager = SwooleHttp2ConnectionManager::getInstance(); } - else - { + else { $httpConnectionManager = SwooleHttpConnectionManager::getInstance(); } } - else - { - if ($isHttp2) - { + else { + if ($isHttp2) { $http2ConnectionManager = $this->http2ConnectionManager; } - else - { + else { $httpConnectionManager = $this->httpConnectionManager; } } - if ([] !== ($queryParams = $request->getQueryParams())) - { + if ([] !== ($queryParams = $request->getQueryParams())) { $request = $request->withUri($request->getUri()->withQuery(http_build_query($queryParams, '', '&'))); } $uri = $request->getUri(); - try - { - $this->poolKey = $poolKey = ConnectionPool::getKey($uri); - if ($isHttp2) - { + try { + $poolKey = ConnectionPool::getKey($uri); + if ($isHttp2) { /** @var \Swoole\Coroutine\Http2\Client $connection */ $connection = $http2ConnectionManager->getConnection($poolKey); } - else - { + else { /** @var \Swoole\Coroutine\Http\Client $connection */ $connection = $httpConnectionManager->getConnection($poolKey); $connection->setDefer(true); @@ -287,42 +249,32 @@ public function sendDefer($request) $this->buildRequest($request, $connection, $http2Request); // 发送 $path = $uri->getPath(); - if ('' === $path) - { + if ('' === $path) { $path = '/'; } $query = $uri->getQuery(); - if ('' !== $query) - { + if ('' !== $query) { $path .= '?' . $query; } - if ($isWebSocket) - { - if ($isHttp2) - { + if ($isWebSocket) { + if ($isHttp2) { throw new \RuntimeException('Http2 swoole handler does not support websocket'); } - if (!$connection->upgrade($path)) - { + if (!$connection->upgrade($path)) { throw new WebSocketException(sprintf('WebSocket connect faled, statusCode: %s, error: %s, errorCode: %s', $connection->statusCode, swoole_strerror($connection->errCode), $connection->errCode), $connection->errCode); } } - elseif (null === ($saveFilePath = $request->getAttribute(Attributes::SAVE_FILE_PATH))) - { - if ($isHttp2) - { + elseif (null === ($saveFilePath = $request->getAttribute(Attributes::SAVE_FILE_PATH))) { + if ($isHttp2) { $result = $connection->send($http2Request); $request = $request->withAttribute(Attributes::PRIVATE_HTTP2_STREAM_ID, $result); } - else - { + else { $connection->execute($path); } } - else - { - if ($isHttp2) - { + else { + if ($isHttp2) { throw new \RuntimeException('Http2 swoole handler does not support download file'); } $connection->download($path, $saveFilePath); @@ -332,21 +284,16 @@ public function sendDefer($request) ->withAttribute(Attributes::PRIVATE_IS_WEBSOCKET, $isHttp2) ->withAttribute(Attributes::PRIVATE_CONNECTION, $connection); } - catch (\Throwable $th) - { + catch (\Throwable $th) { throw $th; } - finally - { - if ($poolIsEnabled && isset($connection) && isset($th)) - { - if ($isHttp2) - { + finally { + if ($poolIsEnabled && isset($connection) && isset($th)) { + if ($isHttp2) { // @phpstan-ignore-next-line $http2ConnectionManager->release($poolKey, $connection); } - else - { + else { // @phpstan-ignore-next-line $httpConnectionManager->release($poolKey, $connection); } @@ -371,34 +318,25 @@ public function recvDefer($request, $timeout = null) $redirectCount = $request->getAttribute(Attributes::PRIVATE_REDIRECT_COUNT, 0); $isHttp2 = '2.0' === $request->getProtocolVersion(); $isWebSocket = $request->getAttribute(Attributes::PRIVATE_WEBSOCKET, false); - try - { + try { $this->getResponse($request, $connection, $isWebSocket, $isHttp2, $timeout); } - finally - { - if (!$isWebSocket) - { - if ($isHttp2) - { - if ($this->poolIsEnabled) - { + finally { + if (!$isWebSocket) { + if ($isHttp2) { + if ($this->poolIsEnabled) { $http2ConnectionManager = SwooleHttp2ConnectionManager::getInstance(); } - else - { + else { $http2ConnectionManager = $this->http2ConnectionManager; } $http2ConnectionManager->release($poolKey, $connection); } - else - { - if ($this->poolIsEnabled) - { + else { + if ($this->poolIsEnabled) { $httpConnectionManager = SwooleHttpConnectionManager::getInstance(); } - else - { + else { $httpConnectionManager = $this->httpConnectionManager; } $httpConnectionManager->release($poolKey, $connection); @@ -407,37 +345,29 @@ public function recvDefer($request, $timeout = null) } $result = &$this->result; $statusCode = $result->getStatusCode(); - if ($retryCount < $request->getAttribute(Attributes::RETRY, 0)) - { - if ($retryCallback = $request->getAttribute(Attributes::RETRY_CALLBACK)) - { + if ($retryCount < $request->getAttribute(Attributes::RETRY, 0)) { + if ($retryCallback = $request->getAttribute(Attributes::RETRY_CALLBACK)) { $retry = !$retryCallback($request, $result, $retryCount); } - else - { + else { // 状态码为5XX或者0才需要重试 $retry = (0 === $statusCode || (5 === (int) ($statusCode / 100))); } - if ($retry) - { + if ($retry) { $request = $request->withAttribute(Attributes::PRIVATE_RETRY_COUNT, ++$retryCount); $deferRequest = $this->sendDefer($request); return $this->recvDefer($deferRequest, $timeout); } } - if (!$isWebSocket && $statusCode >= 300 && $statusCode < 400 && $request->getAttribute(Attributes::FOLLOW_LOCATION, true) && '' !== ($location = $result->getHeaderLine('location'))) - { - if (++$redirectCount <= ($maxRedirects = $request->getAttribute(Attributes::MAX_REDIRECTS, 10))) - { + if (!$isWebSocket && $statusCode >= 300 && $statusCode < 400 && $request->getAttribute(Attributes::FOLLOW_LOCATION, true) && '' !== ($location = $result->getHeaderLine('location'))) { + if (++$redirectCount <= ($maxRedirects = $request->getAttribute(Attributes::MAX_REDIRECTS, 10))) { // 自己实现重定向 $uri = $this->parseRedirectLocation($location, $request->getUri()); - if (\in_array($statusCode, [301, 302, 303])) - { + if (\in_array($statusCode, [301, 302, 303])) { $method = 'GET'; } - else - { + else { $method = $request->getMethod(); } $request = $request->withMethod($method) @@ -447,8 +377,7 @@ public function recvDefer($request, $timeout = null) return $this->recvDefer($deferRequest, $timeout); } - else - { + else { $result = $result->withErrno(-1) ->withError(sprintf('Maximum (%s) redirects followed', $maxRedirects)); @@ -457,8 +386,7 @@ public function recvDefer($request, $timeout = null) } // 下载文件名 $savedFileName = $request->getAttribute(Attributes::SAVE_FILE_PATH); - if (null !== $savedFileName) - { + if (null !== $savedFileName) { $result = $result->withSavedFileName($savedFileName); } $this->cookieManager->gc(); @@ -477,8 +405,7 @@ public function recvDefer($request, $timeout = null) */ public function websocket(&$request, $websocketClient = null) { - if (!$websocketClient) - { + if (!$websocketClient) { $websocketClient = new \Yurun\Util\YurunHttp\WebSocket\Swoole(); } $request = $request->withAttribute(Attributes::PRIVATE_WEBSOCKET, true); @@ -511,17 +438,14 @@ private function parseCookies(&$request, $connection, $http2Request) { $cookieParams = $request->getCookieParams(); $cookieManager = $this->cookieManager; - foreach ($cookieParams as $name => $value) - { + foreach ($cookieParams as $name => $value) { $cookieManager->setCookie($name, $value); } $cookies = $cookieManager->getRequestCookies($request->getUri()); - if ($http2Request) - { + if ($http2Request) { $http2Request->cookies = $cookies; } - else - { + else { $connection->setCookies($cookies); } } @@ -539,35 +463,29 @@ public function buildHttp2Response($request, $connection, $response) { $success = false !== $response; $result = new Response($response->data ?? '', $success ? $response->statusCode : 0); - if ($success) - { + if ($success) { // streamId $result = $result->withStreamId($response->streamId); // headers - if ($response->headers) - { - foreach ($response->headers as $name => $value) - { + if ($response->headers) { + foreach ($response->headers as $name => $value) { $result = $result->withHeader($name, $value); } } // cookies $cookies = []; - if (isset($response->set_cookie_headers)) - { + if (isset($response->set_cookie_headers)) { $cookieManager = $this->cookieManager; - foreach ($response->set_cookie_headers as $value) - { + foreach ($response->set_cookie_headers as $value) { $cookieItem = $cookieManager->addSetCookie($value); $cookies[$cookieItem->name] = (array) $cookieItem; } } $result = $result->withCookieOriginParams($cookies); } - if ($connection) - { + if ($connection) { $result = $result->withError(swoole_strerror($connection->errCode)) ->withErrno($connection->errCode); } @@ -589,32 +507,25 @@ public function buildHttp2Response($request, $connection, $response) private function getResponse($request, $connection, $isWebSocket, $isHttp2, $timeout = null) { $result = &$this->result; - if ($isHttp2) - { + if ($isHttp2) { $response = $connection->recv((float) $timeout); $result = $this->buildHttp2Response($request, $connection, $response); } - else - { + else { $success = $isWebSocket ? true : $connection->recv((float) $timeout); $result = new Response((string) $connection->body, $connection->statusCode); - if ($success) - { + if ($success) { // headers - if ($connection->headers) - { - foreach ($connection->headers as $name => $value) - { + if ($connection->headers) { + foreach ($connection->headers as $name => $value) { $result = $result->withHeader($name, $value); } } // cookies $cookies = []; - if (isset($connection->set_cookie_headers)) - { - foreach ($connection->set_cookie_headers as $value) - { + if (isset($connection->set_cookie_headers)) { + foreach ($connection->set_cookie_headers as $value) { $cookieItem = $this->cookieManager->addSetCookie($value); $cookies[$cookieItem->name] = (array) $cookieItem; } @@ -639,36 +550,29 @@ private function getResponse($request, $connection, $isWebSocket, $isHttp2, $tim private function parseSSL(&$request) { $settings = $request->getAttribute(Attributes::OPTIONS, []); - if ($request->getAttribute(Attributes::IS_VERIFY_CA, false)) - { + if ($request->getAttribute(Attributes::IS_VERIFY_CA, false)) { $settings['ssl_verify_peer'] = true; $caCert = $request->getAttribute(Attributes::CA_CERT); - if (null !== $caCert) - { + if (null !== $caCert) { $settings['ssl_cafile'] = $caCert; } } - else - { + else { $settings['ssl_verify_peer'] = false; } $certPath = $request->getAttribute(Attributes::CERT_PATH, ''); - if ('' !== $certPath) - { + if ('' !== $certPath) { $settings['ssl_cert_file'] = $certPath; } $password = $request->getAttribute(Attributes::CERT_PASSWORD, ''); - if ('' === $password) - { + if ('' === $password) { $password = $request->getAttribute(Attributes::KEY_PASSWORD, ''); } - if ('' !== $password) - { + if ('' !== $password) { $settings['ssl_passphrase'] = $password; } $keyPath = $request->getAttribute(Attributes::KEY_PATH, ''); - if ('' !== $keyPath) - { + if ('' !== $keyPath) { $settings['ssl_key_file'] = $keyPath; } $request = $request->withAttribute(Attributes::OPTIONS, $settings); @@ -684,36 +588,30 @@ private function parseSSL(&$request) private function parseProxy(&$request) { $settings = $request->getAttribute(Attributes::OPTIONS, []); - if ($request->getAttribute(Attributes::USE_PROXY, false)) - { + if ($request->getAttribute(Attributes::USE_PROXY, false)) { $type = $request->getAttribute(Attributes::PROXY_TYPE); - switch ($type) - { + switch ($type) { case 'http': $settings['http_proxy_host'] = $request->getAttribute(Attributes::PROXY_SERVER); $port = $request->getAttribute(Attributes::PROXY_PORT); - if (null !== $port) - { + if (null !== $port) { $settings['http_proxy_port'] = $port; } $settings['http_proxy_user'] = $request->getAttribute(Attributes::PROXY_USERNAME); $password = $request->getAttribute(Attributes::PROXY_PASSWORD); - if (null !== $password) - { + if (null !== $password) { $settings['http_proxy_password'] = $password; } break; case 'socks5': $settings['socks5_host'] = $request->getAttribute(Attributes::PROXY_SERVER); $port = $request->getAttribute(Attributes::PROXY_PORT); - if (null !== $port) - { + if (null !== $port) { $settings['socks5_port'] = $port; } $settings['socks5_username'] = $request->getAttribute(Attributes::PROXY_USERNAME); $password = $request->getAttribute(Attributes::PROXY_PASSWORD); - if (null !== $password) - { + if (null !== $password) { $settings['socks5_password'] = $password; } break; @@ -734,31 +632,25 @@ private function parseNetwork(&$request) $settings = $request->getAttribute(Attributes::OPTIONS, []); // 用户名密码认证处理 $username = $request->getAttribute(Attributes::USERNAME); - if (null === $username) - { + if (null === $username) { $uri = $request->getUri(); $userInfo = $uri->getUserInfo(); - if ($userInfo) - { + if ($userInfo) { $authorization = 'Basic ' . base64_encode($userInfo); } - else - { + else { $authorization = null; } } - else - { + else { $authorization = 'Basic ' . base64_encode($username . ':' . $request->getAttribute(Attributes::PASSWORD, '')); } - if ($authorization) - { + if ($authorization) { $request = $request->withHeader('Authorization', $authorization); } // 超时 $settings['timeout'] = $request->getAttribute(Attributes::TIMEOUT, 30000) / 1000; - if ($settings['timeout'] < 0) - { + if ($settings['timeout'] < 0) { $settings['timeout'] = -1; } // 长连接 @@ -810,8 +702,7 @@ public function coBatch($requests, $timeout = null) $handlers = []; $results = []; $beginTime = microtime(true); - foreach ($requests as $i => &$request) - { + foreach ($requests as $i => &$request) { $results[$i] = null; $handlers[$i] = $handler = new self(); $request = $handler->sendDefer($request); @@ -819,13 +710,10 @@ public function coBatch($requests, $timeout = null) unset($request); $beginTime = microtime(true); $recvTimeout = null; - foreach ($requests as $i => $request) - { - if (null !== $timeout) - { + foreach ($requests as $i => $request) { + if (null !== $timeout) { $recvTimeout = $timeout - (microtime(true) - $beginTime); - if ($recvTimeout <= 0) - { + if ($recvTimeout <= 0) { break; } } @@ -837,12 +725,10 @@ public function coBatch($requests, $timeout = null) public function getHttpConnectionManager(): SwooleHttpConnectionManager { - if (ConnectionPool::isEnabled()) - { + if (ConnectionPool::isEnabled()) { return SwooleHttpConnectionManager::getInstance(); } - else - { + else { return $this->httpConnectionManager; } } diff --git a/src/YurunHttp/Handler/Swoole/SwooleHttp2ConnectionManager.php b/src/YurunHttp/Handler/Swoole/SwooleHttp2ConnectionManager.php index 3ee7c46..ad044b8 100644 --- a/src/YurunHttp/Handler/Swoole/SwooleHttp2ConnectionManager.php +++ b/src/YurunHttp/Handler/Swoole/SwooleHttp2ConnectionManager.php @@ -28,8 +28,7 @@ class SwooleHttp2ConnectionManager implements IConnectionManager */ public static function getInstance() { - if (null === self::$instance) - { + if (null === self::$instance) { return self::$instance = new static(); } @@ -55,15 +54,12 @@ public function getConnectionPools() */ public function getConnectionPool($url) { - if (isset($this->connectionPools[$url])) - { + if (isset($this->connectionPools[$url])) { return $this->connectionPools[$url]; } - else - { + else { $config = ConnectionPool::getConfig($url); - if (null === $config) - { + if (null === $config) { ConnectionPool::setConfig($url); } $config = ConnectionPool::getConfig($url); @@ -135,8 +131,7 @@ public function close() { $connectionPools = $this->connectionPools; $this->connectionPools = []; - foreach ($connectionPools as $connectionPool) - { + foreach ($connectionPools as $connectionPool) { $connectionPool->close(); } } diff --git a/src/YurunHttp/Handler/Swoole/SwooleHttp2ConnectionPool.php b/src/YurunHttp/Handler/Swoole/SwooleHttp2ConnectionPool.php index c2ce25f..19f37e9 100644 --- a/src/YurunHttp/Handler/Swoole/SwooleHttp2ConnectionPool.php +++ b/src/YurunHttp/Handler/Swoole/SwooleHttp2ConnectionPool.php @@ -42,8 +42,7 @@ public function close() $connections = $this->connections; $this->connections = []; $this->channel = new Channel(1024); - foreach ($connections as $connection) - { + foreach ($connections as $connection) { $connection->close(); } } @@ -59,12 +58,10 @@ public function createConnection() $uri = new Uri($config->getUrl()); $scheme = $uri->getScheme(); $client = new Client($uri->getHost(), Uri::getServerPort($uri), 'https' === $scheme || 'wss' === $scheme); - if ($client->connect()) - { + if ($client->connect()) { return $client; } - else - { + else { throw new \RuntimeException(sprintf('Http2 connect failed! errCode: %s, errMsg:%s', $client->errCode, swoole_strerror($client->errCode))); } } @@ -78,14 +75,12 @@ public function getConnection() { $config = $this->getConfig(); $maxConnections = $this->getConfig()->getMaxConnections(); - if ($this->getFree() > 0 || (0 != $maxConnections && $this->getCount() >= $maxConnections)) - { + if ($this->getFree() > 0 || (0 != $maxConnections && $this->getCount() >= $maxConnections)) { $timeout = $config->getWaitTimeout(); return $this->channel->pop(null === $timeout ? -1 : $timeout); } - else - { + else { return $this->connections[] = $this->createConnection(); } } @@ -99,18 +94,14 @@ public function getConnection() */ public function release($connection) { - if ($connection->connected) - { - if (\in_array($connection, $this->connections)) - { + if ($connection->connected) { + if (\in_array($connection, $this->connections)) { $this->channel->push($connection); } } - else - { + else { $index = array_search($connection, $this->connections); - if (false !== $index) - { + if (false !== $index) { unset($this->connections[$index]); } } diff --git a/src/YurunHttp/Handler/Swoole/SwooleHttpConnectionManager.php b/src/YurunHttp/Handler/Swoole/SwooleHttpConnectionManager.php index d0dfee6..e8f0460 100644 --- a/src/YurunHttp/Handler/Swoole/SwooleHttpConnectionManager.php +++ b/src/YurunHttp/Handler/Swoole/SwooleHttpConnectionManager.php @@ -28,8 +28,7 @@ class SwooleHttpConnectionManager implements IConnectionManager */ public static function getInstance() { - if (null === self::$instance) - { + if (null === self::$instance) { return self::$instance = new static(); } @@ -55,15 +54,12 @@ public function getConnectionPools() */ public function getConnectionPool($url) { - if (isset($this->connectionPools[$url])) - { + if (isset($this->connectionPools[$url])) { return $this->connectionPools[$url]; } - else - { + else { $config = ConnectionPool::getConfig($url); - if (null === $config) - { + if (null === $config) { ConnectionPool::setConfig($url); } $config = ConnectionPool::getConfig($url); @@ -135,8 +131,7 @@ public function close() { $connectionPools = $this->connectionPools; $this->connectionPools = []; - foreach ($connectionPools as $connectionPool) - { + foreach ($connectionPools as $connectionPool) { $connectionPool->close(); } } diff --git a/src/YurunHttp/Handler/Swoole/SwooleHttpConnectionPool.php b/src/YurunHttp/Handler/Swoole/SwooleHttpConnectionPool.php index ddc908d..061928c 100644 --- a/src/YurunHttp/Handler/Swoole/SwooleHttpConnectionPool.php +++ b/src/YurunHttp/Handler/Swoole/SwooleHttpConnectionPool.php @@ -42,8 +42,7 @@ public function close() $connections = $this->connections; $this->connections = []; $this->channel = new Channel(1024); - foreach ($connections as $connection) - { + foreach ($connections as $connection) { $connection->close(); } } @@ -71,14 +70,12 @@ public function getConnection() { $config = $this->getConfig(); $maxConnections = $this->getConfig()->getMaxConnections(); - if ($this->getFree() > 0 || (0 != $maxConnections && $this->getCount() >= $maxConnections)) - { + if ($this->getFree() > 0 || (0 != $maxConnections && $this->getCount() >= $maxConnections)) { $timeout = $config->getWaitTimeout(); return $this->channel->pop(null === $timeout ? -1 : $timeout); } - else - { + else { return $this->connections[] = $this->createConnection(); } } @@ -92,8 +89,7 @@ public function getConnection() */ public function release($connection) { - if (\in_array($connection, $this->connections)) - { + if (\in_array($connection, $this->connections)) { $this->channel->push($connection); } } diff --git a/src/YurunHttp/HandlerOptions.php b/src/YurunHttp/HandlerOptions.php index 079f95f..71d0b89 100644 --- a/src/YurunHttp/HandlerOptions.php +++ b/src/YurunHttp/HandlerOptions.php @@ -10,15 +10,15 @@ abstract class HandlerOptions /** * Cookie 管理器数据保存到的文件名. */ - const COOKIE_JAR = 'cookie_jar'; + public const COOKIE_JAR = 'cookie_jar'; /** * 日志对象. */ - const LOGGER = 'logger'; + public const LOGGER = 'logger'; /** * 请求日志格式. */ - const REQUEST_LOG_FORMAT = 'request_log_format'; + public const REQUEST_LOG_FORMAT = 'request_log_format'; } diff --git a/src/YurunHttp/Http/Psr7/AbstractMessage.php b/src/YurunHttp/Http/Psr7/AbstractMessage.php index d906ab6..92edb60 100644 --- a/src/YurunHttp/Http/Psr7/AbstractMessage.php +++ b/src/YurunHttp/Http/Psr7/AbstractMessage.php @@ -42,12 +42,10 @@ abstract class AbstractMessage implements MessageInterface */ public function __construct($body) { - if ($body instanceof \Psr\Http\Message\StreamInterface) - { + if ($body instanceof \Psr\Http\Message\StreamInterface) { $this->body = $body; } - else - { + else { $this->body = new MemoryStream($body); } } @@ -59,7 +57,7 @@ public function __construct($body) * * @return string HTTP protocol version */ - public function getProtocolVersion() + public function getProtocolVersion(): string { return $this->protocolVersion; } @@ -78,7 +76,7 @@ public function getProtocolVersion() * * @return static */ - public function withProtocolVersion($version) + public function withProtocolVersion($version): MessageInterface { $self = clone $this; $self->protocolVersion = $version; @@ -111,7 +109,7 @@ public function withProtocolVersion($version) * key MUST be a header name, and each value MUST be an array of strings * for that header. */ - public function getHeaders() + public function getHeaders(): array { return $this->headers; } @@ -125,11 +123,10 @@ public function getHeaders() * name using a case-insensitive string comparison. Returns false if * no matching header name is found in the message. */ - public function hasHeader($name) + public function hasHeader($name): bool { $lowerName = strtolower($name); - if (isset($this->headerNames[$lowerName])) - { + if (isset($this->headerNames[$lowerName])) { $name = $this->headerNames[$lowerName]; } @@ -151,19 +148,16 @@ public function hasHeader($name) * header. If the header does not appear in the message, this method MUST * return an empty array. */ - public function getHeader($name) + public function getHeader($name): array { $lowerName = strtolower($name); - if (isset($this->headerNames[$lowerName])) - { + if (isset($this->headerNames[$lowerName])) { $name = $this->headerNames[$lowerName]; } - if (isset($this->headers[$name])) - { + if (isset($this->headers[$name])) { return $this->headers[$name]; } - else - { + else { return []; } } @@ -188,15 +182,13 @@ public function getHeader($name) * concatenated together using a comma. If the header does not appear in * the message, this method MUST return an empty string. */ - public function getHeaderLine($name) + public function getHeaderLine($name): string { $lowerName = strtolower($name); - if (isset($this->headerNames[$lowerName])) - { + if (isset($this->headerNames[$lowerName])) { $name = $this->headerNames[$lowerName]; } - if (!isset($this->headers[$name])) - { + if (!isset($this->headers[$name])) { return ''; } @@ -220,7 +212,7 @@ public function getHeaderLine($name) * * @throws \InvalidArgumentException for invalid header names or values */ - public function withHeader($name, $value) + public function withHeader($name, $value): MessageInterface { $self = clone $this; @@ -245,34 +237,28 @@ public function withHeader($name, $value) * * @throws \InvalidArgumentException for invalid header names or values */ - public function withAddedHeader($name, $value) + public function withAddedHeader($name, $value): MessageInterface { $self = clone $this; $lowerName = strtolower($name); - if (isset($self->headerNames[$lowerName])) - { + if (isset($self->headerNames[$lowerName])) { $name = $self->headerNames[$lowerName]; } - else - { + else { $self->headerNames[$lowerName] = $name; } - if (\is_string($value)) - { + if (\is_string($value)) { $value = [$value]; } - elseif (!\is_array($value)) - { + elseif (!\is_array($value)) { throw new \InvalidArgumentException('invalid header names or values'); } - if (isset($self->headers[$name])) - { + if (isset($self->headers[$name])) { $self->headers[$name] = array_merge($self->headers[$name], $value); } - else - { + else { $self->headers[$name] = $value; } @@ -292,16 +278,14 @@ public function withAddedHeader($name, $value) * * @return static */ - public function withoutHeader($name) + public function withoutHeader($name): MessageInterface { $self = clone $this; $lowerName = strtolower($name); - if (isset($self->headerNames[$lowerName])) - { + if (isset($self->headerNames[$lowerName])) { $name = $self->headerNames[$lowerName]; } - if (isset($self->headers[$name])) - { + if (isset($self->headers[$name])) { unset($self->headers[$name]); } @@ -313,7 +297,7 @@ public function withoutHeader($name) * * @return StreamInterface returns the body as a stream */ - public function getBody() + public function getBody(): StreamInterface { return $this->body; } @@ -333,7 +317,7 @@ public function getBody() * * @throws \InvalidArgumentException when the body is not valid */ - public function withBody(StreamInterface $body) + public function withBody(StreamInterface $body): MessageInterface { $self = clone $this; $self->body = $body; @@ -350,8 +334,7 @@ public function withBody(StreamInterface $body) */ protected function setHeaders(array $headers) { - foreach ($headers as $name => $value) - { + foreach ($headers as $name => $value) { $this->setHeader($this, $name, $value); } @@ -370,24 +353,19 @@ protected function setHeaders(array $headers) protected function setHeader($object, $name, $value) { $lowerName = strtolower($name); - if (isset($object->headerNames[$lowerName])) - { + if (isset($object->headerNames[$lowerName])) { $name = $object->headerNames[$lowerName]; } - else - { + else { $object->headerNames[$lowerName] = $name; } - if (\is_string($value)) - { + if (\is_string($value)) { $object->headers[$name] = [$value]; } - elseif (\is_array($value)) - { + elseif (\is_array($value)) { $object->headers[$name] = $value; } - else - { + else { throw new \InvalidArgumentException('invalid header names or values'); } diff --git a/src/YurunHttp/Http/Psr7/Consts/MediaType.php b/src/YurunHttp/Http/Psr7/Consts/MediaType.php index 7516af3..49f5121 100644 --- a/src/YurunHttp/Http/Psr7/Consts/MediaType.php +++ b/src/YurunHttp/Http/Psr7/Consts/MediaType.php @@ -7,53 +7,53 @@ */ abstract class MediaType { - const ALL = '*/*'; + public const ALL = '*/*'; - const APPLICATION_ATOM_XML = 'application/atom+xml'; + public const APPLICATION_ATOM_XML = 'application/atom+xml'; - const APPLICATION_FORM_URLENCODED = 'application/x-www-form-urlencoded'; + public const APPLICATION_FORM_URLENCODED = 'application/x-www-form-urlencoded'; - const APPLICATION_JSON = 'application/json'; + public const APPLICATION_JSON = 'application/json'; - const APPLICATION_JSON_UTF8 = 'application/json;charset=UTF-8'; + public const APPLICATION_JSON_UTF8 = 'application/json;charset=UTF-8'; - const APPLICATION_OCTET_STREAM = 'application/octet-stream'; + public const APPLICATION_OCTET_STREAM = 'application/octet-stream'; - const APPLICATION_PDF = 'application/pdf'; + public const APPLICATION_PDF = 'application/pdf'; - const APPLICATION_PROBLEM_JSON = 'application/problem+json'; + public const APPLICATION_PROBLEM_JSON = 'application/problem+json'; - const APPLICATION_PROBLEM_XML = 'application/problem+xml'; + public const APPLICATION_PROBLEM_XML = 'application/problem+xml'; - const APPLICATION_RSS_XML = 'application/rss+xml'; + public const APPLICATION_RSS_XML = 'application/rss+xml'; - const APPLICATION_STREAM_JSON = 'application/stream+json'; + public const APPLICATION_STREAM_JSON = 'application/stream+json'; - const APPLICATION_XHTML_XML = 'application/xhtml+xml'; + public const APPLICATION_XHTML_XML = 'application/xhtml+xml'; - const APPLICATION_XML = 'application/xml'; + public const APPLICATION_XML = 'application/xml'; - const IMAGE_JPEG = 'image/jpeg'; + public const IMAGE_JPEG = 'image/jpeg'; - const IMAGE_APNG = 'image/apng'; + public const IMAGE_APNG = 'image/apng'; - const IMAGE_PNG = 'image/png'; + public const IMAGE_PNG = 'image/png'; - const IMAGE_GIF = 'image/gif'; + public const IMAGE_GIF = 'image/gif'; - const IMAGE_WEBP = 'image/webp'; + public const IMAGE_WEBP = 'image/webp'; - const MULTIPART_FORM_DATA = 'multipart/form-data'; + public const MULTIPART_FORM_DATA = 'multipart/form-data'; - const TEXT_EVENT_STREAM = 'text/event-stream'; + public const TEXT_EVENT_STREAM = 'text/event-stream'; - const TEXT_HTML = 'text/html'; + public const TEXT_HTML = 'text/html'; - const TEXT_MARKDOWN = 'text/markdown'; + public const TEXT_MARKDOWN = 'text/markdown'; - const TEXT_PLAIN = 'text/plain'; + public const TEXT_PLAIN = 'text/plain'; - const TEXT_XML = 'text/xml'; + public const TEXT_XML = 'text/xml'; /** * @var array @@ -199,12 +199,10 @@ abstract class MediaType public static function getExt($contentType) { list($firstContentType) = explode(';', $contentType, 2); - if (isset(static::$extMap[$firstContentType])) - { - return static::$extMap[$firstContentType]; + if (isset(self::$extMap[$firstContentType])) { + return self::$extMap[$firstContentType]; } - else - { + else { return null; } } diff --git a/src/YurunHttp/Http/Psr7/Consts/RequestHeader.php b/src/YurunHttp/Http/Psr7/Consts/RequestHeader.php index d70c6d4..4e811bd 100644 --- a/src/YurunHttp/Http/Psr7/Consts/RequestHeader.php +++ b/src/YurunHttp/Http/Psr7/Consts/RequestHeader.php @@ -7,36 +7,36 @@ */ abstract class RequestHeader { - const ACCEPT = 'Accept'; - const ACCEPT_CHARSET = 'Accept-Charset'; - const ACCEPT_ENCODING = 'Accept-Encoding'; - const ACCEPT_LANGUAGE = 'Accept-Language'; - const ACCEPT_DATETIME = 'Accept-Datetime'; - const AUTHORIZATION = 'Authorization'; - const CACHE_CONTROL = 'Cache-Control'; - const CONNECTION = 'Connection'; - const COOKIE = 'Cookie'; - const CONTENT_LENGTH = 'Content-Length'; - const CONTENT_MD5 = 'Content-MD5'; - const CONTENT_TYPE = 'Content-Type'; - const DATE = 'Date'; - const EXPECT = 'Expect'; - const FROM = 'From'; - const HOST = 'Host'; - const IF_MATCH = 'If-Match'; - const IF_MODIFIED_SINCE = 'If-Modified-Since'; - const IF_NONE_MATCH = 'If-None-Match'; - const IF_RANGE = 'If-Range'; - const IF_UNMODIFIED_SINCE = 'If-Unmodified-Since'; - const MAX_FORWARDS = 'Max-Forwards'; - const ORIGIN = 'Origin'; - const PRAGMA = 'Pragma'; - const PROXY_AUTHORIZATION = 'Proxy-Authorization'; - const RANGE = 'Range'; - const REFERER = 'Referer'; - const TE = 'TE'; - const USER_AGENT = 'User-Agent'; - const UPGRADE = 'Upgrade'; - const VIA = 'Via'; - const WARNING = 'Warning'; + public const ACCEPT = 'Accept'; + public const ACCEPT_CHARSET = 'Accept-Charset'; + public const ACCEPT_ENCODING = 'Accept-Encoding'; + public const ACCEPT_LANGUAGE = 'Accept-Language'; + public const ACCEPT_DATETIME = 'Accept-Datetime'; + public const AUTHORIZATION = 'Authorization'; + public const CACHE_CONTROL = 'Cache-Control'; + public const CONNECTION = 'Connection'; + public const COOKIE = 'Cookie'; + public const CONTENT_LENGTH = 'Content-Length'; + public const CONTENT_MD5 = 'Content-MD5'; + public const CONTENT_TYPE = 'Content-Type'; + public const DATE = 'Date'; + public const EXPECT = 'Expect'; + public const FROM = 'From'; + public const HOST = 'Host'; + public const IF_MATCH = 'If-Match'; + public const IF_MODIFIED_SINCE = 'If-Modified-Since'; + public const IF_NONE_MATCH = 'If-None-Match'; + public const IF_RANGE = 'If-Range'; + public const IF_UNMODIFIED_SINCE = 'If-Unmodified-Since'; + public const MAX_FORWARDS = 'Max-Forwards'; + public const ORIGIN = 'Origin'; + public const PRAGMA = 'Pragma'; + public const PROXY_AUTHORIZATION = 'Proxy-Authorization'; + public const RANGE = 'Range'; + public const REFERER = 'Referer'; + public const TE = 'TE'; + public const USER_AGENT = 'User-Agent'; + public const UPGRADE = 'Upgrade'; + public const VIA = 'Via'; + public const WARNING = 'Warning'; } diff --git a/src/YurunHttp/Http/Psr7/Consts/RequestMethod.php b/src/YurunHttp/Http/Psr7/Consts/RequestMethod.php index 7848690..456abb8 100644 --- a/src/YurunHttp/Http/Psr7/Consts/RequestMethod.php +++ b/src/YurunHttp/Http/Psr7/Consts/RequestMethod.php @@ -7,19 +7,19 @@ */ abstract class RequestMethod { - const GET = 'GET'; + public const GET = 'GET'; - const POST = 'POST'; + public const POST = 'POST'; - const HEAD = 'HEAD'; + public const HEAD = 'HEAD'; - const PUT = 'PUT'; + public const PUT = 'PUT'; - const PATCH = 'PATCH'; + public const PATCH = 'PATCH'; - const DELETE = 'DELETE'; + public const DELETE = 'DELETE'; - const OPTIONS = 'OPTIONS'; + public const OPTIONS = 'OPTIONS'; - const TRACE = 'TRACE'; + public const TRACE = 'TRACE'; } diff --git a/src/YurunHttp/Http/Psr7/Consts/ResponseHeader.php b/src/YurunHttp/Http/Psr7/Consts/ResponseHeader.php index 6028d0e..a72101e 100644 --- a/src/YurunHttp/Http/Psr7/Consts/ResponseHeader.php +++ b/src/YurunHttp/Http/Psr7/Consts/ResponseHeader.php @@ -7,41 +7,41 @@ */ abstract class ResponseHeader { - const ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin'; - const ACCEPT_PATCH = 'Accept-Patch'; - const ACCEPT_RANGES = 'Accept-Ranges'; - const AGE = 'Age'; - const ALLOW = 'Allow'; - const CACHE_CONTROL = 'Cache-Control'; - const CONNECTION = 'Connection'; - const CONTENT_DISPOSITION = 'Content-Disposition'; - const CONTENT_ENCODING = 'Content-Encoding'; - const CONTENT_LANGUAGE = 'Content-Language'; - const CONTENT_LENGTH = 'Content-Length'; - const CONTENT_LOCATION = 'Content-Location'; - const CONTENT_MD5 = 'Content-MD5'; - const CONTENT_RANGE = 'Content-Range'; - const CONTENT_TYPE = 'Content-Type'; - const DATE = 'Date'; - const ETAG = 'ETag'; - const EXPIRES = 'Expires'; - const LAST_MODIFIED = 'Last-Modified'; - const LINK = 'Link'; - const LOCATION = 'Location'; - const P3P = 'P3P'; - const PRAGMA = 'Pragma'; - const PROXY_AUTHENTICATE = 'Proxy-Authenticate'; - const PUBLIC_KEY_PINS = 'Public-Key-Pins'; - const REFRESH = 'Refresh'; - const RETRY_AFTER = 'Retry-After'; - const SERVER = 'Server'; - const SET_COOKIE = 'Set-Cookie'; - const STATUS = 'Status'; - const TRAILER = 'Trailer'; - const TRANSFER_ENCODING = 'Transfer-Encoding'; - const UPGRADE = 'Upgrade'; - const VARY = 'Vary'; - const VIA = 'Via'; - const WARNING = 'Warning'; - const WWW_AUTHENTICATE = 'WWW-Authenticate'; + public const ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin'; + public const ACCEPT_PATCH = 'Accept-Patch'; + public const ACCEPT_RANGES = 'Accept-Ranges'; + public const AGE = 'Age'; + public const ALLOW = 'Allow'; + public const CACHE_CONTROL = 'Cache-Control'; + public const CONNECTION = 'Connection'; + public const CONTENT_DISPOSITION = 'Content-Disposition'; + public const CONTENT_ENCODING = 'Content-Encoding'; + public const CONTENT_LANGUAGE = 'Content-Language'; + public const CONTENT_LENGTH = 'Content-Length'; + public const CONTENT_LOCATION = 'Content-Location'; + public const CONTENT_MD5 = 'Content-MD5'; + public const CONTENT_RANGE = 'Content-Range'; + public const CONTENT_TYPE = 'Content-Type'; + public const DATE = 'Date'; + public const ETAG = 'ETag'; + public const EXPIRES = 'Expires'; + public const LAST_MODIFIED = 'Last-Modified'; + public const LINK = 'Link'; + public const LOCATION = 'Location'; + public const P3P = 'P3P'; + public const PRAGMA = 'Pragma'; + public const PROXY_AUTHENTICATE = 'Proxy-Authenticate'; + public const PUBLIC_KEY_PINS = 'Public-Key-Pins'; + public const REFRESH = 'Refresh'; + public const RETRY_AFTER = 'Retry-After'; + public const SERVER = 'Server'; + public const SET_COOKIE = 'Set-Cookie'; + public const STATUS = 'Status'; + public const TRAILER = 'Trailer'; + public const TRANSFER_ENCODING = 'Transfer-Encoding'; + public const UPGRADE = 'Upgrade'; + public const VARY = 'Vary'; + public const VIA = 'Via'; + public const WARNING = 'Warning'; + public const WWW_AUTHENTICATE = 'WWW-Authenticate'; } diff --git a/src/YurunHttp/Http/Psr7/Consts/StatusCode.php b/src/YurunHttp/Http/Psr7/Consts/StatusCode.php index edc177d..7decd5b 100644 --- a/src/YurunHttp/Http/Psr7/Consts/StatusCode.php +++ b/src/YurunHttp/Http/Psr7/Consts/StatusCode.php @@ -4,67 +4,67 @@ abstract class StatusCode { - const _CONTINUE = 100; - const SWITCHING_PROTOCOLS = 101; - const PROCESSING = 102; - const OK = 200; - const CREATED = 201; - const ACCEPTED = 202; - const NON_AUTHORITATIVE_INFORMATION = 203; - const NO_CONTENT = 204; - const RESET_CONTENT = 205; - const PARTIAL_CONTENT = 206; - const MULTI_STATUS = 207; - const ALREADY_REPORTED = 208; - const IM_USED = 226; - const MULTIPLE_CHOICES = 300; - const MOVED_PERMANENTLY = 301; - const FOUND = 302; - const SEE_OTHER = 303; - const NOT_MODIFIED = 304; - const USE_PROXY = 305; - const SWITCH_PROXY = 306; - const TEMPORARY_REDIRECT = 307; - const PERMANENT_REDIRECT = 308; - const BAD_REQUEST = 400; - const UNAUTHORIZED = 401; - const PAYMENT_REQUIRED = 402; - const FORBIDDEN = 403; - const NOT_FOUND = 404; - const METHOD_NOT_ALLOWED = 405; - const NOT_ACCEPTABLE = 406; - const PROXY_AUTHENTICATION_REQUIRED = 407; - const REQUEST_TIME_OUT = 408; - const CONFLICT = 409; - const GONE = 410; - const LENGTH_REQUIRED = 411; - const PRECONDITION_FAILED = 412; - const REQUEST_ENTITY_TOO_LARGE = 413; - const REQUEST_URI_TOO_LARGE = 414; - const UNSUPPORTED_MEDIA_TYPE = 415; - const REQUESTED_RANGE_NOT_SATISFIABLE = 416; - const EXPECTATION_FAILED = 417; - const MISDIRECTED_REQUEST = 421; - const UNPROCESSABLE_ENTITY = 422; - const LOCKED = 423; - const FAILED_DEPENDENCY = 424; - const UNORDERED_COLLECTION = 425; - const UPGRADE_REQUIRED = 426; - const PRECONDITION_REQUIRED = 428; - const TOO_MANY_REQUESTS = 429; - const REQUEST_HEADER_FIELDS_TOO_LARGE = 431; - const UNAVAILABLE_FOR_LEGAL_REASONS = 451; - const INTERNAL_SERVER_ERROR = 500; - const NOT_IMPLEMENTED = 501; - const BAD_GATEWAY = 502; - const SERVICE_UNAVAILABLE = 503; - const GATEWAY_TIME_OUT = 504; - const HTTP_VERSION_NOT_SUPPORTED = 505; - const VARIANT_ALSO_NEGOTIATES = 506; - const INSUFFICIENT_STORAGE = 507; - const LOOP_DETECTED = 508; - const NOT_EXTENDED = 510; - const NETWORK_AUTHENTICATION_REQUIRED = 511; + public const _CONTINUE = 100; + public const SWITCHING_PROTOCOLS = 101; + public const PROCESSING = 102; + public const OK = 200; + public const CREATED = 201; + public const ACCEPTED = 202; + public const NON_AUTHORITATIVE_INFORMATION = 203; + public const NO_CONTENT = 204; + public const RESET_CONTENT = 205; + public const PARTIAL_CONTENT = 206; + public const MULTI_STATUS = 207; + public const ALREADY_REPORTED = 208; + public const IM_USED = 226; + public const MULTIPLE_CHOICES = 300; + public const MOVED_PERMANENTLY = 301; + public const FOUND = 302; + public const SEE_OTHER = 303; + public const NOT_MODIFIED = 304; + public const USE_PROXY = 305; + public const SWITCH_PROXY = 306; + public const TEMPORARY_REDIRECT = 307; + public const PERMANENT_REDIRECT = 308; + public const BAD_REQUEST = 400; + public const UNAUTHORIZED = 401; + public const PAYMENT_REQUIRED = 402; + public const FORBIDDEN = 403; + public const NOT_FOUND = 404; + public const METHOD_NOT_ALLOWED = 405; + public const NOT_ACCEPTABLE = 406; + public const PROXY_AUTHENTICATION_REQUIRED = 407; + public const REQUEST_TIME_OUT = 408; + public const CONFLICT = 409; + public const GONE = 410; + public const LENGTH_REQUIRED = 411; + public const PRECONDITION_FAILED = 412; + public const REQUEST_ENTITY_TOO_LARGE = 413; + public const REQUEST_URI_TOO_LARGE = 414; + public const UNSUPPORTED_MEDIA_TYPE = 415; + public const REQUESTED_RANGE_NOT_SATISFIABLE = 416; + public const EXPECTATION_FAILED = 417; + public const MISDIRECTED_REQUEST = 421; + public const UNPROCESSABLE_ENTITY = 422; + public const LOCKED = 423; + public const FAILED_DEPENDENCY = 424; + public const UNORDERED_COLLECTION = 425; + public const UPGRADE_REQUIRED = 426; + public const PRECONDITION_REQUIRED = 428; + public const TOO_MANY_REQUESTS = 429; + public const REQUEST_HEADER_FIELDS_TOO_LARGE = 431; + public const UNAVAILABLE_FOR_LEGAL_REASONS = 451; + public const INTERNAL_SERVER_ERROR = 500; + public const NOT_IMPLEMENTED = 501; + public const BAD_GATEWAY = 502; + public const SERVICE_UNAVAILABLE = 503; + public const GATEWAY_TIME_OUT = 504; + public const HTTP_VERSION_NOT_SUPPORTED = 505; + public const VARIANT_ALSO_NEGOTIATES = 506; + public const INSUFFICIENT_STORAGE = 507; + public const LOOP_DETECTED = 508; + public const NOT_EXTENDED = 510; + public const NETWORK_AUTHENTICATION_REQUIRED = 511; /** * @var array diff --git a/src/YurunHttp/Http/Psr7/Request.php b/src/YurunHttp/Http/Psr7/Request.php index 1e4447c..68bd4c9 100644 --- a/src/YurunHttp/Http/Psr7/Request.php +++ b/src/YurunHttp/Http/Psr7/Request.php @@ -41,12 +41,10 @@ class Request extends AbstractMessage implements RequestInterface public function __construct($uri = null, array $headers = [], $body = '', $method = RequestMethod::GET, $version = '1.1') { parent::__construct($body); - if (!$uri instanceof UriInterface) - { + if (!$uri instanceof UriInterface) { $this->uri = new Uri($uri); } - elseif (null !== $uri) - { + elseif (null !== $uri) { $this->uri = $uri; } $this->setHeaders($headers); @@ -70,7 +68,7 @@ public function __construct($uri = null, array $headers = [], $body = '', $metho * * @return string */ - public function getRequestTarget() + public function getRequestTarget(): string { return null === $this->requestTarget ? (string) $this->uri : $this->requestTarget; } @@ -94,7 +92,7 @@ public function getRequestTarget() * * @return static */ - public function withRequestTarget($requestTarget) + public function withRequestTarget($requestTarget): RequestInterface { $self = clone $this; $self->requestTarget = $requestTarget; @@ -107,7 +105,7 @@ public function withRequestTarget($requestTarget) * * @return string returns the request method */ - public function getMethod() + public function getMethod(): string { return $this->method; } @@ -129,7 +127,7 @@ public function getMethod() * * @throws \InvalidArgumentException for invalid HTTP methods */ - public function withMethod($method) + public function withMethod($method): RequestInterface { $self = clone $this; $self->method = $method; @@ -147,7 +145,7 @@ public function withMethod($method) * @return UriInterface returns a UriInterface instance * representing the URI of the request */ - public function getUri() + public function getUri(): UriInterface { return $this->uri; } @@ -184,12 +182,11 @@ public function getUri() * * @return static */ - public function withUri(UriInterface $uri, $preserveHost = false) + public function withUri(UriInterface $uri, $preserveHost = false): RequestInterface { $self = clone $this; $self->uri = $uri; - if (!$preserveHost) - { + if (!$preserveHost) { $self->headers = []; $self->headerNames = []; } diff --git a/src/YurunHttp/Http/Psr7/Response.php b/src/YurunHttp/Http/Psr7/Response.php index 146fe31..ea60075 100644 --- a/src/YurunHttp/Http/Psr7/Response.php +++ b/src/YurunHttp/Http/Psr7/Response.php @@ -41,7 +41,7 @@ public function __construct($body = '', $statusCode = StatusCode::OK, $reasonPhr * * @return int status code */ - public function getStatusCode() + public function getStatusCode(): int { return $this->statusCode; } @@ -69,16 +69,14 @@ public function getStatusCode() * * @throws \InvalidArgumentException for invalid status code arguments */ - public function withStatus($code, $reasonPhrase = '') + public function withStatus($code, $reasonPhrase = ''): ResponseInterface { $self = clone $this; $self->statusCode = $code; - if ('' === $reasonPhrase) - { + if ('' === $reasonPhrase) { $self->reasonPhrase = StatusCode::getReasonPhrase($code); } - else - { + else { $self->reasonPhrase = $reasonPhrase; } @@ -99,7 +97,7 @@ public function withStatus($code, $reasonPhrase = '') * * @return string reason phrase; must return an empty string if none present */ - public function getReasonPhrase() + public function getReasonPhrase(): string { return $this->reasonPhrase; } diff --git a/src/YurunHttp/Http/Psr7/ServerRequest.php b/src/YurunHttp/Http/Psr7/ServerRequest.php index 1f06fe5..3715995 100644 --- a/src/YurunHttp/Http/Psr7/ServerRequest.php +++ b/src/YurunHttp/Http/Psr7/ServerRequest.php @@ -87,7 +87,7 @@ public function __construct($uri = null, array $headers = [], $body = '', $metho * * @return array */ - public function getServerParams() + public function getServerParams(): array { return $this->server; } @@ -100,7 +100,7 @@ public function getServerParams() * * @return string */ - public function getServerParam($name, $default = null) + public function getServerParam($name, $default = null): string { return isset($this->server[$name]) ? $this->server[$name] : $default; } @@ -115,7 +115,7 @@ public function getServerParam($name, $default = null) * * @return array */ - public function getCookieParams() + public function getCookieParams(): array { return $this->cookies; } @@ -138,7 +138,7 @@ public function getCookieParams() * * @return static */ - public function withCookieParams(array $cookies) + public function withCookieParams(array $cookies): self { $self = clone $this; $self->cookies = $cookies; @@ -151,10 +151,8 @@ public function withCookieParams(array $cookies) * * @param string $name * @param mixed $default - * - * @return mixed */ - public function getCookie($name, $default = null) + public function getCookie(string $name, $default = null): string { return isset($this->cookies[$name]) ? $this->cookies[$name] : $default; } @@ -171,7 +169,7 @@ public function getCookie($name, $default = null) * * @return array */ - public function getQueryParams() + public function getQueryParams(): array { return $this->get; } @@ -199,7 +197,7 @@ public function getQueryParams() * * @return static */ - public function withQueryParams(array $query) + public function withQueryParams(array $query): ServerRequestInterface { $self = clone $this; $self->get = $query; @@ -219,7 +217,7 @@ public function withQueryParams(array $query) * @return UploadedFile[] an array tree of UploadedFileInterface instances; an empty * array MUST be returned if no data is present */ - public function getUploadedFiles() + public function getUploadedFiles(): array { return $this->files; } @@ -237,7 +235,7 @@ public function getUploadedFiles() * * @throws \InvalidArgumentException if an invalid structure is provided */ - public function withUploadedFiles(array $uploadedFiles) + public function withUploadedFiles(array $uploadedFiles): ServerRequestInterface { $self = clone $this; @@ -262,24 +260,21 @@ public function withUploadedFiles(array $uploadedFiles) public function getParsedBody() { $parsedBody = &$this->parsedBody; - if (null === $parsedBody) - { + if (null === $parsedBody) { $body = $this->body; $contentType = strtolower($this->getHeaderLine(RequestHeader::CONTENT_TYPE)); // post if ('POST' === $this->method && \in_array($contentType, [ MediaType::APPLICATION_FORM_URLENCODED, MediaType::MULTIPART_FORM_DATA, - ])) - { + ])) { $parsedBody = $this->post; } // json elseif (\in_array($contentType, [ MediaType::APPLICATION_JSON, MediaType::APPLICATION_JSON_UTF8, - ])) - { + ])) { $parsedBody = json_decode($body, true); } // xml @@ -289,14 +284,12 @@ public function getParsedBody() MediaType::APPLICATION_RSS_XML, MediaType::APPLICATION_XHTML_XML, MediaType::APPLICATION_XML, - ])) - { + ])) { $parsedBody = new \DOMDocument(); $parsedBody->loadXML($body); } // 其它 - else - { + else { $parsedBody = (object) (string) $body; } } @@ -334,7 +327,7 @@ public function getParsedBody() * @throws \InvalidArgumentException if an unsupported argument type is * provided */ - public function withParsedBody($data) + public function withParsedBody($data): ServerRequestInterface { $self = clone $this; $self->parsedBody = $data; @@ -353,7 +346,7 @@ public function withParsedBody($data) * * @return array attributes derived from the request */ - public function getAttributes() + public function getAttributes(): array { return $this->attributes; } @@ -378,12 +371,10 @@ public function getAttributes() public function getAttribute($name, $default = null) { $attributes = $this->attributes; - if (\array_key_exists($name, $attributes)) - { + if (\array_key_exists($name, $attributes)) { return $attributes[$name]; } - else - { + else { return YurunHttp::getAttribute($name, $default); } } @@ -405,7 +396,7 @@ public function getAttribute($name, $default = null) * * @return static */ - public function withAttribute($name, $value) + public function withAttribute($name, $value): ServerRequestInterface { $self = clone $this; $self->attributes[$name] = $value; @@ -429,11 +420,10 @@ public function withAttribute($name, $value) * * @return static */ - public function withoutAttribute($name) + public function withoutAttribute($name): ServerRequestInterface { $self = clone $this; - if (\array_key_exists($name, $self->attributes)) - { + if (\array_key_exists($name, $self->attributes)) { unset($self->attributes[$name]); } @@ -451,14 +441,11 @@ public function withoutAttribute($name) protected function setUploadedFiles(self $object, array $files) { $object->files = []; - foreach ($files as $name => $file) - { - if ($file instanceof UploadedFile) - { + foreach ($files as $name => $file) { + if ($file instanceof UploadedFile) { $object->files[$name] = $file; } - else - { + else { $object->files[$name] = new UploadedFile($file['name'], $file['type'], $file['tmp_name'], $file['size'], $file['error']); } } diff --git a/src/YurunHttp/Http/Psr7/UploadedFile.php b/src/YurunHttp/Http/Psr7/UploadedFile.php index c4e7d58..947d8c1 100644 --- a/src/YurunHttp/Http/Psr7/UploadedFile.php +++ b/src/YurunHttp/Http/Psr7/UploadedFile.php @@ -69,12 +69,10 @@ public function __construct($fileName, $mediaType, $tmpFileName, $size = null, $ $this->fileName = $fileName; $this->mediaType = $mediaType; $this->tmpFileName = $tmpFileName; - if (null === $size) - { + if (null === $size) { $this->size = filesize($tmpFileName); } - else - { + else { $this->size = $size; } $this->error = $error; @@ -97,10 +95,9 @@ public function __construct($fileName, $mediaType, $tmpFileName, $size = null, $ * @throws \RuntimeException in cases when no stream is available or can be * created */ - public function getStream() + public function getStream(): StreamInterface { - if (null === $this->stream) - { + if (null === $this->stream) { $this->stream = new FileStream($this->tmpFileName); } @@ -143,26 +140,21 @@ public function getStream() * @throws \RuntimeException on any error during the move operation, or on * the second or subsequent call to the method */ - public function moveTo($targetPath) + public function moveTo($targetPath): void { - if (!\is_string($targetPath)) - { + if (!\is_string($targetPath)) { throw new \InvalidArgumentException('targetPath specified is invalid'); } - if ($this->isMoved) - { + if ($this->isMoved) { throw new \RuntimeException('file can not be moved'); } - if (is_uploaded_file($this->tmpFileName)) - { + if (is_uploaded_file($this->tmpFileName)) { $this->isMoved = move_uploaded_file($this->tmpFileName, $targetPath); } - else - { + else { $this->isMoved = rename($this->tmpFileName, $targetPath); } - if (!$this->isMoved) - { + if (!$this->isMoved) { throw new \RuntimeException(sprintf('file %s move to %s fail', $this->tmpFileName, $targetPath)); } } @@ -176,7 +168,7 @@ public function moveTo($targetPath) * * @return int|null the file size in bytes or null if unknown */ - public function getSize() + public function getSize(): ?int { return $this->size; } @@ -196,7 +188,7 @@ public function getSize() * * @return int one of PHP's UPLOAD_ERR_XXX constants */ - public function getError() + public function getError(): int { return $this->error; } @@ -214,7 +206,7 @@ public function getError() * @return string|null the filename sent by the client or null if none * was provided */ - public function getClientFilename() + public function getClientFilename(): ?string { return $this->fileName; } @@ -232,7 +224,7 @@ public function getClientFilename() * @return string|null the media type sent by the client or null if none * was provided */ - public function getClientMediaType() + public function getClientMediaType(): ?string { return $this->mediaType; } @@ -242,7 +234,7 @@ public function getClientMediaType() * * @return string */ - public function getTempFileName() + public function getTempFileName(): string { return $this->tmpFileName; } diff --git a/src/YurunHttp/Http/Psr7/Uri.php b/src/YurunHttp/Http/Psr7/Uri.php index b2711e9..692e770 100644 --- a/src/YurunHttp/Http/Psr7/Uri.php +++ b/src/YurunHttp/Http/Psr7/Uri.php @@ -73,16 +73,14 @@ class Uri implements UriInterface public function __construct($uri = '') { $uriOption = parse_url($uri); - if (false === $uriOption) - { + if (false === $uriOption) { throw new \InvalidArgumentException(sprintf('uri %s parse error', $uri)); } $this->scheme = isset($uriOption['scheme']) ? $uriOption['scheme'] : ''; $this->host = isset($uriOption['host']) ? $uriOption['host'] : ''; $this->port = isset($uriOption['port']) ? $uriOption['port'] : null; $this->userInfo = isset($uriOption['user']) ? $uriOption['user'] : ''; - if (isset($uriOption['pass'])) - { + if (isset($uriOption['pass'])) { $this->userInfo .= ':' . $uriOption['pass']; } $this->path = isset($uriOption['path']) ? $uriOption['path'] : ''; @@ -107,13 +105,11 @@ public static function makeUriString($host, $path, $query = '', $port = null, $s { $uri = ''; // 协议 - if ('' !== $scheme) - { + if ('' !== $scheme) { $uri = $scheme . '://'; } // 用户信息 - if ('' !== $userInfo) - { + if ('' !== $userInfo) { $uri .= $userInfo . '@'; } // 主机+端口 @@ -156,8 +152,7 @@ public static function makeUri($host, $path, $query = '', $port = 80, $scheme = public static function getServerPort(UriInterface $uri) { $port = $uri->getPort(); - if (!$port) - { + if (!$port) { $scheme = $uri->getScheme(); $port = isset(static::$schemePorts[$scheme]) ? static::$schemePorts[$scheme] : null; } @@ -176,8 +171,7 @@ public static function getServerPort(UriInterface $uri) public static function getDomain(UriInterface $uri) { $result = $uri->getHost(); - if (null !== ($port = $uri->getPort())) - { + if (null !== ($port = $uri->getPort())) { $result .= ':' . $port; } @@ -199,7 +193,7 @@ public static function getDomain(UriInterface $uri) * * @return string the URI scheme */ - public function getScheme() + public function getScheme(): string { return $this->scheme; } @@ -223,15 +217,13 @@ public function getScheme() * * @return string the URI authority, in "[user-info@]host[:port]" format */ - public function getAuthority() + public function getAuthority(): string { $result = $this->host; - if ('' !== $this->userInfo) - { + if ('' !== $this->userInfo) { $result = $this->userInfo . '@' . $result; } - if (null !== $this->port) - { + if (null !== $this->port) { $result .= ':' . $this->port; } @@ -253,7 +245,7 @@ public function getAuthority() * * @return string the URI user information, in "username[:password]" format */ - public function getUserInfo() + public function getUserInfo(): string { return $this->userInfo; } @@ -270,7 +262,7 @@ public function getUserInfo() * * @return string the URI host */ - public function getHost() + public function getHost(): string { return $this->host; } @@ -290,7 +282,7 @@ public function getHost() * * @return int|null the URI port */ - public function getPort() + public function getPort(): ?int { return $this->port; } @@ -321,7 +313,7 @@ public function getPort() * * @return string the URI path */ - public function getPath() + public function getPath(): string { return $this->path; } @@ -347,7 +339,7 @@ public function getPath() * * @return string the URI query string */ - public function getQuery() + public function getQuery(): string { return $this->query; } @@ -369,7 +361,7 @@ public function getQuery() * * @return string the URI fragment */ - public function getFragment() + public function getFragment(): string { return $this->fragment; } @@ -391,10 +383,9 @@ public function getFragment() * * @throws \InvalidArgumentException for invalid or unsupported schemes */ - public function withScheme($scheme) + public function withScheme($scheme): UriInterface { - if (!\is_string($scheme)) - { + if (!\is_string($scheme)) { throw new \InvalidArgumentException('invalid or unsupported schemes'); } $self = clone $this; @@ -418,12 +409,11 @@ public function withScheme($scheme) * * @return static a new instance with the specified user information */ - public function withUserInfo($user, $password = null) + public function withUserInfo($user, $password = null): UriInterface { $self = clone $this; $self->userInfo = $user; - if (null !== $password) - { + if (null !== $password) { $self->userInfo .= ':' . $password; } @@ -444,7 +434,7 @@ public function withUserInfo($user, $password = null) * * @throws \InvalidArgumentException for invalid hostnames */ - public function withHost($host) + public function withHost($host): UriInterface { $self = clone $this; $self->host = $host; @@ -471,7 +461,7 @@ public function withHost($host) * * @throws \InvalidArgumentException for invalid ports */ - public function withPort($port) + public function withPort($port): UriInterface { $self = clone $this; $self->port = $port; @@ -503,7 +493,7 @@ public function withPort($port) * * @throws \InvalidArgumentException for invalid paths */ - public function withPath($path) + public function withPath($path): UriInterface { $self = clone $this; $self->path = $path; @@ -528,7 +518,7 @@ public function withPath($path) * * @throws \InvalidArgumentException for invalid query strings */ - public function withQuery($query) + public function withQuery($query): UriInterface { $self = clone $this; $self->query = $query; @@ -551,7 +541,7 @@ public function withQuery($query) * * @return static a new instance with the specified fragment */ - public function withFragment($fragment) + public function withFragment($fragment): UriInterface { $self = clone $this; $self->fragment = $fragment; @@ -583,7 +573,7 @@ public function withFragment($fragment) * * @return string */ - public function __toString() + public function __toString(): string { return static::makeUriString($this->host, $this->path, $this->query, $this->port, $this->scheme, $this->fragment, $this->userInfo); } diff --git a/src/YurunHttp/Http/Response.php b/src/YurunHttp/Http/Response.php index f2b6835..705ae2f 100644 --- a/src/YurunHttp/Http/Response.php +++ b/src/YurunHttp/Http/Response.php @@ -110,8 +110,7 @@ public function withCookieOriginParams(array $cookiesOrigin) $self = clone $this; $self->cookiesOrigin = $cookiesOrigin; $self->cookies = []; - foreach ($cookiesOrigin as $name => $value) - { + foreach ($cookiesOrigin as $name => $value) { $self->cookies[$name] = $value['value']; } @@ -162,12 +161,10 @@ public function __construct($body = '', $statusCode = StatusCode::OK, $reasonPhr */ public function body($fromEncoding = null, $toEncoding = 'UTF-8') { - if (null === $fromEncoding) - { + if (null === $fromEncoding) { return (string) $this->getBody(); } - else - { + else { return mb_convert_encoding((string) $this->getBody(), $toEncoding, $fromEncoding); } } @@ -184,8 +181,7 @@ public function body($fromEncoding = null, $toEncoding = 'UTF-8') public function xml($assoc = false, $fromEncoding = null, $toEncoding = 'UTF-8') { $xml = simplexml_load_string($this->body($fromEncoding, $toEncoding), 'SimpleXMLElement', \LIBXML_NOCDATA | \LIBXML_COMPACT); - if ($assoc) - { + if ($assoc) { $xml = (array) $xml; } @@ -218,14 +214,11 @@ public function json($assoc = false, $fromEncoding = null, $toEncoding = 'UTF-8' public function jsonp($assoc = false, $fromEncoding = null, $toEncoding = 'UTF-8') { $jsonp = trim($this->body($fromEncoding, $toEncoding)); - if (isset($jsonp[0]) && '[' !== $jsonp[0] && '{' !== $jsonp[0]) - { + if (isset($jsonp[0]) && '[' !== $jsonp[0] && '{' !== $jsonp[0]) { $begin = strpos($jsonp, '('); - if (false !== $begin) - { + if (false !== $begin) { $end = strrpos($jsonp, ')'); - if (false !== $end) - { + if (false !== $end) { $jsonp = substr($jsonp, $begin + 1, $end - $begin - 1); } } diff --git a/src/YurunHttp/Http2/SwooleClient.php b/src/YurunHttp/Http2/SwooleClient.php index 8226e70..f3e3f21 100644 --- a/src/YurunHttp/Http2/SwooleClient.php +++ b/src/YurunHttp/Http2/SwooleClient.php @@ -90,12 +90,10 @@ public function __construct($host, $port, $ssl, $handler = null) $this->host = $host; $this->port = $port; $this->ssl = $ssl; - if ($handler) - { + if ($handler) { $this->handler = $handler; } - else - { + else { $this->handler = new \Yurun\Util\YurunHttp\Handler\Swoole(); } } @@ -109,11 +107,9 @@ public function connect() { $url = ($this->ssl ? 'https://' : 'http://') . $this->host . ':' . $this->port; $client = $this->handler->getHttp2ConnectionManager()->getConnection($url); - if ($client) - { + if ($client) { $this->http2Client = $client; - if ($this->timeout) - { + if ($this->timeout) { $client->set([ 'timeout' => $this->timeout, ]); @@ -121,8 +117,7 @@ public function connect() return true; } - else - { + else { return false; } } @@ -146,8 +141,7 @@ public function close() { $this->recvCo = false; $recvChannels = &$this->recvChannels; - foreach ($recvChannels as $channel) - { + foreach ($recvChannels as $channel) { $channel->close(); } $recvChannels = []; @@ -170,29 +164,24 @@ public function close() */ public function send($request, $pipeline = false, $dropRecvResponse = false) { - if ('2.0' !== $request->getProtocolVersion()) - { + if ('2.0' !== $request->getProtocolVersion()) { $request = $request->withProtocolVersion('2.0'); } $uri = $request->getUri(); - if ($this->host != $uri->getHost() || $this->port != Uri::getServerPort($uri) || $this->ssl != ('https' === $uri->getScheme() || 'wss' === $uri->getScheme())) - { + if ($this->host != $uri->getHost() || $this->port != Uri::getServerPort($uri) || $this->ssl != ('https' === $uri->getScheme() || 'wss' === $uri->getScheme())) { throw new \RuntimeException(sprintf('Current http2 connection instance just support %s://%s:%s, does not support %s', $this->ssl ? 'https' : 'http', $this->host, $this->port, $uri->__toString())); } $http2Client = $this->http2Client; $request = $request->withAttribute(Attributes::HTTP2_PIPELINE, $pipeline); $this->handler->buildRequest($request, $http2Client, $http2Request); $streamId = $http2Client->send($http2Request); - if ($streamId) - { - if (!$dropRecvResponse) - { + if ($streamId) { + if (!$dropRecvResponse) { $this->recvChannels[$streamId] = new Channel(1); $this->requestMap[$streamId] = $request; } } - else - { + else { $this->close(); } @@ -236,34 +225,27 @@ public function end($streamId) public function recv($streamId = -1, $timeout = null) { $recvCo = $this->recvCo; - if (!$recvCo || !Coroutine::exists($recvCo)) - { + if (!$recvCo || !Coroutine::exists($recvCo)) { $this->startRecvCo(); } $recvChannels = &$this->recvChannels; - if (isset($recvChannels[$streamId])) - { + if (isset($recvChannels[$streamId])) { $channel = $recvChannels[$streamId]; } - else - { + else { $recvChannels[$streamId] = $channel = new Channel(-1 === $streamId ? $this->serverPushQueueLength : 1); } $requestMap = &$this->requestMap; - if (isset($requestMap[$streamId])) - { + if (isset($requestMap[$streamId])) { $request = $requestMap[$streamId]; unset($requestMap[$streamId]); } - else - { + else { $request = null; } $swooleResponse = $channel->pop(null === $timeout ? -1 : $timeout); - if ($this->recvCo === $recvCo) - { - if (-1 !== $streamId) - { + if ($this->recvCo === $recvCo) { + if (-1 !== $streamId) { unset($recvChannels[$streamId]); $channel->close(); } @@ -291,8 +273,7 @@ public function isConnected() */ private function startRecvCo() { - if (!$this->isConnected()) - { + if (!$this->isConnected()) { return false; } @@ -300,24 +281,18 @@ private function startRecvCo() $this->recvCo = $coid = Coroutine::getCid(); $http2Client = &$this->http2Client; $recvChannels = &$this->recvChannels; - while ($coid === $this->recvCo && $this->isConnected()) - { - if ($this->timeout > 0) - { + while ($coid === $this->recvCo && $this->isConnected()) { + if ($this->timeout > 0) { $swooleResponse = $http2Client->recv($this->timeout); } - else - { + else { $swooleResponse = $http2Client->recv(); } - if ($coid !== $this->recvCo) - { + if ($coid !== $this->recvCo) { return; } - if (!$swooleResponse) - { - if ($this->ping()) - { + if (!$swooleResponse) { + if ($this->ping()) { continue; } $this->close(); @@ -325,8 +300,7 @@ private function startRecvCo() return; } $streamId = $swooleResponse->streamId; - if (isset($recvChannels[$streamId]) || (0 === ($streamId & 1) && isset($recvChannels[$streamId = -1]))) - { + if (isset($recvChannels[$streamId]) || (0 === ($streamId & 1) && isset($recvChannels[$streamId = -1]))) { $recvChannels[$streamId]->push($swooleResponse); } } @@ -408,8 +382,7 @@ public function setTimeout($timeout) { $this->timeout = $timeout; $http2Client = $this->http2Client; - if ($http2Client) - { + if ($http2Client) { $http2Client->set([ 'timeout' => $timeout, ]); diff --git a/src/YurunHttp/Pool/Traits/TConnectionPoolConfigs.php b/src/YurunHttp/Pool/Traits/TConnectionPoolConfigs.php index df8acba..dada6a3 100644 --- a/src/YurunHttp/Pool/Traits/TConnectionPoolConfigs.php +++ b/src/YurunHttp/Pool/Traits/TConnectionPoolConfigs.php @@ -24,16 +24,14 @@ trait TConnectionPoolConfigs */ public function setConfig($url, $maxConnections = 0, $waitTimeout = 30) { - if (isset($this->connectionPoolConfigs[$url])) - { + if (isset($this->connectionPoolConfigs[$url])) { $config = $this->connectionPoolConfigs[$url]; $config->setMaxConnections($maxConnections); $config->setWaitTimeout($waitTimeout); return $config; } - else - { + else { return $this->connectionPoolConfigs[$url] = new PoolConfig($url, $maxConnections, $waitTimeout); } } @@ -47,12 +45,10 @@ public function setConfig($url, $maxConnections = 0, $waitTimeout = 30) */ public function getConfig($url) { - if (isset($this->connectionPoolConfigs[$url])) - { + if (isset($this->connectionPoolConfigs[$url])) { return $this->connectionPoolConfigs[$url]; } - else - { + else { return null; } } diff --git a/src/YurunHttp/Random.php b/src/YurunHttp/Random.php index 9caf1ee..ee056fa 100644 --- a/src/YurunHttp/Random.php +++ b/src/YurunHttp/Random.php @@ -45,8 +45,7 @@ public static function text($chars, $min, $max) $length = mt_rand($min, $max); $charLength = mb_strlen($chars); $result = ''; - for ($i = 0; $i < $length; ++$i) - { + for ($i = 0; $i < $length; ++$i) { $result .= mb_substr($chars, mt_rand(1, $charLength) - 1, 1); } diff --git a/src/YurunHttp/Stream/FileStream.php b/src/YurunHttp/Stream/FileStream.php index 9c47481..0be6f8c 100644 --- a/src/YurunHttp/Stream/FileStream.php +++ b/src/YurunHttp/Stream/FileStream.php @@ -35,22 +35,18 @@ class FileStream implements StreamInterface */ public function __construct($uri, $mode = StreamMode::READ_WRITE) { - if (\is_string($uri)) - { + if (\is_string($uri)) { $this->uri = $uri = new Uri($uri); } - elseif ($uri instanceof UriInterface) - { + elseif ($uri instanceof UriInterface) { $this->uri = $uri; } - else - { + else { $uri = $this->uri; } $this->mode = $mode; $stream = fopen($uri, $mode); - if (false === $stream) - { + if (false === $stream) { throw new \RuntimeException(sprintf('Open stream %s error', (string) $uri)); } $this->stream = $stream; @@ -58,8 +54,7 @@ public function __construct($uri, $mode = StreamMode::READ_WRITE) public function __destruct() { - if ($this->stream) - { + if ($this->stream) { $this->close(); } } @@ -79,16 +74,14 @@ public function __destruct() * * @return string */ - public function __toString() + public function __toString(): string { - try - { + try { $this->rewind(); return stream_get_contents($this->stream); } - catch (\Throwable $ex) - { + catch (\Throwable $ex) { return ''; } } @@ -98,7 +91,7 @@ public function __toString() * * @return void */ - public function close() + public function close(): void { fclose($this->stream); $this->stream = null; @@ -124,11 +117,10 @@ public function detach() * * @return int|null returns the size in bytes if known, or null if unknown */ - public function getSize() + public function getSize(): ?int { $stat = fstat($this->stream); - if (false === $stat) - { + if (false === $stat) { throw new \RuntimeException('get stream size error'); } @@ -142,11 +134,10 @@ public function getSize() * * @throws \RuntimeException on error */ - public function tell() + public function tell(): int { $result = ftell($this->stream); - if (false === $result) - { + if (false === $result) { throw new \RuntimeException('stream tell error'); } @@ -158,7 +149,7 @@ public function tell() * * @return bool */ - public function eof() + public function eof(): bool { return feof($this->stream); } @@ -168,7 +159,7 @@ public function eof() * * @return bool */ - public function isSeekable() + public function isSeekable(): bool { return (bool) $this->getMetadata('seekable'); } @@ -189,10 +180,9 @@ public function isSeekable() * * @throws \RuntimeException on failure */ - public function seek($offset, $whence = \SEEK_SET) + public function seek($offset, $whence = \SEEK_SET): void { - if (-1 === fseek($this->stream, $offset, $whence)) - { + if (-1 === fseek($this->stream, $offset, $whence)) { throw new \RuntimeException('seek stream error'); } } @@ -210,10 +200,9 @@ public function seek($offset, $whence = \SEEK_SET) * * @throws \RuntimeException on failure */ - public function rewind() + public function rewind(): void { - if (!rewind($this->stream)) - { + if (!rewind($this->stream)) { throw new \RuntimeException('rewind stream failed'); } } @@ -223,7 +212,7 @@ public function rewind() * * @return bool */ - public function isWritable() + public function isWritable(): bool { return \in_array($this->mode, [ StreamMode::WRITE_CLEAN, @@ -245,11 +234,10 @@ public function isWritable() * * @throws \RuntimeException on failure */ - public function write($string) + public function write($string): int { $result = fwrite($this->stream, $string); - if (false === $result) - { + if (false === $result) { throw new \RuntimeException('write stream failed'); } @@ -261,7 +249,7 @@ public function write($string) * * @return bool */ - public function isReadable() + public function isReadable(): bool { return \in_array($this->mode, [ StreamMode::READ_WRITE, @@ -284,11 +272,10 @@ public function isReadable() * * @throws \RuntimeException if an error occurs */ - public function read($length) + public function read($length): string { $result = fread($this->stream, $length); - if (false === $result) - { + if (false === $result) { throw new \RuntimeException('read stream error'); } @@ -303,11 +290,10 @@ public function read($length) * @throws \RuntimeException if unable to read or an error occurs while * reading */ - public function getContents() + public function getContents(): string { $result = stream_get_contents($this->stream); - if (false === $result) - { + if (false === $result) { throw new \RuntimeException('stream getContents error'); } @@ -332,20 +318,16 @@ public function getMetadata($key = null) { $result = stream_get_meta_data($this->stream); /* @phpstan-ignore-next-line */ - if (!$result) - { + if (!$result) { throw new \RuntimeException('stream getMetadata error'); } - if (null === $key) - { + if (null === $key) { return $result; } - elseif (isset($result[$key])) - { + elseif (isset($result[$key])) { return $result[$key]; } - else - { + else { return null; } } @@ -355,7 +337,7 @@ public function getMetadata($key = null) * * @return UriInterface */ - public function getUri() + public function getUri(): UriInterface { return $this->uri; } diff --git a/src/YurunHttp/Stream/MemoryStream.php b/src/YurunHttp/Stream/MemoryStream.php index 22b2fd6..845993d 100644 --- a/src/YurunHttp/Stream/MemoryStream.php +++ b/src/YurunHttp/Stream/MemoryStream.php @@ -61,7 +61,7 @@ public function __toString() * * @return void */ - public function close() + public function close(): void { $this->content = ''; $this->size = -1; @@ -84,7 +84,7 @@ public function detach() * * @return int|null returns the size in bytes if known, or null if unknown */ - public function getSize() + public function getSize(): ?int { return $this->size; } @@ -96,7 +96,7 @@ public function getSize() * * @throws \RuntimeException on error */ - public function tell() + public function tell(): int { return $this->position; } @@ -106,7 +106,7 @@ public function tell() * * @return bool */ - public function eof() + public function eof(): bool { return $this->position > $this->size; } @@ -116,7 +116,7 @@ public function eof() * * @return bool */ - public function isSeekable() + public function isSeekable(): bool { return true; } @@ -137,13 +137,11 @@ public function isSeekable() * * @throws \RuntimeException on failure */ - public function seek($offset, $whence = \SEEK_SET) + public function seek(int $offset, int $whence = \SEEK_SET): void { - switch ($whence) - { + switch ($whence) { case \SEEK_SET: - if ($offset < 0) - { + if ($offset < 0) { throw new \RuntimeException('offset failure'); } $this->position = $offset; @@ -170,7 +168,7 @@ public function seek($offset, $whence = \SEEK_SET) * * @throws \RuntimeException on failure */ - public function rewind() + public function rewind(): void { $this->position = 0; } @@ -180,7 +178,7 @@ public function rewind() * * @return bool */ - public function isWritable() + public function isWritable(): bool { return true; } @@ -194,7 +192,7 @@ public function isWritable() * * @throws \RuntimeException on failure */ - public function write($string) + public function write($string): int { $content = &$this->content; $position = &$this->position; @@ -211,7 +209,7 @@ public function write($string) * * @return bool */ - public function isReadable() + public function isReadable(): bool { return true; } @@ -228,7 +226,7 @@ public function isReadable() * * @throws \RuntimeException if an error occurs */ - public function read($length) + public function read(int $length): string { $position = &$this->position; $result = substr($this->content, $position, $length); @@ -245,17 +243,15 @@ public function read($length) * @throws \RuntimeException if unable to read or an error occurs while * reading */ - public function getContents() + public function getContents(): string { $position = &$this->position; - if (0 === $position) - { + if (0 === $position) { $position = $this->size; return $this->content; } - else - { + else { return $this->read($this->size - $position); } } @@ -268,13 +264,13 @@ public function getContents() * * @see http://php.net/manual/en/function.stream-get-meta-data.php * - * @param string $key specific metadata to retrieve + * @param string|null $key specific metadata to retrieve * * @return array|mixed|null Returns an associative array if no key is * provided. Returns a specific key value if a key is provided and the * value is found, or null if the key is not found. */ - public function getMetadata($key = null) + public function getMetadata(string $key = null) { return null; } diff --git a/src/YurunHttp/Stream/StreamMode.php b/src/YurunHttp/Stream/StreamMode.php index 05c997b..3e77695 100644 --- a/src/YurunHttp/Stream/StreamMode.php +++ b/src/YurunHttp/Stream/StreamMode.php @@ -10,44 +10,44 @@ abstract class StreamMode /** * 只读方式打开,指针指向开头. */ - const READONLY = 'r'; + public const READONLY = 'r'; /** * 读写方式打开,指针指向开头. */ - const READ_WRITE = 'r+'; + public const READ_WRITE = 'r+'; /** * 写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。 */ - const WRITE_CLEAN = 'w'; + public const WRITE_CLEAN = 'w'; /** * 读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。 */ - const READ_WRITE_CLEAN = 'w+'; + public const READ_WRITE_CLEAN = 'w+'; /** * 写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。 */ - const WRITE_END = 'a'; + public const WRITE_END = 'a'; /** * 读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。 */ - const READ_WRITE_END = 'a+'; + public const READ_WRITE_END = 'a+'; /** * 创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。 * 这和给底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。 * 仅能用于本地文件。 */ - const CREATE_WRITE = 'x'; + public const CREATE_WRITE = 'x'; /** * 创建并以读写方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。 * 这和给底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。 * 仅能用于本地文件。 */ - const CREATE_READ_WRITE = 'x+'; + public const CREATE_READ_WRITE = 'x+'; } diff --git a/src/YurunHttp/Traits/TCookieManager.php b/src/YurunHttp/Traits/TCookieManager.php index 319fe9c..1d5c0f4 100644 --- a/src/YurunHttp/Traits/TCookieManager.php +++ b/src/YurunHttp/Traits/TCookieManager.php @@ -28,8 +28,7 @@ trait TCookieManager private function initCookieManager() { $this->cookieJar = $cookieJar = new CookieJar($this->cookieManager = new CookieManager()); - if (isset($this->options[HandlerOptions::COOKIE_JAR]) && \is_string($this->options[HandlerOptions::COOKIE_JAR])) - { + if (isset($this->options[HandlerOptions::COOKIE_JAR]) && \is_string($this->options[HandlerOptions::COOKIE_JAR])) { $cookieJar->load($this->options[HandlerOptions::COOKIE_JAR]); } } @@ -61,8 +60,7 @@ public function getCookieJar() */ protected function saveCookieJar() { - if (isset($this->options[HandlerOptions::COOKIE_JAR]) && \is_string($this->options[HandlerOptions::COOKIE_JAR])) - { + if (isset($this->options[HandlerOptions::COOKIE_JAR]) && \is_string($this->options[HandlerOptions::COOKIE_JAR])) { $this->cookieJar->save($this->options[HandlerOptions::COOKIE_JAR]); } } diff --git a/src/YurunHttp/Traits/THandler.php b/src/YurunHttp/Traits/THandler.php index 8200bf3..e9cd104 100644 --- a/src/YurunHttp/Traits/THandler.php +++ b/src/YurunHttp/Traits/THandler.php @@ -2,7 +2,6 @@ namespace Yurun\Util\YurunHttp\Traits; -use InvalidArgumentException; use Psr\Http\Message\UriInterface; use Yurun\Util\YurunHttp\Http\Psr7\Uri; @@ -19,31 +18,25 @@ trait THandler public function parseRedirectLocation($location, $currentUri) { $locationUri = new Uri($location); - if ('' === $locationUri->getHost()) - { - if (!isset($location[0])) - { - throw new InvalidArgumentException(sprintf('Invalid $location: %s', $location)); + if ('' === $locationUri->getHost()) { + if (!isset($location[0])) { + throw new \InvalidArgumentException(sprintf('Invalid $location: %s', $location)); } - if ('/' === $location[0]) - { + if ('/' === $location[0]) { $uri = $currentUri->withQuery('')->withPath($location); } - else - { + else { $uri = $currentUri; $path = $currentUri->getPath(); - if ('/' !== substr($path, -1, 1)) - { - $path = $path . '/'; + if ('/' !== substr($path, -1, 1)) { + $path .= '/'; } $path .= $location; $uri = $uri->withPath($path); } $uri = $uri->withHost($currentUri->getHost())->withPort($currentUri->getPort()); } - else - { + else { $uri = $locationUri; } @@ -59,10 +52,8 @@ public function parseRedirectLocation($location, $currentUri) */ protected function checkRequests($requests) { - foreach ($requests as $request) - { - if (!$request instanceof \Yurun\Util\YurunHttp\Http\Request) - { + foreach ($requests as $request) { + if (!$request instanceof \Yurun\Util\YurunHttp\Http\Request) { throw new \InvalidArgumentException('Request must be instance of \Yurun\Util\YurunHttp\Http\Request'); } } diff --git a/src/YurunHttp/Traits/TLogger.php b/src/YurunHttp/Traits/TLogger.php index c085c53..b56368b 100644 --- a/src/YurunHttp/Traits/TLogger.php +++ b/src/YurunHttp/Traits/TLogger.php @@ -24,16 +24,13 @@ protected function getLogger() protected function logRequest($request, $response) { $logger = $this->getLogger(); - if (!$logger) - { + if (!$logger) { return; } - if (isset($this->options[HandlerOptions::REQUEST_LOG_FORMAT])) - { + if (isset($this->options[HandlerOptions::REQUEST_LOG_FORMAT])) { $requestLogFormat = $this->options[HandlerOptions::REQUEST_LOG_FORMAT]; } - else - { + else { $requestLogFormat = <<<'STR' Request: [{method}] {url} Response: statusCode: [{status_code}], contentLength: {content_length}, errno: {errno}, error: {error}, useTime: {time} @@ -41,8 +38,7 @@ protected function logRequest($request, $response) } $message = preg_replace_callback('/\{([^\}]+)\}/', function ($matches) use ($request, $response) { - switch ($matches[1]) - { + switch ($matches[1]) { case 'method': return $request->getMethod(); case 'url': @@ -51,8 +47,7 @@ protected function logRequest($request, $response) return $request->getBody()->__toString(); case 'request_headers': $headers = []; - foreach ($request->getHeaders() as $name => $value) - { + foreach ($request->getHeaders() as $name => $value) { $headers[] = $name . ': ' . implode(',', $value); } @@ -67,8 +62,7 @@ protected function logRequest($request, $response) return $response->getError(); case 'response_headers': $headers = []; - foreach ($response->getHeaders() as $name => $value) - { + foreach ($response->getHeaders() as $name => $value) { $headers[] = $name . ': ' . implode(',', $value); } diff --git a/src/YurunHttp/WebSocket/Swoole.php b/src/YurunHttp/WebSocket/Swoole.php index 3d273ba..ce0c09b 100644 --- a/src/YurunHttp/WebSocket/Swoole.php +++ b/src/YurunHttp/WebSocket/Swoole.php @@ -124,8 +124,7 @@ public function send($data) { $handler = $this->handler; $result = $handler->push($data); - if (!$result) - { + if (!$result) { $errCode = $handler->errCode; throw new WebSocketException(sprintf('Send Failed, error: %s, errorCode: %s', swoole_strerror($errCode), $errCode), $errCode); } @@ -143,8 +142,7 @@ public function send($data) public function recv($timeout = null) { $result = $this->handler->recv((float) $timeout); - if (!$result) - { + if (!$result) { return false; } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 8436467..13ff73d 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -13,8 +13,7 @@ function testEnv($name, $default = null) { $result = getenv($name); - if (false === $result) - { + if (false === $result) { return $default; } @@ -26,48 +25,39 @@ function testEnv($name, $default = null) echo 'Starting Http server...', \PHP_EOL; echo `{$cmd}`, \PHP_EOL; $serverStarted = false; -for ($i = 0; $i < 10; ++$i) -{ +for ($i = 0; $i < 10; ++$i) { $context = stream_context_create(['http' => ['timeout' => 1]]); - if ('YurunHttp' === @file_get_contents(testEnv('HTTP_SERVER_HOST', 'http://127.0.0.1:8899/'), false, $context)) - { + if ('YurunHttp' === @file_get_contents(testEnv('HTTP_SERVER_HOST', 'http://127.0.0.1:8898/'), false, $context)) { $serverStarted = true; break; } sleep(1); } -if ($serverStarted) -{ +if ($serverStarted) { echo 'Http server started!', \PHP_EOL; } -else -{ +else { throw new \RuntimeException('Http server start failed'); } -if (SWOOLE_ON) -{ +if (SWOOLE_ON) { // WebSocket Server $cmd = __DIR__ . '/server/WebSocket/start-server.sh'; echo 'Starting WebSocket server...', \PHP_EOL; echo `{$cmd}`, \PHP_EOL; $serverStarted = false; - for ($i = 0; $i < 10; ++$i) - { + for ($i = 0; $i < 10; ++$i) { @file_get_contents(str_replace('ws://', 'http://', testEnv('WS_SERVER_HOST', 'ws://127.0.0.1:8900/'))); - if (isset($http_response_header[0]) && 'HTTP/1.1 400 Bad Request' === $http_response_header[0]) - { + if (isset($http_response_header[0]) && 'HTTP/1.1 400 Bad Request' === $http_response_header[0]) { $serverStarted = true; break; } sleep(1); } - if ($serverStarted) - { + if ($serverStarted) { echo 'WebSocekt server started!', \PHP_EOL; } - else - { + else { throw new \RuntimeException('WebSocekt server start failed'); } @@ -76,22 +66,18 @@ function testEnv($name, $default = null) echo 'Starting Http2 server...', \PHP_EOL; echo `{$cmd}`, \PHP_EOL; $serverStarted = false; - for ($i = 0; $i < 10; ++$i) - { + for ($i = 0; $i < 10; ++$i) { @file_get_contents(testEnv('HTTP2_SERVER_HOST', 'http://127.0.0.1:8901/')); - if (isset($http_response_header[0]) && 'HTTP/1.1 200 OK' === $http_response_header[0]) - { + if (isset($http_response_header[0]) && 'HTTP/1.1 200 OK' === $http_response_header[0]) { $serverStarted = true; break; } sleep(1); } - if ($serverStarted) - { + if ($serverStarted) { echo 'Http2 server started!', \PHP_EOL; } - else - { + else { throw new \RuntimeException('Http2 server start failed'); } } @@ -103,8 +89,7 @@ function testEnv($name, $default = null) echo `{$cmd}`, \PHP_EOL; echo 'Http Server stoped!', \PHP_EOL; - if (SWOOLE_ON) - { + if (SWOOLE_ON) { $cmd = __DIR__ . '/server/WebSocket/stop-server.sh'; echo 'Stoping WebSocket server...', \PHP_EOL; echo `{$cmd}`, \PHP_EOL; diff --git a/tests/server/Http/WorkermanHttp.php b/tests/server/Http/WorkermanHttp.php index 837a338..f444314 100644 --- a/tests/server/Http/WorkermanHttp.php +++ b/tests/server/Http/WorkermanHttp.php @@ -59,8 +59,7 @@ class WorkermanHttp */ public static function sessionName($name = null) { - if (null !== $name && '' !== $name) - { + if (null !== $name && '' !== $name) { static::$_sessionName = (string) $name; } @@ -76,8 +75,7 @@ public static function sessionName($name = null) */ public static function requestClass($class_name = null) { - if ($class_name) - { + if ($class_name) { static::$_requestClass = $class_name; } @@ -107,16 +105,13 @@ public static function enableCache($value) public static function input($recv_buffer, TcpConnection $connection) { static $input = []; - if (!isset($recv_buffer[512]) && isset($input[$recv_buffer])) - { + if (!isset($recv_buffer[512]) && isset($input[$recv_buffer])) { return $input[$recv_buffer]; } $crlf_pos = strpos($recv_buffer, "\r\n\r\n"); - if (false === $crlf_pos) - { + if (false === $crlf_pos) { // Judge whether the package length exceeds the limit. - if ($recv_len = strlen($recv_buffer) >= 16384) - { + if ($recv_len = strlen($recv_buffer) >= 16384) { $connection->close("HTTP/1.1 413 Request Entity Too Large\r\n\r\n"); return 0; @@ -128,43 +123,34 @@ public static function input($recv_buffer, TcpConnection $connection) $head_len = $crlf_pos + 4; $method = strstr($recv_buffer, ' ', true); - if ('GET' === $method || 'OPTIONS' === $method || 'HEAD' === $method || 'DELETE' === $method) - { - if (!isset($recv_buffer[512])) - { + if ('GET' === $method || 'OPTIONS' === $method || 'HEAD' === $method || 'DELETE' === $method) { + if (!isset($recv_buffer[512])) { $input[$recv_buffer] = $head_len; - if (count($input) > 512) - { + if (count($input) > 512) { unset($input[key($input)]); } } } - elseif ('POST' !== $method && 'PUT' !== $method) - { + elseif ('POST' !== $method && 'PUT' !== $method) { $connection->close("HTTP/1.1 400 Bad Request\r\n\r\n", true); return 0; } $header = substr($recv_buffer, 0, $crlf_pos); - if ($pos = strpos($header, "\r\nContent-Length: ")) - { + if ($pos = strpos($header, "\r\nContent-Length: ")) { $length = $head_len + (int) substr($header, $pos + 18, 10); } - elseif (preg_match("/\r\ncontent-length: ?(\d+)/i", $header, $match)) - { - $length = $head_len + $match[1]; + elseif (preg_match("/\r\ncontent-length: ?(\d+)/i", $header, $match)) { + $length = $head_len + (int) $match[1]; } - else - { + else { $length = $head_len; } - if (!isset($recv_buffer[512])) - { + if (!isset($recv_buffer[512])) { $input[$recv_buffer] = $length; - if (count($input) > 512) - { + if (count($input) > 512) { unset($input[key($input)]); } } @@ -184,8 +170,7 @@ public static function decode($recv_buffer, TcpConnection $connection) { static $requests = []; $cacheable = static::$_enableCache && !isset($recv_buffer[512]); - if (true === $cacheable && isset($requests[$recv_buffer])) - { + if (true === $cacheable && isset($requests[$recv_buffer])) { $request = $requests[$recv_buffer]; $request->connection = $connection; $connection->__request = $request; @@ -196,11 +181,9 @@ public static function decode($recv_buffer, TcpConnection $connection) $request = new static::$_requestClass($recv_buffer); $request->connection = $connection; $connection->__request = $request; - if (true === $cacheable) - { + if (true === $cacheable) { $requests[$recv_buffer] = $request; - if (count($requests) > 512) - { + if (count($requests) > 512) { unset($requests[key($requests)]); } } @@ -218,28 +201,21 @@ public static function decode($recv_buffer, TcpConnection $connection) */ public static function encode($response, TcpConnection $connection) { - if (isset($connection->__request)) - { + if (isset($connection->__request)) { $connection->__request->session = null; $connection->__request->connection = null; $connection->__request = null; } - if (is_scalar($response) || null === $response) - { + if (is_scalar($response) || null === $response) { $ext_header = ''; - if (isset($connection->__header)) - { - foreach ($connection->__header as $name => $value) - { - if (is_array($value)) - { - foreach ($value as $item) - { + if (isset($connection->__header)) { + foreach ($connection->__header as $name => $value) { + if (is_array($value)) { + foreach ($value as $item) { $ext_header = "$name: $item\r\n"; } } - else - { + else { $ext_header = "$name: $value\r\n"; } } @@ -250,14 +226,13 @@ public static function encode($response, TcpConnection $connection) return "HTTP/1.1 200 OK\r\nServer: workerman\r\n{$ext_header}Connection: keep-alive\r\nContent-Type: text/html;charset=utf-8\r\nContent-Length: $body_len\r\n\r\n$response"; } - if (isset($connection->__header)) - { + if (isset($connection->__header)) { $response->withHeaders($connection->__header); unset($connection->__header); } - if (isset($response->file)) - { + // @phpstan-ignore-next-line + if (isset($response->file)) { $file = $response->file['file']; $offset = $response->file['offset']; $length = $response->file['length']; @@ -267,20 +242,17 @@ public static function encode($response, TcpConnection $connection) 'Content-Length' => $body_len, 'Accept-Ranges' => 'bytes', ]); - if ($offset || $length) - { + if ($offset || $length) { $offset_end = $offset + $body_len - 1; $response->header('Content-Range', "bytes $offset-$offset_end/$file_size"); } - if ($body_len < 2 * 1024 * 1024) - { + if ($body_len < 2 * 1024 * 1024) { $connection->send((string) $response . file_get_contents($file, false, null, $offset, $body_len), true); return ''; } $handler = fopen($file, 'r'); - if (false === $handler) - { + if (false === $handler) { $connection->close(new Response(403, [], '403 Forbidden')); return ''; @@ -308,24 +280,20 @@ protected static function sendStream(TcpConnection $connection, $handler, $offse { /* @phpstan-ignore-next-line */ $connection->bufferFull = false; - if (0 !== $offset) - { + if (0 !== $offset) { fseek($handler, $offset); } $offset_end = $offset + $length; // Read file content from disk piece by piece and send to client. $do_write = function () use ($connection, $handler, $length, $offset_end) { // Send buffer not full. - while (false === $connection->bufferFull) - { + while (false === $connection->bufferFull) { // Read from disk. $size = 1024 * 1024; - if (0 !== $length) - { + if (0 !== $length) { $tell = ftell($handler); $remain_size = $offset_end - $tell; - if ($remain_size <= 0) - { + if ($remain_size <= 0) { fclose($handler); /* @phpstan-ignore-next-line */ $connection->onBufferDrain = null; @@ -337,8 +305,7 @@ protected static function sendStream(TcpConnection $connection, $handler, $offse $buffer = fread($handler, $size); // Read eof. - if ('' === $buffer || false === $buffer) - { + if ('' === $buffer || false === $buffer) { fclose($handler); /* @phpstan-ignore-next-line */ $connection->onBufferDrain = null; @@ -369,18 +336,14 @@ protected static function sendStream(TcpConnection $connection, $handler, $offse */ public static function uploadTmpDir($dir = null) { - if (null !== $dir) - { + if (null !== $dir) { static::$_uploadTmpDir = $dir; } - if ('' === static::$_uploadTmpDir) - { - if ($upload_tmp_dir = ini_get('upload_tmp_dir')) - { + if ('' === static::$_uploadTmpDir) { + if ($upload_tmp_dir = ini_get('upload_tmp_dir')) { static::$_uploadTmpDir = $upload_tmp_dir; } - elseif ($upload_tmp_dir = sys_get_temp_dir()) - { + elseif ($upload_tmp_dir = sys_get_temp_dir()) { static::$_uploadTmpDir = $upload_tmp_dir; } } diff --git a/tests/server/Http/server.php b/tests/server/Http/server.php index 88c51a3..9f57130 100644 --- a/tests/server/Http/server.php +++ b/tests/server/Http/server.php @@ -9,7 +9,7 @@ require_once __DIR__ . '/WorkermanHttp.php'; // #### http worker #### -$http_worker = new Worker('tcp://0.0.0.0:8899'); +$http_worker = new Worker('tcp://0.0.0.0:8898'); $http_worker->protocol = WorkermanHttp::class; @@ -19,12 +19,10 @@ // Emitted when data received $http_worker->onMessage = function (TcpConnection $connection, Request $request) { // var_dump($request->method(), $request->get('a')); - switch ($request->get('a')) - { + switch ($request->get('a')) { case 'info': $files = $request->file(); - foreach ($files as &$file) - { + foreach ($files as &$file) { $file['hash'] = md5(file_get_contents($file['tmp_name'])); } $connection->send(new Response(200, [ @@ -92,8 +90,7 @@ $connection->send($response); break; case 'download1': - if ('nb' === $request->post('yurunhttp') && 'POST' === $request->method()) - { + if ('nb' === $request->post('yurunhttp') && 'POST' === $request->method()) { $response = new Response(200, [ 'Content-Type' => 'text/html; charset=UTF-8', ], 'YurunHttp Hello World'); @@ -102,8 +99,7 @@ } break; case 'download2': - if ('nb' === $request->post('yurunhttp') && 'POST' === $request->method()) - { + if ('nb' === $request->post('yurunhttp') && 'POST' === $request->method()) { $connection->send('

YurunHttp Hello World

'); } break; diff --git a/tests/server/Http2/http2-server.php b/tests/server/Http2/http2-server.php index 0aaae95..c433c29 100644 --- a/tests/server/Http2/http2-server.php +++ b/tests/server/Http2/http2-server.php @@ -8,8 +8,7 @@ 'worker_num' => 1, ]); $http->on('request', function (Swoole\Http\Request $request, Swoole\Http\Response $response) { - switch ($request->server['path_info']) - { + switch ($request->server['path_info']) { case '/': $response->header('trailer', 'yurun'); $response->trailer('yurun', 'niubi'); diff --git a/tests/server/WebSocket/ws-server.php b/tests/server/WebSocket/ws-server.php index def046d..57b393c 100644 --- a/tests/server/WebSocket/ws-server.php +++ b/tests/server/WebSocket/ws-server.php @@ -9,8 +9,7 @@ $server->on('message', function (Swoole\WebSocket\Server $server, $frame) use (&$userNameStore) { $data = json_decode($frame->data, true); - switch ($data['action']) - { + switch ($data['action']) { case 'login': $userNameStore[$frame->fd] = $data['username']; $server->push($frame->fd, json_encode(['success' => true])); @@ -22,8 +21,7 @@ }); $server->on('close', function ($ser, $fd) use (&$userNameStore) { - if (isset($userNameStore[$fd])) - { + if (isset($userNameStore[$fd])) { unset($userNameStore[$fd]); } }); diff --git a/tests/unit/BaseTest.php b/tests/unit/BaseTest.php index 85e8879..0866a27 100644 --- a/tests/unit/BaseTest.php +++ b/tests/unit/BaseTest.php @@ -43,7 +43,7 @@ abstract class BaseTest extends TestCase public function __construct($name = null, array $data = [], $dataName = '') { parent::__construct($name, $data, $dataName); - $this->host = testEnv('HTTP_SERVER_HOST', 'http://127.0.0.1:8899/'); + $this->host = testEnv('HTTP_SERVER_HOST', 'http://127.0.0.1:8898/'); $this->wsHost = testEnv('WS_SERVER_HOST', 'ws://127.0.0.1:8900/'); $this->http2Host = testEnv('HTTP2_SERVER_HOST', 'http://127.0.0.1:8901/'); $this->wssHost = testEnv('WSS_SERVER_HOST', 'wss://127.0.0.1:8902/'); diff --git a/tests/unit/DefaultHandlerTest.php b/tests/unit/DefaultHandlerTest.php index c27b4b6..867c1e6 100644 --- a/tests/unit/DefaultHandlerTest.php +++ b/tests/unit/DefaultHandlerTest.php @@ -10,10 +10,9 @@ class DefaultHandlerTest extends BaseTest { use TSwooleHandlerTest; - public function testCurl() + public function testCurl(): void { - if (\extension_loaded('swoole')) - { + if (\extension_loaded('swoole')) { $this->assertEquals(-1, Coroutine::getuid()); } YurunHttp::setDefaultHandler(null); @@ -21,7 +20,7 @@ public function testCurl() $this->assertInstanceOf(\Yurun\Util\YurunHttp\Handler\Curl::class, YurunHttp::getHandler()); } - public function testSwoole() + public function testSwoole(): void { $this->call(function () { $this->assertNotEquals(-1, Coroutine::getuid()); @@ -31,15 +30,14 @@ public function testSwoole() }); } - public function testSetDefaultHandler() + public function testSetDefaultHandler(): void { YurunHttp::setDefaultHandler(null); $this->assertNull(YurunHttp::getDefaultHandler()); YurunHttp::setDefaultHandler(\Yurun\Util\YurunHttp\Handler\Curl::class); $this->assertInstanceOf(\Yurun\Util\YurunHttp\Handler\Curl::class, YurunHttp::getHandler()); - if (\PHP_VERSION_ID >= 50600) - { + if (\PHP_VERSION_ID >= 50600) { YurunHttp::setDefaultHandler(null); $this->assertNull(YurunHttp::getDefaultHandler()); YurunHttp::setDefaultHandler(\Exception::class); diff --git a/tests/unit/Http2/SwooleHttp2Test.php b/tests/unit/Http2/SwooleHttp2Test.php index f309b1e..ec10abe 100644 --- a/tests/unit/Http2/SwooleHttp2Test.php +++ b/tests/unit/Http2/SwooleHttp2Test.php @@ -14,7 +14,7 @@ class SwooleHttp2Test extends BaseTest { use TSwooleHandlerTest; - public function testHttp2() + public function testHttp2(): void { $this->call(function () { $http = new HttpRequest(); @@ -43,7 +43,7 @@ public function testHttp2() }); } - public function testHttp2ByUrl() + public function testHttp2ByUrl(): void { $this->call(function () { $http = new HttpRequest(); @@ -70,7 +70,7 @@ public function testHttp2ByUrl() }); } - public function testMuiltCo() + public function testMuiltCo(): void { $this->call(function () { $uri = new Uri($this->http2Host); @@ -105,8 +105,7 @@ public function testMuiltCo() $count = 10; $channel = new Channel($count); - for ($i = 0; $i < $count; ++$i) - { + for ($i = 0; $i < $count; ++$i) { go(function () use ($i, $client, $channel, $httpRequest, $fd) { $request = $httpRequest->buildRequest($this->http2Host, [ 'date' => $i, @@ -121,19 +120,18 @@ public function testMuiltCo() }); } $returnCount = 0; - do - { - if ($channel->pop()) - { + do { + if ($channel->pop()) { ++$returnCount; } - } while ($returnCount < $count); + } + while ($returnCount < $count); $client->close(); }); } - public function testPipeline1() + public function testPipeline1(): void { $this->call(function () { $uri = new Uri($this->http2Host); @@ -165,19 +163,17 @@ public function testPipeline1() $this->assertEquals('yurun', $response->getHeaderLine('trailer')); $client->close(); /* @phpstan-ignore-next-line */ - if (version_compare(\SWOOLE_VERSION, '4.4.13', '<')) - { + if (version_compare(\SWOOLE_VERSION, '4.4.13', '<')) { // Swoole <= 4.4.12 BUG $this->markTestSkipped(sprintf('Swoole version %s < 4.4.13', \SWOOLE_VERSION)); } - else - { + else { $this->assertEquals('niubi', $response->getHeaderLine('yurun')); } }); } - public function testPipeline2() + public function testPipeline2(): void { $this->call(function () { $uri = new Uri($this->http2Host); @@ -208,13 +204,11 @@ public function testPipeline2() $this->assertEquals('yurun', $response->getHeaderLine('trailer')); $client->close(); /* @phpstan-ignore-next-line */ - if (version_compare(\SWOOLE_VERSION, '4.4.13', '<')) - { + if (version_compare(\SWOOLE_VERSION, '4.4.13', '<')) { // Swoole <= 4.4.12 BUG $this->markTestSkipped(sprintf('Swoole version %s < 4.4.13', \SWOOLE_VERSION)); } - else - { + else { $this->assertEquals('niubi', $response->getHeaderLine('yurun')); } }); @@ -225,7 +219,7 @@ public function testPipeline2() * * @return void */ - public function testHttp2ResponseGetRequest() + public function testHttp2ResponseGetRequest(): void { $this->call(function () { $http = new HttpRequest(); @@ -251,7 +245,7 @@ public function testHttp2ResponseGetRequest() * * @return void */ - public function testHttp2ResponseGetRequest2() + public function testHttp2ResponseGetRequest2(): void { $this->call(function () { $uri = new Uri($this->http2Host); diff --git a/tests/unit/HttpRequestTest/CurlPoolTest.php b/tests/unit/HttpRequestTest/CurlPoolTest.php index aa36c60..cd9a25e 100644 --- a/tests/unit/HttpRequestTest/CurlPoolTest.php +++ b/tests/unit/HttpRequestTest/CurlPoolTest.php @@ -9,14 +9,13 @@ class CurlPoolTest extends BaseTest { - public function test() + public function test(): void { $this->call(function () { // 启用连接池 ConnectionPool::enable(); - try - { + try { // 为这个地址设置限制连接池连接数量3个 // 一定不要有 / 及后续参数等 $url = rtrim($this->host, '/'); @@ -44,8 +43,7 @@ public function test() $this->assertEquals(1, $pool->getFree()); $this->assertEquals(0, $pool->getUsed()); } - finally - { + finally { ConnectionPool::disable(); } }); diff --git a/tests/unit/HttpRequestTest/HttpRequestTest.php b/tests/unit/HttpRequestTest/HttpRequestTest.php index fbfa957..c21c451 100644 --- a/tests/unit/HttpRequestTest/HttpRequestTest.php +++ b/tests/unit/HttpRequestTest/HttpRequestTest.php @@ -20,7 +20,7 @@ class HttpRequestTest extends BaseTest * * @return void */ - public function testHelloWorld() + public function testHelloWorld(): void { $this->call(function () { $http = new HttpRequest(); @@ -35,7 +35,7 @@ public function testHelloWorld() * * @return void */ - public function testJson() + public function testJson(): void { $this->call(function () { $http = new HttpRequest(); @@ -51,7 +51,7 @@ public function testJson() * * @return void */ - public function testGetParams() + public function testGetParams(): void { $this->call(function () { $http = new HttpRequest(); @@ -69,7 +69,7 @@ public function testGetParams() * * @return void */ - public function testGetParams2() + public function testGetParams2(): void { $this->call(function () { $http = new HttpRequest(); @@ -90,7 +90,7 @@ public function testGetParams2() * * @return void */ - public function testPostParams() + public function testPostParams(): void { $this->call(function () { $http = new HttpRequest(); @@ -119,7 +119,7 @@ public function testPostParams() * * @return void */ - public function testPutRequest() + public function testPutRequest(): void { $this->call(function () { $http = new HttpRequest(); @@ -135,7 +135,7 @@ public function testPutRequest() * * @return void */ - public function testCookieParams() + public function testCookieParams(): void { $this->call(function () { $http = new HttpRequest(); @@ -158,7 +158,7 @@ public function testCookieParams() * * @return void */ - public function testRequestHeaders() + public function testRequestHeaders(): void { $this->call(function () { $http = new HttpRequest(); @@ -188,7 +188,7 @@ public function testRequestHeaders() * * @return void */ - public function testResponseHeaders() + public function testResponseHeaders(): void { $this->call(function () { $http = new HttpRequest(); @@ -203,7 +203,7 @@ public function testResponseHeaders() * * @return void */ - public function testCookieManager() + public function testCookieManager(): void { $this->call(function () { $http = new HttpRequest(); @@ -216,16 +216,14 @@ public function testCookieManager() ]; $data = null; - for ($i = 0; $i < 2; ++$i) - { + for ($i = 0; $i < 2; ++$i) { sleep(1); $response = $http->get($this->host . '?a=info'); $this->assertResponse($response); $data = $response->json(true); - if ($compareCookie === $data['cookie']) - { + if ($compareCookie === $data['cookie']) { break; } } @@ -250,21 +248,19 @@ public function testCookieManager() * * @return void */ - public function testAutoRedirect() + public function testAutoRedirect(): void { $this->call(function () { $http = new HttpRequest(); - foreach ([301, 302] as $statusCode) - { + foreach ([301, 302] as $statusCode) { $response = $http->post($this->host . '?a=redirect' . $statusCode); $this->assertResponse($response); $data = $response->json(true); $this->assertEquals('GET', $data['method'], $statusCode . ' method error'); } - foreach ([307, 308] as $statusCode) - { + foreach ([307, 308] as $statusCode) { $response = $http->post($this->host . '?a=redirect' . $statusCode); $this->assertResponse($response); $data = $response->json(true); @@ -278,7 +274,7 @@ public function testAutoRedirect() * * @return void */ - public function testDisableAutoRedirect() + public function testDisableAutoRedirect(): void { $this->call(function () { $http = new HttpRequest(); @@ -295,7 +291,7 @@ public function testDisableAutoRedirect() * * @return void */ - public function testLimitMaxRedirects() + public function testLimitMaxRedirects(): void { $this->call(function () { $http = new HttpRequest(); @@ -311,7 +307,7 @@ public function testLimitMaxRedirects() * * @return void */ - public function testRedirectOther() + public function testRedirectOther(): void { $this->call(function () { $http = new HttpRequest(); @@ -327,7 +323,7 @@ public function testRedirectOther() /** * @return void */ - public function testRedirectCookie() + public function testRedirectCookie(): void { $this->call(function () { $http = new HttpRequest(); @@ -346,7 +342,7 @@ public function testRedirectCookie() * * @return void */ - public function testUploadSingle() + public function testUploadSingle(): void { $this->call(function () { $http = new HttpRequest(); @@ -372,7 +368,7 @@ public function testUploadSingle() * * @return void */ - public function testUploadMulti() + public function testUploadMulti(): void { $this->call(function () { $http = new HttpRequest(); @@ -408,7 +404,7 @@ public function testUploadMulti() * * @return void */ - public function testBody() + public function testBody(): void { $this->call(function () { $http = new HttpRequest(); @@ -435,7 +431,7 @@ public function testBody() * * @return void */ - public function testResponseGetRequest() + public function testResponseGetRequest(): void { $this->call(function () { $http = new HttpRequest(); @@ -447,12 +443,11 @@ public function testResponseGetRequest() }); } - public function test304() + public function test304(): void { $this->call(function () { /* @phpstan-ignore-next-line */ - if (method_exists(Coroutine::class, 'getuid') && Coroutine::getuid() > 0 && version_compare(\SWOOLE_VERSION, '4.4.17', '<')) - { + if (method_exists(Coroutine::class, 'getuid') && Coroutine::getuid() > 0 && version_compare(\SWOOLE_VERSION, '4.4.17', '<')) { $this->markTestSkipped('Swoole must >= 4.4.17'); } $http = new HttpRequest(); @@ -463,7 +458,7 @@ public function test304() }); } - public function testUriWithAuth() + public function testUriWithAuth(): void { $this->call(function () { $http = new HttpRequest(); @@ -479,13 +474,12 @@ public function testUriWithAuth() * * @return void */ - public function testDownload() + public function testDownload(): void { $this->call(function () { $http = new HttpRequest(); $fileName = __DIR__ . '/download.txt'; - if (is_file($fileName)) - { + if (is_file($fileName)) { unlink($fileName); } $this->assertFalse(is_file($fileName)); @@ -501,13 +495,12 @@ public function testDownload() * * @return void */ - public function testDownloadAutoExt() + public function testDownloadAutoExt(): void { $this->call(function () { $http = new HttpRequest(); $fileName = __DIR__ . '/download.html'; - if (is_file($fileName)) - { + if (is_file($fileName)) { unlink($fileName); } $this->assertFalse(is_file($fileName)); @@ -523,13 +516,12 @@ public function testDownloadAutoExt() * * @return void */ - public function testDownloadWithRedirect() + public function testDownloadWithRedirect(): void { $this->call(function () { $http = new HttpRequest(); $fileName = __DIR__ . '/download.html'; - if (is_file($fileName)) - { + if (is_file($fileName)) { unlink($fileName); } $this->assertFalse(is_file($fileName)); @@ -545,7 +537,7 @@ public function testDownloadWithRedirect() * * @return void */ - public function testCustomHost() + public function testCustomHost(): void { $this->call(function () { $http = new HttpRequest(); @@ -561,27 +553,24 @@ public function testCustomHost() * * @return void */ - public function testCoBatch() + public function testCoBatch(): void { $this->call(function () { $time = time(); $fileName = __DIR__ . '/download.txt'; - if (is_file($fileName)) - { + if (is_file($fileName)) { unlink($fileName); } $this->assertFalse(is_file($fileName)); $fileName2Temp = __DIR__ . '/download2.*'; $fileName2 = __DIR__ . '/download2.html'; - if (is_file($fileName2)) - { + if (is_file($fileName2)) { unlink($fileName2); } $this->assertFalse(is_file($fileName2)); $fileName3Temp = __DIR__ . '/download3.*'; $fileName3 = __DIR__ . '/download3.html'; - if (is_file($fileName3)) - { + if (is_file($fileName3)) { unlink($fileName3); } $this->assertFalse(is_file($fileName3)); @@ -593,46 +582,39 @@ public function testCoBatch() 'a' => (new HttpRequest())->url($this->host . '?a=redirect&url=/?a=download3')->requestBody('yurunhttp=nb')->saveFile($fileName3Temp), ]); - foreach ($result as $i => $response) - { - if (0 === $i) - { + foreach ($result as $i => $response) { + if (0 === $i) { $this->assertResponse($response); $this->assertEquals('YurunHttp', $response->body()); $this->assertNotNull($response->getRequest()); } - elseif (1 === $i) - { + elseif (1 === $i) { $data = $response->json(true); $this->assertEquals('GET', isset($data['method']) ? $data['method'] : null); $this->assertEquals($time, isset($data['get']['time']) ? $data['get']['time'] : null); $this->assertNotNull($response->getRequest()); } - elseif (2 === $i) - { + elseif (2 === $i) { $this->assertTrue(is_file($fileName)); $this->assertEquals('YurunHttp Hello World', file_get_contents($fileName)); $this->assertNotNull($response->getRequest()); $this->assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type')); $this->assertEquals('1', $response->getCookie('a')); } - elseif (3 === $i) - { + elseif (3 === $i) { $this->assertTrue(is_file($fileName2)); $this->assertEquals('YurunHttp Hello World', file_get_contents($fileName2)); $this->assertNotNull($response->getRequest()); $this->assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type')); $this->assertEquals('1', $response->getCookie('a')); } - elseif ('a' === $i) - { + elseif ('a' === $i) { $this->assertTrue(is_file($fileName3)); $this->assertEquals('download3', file_get_contents($fileName3)); $this->assertNotNull($response->getRequest()); $this->assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type')); } - else - { + else { throw new \RuntimeException(sprintf('Unknown %s', $i)); } } @@ -644,7 +626,7 @@ public function testCoBatch() * * @return void */ - public function testCoBatchTimeout() + public function testCoBatchTimeout(): void { $this->call(function () { $result = Batch::run([ @@ -655,12 +637,11 @@ public function testCoBatchTimeout() }); } - public function testMemoryLeak() + public function testMemoryLeak(): void { $this->call(function () { $memorys = [1, 2, 3, 4, 5]; - for ($i = 0; $i < 5; ++$i) - { + for ($i = 0; $i < 5; ++$i) { $http = new HttpRequest(); $http->get($this->host); $memorys[$i] = memory_get_usage(); @@ -669,8 +650,7 @@ public function testMemoryLeak() $this->assertCount(1, array_unique($memorys)); $memorys = [1, 2, 3, 4, 5]; - for ($i = 0; $i < 5; ++$i) - { + for ($i = 0; $i < 5; ++$i) { YurunHttp::send(new Request($this->host)); $memorys[$i] = memory_get_usage(); } @@ -679,8 +659,7 @@ public function testMemoryLeak() $memorys = [1, 2, 3, 4, 5]; $time = time(); - for ($i = 0; $i < 5; ++$i) - { + for ($i = 0; $i < 5; ++$i) { Batch::run([ (new HttpRequest())->url($this->host), (new HttpRequest())->url($this->host . '?a=info&time=' . $time), @@ -692,7 +671,7 @@ public function testMemoryLeak() }); } - public function testHead() + public function testHead(): void { $this->call(function () { $http = new HttpRequest(); @@ -706,7 +685,7 @@ public function testHead() * * @return void */ - public function testBug19() + public function testBug19(): void { $this->call(function () { $http = new HttpRequest(); @@ -723,7 +702,7 @@ public function testBug19() * * @return void */ - public function testCookieJar() + public function testCookieJar(): void { $this->call(function () { $http = new HttpRequest([ diff --git a/tests/unit/HttpRequestTest/SwoolePoolTest.php b/tests/unit/HttpRequestTest/SwoolePoolTest.php index 4104289..a9cc9af 100644 --- a/tests/unit/HttpRequestTest/SwoolePoolTest.php +++ b/tests/unit/HttpRequestTest/SwoolePoolTest.php @@ -12,14 +12,13 @@ class SwoolePoolTest extends BaseTest { use TSwooleHandlerTest; - public function test() + public function test(): void { $this->call(function () { // 启用连接池 ConnectionPool::enable(); - try - { + try { // 为这个地址设置限制连接池连接数量3个 // 一定不要有 / 及后续参数等 $url = rtrim($this->host, '/'); @@ -47,8 +46,7 @@ public function test() $this->assertEquals(1, $pool->getFree()); $this->assertEquals(0, $pool->getUsed()); } - finally - { + finally { ConnectionPool::disable(); } }); diff --git a/tests/unit/Traits/TSwooleHandlerTest.php b/tests/unit/Traits/TSwooleHandlerTest.php index e7f4789..1c04823 100644 --- a/tests/unit/Traits/TSwooleHandlerTest.php +++ b/tests/unit/Traits/TSwooleHandlerTest.php @@ -13,50 +13,41 @@ trait TSwooleHandlerTest */ protected function call($callable) { - if (!\extension_loaded('swoole')) - { + if (!\extension_loaded('swoole')) { $this->markTestSkipped('Does not installed ext/swoole'); } - if (\defined('SWOOLE_HOOK_ALL')) - { + if (\defined('SWOOLE_HOOK_ALL')) { $flags = \SWOOLE_HOOK_ALL; - if (\defined('SWOOLE_HOOK_NATIVE_CURL')) - { + if (\defined('SWOOLE_HOOK_NATIVE_CURL')) { $flags ^= \SWOOLE_HOOK_NATIVE_CURL; } } - else - { + else { $flags = true; } \Swoole\Runtime::enableCoroutine($flags); $throwable = null; $end = false; go(function () use ($callable, &$throwable, &$end) { - try - { + try { YurunHttp::setDefaultHandler(\Yurun\Util\YurunHttp\Handler\Swoole::class); $callable(); } - catch (\Throwable $th) - { + catch (\Throwable $th) { $throwable = $th; } $end = true; }); // @phpstan-ignore-next-line - while (!$end) - { + while (!$end) { swoole_event_dispatch(); } // @phpstan-ignore-next-line \Swoole\Runtime::enableCoroutine(false); - if ($throwable) - { + if ($throwable) { throw $throwable; } - else - { + else { $this->assertEquals(1, 1); } } diff --git a/tests/unit/WebSocketTest/WebSocketTest.php b/tests/unit/WebSocketTest/WebSocketTest.php index f60434a..45d2360 100644 --- a/tests/unit/WebSocketTest/WebSocketTest.php +++ b/tests/unit/WebSocketTest/WebSocketTest.php @@ -10,7 +10,7 @@ class WebSocketTest extends BaseTest { use TSwooleHandlerTest; - public function testWebSocket() + public function testWebSocket(): void { $this->call(function () { $http = new HttpRequest(); @@ -33,7 +33,7 @@ public function testWebSocket() }); } - public function testWSS() + public function testWSS(): void { $this->call(function () { $http = new HttpRequest(); @@ -56,12 +56,11 @@ public function testWSS() }); } - public function testMemoryLeak() + public function testMemoryLeak(): void { $this->call(function () { $memorys = [1, 2, 3, 4, 5]; - for ($i = 0; $i < 5; ++$i) - { + for ($i = 0; $i < 5; ++$i) { $http = new HttpRequest(); $client = $http->websocket($this->wsHost); $client->close(); From b2539d77639ca420518cb41f77ce1e9aa28eecf7 Mon Sep 17 00:00:00 2001 From: Yurun Date: Fri, 13 Oct 2023 16:00:27 +0800 Subject: [PATCH 02/12] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ci.yml | 5 +- .github/workflows/phpcs.yml | 2 +- .github/workflows/phpstan.yml | 2 +- examples/http2Client.php | 12 +- examples/pool-curl.php | 3 +- examples/pool-swoole.php | 6 +- examples/websocket.php | 3 +- src/HttpRequest.php | 82 +++-- src/YurunHttp.php | 56 +-- src/YurunHttp/Attributes.php | 84 ++--- src/YurunHttp/Co/Batch.php | 30 +- src/YurunHttp/ConnectionPool.php | 27 +- src/YurunHttp/Cookie/CookieItem.php | 27 +- src/YurunHttp/Cookie/CookieJar.php | 6 +- src/YurunHttp/Cookie/CookieManager.php | 96 ++++-- src/YurunHttp/FormDataBuilder.php | 9 +- src/YurunHttp/Handler/Curl.php | 267 ++++++++++----- .../Handler/Curl/CurlConnectionPool.php | 18 +- .../Curl/CurlHttpConnectionManager.php | 15 +- src/YurunHttp/Handler/Swoole.php | 321 ++++++++++++------ .../Swoole/SwooleHttp2ConnectionManager.php | 15 +- .../Swoole/SwooleHttp2ConnectionPool.php | 27 +- .../Swoole/SwooleHttpConnectionManager.php | 15 +- .../Swoole/SwooleHttpConnectionPool.php | 12 +- src/YurunHttp/HandlerOptions.php | 6 +- src/YurunHttp/Http/Psr7/AbstractMessage.php | 66 ++-- src/YurunHttp/Http/Psr7/Consts/MediaType.php | 54 +-- .../Http/Psr7/Consts/RequestHeader.php | 64 ++-- .../Http/Psr7/Consts/RequestMethod.php | 16 +- .../Http/Psr7/Consts/ResponseHeader.php | 74 ++-- src/YurunHttp/Http/Psr7/Consts/StatusCode.php | 122 +++---- src/YurunHttp/Http/Psr7/Request.php | 9 +- src/YurunHttp/Http/Psr7/Response.php | 6 +- src/YurunHttp/Http/Psr7/ServerRequest.php | 33 +- src/YurunHttp/Http/Psr7/UploadedFile.php | 24 +- src/YurunHttp/Http/Psr7/Uri.php | 30 +- src/YurunHttp/Http/Response.php | 21 +- src/YurunHttp/Http2/SwooleClient.php | 81 +++-- .../Pool/Traits/TConnectionPoolConfigs.php | 12 +- src/YurunHttp/Random.php | 3 +- src/YurunHttp/Stream/FileStream.php | 54 ++- src/YurunHttp/Stream/MemoryStream.php | 12 +- src/YurunHttp/Stream/StreamMode.php | 16 +- src/YurunHttp/Traits/TCookieManager.php | 6 +- src/YurunHttp/Traits/THandler.php | 24 +- src/YurunHttp/Traits/TLogger.php | 18 +- src/YurunHttp/WebSocket/Swoole.php | 6 +- tests/bootstrap.php | 45 ++- tests/server/Http/WorkermanHttp.php | 114 ++++--- tests/server/Http/server.php | 12 +- tests/server/Http2/http2-server.php | 3 +- tests/server/WebSocket/ws-server.php | 6 +- tests/unit/DefaultHandlerTest.php | 6 +- tests/unit/Http2/SwooleHttp2Test.php | 21 +- tests/unit/HttpRequestTest/CurlPoolTest.php | 6 +- .../unit/HttpRequestTest/HttpRequestTest.php | 63 ++-- tests/unit/HttpRequestTest/SwoolePoolTest.php | 6 +- tests/unit/Traits/TSwooleHandlerTest.php | 27 +- tests/unit/WebSocketTest/WebSocketTest.php | 3 +- 59 files changed, 1400 insertions(+), 809 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f27eb6e..c3b6911 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,7 +9,7 @@ jobs: strategy: fail-fast: false matrix: - php: [5.5, 5.6, 7.0, 7.1] + php: [7.0, 7.1] env: PHP_DOCKER_VERSION: ${{ matrix.php }} @@ -32,6 +32,9 @@ jobs: matrix: swoole: [ + 5.1-php8.0, + 5.1-php8.1, + 5.1-php8.2, 5.0-php8.0, 5.0-php8.1, 5.0-php8.2, diff --git a/.github/workflows/phpcs.yml b/.github/workflows/phpcs.yml index 584d2c5..18f3b69 100644 --- a/.github/workflows/phpcs.yml +++ b/.github/workflows/phpcs.yml @@ -9,7 +9,7 @@ jobs: strategy: fail-fast: false matrix: - swoole: [4.6-php7.4] + swoole: [5.0-php8.2] env: SWOOLE_DOCKER_VERSION: ${{ matrix.swoole }} diff --git a/.github/workflows/phpstan.yml b/.github/workflows/phpstan.yml index a15b7c5..0077f0c 100644 --- a/.github/workflows/phpstan.yml +++ b/.github/workflows/phpstan.yml @@ -9,7 +9,7 @@ jobs: strategy: fail-fast: false matrix: - swoole: [4.6-php7.4] + swoole: [5.0-php8.2] env: SWOOLE_DOCKER_VERSION: ${{ matrix.swoole }} diff --git a/examples/http2Client.php b/examples/http2Client.php index 595bbb6..6a37902 100644 --- a/examples/http2Client.php +++ b/examples/http2Client.php @@ -19,7 +19,8 @@ // 接收服务端主动推送 $client->setServerPushQueueLength(16); // 接收服务端推送的队列长度 go(function () use ($client) { - do { + do + { $response = $client->recv(); var_dump($response->body()); } @@ -31,7 +32,8 @@ $count = 10; $channel = new Channel($count); - for ($i = 0; $i < $count; ++$i) { + for ($i = 0; $i < $count; ++$i) + { go(function () use ($i, $client, $channel, $httpRequest, $uri) { $request = $httpRequest->header('aaa', 'bbb')->buildRequest($uri, [ 'date' => $i, @@ -45,8 +47,10 @@ }); } $returnCount = 0; - do { - if ($channel->pop()) { + do + { + if ($channel->pop()) + { ++$returnCount; } } diff --git a/examples/pool-curl.php b/examples/pool-curl.php index 1cac794..a74eb47 100644 --- a/examples/pool-curl.php +++ b/examples/pool-curl.php @@ -8,7 +8,8 @@ function dumpPoolInfo() { - foreach (CurlHttpConnectionManager::getInstance()->getConnectionPools() as $pool) { + foreach (CurlHttpConnectionManager::getInstance()->getConnectionPools() as $pool) + { var_dump($pool->getConfig()->getUrl() . ': Count=' . $pool->getCount() . ', Free=' . $pool->getFree() . ', Used=' . $pool->getUsed()); } } diff --git a/examples/pool-swoole.php b/examples/pool-swoole.php index 33e986e..fe75adb 100644 --- a/examples/pool-swoole.php +++ b/examples/pool-swoole.php @@ -9,7 +9,8 @@ function dumpPoolInfo() { - foreach (SwooleHttpConnectionManager::getInstance()->getConnectionPools() as $pool) { + foreach (SwooleHttpConnectionManager::getInstance()->getConnectionPools() as $pool) + { var_dump($pool->getConfig()->getUrl() . ': Count=' . $pool->getCount() . ', Free=' . $pool->getFree() . ', Used=' . $pool->getUsed()); } } @@ -29,7 +30,8 @@ function dumpPoolInfo() }); $wg = new \Swoole\Coroutine\WaitGroup(); - for ($i = 0; $i < 10; ++$i) { + for ($i = 0; $i < 10; ++$i) + { $wg->add(); go(function () use ($wg) { $http = new HttpRequest(); diff --git a/examples/websocket.php b/examples/websocket.php index 01564c8..65f3d54 100644 --- a/examples/websocket.php +++ b/examples/websocket.php @@ -12,7 +12,8 @@ $http = new HttpRequest(); $http->header('Origin', 'http://coolaf.com'); $client = $http->websocket($url); - if (!$client->isConnected()) { + if (!$client->isConnected()) + { throw new \RuntimeException('Connect failed'); } $time = time() . ''; diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 713b329..f3fcd9f 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -236,12 +236,12 @@ class HttpRequest /** * 自动扩展名标志. */ - public const AUTO_EXT_FLAG = '.*'; + const AUTO_EXT_FLAG = '.*'; /** * 自动扩展名用的临时文件名. */ - public const AUTO_EXT_TEMP_EXT = '.tmp'; + const AUTO_EXT_TEMP_EXT = '.tmp'; /** * 构造方法. @@ -300,7 +300,8 @@ public function open($options = []) */ public function close() { - if ($this->handler) { + if ($this->handler) + { $handler = $this->handler; $this->handler = null; $handler->close(); @@ -389,7 +390,8 @@ public function requestBody($requestBody) public function options($options) { $thisOptions = &$this->options; - foreach ($options as $key => $value) { + foreach ($options as $key => $value) + { $thisOptions[$key] = $value; } @@ -451,7 +453,8 @@ public function header($header, $value) public function rawHeaders($headers) { $thisHeaders = &$this->headers; - foreach ($headers as $header) { + foreach ($headers as $header) + { $list = explode(':', $header, 2); $thisHeaders[trim($list[0])] = trim($list[1]); } @@ -706,10 +709,12 @@ public function proxyAuth($username, $password) */ public function timeout($timeout = null, $connectTimeout = null) { - if (null !== $timeout) { + if (null !== $timeout) + { $this->timeout = $timeout; } - if (null !== $connectTimeout) { + if (null !== $connectTimeout) + { $this->connectTimeout = $connectTimeout; } @@ -788,10 +793,12 @@ public function getSavePath() public function sslCert($path, $type = null, $password = null) { $this->certPath = $path; - if (null !== $type) { + if (null !== $type) + { $this->certType = $type; } - if (null !== $password) { + if (null !== $password) + { $this->certPassword = $password; } @@ -810,10 +817,12 @@ public function sslCert($path, $type = null, $password = null) public function sslKey($path, $type = null, $password = null) { $this->keyPath = $path; - if (null !== $type) { + if (null !== $type) + { $this->keyType = $type; } - if (null !== $password) { + if (null !== $password) + { $this->keyPassword = $password; } @@ -859,28 +868,35 @@ public function connectionPool($connectionPool) protected function parseRequestBody($requestBody, $contentType) { $body = $files = []; - if (\is_string($requestBody)) { + if (\is_string($requestBody)) + { $body = $requestBody; } - elseif (\is_array($requestBody) || \is_object($requestBody)) { - switch ($contentType) { + elseif (\is_array($requestBody) || \is_object($requestBody)) + { + switch ($contentType) + { case 'json': $body = json_encode($requestBody); $this->header('Content-Type', MediaType::APPLICATION_JSON); break; default: - foreach ($requestBody as $k => $v) { - if ($v instanceof UploadedFile) { + foreach ($requestBody as $k => $v) + { + if ($v instanceof UploadedFile) + { $files[$k] = $v; } - else { + else + { $body[$k] = $v; } } $body = http_build_query($body, '', '&'); } } - else { + else + { throw new \InvalidArgumentException('$requestBody only can be string or array'); } @@ -899,10 +915,12 @@ protected function parseRequestBody($requestBody, $contentType) */ public function buildRequest($url = null, $requestBody = null, $method = null, $contentType = null) { - if (null === $url) { + if (null === $url) + { $url = $this->url; } - if (null === $method) { + if (null === $method) + { $method = $this->method; } list($body, $files) = $this->parseRequestBody(null === $requestBody ? $this->content : $requestBody, $contentType); @@ -934,7 +952,8 @@ public function buildRequest($url = null, $requestBody = null, $method = null, $ ->withAttribute(Attributes::RETRY_CALLBACK, $this->retryCallback) ->withProtocolVersion($this->protocolVersion) ; - foreach ($this->proxy as $name => $value) { + foreach ($this->proxy as $name => $value) + { $request = $request->withAttribute('proxy.' . $name, $value); } @@ -987,11 +1006,14 @@ public function sendHttp2WithoutRecv($url = null, $requestBody = null, $method = */ public function get($url = null, $requestBody = null) { - if (!empty($requestBody)) { - if (strpos($url, '?')) { + if (!empty($requestBody)) + { + if (strpos($url, '?')) + { $url .= '&'; } - else { + else + { $url .= '?'; } $url .= http_build_query($requestBody, '', '&'); @@ -1083,7 +1105,8 @@ public function download($fileName, $url = null, $requestBody = null, $method = { $isAutoExt = self::checkDownloadIsAutoExt($fileName, $fileName); $result = $this->saveFile($fileName)->send($url, $requestBody, $method); - if ($isAutoExt) { + if ($isAutoExt) + { self::parseDownloadAutoExt($result, $fileName); } $this->saveFileOption = []; @@ -1116,7 +1139,8 @@ public function websocket($url = null) public static function checkDownloadIsAutoExt($fileName, &$tempFileName) { $flagLength = \strlen(self::AUTO_EXT_FLAG); - if (self::AUTO_EXT_FLAG !== substr($fileName, -$flagLength)) { + if (self::AUTO_EXT_FLAG !== substr($fileName, -$flagLength)) + { return false; } $tempFileName = substr($fileName, 0, -$flagLength) . self::AUTO_EXT_TEMP_EXT; @@ -1135,7 +1159,8 @@ public static function checkDownloadIsAutoExt($fileName, &$tempFileName) public static function parseDownloadAutoExt(&$response, $tempFileName) { $ext = MediaType::getExt($response->getHeaderLine('Content-Type')); - if (null === $ext) { + if (null === $ext) + { $ext = 'file'; } $savedFileName = substr($tempFileName, 0, -\strlen(self::AUTO_EXT_TEMP_EXT)) . '.' . $ext; @@ -1144,7 +1169,8 @@ public static function parseDownloadAutoExt(&$response, $tempFileName) } } -if (\extension_loaded('curl')) { +if (\extension_loaded('curl')) +{ // 代理认证方式 HttpRequest::$proxyAuths = [ 'basic' => \CURLAUTH_BASIC, diff --git a/src/YurunHttp.php b/src/YurunHttp.php index 7144831..f1ab98f 100644 --- a/src/YurunHttp.php +++ b/src/YurunHttp.php @@ -24,7 +24,7 @@ abstract class YurunHttp /** * 版本号. */ - public const VERSION = '4.3'; + const VERSION = '4.3'; /** * 设置默认处理器类. @@ -57,17 +57,21 @@ public static function getDefaultHandler() */ public static function getHandler($options = []) { - if (self::$defaultHandler) { + if (self::$defaultHandler) + { $class = self::$defaultHandler; // @phpstan-ignore-next-line - if (!is_subclass_of($class, IHandler::class)) { + if (!is_subclass_of($class, IHandler::class)) + { throw new \RuntimeException(sprintf('Class %s does not implement %s', $class, IHandler::class)); } } - elseif (\defined('SWOOLE_VERSION') && Coroutine::getuid() > -1) { + elseif (\defined('SWOOLE_VERSION') && Coroutine::getuid() > -1) + { $class = \Yurun\Util\YurunHttp\Handler\Swoole::class; } - else { + else + { $class = \Yurun\Util\YurunHttp\Handler\Curl::class; } @@ -85,28 +89,35 @@ public static function getHandler($options = []) */ public static function send($request, $handlerClass = null, $options = []) { - if ($handlerClass instanceof IHandler) { + if ($handlerClass instanceof IHandler) + { $handler = $handlerClass; $needClose = false; } - else { + else + { $needClose = true; - if (null === $handlerClass) { + if (null === $handlerClass) + { $handler = static::getHandler($options); } - else { + else + { /** @var IHandler $handler */ $handler = new $handlerClass(); } } - foreach (self::$attributes as $name => $value) { - if (null === $request->getAttribute($name)) { + foreach (self::$attributes as $name => $value) + { + if (null === $request->getAttribute($name)) + { $request = $request->withAttribute($name, $value); } } $handler->send($request); $response = $handler->recv(); - if ($needClose) { + if ($needClose) + { $handler->close(); } @@ -124,17 +135,22 @@ public static function send($request, $handlerClass = null, $options = []) */ public static function websocket($request, $handlerClass = null, $options = []) { - if ($handlerClass instanceof IHandler) { + if ($handlerClass instanceof IHandler) + { $handler = $handlerClass; } - elseif (null === $handlerClass) { + elseif (null === $handlerClass) + { $handler = static::getHandler($options); } - else { + else + { $handler = new $handlerClass(); } - foreach (self::$attributes as $name => $value) { - if (null === $request->getAttribute($name)) { + foreach (self::$attributes as $name => $value) + { + if (null === $request->getAttribute($name)) + { $request = $request->withAttribute($name, $value); } } @@ -162,10 +178,12 @@ public static function getAttributes() */ public static function getAttribute($name, $default = null) { - if (\array_key_exists($name, self::$attributes)) { + if (\array_key_exists($name, self::$attributes)) + { return self::$attributes[$name]; } - else { + else + { return $default; } } diff --git a/src/YurunHttp/Attributes.php b/src/YurunHttp/Attributes.php index 9ed4c65..cac9a3d 100644 --- a/src/YurunHttp/Attributes.php +++ b/src/YurunHttp/Attributes.php @@ -12,210 +12,210 @@ abstract class Attributes /** * 客户端参数. */ - public const OPTIONS = 'options'; + const OPTIONS = 'options'; /** * 全局默认 UserAgent. */ - public const USER_AGENT = 'userAgent'; + const USER_AGENT = 'userAgent'; /** * 重试次数. */ - public const RETRY = 'retry'; + const RETRY = 'retry'; /** * 重试回调. */ - public const RETRY_CALLBACK = 'retry_callback'; + const RETRY_CALLBACK = 'retry_callback'; /** * 下载文件保存路径. */ - public const SAVE_FILE_PATH = 'saveFilePath'; + const SAVE_FILE_PATH = 'saveFilePath'; /** * 保存文件的模型. */ - public const SAVE_FILE_MODE = 'saveFileMode'; + const SAVE_FILE_MODE = 'saveFileMode'; /** * 允许重定向. */ - public const FOLLOW_LOCATION = 'followLocation'; + const FOLLOW_LOCATION = 'followLocation'; /** * 最大允许重定向次数. */ - public const MAX_REDIRECTS = 'maxRedirects'; + const MAX_REDIRECTS = 'maxRedirects'; /** * 是否验证 CA 证书. */ - public const IS_VERIFY_CA = 'isVerifyCA'; + const IS_VERIFY_CA = 'isVerifyCA'; /** * CA 证书. */ - public const CA_CERT = 'caCert'; + const CA_CERT = 'caCert'; /** * SSL 证书类型. */ - public const CERT_TYPE = 'certType'; + const CERT_TYPE = 'certType'; /** * SSL 证书路径. */ - public const CERT_PATH = 'certPath'; + const CERT_PATH = 'certPath'; /** * SSL 证书密码 */ - public const CERT_PASSWORD = 'certPassword'; + const CERT_PASSWORD = 'certPassword'; /** * SSL 密钥类型. */ - public const KEY_TYPE = 'keyType'; + const KEY_TYPE = 'keyType'; /** * SSL 密钥路径. */ - public const KEY_PATH = 'keyPath'; + const KEY_PATH = 'keyPath'; /** * SSL 密钥密码 */ - public const KEY_PASSWORD = 'keyPassword'; + const KEY_PASSWORD = 'keyPassword'; /** * 使用代理. */ - public const USE_PROXY = 'useProxy'; + const USE_PROXY = 'useProxy'; /** * 代理类型. */ - public const PROXY_TYPE = 'proxy.type'; + const PROXY_TYPE = 'proxy.type'; /** * 代理服务器地址 */ - public const PROXY_SERVER = 'proxy.server'; + const PROXY_SERVER = 'proxy.server'; /** * 代理服务器端口. */ - public const PROXY_PORT = 'proxy.port'; + const PROXY_PORT = 'proxy.port'; /** * 代理用户名. */ - public const PROXY_USERNAME = 'proxy.username'; + const PROXY_USERNAME = 'proxy.username'; /** * 代理密码 */ - public const PROXY_PASSWORD = 'proxy.password'; + const PROXY_PASSWORD = 'proxy.password'; /** * 代理的 Basic 认证配置. */ - public const PROXY_AUTH = 'proxy.auth'; + const PROXY_AUTH = 'proxy.auth'; /** * 认证用户名. */ - public const USERNAME = 'username'; + const USERNAME = 'username'; /** * 认证密码 */ - public const PASSWORD = 'password'; + const PASSWORD = 'password'; /** * 超时时间. */ - public const TIMEOUT = 'timeout'; + const TIMEOUT = 'timeout'; /** * 连接超时. */ - public const CONNECT_TIMEOUT = 'connectTimeout'; + const CONNECT_TIMEOUT = 'connectTimeout'; /** * 保持长连接. */ - public const KEEP_ALIVE = 'keep_alive'; + const KEEP_ALIVE = 'keep_alive'; /** * 下载限速 */ - public const DOWNLOAD_SPEED = 'downloadSpeed'; + const DOWNLOAD_SPEED = 'downloadSpeed'; /** * 上传限速 */ - public const UPLOAD_SPEED = 'uploadSpeed'; + const UPLOAD_SPEED = 'uploadSpeed'; /** * 使用自定义重定向操作. */ - public const CUSTOM_LOCATION = 'customLocation'; + const CUSTOM_LOCATION = 'customLocation'; /** * http2 请求不调用 recv(). */ - public const HTTP2_NOT_RECV = 'http2_not_recv'; + const HTTP2_NOT_RECV = 'http2_not_recv'; /** * 启用 Http2 pipeline. */ - public const HTTP2_PIPELINE = 'http2_pipeline'; + const HTTP2_PIPELINE = 'http2_pipeline'; /** * 启用连接池. */ - public const CONNECTION_POOL = 'connection_pool'; + const CONNECTION_POOL = 'connection_pool'; /** * 重试计数. */ - public const PRIVATE_RETRY_COUNT = '__retryCount'; + const PRIVATE_RETRY_COUNT = '__retryCount'; /** * 重定向计数. */ - public const PRIVATE_REDIRECT_COUNT = '__redirectCount'; + const PRIVATE_REDIRECT_COUNT = '__redirectCount'; /** * WebSocket 请求 */ - public const PRIVATE_WEBSOCKET = '__websocket'; + const PRIVATE_WEBSOCKET = '__websocket'; /** * Http2 流ID. */ - public const PRIVATE_HTTP2_STREAM_ID = '__http2StreamId'; + const PRIVATE_HTTP2_STREAM_ID = '__http2StreamId'; /** * 是否为 Http2. */ - public const PRIVATE_IS_HTTP2 = '__isHttp2'; + const PRIVATE_IS_HTTP2 = '__isHttp2'; /** * 是否为 WebSocket. */ - public const PRIVATE_IS_WEBSOCKET = '__isWebSocket'; + const PRIVATE_IS_WEBSOCKET = '__isWebSocket'; /** * 连接对象 */ - public const PRIVATE_CONNECTION = '__connection'; + const PRIVATE_CONNECTION = '__connection'; /** * 连接池的键. */ - public const PRIVATE_POOL_KEY = '__poolKey'; + const PRIVATE_POOL_KEY = '__poolKey'; } diff --git a/src/YurunHttp/Co/Batch.php b/src/YurunHttp/Co/Batch.php index b7a4ef5..185205d 100644 --- a/src/YurunHttp/Co/Batch.php +++ b/src/YurunHttp/Co/Batch.php @@ -22,35 +22,45 @@ public static function run($requests, $timeout = null, $handlerClass = null, $op { $batchRequests = []; $downloadAutoExt = []; - foreach ($requests as $i => $request) { - if ($request instanceof HttpRequest) { + foreach ($requests as $i => $request) + { + if ($request instanceof HttpRequest) + { $savePath = $request->getSavePath(); - if (null !== $savePath && HttpRequest::checkDownloadIsAutoExt($savePath, $savePath)) { + if (null !== $savePath && HttpRequest::checkDownloadIsAutoExt($savePath, $savePath)) + { $request->saveFileOption['filePath'] = $savePath; $downloadAutoExt[] = $i; } $batchRequests[$i] = $request->buildRequest(); } - elseif (!$request instanceof \Yurun\Util\YurunHttp\Http\Request) { + elseif (!$request instanceof \Yurun\Util\YurunHttp\Http\Request) + { throw new \InvalidArgumentException('Request must be instance of \Yurun\Util\YurunHttp\Http\Request or \Yurun\Util\HttpRequest'); } } - if (null === $handlerClass) { + if (null === $handlerClass) + { $handler = YurunHttp::getHandler($options); } - else { + else + { $handler = new $handlerClass(); } /** @var \Yurun\Util\YurunHttp\Handler\IHandler $handler */ $result = $handler->coBatch($batchRequests, $timeout); - foreach ($downloadAutoExt as $i) { - if (isset($result[$i])) { + foreach ($downloadAutoExt as $i) + { + if (isset($result[$i])) + { $response = &$result[$i]; } - else { + else + { $response = null; } - if ($response) { + if ($response) + { HttpRequest::parseDownloadAutoExt($response, $response->getRequest()->getAttribute(Attributes::SAVE_FILE_PATH)); } unset($response); diff --git a/src/YurunHttp/ConnectionPool.php b/src/YurunHttp/ConnectionPool.php index 50316e9..c1bd526 100644 --- a/src/YurunHttp/ConnectionPool.php +++ b/src/YurunHttp/ConnectionPool.php @@ -80,23 +80,28 @@ public static function disable() */ public static function setConfig($url, $maxConnections = 0, $waitTimeout = 30) { - if (isset(self::$connectionPoolConfigs[$url])) { + if (isset(self::$connectionPoolConfigs[$url])) + { $config = self::$connectionPoolConfigs[$url]; $config->setMaxConnections($maxConnections); $config->setWaitTimeout($waitTimeout); } - else { + else + { self::$connectionPoolConfigs[$url] = $config = new PoolConfig($url, $maxConnections, $waitTimeout); } - foreach (self::$connectionManagers as $class) { + foreach (self::$connectionManagers as $class) + { /** @var IConnectionManager $connectionManager */ $connectionManager = $class::getInstance(); $connectionManagerConfig = $connectionManager->getConfig($url); - if ($connectionManagerConfig) { + if ($connectionManagerConfig) + { $connectionManagerConfig->setMaxConnections($maxConnections); $connectionManagerConfig->setWaitTimeout($waitTimeout); } - else { + else + { $connectionManager->setConfig($url, $maxConnections, $waitTimeout); } } @@ -111,10 +116,12 @@ public static function setConfig($url, $maxConnections = 0, $waitTimeout = 30) */ public static function getConfig($url) { - if (isset(self::$connectionPoolConfigs[$url])) { + if (isset(self::$connectionPoolConfigs[$url])) + { return self::$connectionPoolConfigs[$url]; } - else { + else + { return null; } } @@ -128,10 +135,12 @@ public static function getConfig($url) */ public static function getKey($url) { - if ($url instanceof UriInterface) { + if ($url instanceof UriInterface) + { return $url->getScheme() . '://' . Uri::getDomain($url); } - else { + else + { return $url; } } diff --git a/src/YurunHttp/Cookie/CookieItem.php b/src/YurunHttp/Cookie/CookieItem.php index 3675148..7f469d4 100644 --- a/src/YurunHttp/Cookie/CookieItem.php +++ b/src/YurunHttp/Cookie/CookieItem.php @@ -86,7 +86,8 @@ public function __construct($name, $value, $expires = 0, $path = '/', $domain = public static function newInstance($data) { $object = new static('', ''); - foreach ($data as $k => $v) { + foreach ($data as $k => $v) + { $object->$k = $v; } @@ -102,25 +103,32 @@ public static function newInstance($data) */ public static function fromSetCookie($setCookieContent) { - if (preg_match_all('/;?\s*((?P[^=;]+)=(?P[^;]+)|((?P[^=;]+)))/', $setCookieContent, $matches) > 0) { + if (preg_match_all('/;?\s*((?P[^=;]+)=(?P[^;]+)|((?P[^=;]+)))/', $setCookieContent, $matches) > 0) + { $name = $matches['name'][0]; $value = $matches['value'][0]; unset($matches['name'][0], $matches['value'][0]); $data = array_combine(array_map('strtolower', $matches['name']), $matches['value']); - if (isset($data[''])) { + if (isset($data[''])) + { unset($data['']); } - if (isset($data['max-age'])) { + if (isset($data['max-age'])) + { $expires = time() + $data['max-age']; } - elseif (isset($data['expires'])) { + elseif (isset($data['expires'])) + { $expires = strtotime($data['expires']); } - else { + else + { $expires = null; } - foreach ($matches['name2'] as $boolItemName) { - if ('' !== $boolItemName) { + foreach ($matches['name2'] as $boolItemName) + { + if ('' !== $boolItemName) + { $data[strtolower($boolItemName)] = true; } } @@ -128,7 +136,8 @@ public static function fromSetCookie($setCookieContent) return $object; } - else { + else + { return null; } } diff --git a/src/YurunHttp/Cookie/CookieJar.php b/src/YurunHttp/Cookie/CookieJar.php index 11c20e4..110f4fd 100644 --- a/src/YurunHttp/Cookie/CookieJar.php +++ b/src/YurunHttp/Cookie/CookieJar.php @@ -24,7 +24,8 @@ public function __construct($cookieManager) */ public function load($fileName) { - if (is_file($fileName)) { + if (is_file($fileName)) + { $data = json_decode(file_get_contents($fileName), true); $this->cookieManager->setCookieList($data); } @@ -38,7 +39,8 @@ public function load($fileName) public function save($fileName) { $data = []; - foreach ($this->cookieManager->getCookieList() as $cookieItem) { + foreach ($this->cookieManager->getCookieList() as $cookieItem) + { $data[] = (array) $cookieItem; } file_put_contents($fileName, json_encode($data, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE)); diff --git a/src/YurunHttp/Cookie/CookieManager.php b/src/YurunHttp/Cookie/CookieManager.php index 9f2691a..46cbf94 100644 --- a/src/YurunHttp/Cookie/CookieManager.php +++ b/src/YurunHttp/Cookie/CookieManager.php @@ -50,7 +50,8 @@ public function setCookieList($cookieList) $this->autoIncrementId = 1; $this->cookieList = []; $this->relationMap = []; - foreach ($cookieList as $item) { + foreach ($cookieList as $item) + { $item = CookieItem::newInstance($item); $this->insertCookie($item); } @@ -76,10 +77,12 @@ public function getCookieList() public function addSetCookie($setCookie) { $item = CookieItem::fromSetCookie($setCookie); - if (($id = $this->findCookie($item)) > 0) { + if (($id = $this->findCookie($item)) > 0) + { $this->updateCookie($id, $item); } - else { + else + { $this->insertCookie($item); } @@ -102,10 +105,12 @@ public function addSetCookie($setCookie) public function setCookie($name, $value, $expires = 0, $path = '/', $domain = '', $secure = false, $httpOnly = false) { $item = new CookieItem($name, $value, $expires, $path, $domain, $secure, $httpOnly); - if (($id = $this->findCookie($item)) > 0) { + if (($id = $this->findCookie($item)) > 0) + { $this->updateCookie($id, $item); } - else { + else + { $this->insertCookie($item); } @@ -132,24 +137,32 @@ public function count() public function getRequestCookies($uri) { // @phpstan-ignore-next-line - if (\defined('SWOOLE_VERSION') && \SWOOLE_VERSION < 4.4) { + if (\defined('SWOOLE_VERSION') && \SWOOLE_VERSION < 4.4) + { // Fix bug: https://github.com/swoole/swoole-src/pull/2644 $result = json_decode('[]', true); } - else { + else + { $result = []; } $uriDomain = Uri::getDomain($uri); $uriPath = $uri->getPath(); $cookieList = &$this->cookieList; $time = time(); - foreach ($this->relationMap as $relationDomain => $list1) { - if ('' === $relationDomain || $this->checkDomain($uriDomain, $relationDomain)) { - foreach ($list1 as $path => $idList) { - if ($this->checkPath($uriPath, $path)) { - foreach ($idList as $id) { + foreach ($this->relationMap as $relationDomain => $list1) + { + if ('' === $relationDomain || $this->checkDomain($uriDomain, $relationDomain)) + { + foreach ($list1 as $path => $idList) + { + if ($this->checkPath($uriPath, $path)) + { + foreach ($idList as $id) + { $cookieItem = $cookieList[$id]; - if ((0 === $cookieItem->expires || $cookieItem->expires > $time) && (!$cookieItem->secure || 'https' === $uri->getScheme() || 'wss' === $uri->getScheme())) { + if ((0 === $cookieItem->expires || $cookieItem->expires > $time) && (!$cookieItem->secure || 'https' === $uri->getScheme() || 'wss' === $uri->getScheme())) + { $result[$cookieItem->name] = $cookieItem->value; } } @@ -171,7 +184,8 @@ public function getRequestCookies($uri) public function getRequestCookieString($uri) { $content = ''; - foreach ($this->getRequestCookies($uri) as $name => $value) { + foreach ($this->getRequestCookies($uri) as $name => $value) + { $content .= "{$name}={$value}; "; } @@ -189,7 +203,8 @@ public function getRequestCookieString($uri) */ public function getCookieItem($name, $domain = '', $path = '/') { - if (isset($this->relationMap[$domain][$path][$name])) { + if (isset($this->relationMap[$domain][$path][$name])) + { $id = $this->relationMap[$domain][$path][$name]; return $this->cookieList[$id]; @@ -205,12 +220,16 @@ public function getCookieItem($name, $domain = '', $path = '/') */ public function gc() { - if ($this->cookieList) { + if ($this->cookieList) + { $time = time(); - foreach ($this->cookieList as $id => $item) { - if ($item->expires > 0 && $time >= $item->expires) { + foreach ($this->cookieList as $id => $item) + { + if ($item->expires > 0 && $time >= $item->expires) + { unset($this->cookieList[$id]); - if (isset($this->relationMap[$item->domain][$item->path][$item->name]) && $id === $this->relationMap[$item->domain][$item->path][$item->name]) { + if (isset($this->relationMap[$item->domain][$item->path][$item->name]) && $id === $this->relationMap[$item->domain][$item->path][$item->name]) + { unset($this->relationMap[$item->domain][$item->path][$item->name]); } } @@ -245,35 +264,44 @@ private function checkPath($uriPath, $cookiePath) { $uriPath = rtrim($uriPath, '/'); $cookiePath = rtrim($cookiePath, '/'); - if ($uriPath === $cookiePath) { + if ($uriPath === $cookiePath) + { return true; } $uriPathDSCount = substr_count($uriPath, '/'); $cookiePathDSCount = substr_count($cookiePath, '/'); - if ('' === $uriPath) { + if ('' === $uriPath) + { $uriPath = '/'; } - if ('' === $cookiePath) { + if ('' === $cookiePath) + { $cookiePath = '/'; } - if ($uriPathDSCount > $cookiePathDSCount) { - if (version_compare(\PHP_VERSION, '7.0', '>=')) { + if ($uriPathDSCount > $cookiePathDSCount) + { + if (version_compare(\PHP_VERSION, '7.0', '>=')) + { $path = \dirname($uriPath, $uriPathDSCount - $cookiePathDSCount); } - else { + else + { $count = $uriPathDSCount - $cookiePathDSCount; $path = $uriPath; - while ($count--) { + while ($count--) + { $path = \dirname($path); } } - if ('\\' === \DIRECTORY_SEPARATOR && str_contains($path, \DIRECTORY_SEPARATOR)) { + if ('\\' === \DIRECTORY_SEPARATOR && str_contains($path, \DIRECTORY_SEPARATOR)) + { $path = str_replace(\DIRECTORY_SEPARATOR, '/', $path); } return $path === $cookiePath; } - else { + else + { return false; } } @@ -288,10 +316,12 @@ private function checkPath($uriPath, $cookiePath) */ private function updateCookie($id, $item) { - if (isset($this->cookieList[$id])) { + if (isset($this->cookieList[$id])) + { $object = $this->cookieList[$id]; // @phpstan-ignore-next-line - foreach ($item as $k => $v) { + foreach ($item as $k => $v) + { $object->$k = $v; } } @@ -322,10 +352,12 @@ private function insertCookie($item) */ private function findCookie($item) { - if (isset($this->relationMap[$item->domain][$item->path][$item->name])) { + if (isset($this->relationMap[$item->domain][$item->path][$item->name])) + { return $this->relationMap[$item->domain][$item->path][$item->name]; } - else { + else + { return null; } } diff --git a/src/YurunHttp/FormDataBuilder.php b/src/YurunHttp/FormDataBuilder.php index 47accb8..0321376 100644 --- a/src/YurunHttp/FormDataBuilder.php +++ b/src/YurunHttp/FormDataBuilder.php @@ -16,14 +16,17 @@ abstract class FormDataBuilder public static function build($body, $files, &$boundary) { $result = ''; - if (!\is_array($body)) { + if (!\is_array($body)) + { parse_str($body, $body); } $boundary = Random::letter(8, 16); - foreach ($body as $k => $v) { + foreach ($body as $k => $v) + { $result .= sprintf("--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", $boundary, $k, $v); } - foreach ($files as $name => $file) { + foreach ($files as $name => $file) + { $result .= sprintf("--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n", $boundary, $name, basename($file->getClientFilename()), $file->getClientMediaType()) . $file->getStream()->getContents() . "\r\n"; } $result .= sprintf("--%s--\r\n", $boundary); diff --git a/src/YurunHttp/Handler/Curl.php b/src/YurunHttp/Handler/Curl.php index 06871e4..2123376 100644 --- a/src/YurunHttp/Handler/Curl.php +++ b/src/YurunHttp/Handler/Curl.php @@ -98,7 +98,8 @@ class Curl implements IHandler public function __construct($options = []) { $this->options = $options; - if (null === self::$defaultUA) { + if (null === self::$defaultUA) + { $version = curl_version(); self::$defaultUA = sprintf('Mozilla/5.0 YurunHttp/%s Curl/%s', YurunHttp::VERSION, isset($version['version']) ? $version['version'] : 'unknown'); } @@ -112,11 +113,14 @@ public function __construct($options = []) */ public function close() { - if ($this->handler) { - if ($this->poolIsEnabled) { + if ($this->handler) + { + if ($this->poolIsEnabled) + { CurlHttpConnectionManager::getInstance()->release($this->poolKey, $this->handler); } - else { + else + { curl_close($this->handler); } $this->handler = null; @@ -133,35 +137,43 @@ public function close() public function send(&$request) { $this->poolIsEnabled = $poolIsEnabled = ConnectionPool::isEnabled() && false !== $request->getAttribute(Attributes::CONNECTION_POOL); - if ($poolIsEnabled) { + if ($poolIsEnabled) + { $httpConnectionManager = CurlHttpConnectionManager::getInstance(); } - try { + try + { $this->request = $request; $request = &$this->request; $handler = &$this->handler; - if ($handler) { + if ($handler) + { curl_reset($handler); } - else { - if ($poolIsEnabled) { + else + { + if ($poolIsEnabled) + { $this->poolKey = $poolKey = ConnectionPool::getKey($request->getUri()); $handler = $httpConnectionManager->getConnection($poolKey); curl_reset($handler); } - else { + else + { $handler = curl_init(); } } $files = $request->getUploadedFiles(); $body = (string) $request->getBody(); - if (!empty($files)) { + if (!empty($files)) + { $body = FormDataBuilder::build($body, $files, $boundary); $request = $request->withHeader('Content-Type', MediaType::MULTIPART_FORM_DATA . '; boundary=' . $boundary); } $this->buildCurlHandlerBase($request, $handler, $receiveHeaders, $saveFileFp); - if ([] !== ($queryParams = $request->getQueryParams())) { + if ([] !== ($queryParams = $request->getQueryParams())) + { $request = $request->withUri($request->getUri()->withQuery(http_build_query($queryParams, '', '&'))); } $uri = $request->getUri(); @@ -171,45 +183,58 @@ public function send(&$request) $retry = $request->getAttribute(Attributes::RETRY, 0); $retryCallback = $request->getAttribute(Attributes::RETRY_CALLBACK); $beginTime = microtime(true); - while (true) { + while (true) + { // 请求方法 - if ($isLocation && \in_array($statusCode, [301, 302, 303])) { + if ($isLocation && \in_array($statusCode, [301, 302, 303])) + { $method = 'GET'; } - else { + else + { $method = $request->getMethod(); } - if ('GET' !== $method) { + if ('GET' !== $method) + { $bodyContent = $body; } - else { + else + { $bodyContent = false; } $this->buildCurlHandlerEx($request, $handler, $uri, $method, $bodyContent); $result = null; - for ($i = 0; $i <= $retry; ++$i) { + for ($i = 0; $i <= $retry; ++$i) + { $receiveHeaders = []; $curlResult = curl_exec($handler); $this->result = $this->getResponse($request, $handler, $curlResult, $receiveHeaders); $result = &$this->result; - if ($retryCallback) { - if ($retryCallback($request, $result, $i)) { + if ($retryCallback) + { + if ($retryCallback($request, $result, $i)) + { break; } } - else { + else + { $statusCode = $result->getStatusCode(); // 状态码为5XX或者0才需要重试 - if (!(0 === $statusCode || (5 === (int) ($statusCode / 100)))) { + if (!(0 === $statusCode || (5 === (int) ($statusCode / 100)))) + { break; } } } - if ($request->getAttribute(Attributes::FOLLOW_LOCATION, true) && ($statusCode >= 300 && $statusCode < 400) && $result && '' !== ($location = $result->getHeaderLine('location'))) { + if ($request->getAttribute(Attributes::FOLLOW_LOCATION, true) && ($statusCode >= 300 && $statusCode < 400) && $result && '' !== ($location = $result->getHeaderLine('location'))) + { $maxRedirects = $request->getAttribute(Attributes::MAX_REDIRECTS, 10); - if (++$redirectCount <= $maxRedirects) { + if (++$redirectCount <= $maxRedirects) + { // 重定向清除之前下载的文件 - if (null !== $saveFileFp) { + if (null !== $saveFileFp) + { ftruncate($saveFileFp, 0); fseek($saveFileFp, 0); } @@ -217,7 +242,8 @@ public function send(&$request) $uri = $this->parseRedirectLocation($location, $uri); continue; } - else { + else + { $result = $result->withErrno(-1) ->withError(sprintf('Maximum (%s) redirects followed', $maxRedirects)); } @@ -230,14 +256,18 @@ public function send(&$request) } // 关闭保存至文件的句柄 - if (null !== $saveFileFp) { + if (null !== $saveFileFp) + { fclose($saveFileFp); $saveFileFp = null; } } - finally { - if ($this->handler) { - if ($poolIsEnabled) { + finally + { + if ($this->handler) + { + if ($poolIsEnabled) + { // @phpstan-ignore-next-line $httpConnectionManager->release($this->poolKey, $this->handler); $this->handler = null; @@ -260,28 +290,34 @@ private function buildCurlHandlerBase(&$request, $handler, &$headers = null, &$s { $options = $request->getAttribute(Attributes::OPTIONS, []); // 返回内容 - if (!isset($options[\CURLOPT_RETURNTRANSFER])) { + if (!isset($options[\CURLOPT_RETURNTRANSFER])) + { $options[\CURLOPT_RETURNTRANSFER] = true; } // 保存cookie - if (!isset($options[\CURLOPT_COOKIEJAR])) { + if (!isset($options[\CURLOPT_COOKIEJAR])) + { $options[\CURLOPT_COOKIEJAR] = 'php://memory'; } // 允许复用连接 - if (!isset($options[\CURLOPT_FORBID_REUSE])) { + if (!isset($options[\CURLOPT_FORBID_REUSE])) + { $options[\CURLOPT_FORBID_REUSE] = false; } // 自动重定向 - if (!isset($options[\CURLOPT_MAXREDIRS])) { + if (!isset($options[\CURLOPT_MAXREDIRS])) + { $options[\CURLOPT_MAXREDIRS] = $request->getAttribute(Attributes::MAX_REDIRECTS, 10); } // 自动解压缩支持 $acceptEncoding = $request->getHeaderLine('Accept-Encoding'); - if ('' !== $acceptEncoding) { + if ('' !== $acceptEncoding) + { $options[\CURLOPT_ENCODING] = $acceptEncoding; } - else { + else + { $options[\CURLOPT_ENCODING] = ''; } $this->parseOptions($request, $options, $headers, $saveFileFp); @@ -306,25 +342,31 @@ private function buildCurlHandlerBase(&$request, $handler, &$headers = null, &$s */ private function buildCurlHandlerEx(&$request, $handler, $uri = null, $method = null, $body = null) { - if (null === $uri) { + if (null === $uri) + { $uri = $request->getUri(); } - if (null === $method) { + if (null === $method) + { $method = $request->getMethod(); } - if (null === $body) { + if (null === $body) + { $body = (string) $request->getBody(); } - switch ($request->getProtocolVersion()) { + switch ($request->getProtocolVersion()) + { case '1.0': $httpVersion = \CURL_HTTP_VERSION_1_0; break; case '2.0': $ssl = 'https' === $uri->getScheme(); - if ($ssl) { + if ($ssl) + { $httpVersion = \CURL_HTTP_VERSION_2TLS; } - else { + else + { $httpVersion = \CURL_HTTP_VERSION_2; } break; @@ -336,11 +378,13 @@ private function buildCurlHandlerEx(&$request, $handler, $uri = null, $method = \CURLOPT_HTTP_VERSION => $httpVersion, ]; // 请求方法 - if ($body && 'GET' !== $method) { + if ($body && 'GET' !== $method) + { $requestOptions[\CURLOPT_POSTFIELDS] = $body; } $requestOptions[\CURLOPT_CUSTOMREQUEST] = $method; - if ('HEAD' === $method) { + if ('HEAD' === $method) + { $requestOptions[\CURLOPT_NOBODY] = true; } curl_setopt_array($handler, $requestOptions); @@ -369,7 +413,8 @@ public function recv() private function getResponse($request, $handler, $body, $receiveHeaders) { // PHP 7.0.0开始substr()的 string 字符串长度与 start 相同时将返回一个空字符串。在之前的版本中,这种情况将返回 FALSE 。 - if (false === $body) { + if (false === $body) + { $body = ''; } @@ -378,20 +423,23 @@ private function getResponse($request, $handler, $body, $receiveHeaders) // headers $headers = $this->parseHeaderOneRequest($receiveHeaders); - foreach ($headers as $name => $value) { + foreach ($headers as $name => $value) + { $result = $result->withAddedHeader($name, $value); } // cookies $cookies = []; $cookieManager = $this->cookieManager; - foreach ($result->getHeader('set-cookie') as $content) { + foreach ($result->getHeader('set-cookie') as $content) + { $cookieItem = $cookieManager->addSetCookie($content); $cookies[$cookieItem->name] = (array) $cookieItem; } // 下载文件名 - if ($savedFileName = $request->getAttribute(Attributes::SAVE_FILE_PATH)) { + if ($savedFileName = $request->getAttribute(Attributes::SAVE_FILE_PATH)) + { $result = $result->withSavedFileName($savedFileName); } @@ -413,19 +461,24 @@ private function parseHeaderOneRequest($headers) $tmpHeaders = []; $count = \count($headers); // 从1开始,第0行包含了协议信息和状态信息,排除该行 - for ($i = 1; $i < $count; ++$i) { + for ($i = 1; $i < $count; ++$i) + { $line = trim($headers[$i]); - if (empty($line) || false == strstr($line, ':')) { + if (empty($line) || false == strstr($line, ':')) + { continue; } list($key, $value) = explode(':', $line, 2); $key = trim($key); $value = trim($value); - if (isset($tmpHeaders[$key])) { - if (\is_array($tmpHeaders[$key])) { + if (isset($tmpHeaders[$key])) + { + if (\is_array($tmpHeaders[$key])) + { $tmpHeaders[$key][] = $value; } - else { + else + { $tmp = $tmpHeaders[$key]; $tmpHeaders[$key] = [ $tmp, @@ -433,7 +486,8 @@ private function parseHeaderOneRequest($headers) ]; } } - else { + else + { $tmpHeaders[$key] = $value; } } @@ -451,23 +505,27 @@ private function parseHeaderOneRequest($headers) */ private function parseSSL(&$request, &$options) { - if ($request->getAttribute(Attributes::IS_VERIFY_CA, false)) { + if ($request->getAttribute(Attributes::IS_VERIFY_CA, false)) + { $options[\CURLOPT_SSL_VERIFYPEER] = true; $options[\CURLOPT_CAINFO] = $request->getAttribute(Attributes::CA_CERT); $options[\CURLOPT_SSL_VERIFYHOST] = 2; } - else { + else + { $options[\CURLOPT_SSL_VERIFYPEER] = false; $options[\CURLOPT_SSL_VERIFYHOST] = 0; } $certPath = $request->getAttribute(Attributes::CERT_PATH, ''); - if ('' !== $certPath) { + if ('' !== $certPath) + { $options[\CURLOPT_SSLCERT] = $certPath; $options[\CURLOPT_SSLCERTPASSWD] = $request->getAttribute(Attributes::CERT_PASSWORD); $options[\CURLOPT_SSLCERTTYPE] = $request->getAttribute(Attributes::CERT_TYPE, 'pem'); } $keyPath = $request->getAttribute(Attributes::KEY_PATH, ''); - if ('' !== $keyPath) { + if ('' !== $keyPath) + { $options[\CURLOPT_SSLKEY] = $keyPath; $options[\CURLOPT_SSLKEYPASSWD] = $request->getAttribute(Attributes::KEY_PASSWORD); $options[\CURLOPT_SSLKEYTYPE] = $request->getAttribute(Attributes::KEY_TYPE, 'pem'); @@ -486,25 +544,30 @@ private function parseSSL(&$request, &$options) */ private function parseOptions(&$request, &$options, &$headers = null, &$saveFileFp = null) { - if (isset($options[\CURLOPT_HEADERFUNCTION])) { + if (isset($options[\CURLOPT_HEADERFUNCTION])) + { $headerCallable = $options[\CURLOPT_HEADERFUNCTION]; } - else { + else + { $headerCallable = null; } $headers = []; $options[\CURLOPT_HEADERFUNCTION] = function ($handler, $header) use ($headerCallable, &$headers) { $headers[] = $header; - if ($headerCallable) { + if ($headerCallable) + { $headerCallable($handler, $header); } return \strlen($header); }; // 请求结果保存为文件 - if (null !== ($saveFilePath = $request->getAttribute(Attributes::SAVE_FILE_PATH))) { + if (null !== ($saveFilePath = $request->getAttribute(Attributes::SAVE_FILE_PATH))) + { $last = substr($saveFilePath, -1, 1); - if ('/' === $last || '\\' === $last) { + if ('/' === $last || '\\' === $last) + { // 自动获取文件名 $saveFilePath .= basename($request->getUri()->__toString()); } @@ -525,7 +588,8 @@ private function parseOptions(&$request, &$options, &$headers = null, &$saveFile */ private function parseProxy(&$request, &$options) { - if ($request->getAttribute(Attributes::USE_PROXY, false)) { + if ($request->getAttribute(Attributes::USE_PROXY, false)) + { $type = $request->getAttribute(Attributes::PROXY_TYPE, 'http'); $options[\CURLOPT_PROXYAUTH] = self::$proxyAuths[$request->getAttribute(Attributes::PROXY_AUTH, 'basic')]; $options[\CURLOPT_PROXY] = $request->getAttribute(Attributes::PROXY_SERVER); @@ -545,10 +609,12 @@ private function parseProxy(&$request, &$options) */ private function parseHeaders(&$request, &$options) { - if (!$request->hasHeader('User-Agent')) { + if (!$request->hasHeader('User-Agent')) + { $request = $request->withHeader('User-Agent', $request->getAttribute(Attributes::USER_AGENT, self::$defaultUA)); } - if (!$request->hasHeader('Connection') && $request->getProtocolVersion() >= 1.1) { + if (!$request->hasHeader('Connection') && $request->getProtocolVersion() >= 1.1) + { $request = $request->withHeader('Connection', 'Keep-Alive')->withHeader('Keep-Alive', '300'); } $options[\CURLOPT_HTTPHEADER] = $this->parseHeadersFormat($request); @@ -564,7 +630,8 @@ private function parseHeaders(&$request, &$options) private function parseHeadersFormat($request) { $headers = []; - foreach ($request->getHeaders() as $name => $value) { + foreach ($request->getHeaders() as $name => $value) + { $headers[] = $name . ': ' . implode(',', $value); } @@ -582,11 +649,13 @@ private function parseHeadersFormat($request) private function parseCookies(&$request, &$options) { $cookieManager = $this->cookieManager; - foreach ($request->getCookieParams() as $name => $value) { + foreach ($request->getCookieParams() as $name => $value) + { $cookieManager->setCookie($name, $value); } $cookie = $cookieManager->getRequestCookieString($request->getUri()); - if ('' !== $cookie) { + if ('' !== $cookie) + { $options[\CURLOPT_COOKIE] = $cookie; } } @@ -603,10 +672,12 @@ private function parseNetwork(&$request, &$options) { // 用户名密码处理 $username = $request->getAttribute(Attributes::USERNAME); - if (null != $username) { + if (null != $username) + { $userPwd = $username . ':' . $request->getAttribute(Attributes::PASSWORD, ''); } - else { + else + { $userPwd = ''; } // 连接超时 @@ -659,15 +730,18 @@ public function coBatch($requests, $timeout = null) $curlHandlers = $recvHeaders = $saveFileFps = []; $result = []; $needRedirectRequests = []; - try { - foreach ($requests as $k => $request) { + try + { + foreach ($requests as $k => $request) + { $result[$k] = null; $curlHandler = curl_init(); $recvHeaders[$k] = $saveFileFps[$k] = null; $this->buildCurlHandlerBase($request, $curlHandler, $recvHeaders[$k], $saveFileFps[$k]); $files = $request->getUploadedFiles(); $body = (string) $request->getBody(); - if (!empty($files)) { + if (!empty($files)) + { $body = FormDataBuilder::build($body, $files, $boundary); $request = $request->withHeader('Content-Type', MediaType::MULTIPART_FORM_DATA . '; boundary=' . $boundary); } @@ -678,20 +752,25 @@ public function coBatch($requests, $timeout = null) $running = null; $beginTime = microtime(true); // 执行批处理句柄 - while (true) { + while (true) + { curl_multi_exec($mh, $running); - if ($running > 0) { - if ($timeout && microtime(true) - $beginTime >= $timeout) { + if ($running > 0) + { + if ($timeout && microtime(true) - $beginTime >= $timeout) + { break; } usleep(5000); // 每次延时 5 毫秒 } - else { + else + { break; } } - foreach ($requests as $k => $request) { + foreach ($requests as $k => $request) + { $handler = $curlHandlers[$k]; $receiveHeaders = $recvHeaders[$k]; $curlResult = curl_multi_getcontent($handler); @@ -700,18 +779,22 @@ public function coBatch($requests, $timeout = null) // 重定向处理 $statusCode = $response->getStatusCode(); $redirectCount = $request->getAttribute(Attributes::PRIVATE_REDIRECT_COUNT); - if ($request->getAttribute(Attributes::FOLLOW_LOCATION, true) && ($statusCode >= 300 && $statusCode < 400) && '' !== ($location = $response->getHeaderLine('location'))) { + if ($request->getAttribute(Attributes::FOLLOW_LOCATION, true) && ($statusCode >= 300 && $statusCode < 400) && '' !== ($location = $response->getHeaderLine('location'))) + { $maxRedirects = $request->getAttribute(Attributes::MAX_REDIRECTS, 10); - if (++$redirectCount <= $maxRedirects) { + if (++$redirectCount <= $maxRedirects) + { $request = $request->withAttribute(Attributes::PRIVATE_REDIRECT_COUNT, $redirectCount); - if (\in_array($statusCode, [301, 302, 303])) { + if (\in_array($statusCode, [301, 302, 303])) + { $request = $request->withMethod('GET')->withBody(new MemoryStream()); } $request = $request->withUri($this->parseRedirectLocation($location, $request->getUri())); $needRedirectRequests[$k] = $request; continue; } - else { + else + { $response = $response->withErrno(-1) ->withError(sprintf('Maximum (%s) redirects followed', $maxRedirects)); } @@ -723,21 +806,27 @@ public function coBatch($requests, $timeout = null) $this->cookieManager->gc(); $this->saveCookieJar(); } - finally { - foreach ($saveFileFps as $fp) { + finally + { + foreach ($saveFileFps as $fp) + { // @phpstan-ignore-next-line - if ($fp) { + if ($fp) + { fclose($fp); } } - foreach ($curlHandlers as $curlHandler) { + foreach ($curlHandlers as $curlHandler) + { curl_multi_remove_handle($mh, $curlHandler); curl_close($curlHandler); } curl_multi_close($mh); } - if ($needRedirectRequests) { - foreach ($this->coBatch($needRedirectRequests, $timeout) as $k => $response) { + if ($needRedirectRequests) + { + foreach ($this->coBatch($needRedirectRequests, $timeout) as $k => $response) + { $result[$k] = $response; } } diff --git a/src/YurunHttp/Handler/Curl/CurlConnectionPool.php b/src/YurunHttp/Handler/Curl/CurlConnectionPool.php index e6b9ad8..7ca5ad8 100644 --- a/src/YurunHttp/Handler/Curl/CurlConnectionPool.php +++ b/src/YurunHttp/Handler/Curl/CurlConnectionPool.php @@ -39,7 +39,8 @@ public function close() $connections = $this->connections; $this->connections = []; $this->queue = new \SplQueue(); - foreach ($connections as $connection) { + foreach ($connections as $connection) + { curl_close($connection); } } @@ -61,15 +62,19 @@ public function createConnection() */ public function getConnection() { - if ($this->getFree() > 0) { + if ($this->getFree() > 0) + { return $this->queue->dequeue(); } - else { + else + { $maxConnections = $this->getConfig()->getMaxConnections(); - if (0 != $maxConnections && $this->getCount() >= $maxConnections) { + if (0 != $maxConnections && $this->getCount() >= $maxConnections) + { return false; } - else { + else + { return $this->connections[] = $this->createConnection(); } } @@ -84,7 +89,8 @@ public function getConnection() */ public function release($connection) { - if (\in_array($connection, $this->connections)) { + if (\in_array($connection, $this->connections)) + { $this->queue->enqueue($connection); } } diff --git a/src/YurunHttp/Handler/Curl/CurlHttpConnectionManager.php b/src/YurunHttp/Handler/Curl/CurlHttpConnectionManager.php index 7fe4732..9daeb5e 100644 --- a/src/YurunHttp/Handler/Curl/CurlHttpConnectionManager.php +++ b/src/YurunHttp/Handler/Curl/CurlHttpConnectionManager.php @@ -28,7 +28,8 @@ class CurlHttpConnectionManager implements IConnectionManager */ public static function getInstance() { - if (null === self::$instance) { + if (null === self::$instance) + { return self::$instance = new static(); } @@ -54,12 +55,15 @@ public function getConnectionPools() */ public function getConnectionPool($url) { - if (isset($this->connectionPools[$url])) { + if (isset($this->connectionPools[$url])) + { return $this->connectionPools[$url]; } - else { + else + { $config = ConnectionPool::getConfig($url); - if (null === $config) { + if (null === $config) + { ConnectionPool::setConfig($url); } $config = ConnectionPool::getConfig($url); @@ -131,7 +135,8 @@ public function close() { $connectionPools = $this->connectionPools; $this->connectionPools = []; - foreach ($connectionPools as $connectionPool) { + foreach ($connectionPools as $connectionPool) + { $connectionPool->close(); } } diff --git a/src/YurunHttp/Handler/Swoole.php b/src/YurunHttp/Handler/Swoole.php index 598dcda..251a74e 100644 --- a/src/YurunHttp/Handler/Swoole.php +++ b/src/YurunHttp/Handler/Swoole.php @@ -70,7 +70,8 @@ class Swoole implements IHandler public function __construct($options = []) { $this->options = $options; - if (null === self::$defaultUA) { + if (null === self::$defaultUA) + { self::$defaultUA = sprintf('Mozilla/5.0 YurunHttp/%s Swoole/%s', YurunHttp::VERSION, \defined('SWOOLE_VERSION') ? \SWOOLE_VERSION : 'unknown'); } $this->initCookieManager(); @@ -100,18 +101,22 @@ public function close() */ public function buildRequest($request, $connection, &$http2Request) { - if ($isHttp2 = '2.0' === $request->getProtocolVersion()) { + if ($isHttp2 = '2.0' === $request->getProtocolVersion()) + { $http2Request = new Http2Request(); } - else { + else + { $http2Request = null; } $uri = $request->getUri(); // method - if ($isHttp2) { + if ($isHttp2) + { $http2Request->method = $request->getMethod(); } - else { + else + { $connection->setMethod($request->getMethod()); } // cookie @@ -119,23 +124,29 @@ public function buildRequest($request, $connection, &$http2Request) // body $hasFile = false; $redirectCount = $request->getAttribute(Attributes::PRIVATE_REDIRECT_COUNT, 0); - if ($redirectCount <= 0) { + if ($redirectCount <= 0) + { $files = $request->getUploadedFiles(); $body = (string) $request->getBody(); - if (!empty($files)) { - if ($isHttp2) { + if (!empty($files)) + { + if ($isHttp2) + { throw new \RuntimeException('Http2 swoole handler does not support upload file'); } $hasFile = true; - foreach ($files as $name => $file) { + foreach ($files as $name => $file) + { $connection->addFile($file->getTempFileName(), $name, $file->getClientMediaType(), basename($file->getClientFilename())); } parse_str($body, $body); } - if ($isHttp2) { + if ($isHttp2) + { $http2Request->data = $body; } - else { + else + { $connection->setData($body); } } @@ -145,37 +156,46 @@ public function buildRequest($request, $connection, &$http2Request) $this->parseNetwork($request); // 设置客户端参数 $settings = $request->getAttribute(Attributes::OPTIONS, []); - if ($settings) { + if ($settings) + { $connection->set($settings); } // headers - if (!$request->hasHeader('Host')) { + if (!$request->hasHeader('Host')) + { $request = $request->withHeader('Host', Uri::getDomain($uri)); } - if (!$hasFile && !$request->hasHeader('Content-Type')) { + if (!$hasFile && !$request->hasHeader('Content-Type')) + { $request = $request->withHeader('Content-Type', MediaType::APPLICATION_FORM_URLENCODED); } - if (!$request->hasHeader('User-Agent')) { + if (!$request->hasHeader('User-Agent')) + { $request = $request->withHeader('User-Agent', $request->getAttribute(Attributes::USER_AGENT, self::$defaultUA)); } $headers = []; - foreach ($request->getHeaders() as $name => $value) { + foreach ($request->getHeaders() as $name => $value) + { $headers[$name] = implode(',', $value); } - if ($isHttp2) { + if ($isHttp2) + { $http2Request->headers = $headers; $http2Request->pipeline = $request->getAttribute(Attributes::HTTP2_PIPELINE, false); $path = $uri->getPath(); - if ('' === $path) { + if ('' === $path) + { $path = '/'; } $query = $uri->getQuery(); - if ('' !== $query) { + if ('' !== $query) + { $path .= '?' . $query; } $http2Request->path = $path; } - else { + else + { $connection->setHeaders($headers); } } @@ -192,7 +212,8 @@ public function send(&$request) $this->poolIsEnabled = ConnectionPool::isEnabled() && false !== $request->getAttribute(Attributes::CONNECTION_POOL); $beginTime = microtime(true); $request = $this->sendDefer($request); - if ($request->getAttribute(Attributes::PRIVATE_IS_HTTP2) && $request->getAttribute(Attributes::HTTP2_NOT_RECV)) { + if ($request->getAttribute(Attributes::PRIVATE_IS_HTTP2) && $request->getAttribute(Attributes::HTTP2_NOT_RECV)) + { return true; } @@ -212,33 +233,43 @@ public function send(&$request) public function sendDefer($request) { $isHttp2 = '2.0' === $request->getProtocolVersion(); - if ($poolIsEnabled = $this->poolIsEnabled) { - if ($isHttp2) { + if ($poolIsEnabled = $this->poolIsEnabled) + { + if ($isHttp2) + { $http2ConnectionManager = SwooleHttp2ConnectionManager::getInstance(); } - else { + else + { $httpConnectionManager = SwooleHttpConnectionManager::getInstance(); } } - else { - if ($isHttp2) { + else + { + if ($isHttp2) + { $http2ConnectionManager = $this->http2ConnectionManager; } - else { + else + { $httpConnectionManager = $this->httpConnectionManager; } } - if ([] !== ($queryParams = $request->getQueryParams())) { + if ([] !== ($queryParams = $request->getQueryParams())) + { $request = $request->withUri($request->getUri()->withQuery(http_build_query($queryParams, '', '&'))); } $uri = $request->getUri(); - try { + try + { $poolKey = ConnectionPool::getKey($uri); - if ($isHttp2) { + if ($isHttp2) + { /** @var \Swoole\Coroutine\Http2\Client $connection */ $connection = $http2ConnectionManager->getConnection($poolKey); } - else { + else + { /** @var \Swoole\Coroutine\Http\Client $connection */ $connection = $httpConnectionManager->getConnection($poolKey); $connection->setDefer(true); @@ -249,32 +280,42 @@ public function sendDefer($request) $this->buildRequest($request, $connection, $http2Request); // 发送 $path = $uri->getPath(); - if ('' === $path) { + if ('' === $path) + { $path = '/'; } $query = $uri->getQuery(); - if ('' !== $query) { + if ('' !== $query) + { $path .= '?' . $query; } - if ($isWebSocket) { - if ($isHttp2) { + if ($isWebSocket) + { + if ($isHttp2) + { throw new \RuntimeException('Http2 swoole handler does not support websocket'); } - if (!$connection->upgrade($path)) { + if (!$connection->upgrade($path)) + { throw new WebSocketException(sprintf('WebSocket connect faled, statusCode: %s, error: %s, errorCode: %s', $connection->statusCode, swoole_strerror($connection->errCode), $connection->errCode), $connection->errCode); } } - elseif (null === ($saveFilePath = $request->getAttribute(Attributes::SAVE_FILE_PATH))) { - if ($isHttp2) { + elseif (null === ($saveFilePath = $request->getAttribute(Attributes::SAVE_FILE_PATH))) + { + if ($isHttp2) + { $result = $connection->send($http2Request); $request = $request->withAttribute(Attributes::PRIVATE_HTTP2_STREAM_ID, $result); } - else { + else + { $connection->execute($path); } } - else { - if ($isHttp2) { + else + { + if ($isHttp2) + { throw new \RuntimeException('Http2 swoole handler does not support download file'); } $connection->download($path, $saveFilePath); @@ -284,16 +325,21 @@ public function sendDefer($request) ->withAttribute(Attributes::PRIVATE_IS_WEBSOCKET, $isHttp2) ->withAttribute(Attributes::PRIVATE_CONNECTION, $connection); } - catch (\Throwable $th) { + catch (\Throwable $th) + { throw $th; } - finally { - if ($poolIsEnabled && isset($connection) && isset($th)) { - if ($isHttp2) { + finally + { + if ($poolIsEnabled && isset($connection) && isset($th)) + { + if ($isHttp2) + { // @phpstan-ignore-next-line $http2ConnectionManager->release($poolKey, $connection); } - else { + else + { // @phpstan-ignore-next-line $httpConnectionManager->release($poolKey, $connection); } @@ -318,25 +364,34 @@ public function recvDefer($request, $timeout = null) $redirectCount = $request->getAttribute(Attributes::PRIVATE_REDIRECT_COUNT, 0); $isHttp2 = '2.0' === $request->getProtocolVersion(); $isWebSocket = $request->getAttribute(Attributes::PRIVATE_WEBSOCKET, false); - try { + try + { $this->getResponse($request, $connection, $isWebSocket, $isHttp2, $timeout); } - finally { - if (!$isWebSocket) { - if ($isHttp2) { - if ($this->poolIsEnabled) { + finally + { + if (!$isWebSocket) + { + if ($isHttp2) + { + if ($this->poolIsEnabled) + { $http2ConnectionManager = SwooleHttp2ConnectionManager::getInstance(); } - else { + else + { $http2ConnectionManager = $this->http2ConnectionManager; } $http2ConnectionManager->release($poolKey, $connection); } - else { - if ($this->poolIsEnabled) { + else + { + if ($this->poolIsEnabled) + { $httpConnectionManager = SwooleHttpConnectionManager::getInstance(); } - else { + else + { $httpConnectionManager = $this->httpConnectionManager; } $httpConnectionManager->release($poolKey, $connection); @@ -345,29 +400,37 @@ public function recvDefer($request, $timeout = null) } $result = &$this->result; $statusCode = $result->getStatusCode(); - if ($retryCount < $request->getAttribute(Attributes::RETRY, 0)) { - if ($retryCallback = $request->getAttribute(Attributes::RETRY_CALLBACK)) { + if ($retryCount < $request->getAttribute(Attributes::RETRY, 0)) + { + if ($retryCallback = $request->getAttribute(Attributes::RETRY_CALLBACK)) + { $retry = !$retryCallback($request, $result, $retryCount); } - else { + else + { // 状态码为5XX或者0才需要重试 $retry = (0 === $statusCode || (5 === (int) ($statusCode / 100))); } - if ($retry) { + if ($retry) + { $request = $request->withAttribute(Attributes::PRIVATE_RETRY_COUNT, ++$retryCount); $deferRequest = $this->sendDefer($request); return $this->recvDefer($deferRequest, $timeout); } } - if (!$isWebSocket && $statusCode >= 300 && $statusCode < 400 && $request->getAttribute(Attributes::FOLLOW_LOCATION, true) && '' !== ($location = $result->getHeaderLine('location'))) { - if (++$redirectCount <= ($maxRedirects = $request->getAttribute(Attributes::MAX_REDIRECTS, 10))) { + if (!$isWebSocket && $statusCode >= 300 && $statusCode < 400 && $request->getAttribute(Attributes::FOLLOW_LOCATION, true) && '' !== ($location = $result->getHeaderLine('location'))) + { + if (++$redirectCount <= ($maxRedirects = $request->getAttribute(Attributes::MAX_REDIRECTS, 10))) + { // 自己实现重定向 $uri = $this->parseRedirectLocation($location, $request->getUri()); - if (\in_array($statusCode, [301, 302, 303])) { + if (\in_array($statusCode, [301, 302, 303])) + { $method = 'GET'; } - else { + else + { $method = $request->getMethod(); } $request = $request->withMethod($method) @@ -377,7 +440,8 @@ public function recvDefer($request, $timeout = null) return $this->recvDefer($deferRequest, $timeout); } - else { + else + { $result = $result->withErrno(-1) ->withError(sprintf('Maximum (%s) redirects followed', $maxRedirects)); @@ -386,7 +450,8 @@ public function recvDefer($request, $timeout = null) } // 下载文件名 $savedFileName = $request->getAttribute(Attributes::SAVE_FILE_PATH); - if (null !== $savedFileName) { + if (null !== $savedFileName) + { $result = $result->withSavedFileName($savedFileName); } $this->cookieManager->gc(); @@ -405,7 +470,8 @@ public function recvDefer($request, $timeout = null) */ public function websocket(&$request, $websocketClient = null) { - if (!$websocketClient) { + if (!$websocketClient) + { $websocketClient = new \Yurun\Util\YurunHttp\WebSocket\Swoole(); } $request = $request->withAttribute(Attributes::PRIVATE_WEBSOCKET, true); @@ -438,14 +504,17 @@ private function parseCookies(&$request, $connection, $http2Request) { $cookieParams = $request->getCookieParams(); $cookieManager = $this->cookieManager; - foreach ($cookieParams as $name => $value) { + foreach ($cookieParams as $name => $value) + { $cookieManager->setCookie($name, $value); } $cookies = $cookieManager->getRequestCookies($request->getUri()); - if ($http2Request) { + if ($http2Request) + { $http2Request->cookies = $cookies; } - else { + else + { $connection->setCookies($cookies); } } @@ -463,29 +532,35 @@ public function buildHttp2Response($request, $connection, $response) { $success = false !== $response; $result = new Response($response->data ?? '', $success ? $response->statusCode : 0); - if ($success) { + if ($success) + { // streamId $result = $result->withStreamId($response->streamId); // headers - if ($response->headers) { - foreach ($response->headers as $name => $value) { + if ($response->headers) + { + foreach ($response->headers as $name => $value) + { $result = $result->withHeader($name, $value); } } // cookies $cookies = []; - if (isset($response->set_cookie_headers)) { + if (isset($response->set_cookie_headers)) + { $cookieManager = $this->cookieManager; - foreach ($response->set_cookie_headers as $value) { + foreach ($response->set_cookie_headers as $value) + { $cookieItem = $cookieManager->addSetCookie($value); $cookies[$cookieItem->name] = (array) $cookieItem; } } $result = $result->withCookieOriginParams($cookies); } - if ($connection) { + if ($connection) + { $result = $result->withError(swoole_strerror($connection->errCode)) ->withErrno($connection->errCode); } @@ -507,25 +582,32 @@ public function buildHttp2Response($request, $connection, $response) private function getResponse($request, $connection, $isWebSocket, $isHttp2, $timeout = null) { $result = &$this->result; - if ($isHttp2) { + if ($isHttp2) + { $response = $connection->recv((float) $timeout); $result = $this->buildHttp2Response($request, $connection, $response); } - else { + else + { $success = $isWebSocket ? true : $connection->recv((float) $timeout); $result = new Response((string) $connection->body, $connection->statusCode); - if ($success) { + if ($success) + { // headers - if ($connection->headers) { - foreach ($connection->headers as $name => $value) { + if ($connection->headers) + { + foreach ($connection->headers as $name => $value) + { $result = $result->withHeader($name, $value); } } // cookies $cookies = []; - if (isset($connection->set_cookie_headers)) { - foreach ($connection->set_cookie_headers as $value) { + if (isset($connection->set_cookie_headers)) + { + foreach ($connection->set_cookie_headers as $value) + { $cookieItem = $this->cookieManager->addSetCookie($value); $cookies[$cookieItem->name] = (array) $cookieItem; } @@ -550,29 +632,36 @@ private function getResponse($request, $connection, $isWebSocket, $isHttp2, $tim private function parseSSL(&$request) { $settings = $request->getAttribute(Attributes::OPTIONS, []); - if ($request->getAttribute(Attributes::IS_VERIFY_CA, false)) { + if ($request->getAttribute(Attributes::IS_VERIFY_CA, false)) + { $settings['ssl_verify_peer'] = true; $caCert = $request->getAttribute(Attributes::CA_CERT); - if (null !== $caCert) { + if (null !== $caCert) + { $settings['ssl_cafile'] = $caCert; } } - else { + else + { $settings['ssl_verify_peer'] = false; } $certPath = $request->getAttribute(Attributes::CERT_PATH, ''); - if ('' !== $certPath) { + if ('' !== $certPath) + { $settings['ssl_cert_file'] = $certPath; } $password = $request->getAttribute(Attributes::CERT_PASSWORD, ''); - if ('' === $password) { + if ('' === $password) + { $password = $request->getAttribute(Attributes::KEY_PASSWORD, ''); } - if ('' !== $password) { + if ('' !== $password) + { $settings['ssl_passphrase'] = $password; } $keyPath = $request->getAttribute(Attributes::KEY_PATH, ''); - if ('' !== $keyPath) { + if ('' !== $keyPath) + { $settings['ssl_key_file'] = $keyPath; } $request = $request->withAttribute(Attributes::OPTIONS, $settings); @@ -588,30 +677,36 @@ private function parseSSL(&$request) private function parseProxy(&$request) { $settings = $request->getAttribute(Attributes::OPTIONS, []); - if ($request->getAttribute(Attributes::USE_PROXY, false)) { + if ($request->getAttribute(Attributes::USE_PROXY, false)) + { $type = $request->getAttribute(Attributes::PROXY_TYPE); - switch ($type) { + switch ($type) + { case 'http': $settings['http_proxy_host'] = $request->getAttribute(Attributes::PROXY_SERVER); $port = $request->getAttribute(Attributes::PROXY_PORT); - if (null !== $port) { + if (null !== $port) + { $settings['http_proxy_port'] = $port; } $settings['http_proxy_user'] = $request->getAttribute(Attributes::PROXY_USERNAME); $password = $request->getAttribute(Attributes::PROXY_PASSWORD); - if (null !== $password) { + if (null !== $password) + { $settings['http_proxy_password'] = $password; } break; case 'socks5': $settings['socks5_host'] = $request->getAttribute(Attributes::PROXY_SERVER); $port = $request->getAttribute(Attributes::PROXY_PORT); - if (null !== $port) { + if (null !== $port) + { $settings['socks5_port'] = $port; } $settings['socks5_username'] = $request->getAttribute(Attributes::PROXY_USERNAME); $password = $request->getAttribute(Attributes::PROXY_PASSWORD); - if (null !== $password) { + if (null !== $password) + { $settings['socks5_password'] = $password; } break; @@ -632,25 +727,31 @@ private function parseNetwork(&$request) $settings = $request->getAttribute(Attributes::OPTIONS, []); // 用户名密码认证处理 $username = $request->getAttribute(Attributes::USERNAME); - if (null === $username) { + if (null === $username) + { $uri = $request->getUri(); $userInfo = $uri->getUserInfo(); - if ($userInfo) { + if ($userInfo) + { $authorization = 'Basic ' . base64_encode($userInfo); } - else { + else + { $authorization = null; } } - else { + else + { $authorization = 'Basic ' . base64_encode($username . ':' . $request->getAttribute(Attributes::PASSWORD, '')); } - if ($authorization) { + if ($authorization) + { $request = $request->withHeader('Authorization', $authorization); } // 超时 $settings['timeout'] = $request->getAttribute(Attributes::TIMEOUT, 30000) / 1000; - if ($settings['timeout'] < 0) { + if ($settings['timeout'] < 0) + { $settings['timeout'] = -1; } // 长连接 @@ -702,7 +803,8 @@ public function coBatch($requests, $timeout = null) $handlers = []; $results = []; $beginTime = microtime(true); - foreach ($requests as $i => &$request) { + foreach ($requests as $i => &$request) + { $results[$i] = null; $handlers[$i] = $handler = new self(); $request = $handler->sendDefer($request); @@ -710,10 +812,13 @@ public function coBatch($requests, $timeout = null) unset($request); $beginTime = microtime(true); $recvTimeout = null; - foreach ($requests as $i => $request) { - if (null !== $timeout) { + foreach ($requests as $i => $request) + { + if (null !== $timeout) + { $recvTimeout = $timeout - (microtime(true) - $beginTime); - if ($recvTimeout <= 0) { + if ($recvTimeout <= 0) + { break; } } @@ -725,10 +830,12 @@ public function coBatch($requests, $timeout = null) public function getHttpConnectionManager(): SwooleHttpConnectionManager { - if (ConnectionPool::isEnabled()) { + if (ConnectionPool::isEnabled()) + { return SwooleHttpConnectionManager::getInstance(); } - else { + else + { return $this->httpConnectionManager; } } diff --git a/src/YurunHttp/Handler/Swoole/SwooleHttp2ConnectionManager.php b/src/YurunHttp/Handler/Swoole/SwooleHttp2ConnectionManager.php index ad044b8..3ee7c46 100644 --- a/src/YurunHttp/Handler/Swoole/SwooleHttp2ConnectionManager.php +++ b/src/YurunHttp/Handler/Swoole/SwooleHttp2ConnectionManager.php @@ -28,7 +28,8 @@ class SwooleHttp2ConnectionManager implements IConnectionManager */ public static function getInstance() { - if (null === self::$instance) { + if (null === self::$instance) + { return self::$instance = new static(); } @@ -54,12 +55,15 @@ public function getConnectionPools() */ public function getConnectionPool($url) { - if (isset($this->connectionPools[$url])) { + if (isset($this->connectionPools[$url])) + { return $this->connectionPools[$url]; } - else { + else + { $config = ConnectionPool::getConfig($url); - if (null === $config) { + if (null === $config) + { ConnectionPool::setConfig($url); } $config = ConnectionPool::getConfig($url); @@ -131,7 +135,8 @@ public function close() { $connectionPools = $this->connectionPools; $this->connectionPools = []; - foreach ($connectionPools as $connectionPool) { + foreach ($connectionPools as $connectionPool) + { $connectionPool->close(); } } diff --git a/src/YurunHttp/Handler/Swoole/SwooleHttp2ConnectionPool.php b/src/YurunHttp/Handler/Swoole/SwooleHttp2ConnectionPool.php index 19f37e9..c2ce25f 100644 --- a/src/YurunHttp/Handler/Swoole/SwooleHttp2ConnectionPool.php +++ b/src/YurunHttp/Handler/Swoole/SwooleHttp2ConnectionPool.php @@ -42,7 +42,8 @@ public function close() $connections = $this->connections; $this->connections = []; $this->channel = new Channel(1024); - foreach ($connections as $connection) { + foreach ($connections as $connection) + { $connection->close(); } } @@ -58,10 +59,12 @@ public function createConnection() $uri = new Uri($config->getUrl()); $scheme = $uri->getScheme(); $client = new Client($uri->getHost(), Uri::getServerPort($uri), 'https' === $scheme || 'wss' === $scheme); - if ($client->connect()) { + if ($client->connect()) + { return $client; } - else { + else + { throw new \RuntimeException(sprintf('Http2 connect failed! errCode: %s, errMsg:%s', $client->errCode, swoole_strerror($client->errCode))); } } @@ -75,12 +78,14 @@ public function getConnection() { $config = $this->getConfig(); $maxConnections = $this->getConfig()->getMaxConnections(); - if ($this->getFree() > 0 || (0 != $maxConnections && $this->getCount() >= $maxConnections)) { + if ($this->getFree() > 0 || (0 != $maxConnections && $this->getCount() >= $maxConnections)) + { $timeout = $config->getWaitTimeout(); return $this->channel->pop(null === $timeout ? -1 : $timeout); } - else { + else + { return $this->connections[] = $this->createConnection(); } } @@ -94,14 +99,18 @@ public function getConnection() */ public function release($connection) { - if ($connection->connected) { - if (\in_array($connection, $this->connections)) { + if ($connection->connected) + { + if (\in_array($connection, $this->connections)) + { $this->channel->push($connection); } } - else { + else + { $index = array_search($connection, $this->connections); - if (false !== $index) { + if (false !== $index) + { unset($this->connections[$index]); } } diff --git a/src/YurunHttp/Handler/Swoole/SwooleHttpConnectionManager.php b/src/YurunHttp/Handler/Swoole/SwooleHttpConnectionManager.php index e8f0460..d0dfee6 100644 --- a/src/YurunHttp/Handler/Swoole/SwooleHttpConnectionManager.php +++ b/src/YurunHttp/Handler/Swoole/SwooleHttpConnectionManager.php @@ -28,7 +28,8 @@ class SwooleHttpConnectionManager implements IConnectionManager */ public static function getInstance() { - if (null === self::$instance) { + if (null === self::$instance) + { return self::$instance = new static(); } @@ -54,12 +55,15 @@ public function getConnectionPools() */ public function getConnectionPool($url) { - if (isset($this->connectionPools[$url])) { + if (isset($this->connectionPools[$url])) + { return $this->connectionPools[$url]; } - else { + else + { $config = ConnectionPool::getConfig($url); - if (null === $config) { + if (null === $config) + { ConnectionPool::setConfig($url); } $config = ConnectionPool::getConfig($url); @@ -131,7 +135,8 @@ public function close() { $connectionPools = $this->connectionPools; $this->connectionPools = []; - foreach ($connectionPools as $connectionPool) { + foreach ($connectionPools as $connectionPool) + { $connectionPool->close(); } } diff --git a/src/YurunHttp/Handler/Swoole/SwooleHttpConnectionPool.php b/src/YurunHttp/Handler/Swoole/SwooleHttpConnectionPool.php index 061928c..ddc908d 100644 --- a/src/YurunHttp/Handler/Swoole/SwooleHttpConnectionPool.php +++ b/src/YurunHttp/Handler/Swoole/SwooleHttpConnectionPool.php @@ -42,7 +42,8 @@ public function close() $connections = $this->connections; $this->connections = []; $this->channel = new Channel(1024); - foreach ($connections as $connection) { + foreach ($connections as $connection) + { $connection->close(); } } @@ -70,12 +71,14 @@ public function getConnection() { $config = $this->getConfig(); $maxConnections = $this->getConfig()->getMaxConnections(); - if ($this->getFree() > 0 || (0 != $maxConnections && $this->getCount() >= $maxConnections)) { + if ($this->getFree() > 0 || (0 != $maxConnections && $this->getCount() >= $maxConnections)) + { $timeout = $config->getWaitTimeout(); return $this->channel->pop(null === $timeout ? -1 : $timeout); } - else { + else + { return $this->connections[] = $this->createConnection(); } } @@ -89,7 +92,8 @@ public function getConnection() */ public function release($connection) { - if (\in_array($connection, $this->connections)) { + if (\in_array($connection, $this->connections)) + { $this->channel->push($connection); } } diff --git a/src/YurunHttp/HandlerOptions.php b/src/YurunHttp/HandlerOptions.php index 71d0b89..079f95f 100644 --- a/src/YurunHttp/HandlerOptions.php +++ b/src/YurunHttp/HandlerOptions.php @@ -10,15 +10,15 @@ abstract class HandlerOptions /** * Cookie 管理器数据保存到的文件名. */ - public const COOKIE_JAR = 'cookie_jar'; + const COOKIE_JAR = 'cookie_jar'; /** * 日志对象. */ - public const LOGGER = 'logger'; + const LOGGER = 'logger'; /** * 请求日志格式. */ - public const REQUEST_LOG_FORMAT = 'request_log_format'; + const REQUEST_LOG_FORMAT = 'request_log_format'; } diff --git a/src/YurunHttp/Http/Psr7/AbstractMessage.php b/src/YurunHttp/Http/Psr7/AbstractMessage.php index 92edb60..3908694 100644 --- a/src/YurunHttp/Http/Psr7/AbstractMessage.php +++ b/src/YurunHttp/Http/Psr7/AbstractMessage.php @@ -42,10 +42,12 @@ abstract class AbstractMessage implements MessageInterface */ public function __construct($body) { - if ($body instanceof \Psr\Http\Message\StreamInterface) { + if ($body instanceof \Psr\Http\Message\StreamInterface) + { $this->body = $body; } - else { + else + { $this->body = new MemoryStream($body); } } @@ -126,7 +128,8 @@ public function getHeaders(): array public function hasHeader($name): bool { $lowerName = strtolower($name); - if (isset($this->headerNames[$lowerName])) { + if (isset($this->headerNames[$lowerName])) + { $name = $this->headerNames[$lowerName]; } @@ -151,13 +154,16 @@ public function hasHeader($name): bool public function getHeader($name): array { $lowerName = strtolower($name); - if (isset($this->headerNames[$lowerName])) { + if (isset($this->headerNames[$lowerName])) + { $name = $this->headerNames[$lowerName]; } - if (isset($this->headers[$name])) { + if (isset($this->headers[$name])) + { return $this->headers[$name]; } - else { + else + { return []; } } @@ -185,10 +191,12 @@ public function getHeader($name): array public function getHeaderLine($name): string { $lowerName = strtolower($name); - if (isset($this->headerNames[$lowerName])) { + if (isset($this->headerNames[$lowerName])) + { $name = $this->headerNames[$lowerName]; } - if (!isset($this->headers[$name])) { + if (!isset($this->headers[$name])) + { return ''; } @@ -241,24 +249,30 @@ public function withAddedHeader($name, $value): MessageInterface { $self = clone $this; $lowerName = strtolower($name); - if (isset($self->headerNames[$lowerName])) { + if (isset($self->headerNames[$lowerName])) + { $name = $self->headerNames[$lowerName]; } - else { + else + { $self->headerNames[$lowerName] = $name; } - if (\is_string($value)) { + if (\is_string($value)) + { $value = [$value]; } - elseif (!\is_array($value)) { + elseif (!\is_array($value)) + { throw new \InvalidArgumentException('invalid header names or values'); } - if (isset($self->headers[$name])) { + if (isset($self->headers[$name])) + { $self->headers[$name] = array_merge($self->headers[$name], $value); } - else { + else + { $self->headers[$name] = $value; } @@ -282,10 +296,12 @@ public function withoutHeader($name): MessageInterface { $self = clone $this; $lowerName = strtolower($name); - if (isset($self->headerNames[$lowerName])) { + if (isset($self->headerNames[$lowerName])) + { $name = $self->headerNames[$lowerName]; } - if (isset($self->headers[$name])) { + if (isset($self->headers[$name])) + { unset($self->headers[$name]); } @@ -334,7 +350,8 @@ public function withBody(StreamInterface $body): MessageInterface */ protected function setHeaders(array $headers) { - foreach ($headers as $name => $value) { + foreach ($headers as $name => $value) + { $this->setHeader($this, $name, $value); } @@ -353,19 +370,24 @@ protected function setHeaders(array $headers) protected function setHeader($object, $name, $value) { $lowerName = strtolower($name); - if (isset($object->headerNames[$lowerName])) { + if (isset($object->headerNames[$lowerName])) + { $name = $object->headerNames[$lowerName]; } - else { + else + { $object->headerNames[$lowerName] = $name; } - if (\is_string($value)) { + if (\is_string($value)) + { $object->headers[$name] = [$value]; } - elseif (\is_array($value)) { + elseif (\is_array($value)) + { $object->headers[$name] = $value; } - else { + else + { throw new \InvalidArgumentException('invalid header names or values'); } diff --git a/src/YurunHttp/Http/Psr7/Consts/MediaType.php b/src/YurunHttp/Http/Psr7/Consts/MediaType.php index 49f5121..a066f06 100644 --- a/src/YurunHttp/Http/Psr7/Consts/MediaType.php +++ b/src/YurunHttp/Http/Psr7/Consts/MediaType.php @@ -7,53 +7,53 @@ */ abstract class MediaType { - public const ALL = '*/*'; + const ALL = '*/*'; - public const APPLICATION_ATOM_XML = 'application/atom+xml'; + const APPLICATION_ATOM_XML = 'application/atom+xml'; - public const APPLICATION_FORM_URLENCODED = 'application/x-www-form-urlencoded'; + const APPLICATION_FORM_URLENCODED = 'application/x-www-form-urlencoded'; - public const APPLICATION_JSON = 'application/json'; + const APPLICATION_JSON = 'application/json'; - public const APPLICATION_JSON_UTF8 = 'application/json;charset=UTF-8'; + const APPLICATION_JSON_UTF8 = 'application/json;charset=UTF-8'; - public const APPLICATION_OCTET_STREAM = 'application/octet-stream'; + const APPLICATION_OCTET_STREAM = 'application/octet-stream'; - public const APPLICATION_PDF = 'application/pdf'; + const APPLICATION_PDF = 'application/pdf'; - public const APPLICATION_PROBLEM_JSON = 'application/problem+json'; + const APPLICATION_PROBLEM_JSON = 'application/problem+json'; - public const APPLICATION_PROBLEM_XML = 'application/problem+xml'; + const APPLICATION_PROBLEM_XML = 'application/problem+xml'; - public const APPLICATION_RSS_XML = 'application/rss+xml'; + const APPLICATION_RSS_XML = 'application/rss+xml'; - public const APPLICATION_STREAM_JSON = 'application/stream+json'; + const APPLICATION_STREAM_JSON = 'application/stream+json'; - public const APPLICATION_XHTML_XML = 'application/xhtml+xml'; + const APPLICATION_XHTML_XML = 'application/xhtml+xml'; - public const APPLICATION_XML = 'application/xml'; + const APPLICATION_XML = 'application/xml'; - public const IMAGE_JPEG = 'image/jpeg'; + const IMAGE_JPEG = 'image/jpeg'; - public const IMAGE_APNG = 'image/apng'; + const IMAGE_APNG = 'image/apng'; - public const IMAGE_PNG = 'image/png'; + const IMAGE_PNG = 'image/png'; - public const IMAGE_GIF = 'image/gif'; + const IMAGE_GIF = 'image/gif'; - public const IMAGE_WEBP = 'image/webp'; + const IMAGE_WEBP = 'image/webp'; - public const MULTIPART_FORM_DATA = 'multipart/form-data'; + const MULTIPART_FORM_DATA = 'multipart/form-data'; - public const TEXT_EVENT_STREAM = 'text/event-stream'; + const TEXT_EVENT_STREAM = 'text/event-stream'; - public const TEXT_HTML = 'text/html'; + const TEXT_HTML = 'text/html'; - public const TEXT_MARKDOWN = 'text/markdown'; + const TEXT_MARKDOWN = 'text/markdown'; - public const TEXT_PLAIN = 'text/plain'; + const TEXT_PLAIN = 'text/plain'; - public const TEXT_XML = 'text/xml'; + const TEXT_XML = 'text/xml'; /** * @var array @@ -199,10 +199,12 @@ abstract class MediaType public static function getExt($contentType) { list($firstContentType) = explode(';', $contentType, 2); - if (isset(self::$extMap[$firstContentType])) { + if (isset(self::$extMap[$firstContentType])) + { return self::$extMap[$firstContentType]; } - else { + else + { return null; } } diff --git a/src/YurunHttp/Http/Psr7/Consts/RequestHeader.php b/src/YurunHttp/Http/Psr7/Consts/RequestHeader.php index 4e811bd..d70c6d4 100644 --- a/src/YurunHttp/Http/Psr7/Consts/RequestHeader.php +++ b/src/YurunHttp/Http/Psr7/Consts/RequestHeader.php @@ -7,36 +7,36 @@ */ abstract class RequestHeader { - public const ACCEPT = 'Accept'; - public const ACCEPT_CHARSET = 'Accept-Charset'; - public const ACCEPT_ENCODING = 'Accept-Encoding'; - public const ACCEPT_LANGUAGE = 'Accept-Language'; - public const ACCEPT_DATETIME = 'Accept-Datetime'; - public const AUTHORIZATION = 'Authorization'; - public const CACHE_CONTROL = 'Cache-Control'; - public const CONNECTION = 'Connection'; - public const COOKIE = 'Cookie'; - public const CONTENT_LENGTH = 'Content-Length'; - public const CONTENT_MD5 = 'Content-MD5'; - public const CONTENT_TYPE = 'Content-Type'; - public const DATE = 'Date'; - public const EXPECT = 'Expect'; - public const FROM = 'From'; - public const HOST = 'Host'; - public const IF_MATCH = 'If-Match'; - public const IF_MODIFIED_SINCE = 'If-Modified-Since'; - public const IF_NONE_MATCH = 'If-None-Match'; - public const IF_RANGE = 'If-Range'; - public const IF_UNMODIFIED_SINCE = 'If-Unmodified-Since'; - public const MAX_FORWARDS = 'Max-Forwards'; - public const ORIGIN = 'Origin'; - public const PRAGMA = 'Pragma'; - public const PROXY_AUTHORIZATION = 'Proxy-Authorization'; - public const RANGE = 'Range'; - public const REFERER = 'Referer'; - public const TE = 'TE'; - public const USER_AGENT = 'User-Agent'; - public const UPGRADE = 'Upgrade'; - public const VIA = 'Via'; - public const WARNING = 'Warning'; + const ACCEPT = 'Accept'; + const ACCEPT_CHARSET = 'Accept-Charset'; + const ACCEPT_ENCODING = 'Accept-Encoding'; + const ACCEPT_LANGUAGE = 'Accept-Language'; + const ACCEPT_DATETIME = 'Accept-Datetime'; + const AUTHORIZATION = 'Authorization'; + const CACHE_CONTROL = 'Cache-Control'; + const CONNECTION = 'Connection'; + const COOKIE = 'Cookie'; + const CONTENT_LENGTH = 'Content-Length'; + const CONTENT_MD5 = 'Content-MD5'; + const CONTENT_TYPE = 'Content-Type'; + const DATE = 'Date'; + const EXPECT = 'Expect'; + const FROM = 'From'; + const HOST = 'Host'; + const IF_MATCH = 'If-Match'; + const IF_MODIFIED_SINCE = 'If-Modified-Since'; + const IF_NONE_MATCH = 'If-None-Match'; + const IF_RANGE = 'If-Range'; + const IF_UNMODIFIED_SINCE = 'If-Unmodified-Since'; + const MAX_FORWARDS = 'Max-Forwards'; + const ORIGIN = 'Origin'; + const PRAGMA = 'Pragma'; + const PROXY_AUTHORIZATION = 'Proxy-Authorization'; + const RANGE = 'Range'; + const REFERER = 'Referer'; + const TE = 'TE'; + const USER_AGENT = 'User-Agent'; + const UPGRADE = 'Upgrade'; + const VIA = 'Via'; + const WARNING = 'Warning'; } diff --git a/src/YurunHttp/Http/Psr7/Consts/RequestMethod.php b/src/YurunHttp/Http/Psr7/Consts/RequestMethod.php index 456abb8..7848690 100644 --- a/src/YurunHttp/Http/Psr7/Consts/RequestMethod.php +++ b/src/YurunHttp/Http/Psr7/Consts/RequestMethod.php @@ -7,19 +7,19 @@ */ abstract class RequestMethod { - public const GET = 'GET'; + const GET = 'GET'; - public const POST = 'POST'; + const POST = 'POST'; - public const HEAD = 'HEAD'; + const HEAD = 'HEAD'; - public const PUT = 'PUT'; + const PUT = 'PUT'; - public const PATCH = 'PATCH'; + const PATCH = 'PATCH'; - public const DELETE = 'DELETE'; + const DELETE = 'DELETE'; - public const OPTIONS = 'OPTIONS'; + const OPTIONS = 'OPTIONS'; - public const TRACE = 'TRACE'; + const TRACE = 'TRACE'; } diff --git a/src/YurunHttp/Http/Psr7/Consts/ResponseHeader.php b/src/YurunHttp/Http/Psr7/Consts/ResponseHeader.php index a72101e..6028d0e 100644 --- a/src/YurunHttp/Http/Psr7/Consts/ResponseHeader.php +++ b/src/YurunHttp/Http/Psr7/Consts/ResponseHeader.php @@ -7,41 +7,41 @@ */ abstract class ResponseHeader { - public const ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin'; - public const ACCEPT_PATCH = 'Accept-Patch'; - public const ACCEPT_RANGES = 'Accept-Ranges'; - public const AGE = 'Age'; - public const ALLOW = 'Allow'; - public const CACHE_CONTROL = 'Cache-Control'; - public const CONNECTION = 'Connection'; - public const CONTENT_DISPOSITION = 'Content-Disposition'; - public const CONTENT_ENCODING = 'Content-Encoding'; - public const CONTENT_LANGUAGE = 'Content-Language'; - public const CONTENT_LENGTH = 'Content-Length'; - public const CONTENT_LOCATION = 'Content-Location'; - public const CONTENT_MD5 = 'Content-MD5'; - public const CONTENT_RANGE = 'Content-Range'; - public const CONTENT_TYPE = 'Content-Type'; - public const DATE = 'Date'; - public const ETAG = 'ETag'; - public const EXPIRES = 'Expires'; - public const LAST_MODIFIED = 'Last-Modified'; - public const LINK = 'Link'; - public const LOCATION = 'Location'; - public const P3P = 'P3P'; - public const PRAGMA = 'Pragma'; - public const PROXY_AUTHENTICATE = 'Proxy-Authenticate'; - public const PUBLIC_KEY_PINS = 'Public-Key-Pins'; - public const REFRESH = 'Refresh'; - public const RETRY_AFTER = 'Retry-After'; - public const SERVER = 'Server'; - public const SET_COOKIE = 'Set-Cookie'; - public const STATUS = 'Status'; - public const TRAILER = 'Trailer'; - public const TRANSFER_ENCODING = 'Transfer-Encoding'; - public const UPGRADE = 'Upgrade'; - public const VARY = 'Vary'; - public const VIA = 'Via'; - public const WARNING = 'Warning'; - public const WWW_AUTHENTICATE = 'WWW-Authenticate'; + const ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin'; + const ACCEPT_PATCH = 'Accept-Patch'; + const ACCEPT_RANGES = 'Accept-Ranges'; + const AGE = 'Age'; + const ALLOW = 'Allow'; + const CACHE_CONTROL = 'Cache-Control'; + const CONNECTION = 'Connection'; + const CONTENT_DISPOSITION = 'Content-Disposition'; + const CONTENT_ENCODING = 'Content-Encoding'; + const CONTENT_LANGUAGE = 'Content-Language'; + const CONTENT_LENGTH = 'Content-Length'; + const CONTENT_LOCATION = 'Content-Location'; + const CONTENT_MD5 = 'Content-MD5'; + const CONTENT_RANGE = 'Content-Range'; + const CONTENT_TYPE = 'Content-Type'; + const DATE = 'Date'; + const ETAG = 'ETag'; + const EXPIRES = 'Expires'; + const LAST_MODIFIED = 'Last-Modified'; + const LINK = 'Link'; + const LOCATION = 'Location'; + const P3P = 'P3P'; + const PRAGMA = 'Pragma'; + const PROXY_AUTHENTICATE = 'Proxy-Authenticate'; + const PUBLIC_KEY_PINS = 'Public-Key-Pins'; + const REFRESH = 'Refresh'; + const RETRY_AFTER = 'Retry-After'; + const SERVER = 'Server'; + const SET_COOKIE = 'Set-Cookie'; + const STATUS = 'Status'; + const TRAILER = 'Trailer'; + const TRANSFER_ENCODING = 'Transfer-Encoding'; + const UPGRADE = 'Upgrade'; + const VARY = 'Vary'; + const VIA = 'Via'; + const WARNING = 'Warning'; + const WWW_AUTHENTICATE = 'WWW-Authenticate'; } diff --git a/src/YurunHttp/Http/Psr7/Consts/StatusCode.php b/src/YurunHttp/Http/Psr7/Consts/StatusCode.php index 7decd5b..edc177d 100644 --- a/src/YurunHttp/Http/Psr7/Consts/StatusCode.php +++ b/src/YurunHttp/Http/Psr7/Consts/StatusCode.php @@ -4,67 +4,67 @@ abstract class StatusCode { - public const _CONTINUE = 100; - public const SWITCHING_PROTOCOLS = 101; - public const PROCESSING = 102; - public const OK = 200; - public const CREATED = 201; - public const ACCEPTED = 202; - public const NON_AUTHORITATIVE_INFORMATION = 203; - public const NO_CONTENT = 204; - public const RESET_CONTENT = 205; - public const PARTIAL_CONTENT = 206; - public const MULTI_STATUS = 207; - public const ALREADY_REPORTED = 208; - public const IM_USED = 226; - public const MULTIPLE_CHOICES = 300; - public const MOVED_PERMANENTLY = 301; - public const FOUND = 302; - public const SEE_OTHER = 303; - public const NOT_MODIFIED = 304; - public const USE_PROXY = 305; - public const SWITCH_PROXY = 306; - public const TEMPORARY_REDIRECT = 307; - public const PERMANENT_REDIRECT = 308; - public const BAD_REQUEST = 400; - public const UNAUTHORIZED = 401; - public const PAYMENT_REQUIRED = 402; - public const FORBIDDEN = 403; - public const NOT_FOUND = 404; - public const METHOD_NOT_ALLOWED = 405; - public const NOT_ACCEPTABLE = 406; - public const PROXY_AUTHENTICATION_REQUIRED = 407; - public const REQUEST_TIME_OUT = 408; - public const CONFLICT = 409; - public const GONE = 410; - public const LENGTH_REQUIRED = 411; - public const PRECONDITION_FAILED = 412; - public const REQUEST_ENTITY_TOO_LARGE = 413; - public const REQUEST_URI_TOO_LARGE = 414; - public const UNSUPPORTED_MEDIA_TYPE = 415; - public const REQUESTED_RANGE_NOT_SATISFIABLE = 416; - public const EXPECTATION_FAILED = 417; - public const MISDIRECTED_REQUEST = 421; - public const UNPROCESSABLE_ENTITY = 422; - public const LOCKED = 423; - public const FAILED_DEPENDENCY = 424; - public const UNORDERED_COLLECTION = 425; - public const UPGRADE_REQUIRED = 426; - public const PRECONDITION_REQUIRED = 428; - public const TOO_MANY_REQUESTS = 429; - public const REQUEST_HEADER_FIELDS_TOO_LARGE = 431; - public const UNAVAILABLE_FOR_LEGAL_REASONS = 451; - public const INTERNAL_SERVER_ERROR = 500; - public const NOT_IMPLEMENTED = 501; - public const BAD_GATEWAY = 502; - public const SERVICE_UNAVAILABLE = 503; - public const GATEWAY_TIME_OUT = 504; - public const HTTP_VERSION_NOT_SUPPORTED = 505; - public const VARIANT_ALSO_NEGOTIATES = 506; - public const INSUFFICIENT_STORAGE = 507; - public const LOOP_DETECTED = 508; - public const NOT_EXTENDED = 510; - public const NETWORK_AUTHENTICATION_REQUIRED = 511; + const _CONTINUE = 100; + const SWITCHING_PROTOCOLS = 101; + const PROCESSING = 102; + const OK = 200; + const CREATED = 201; + const ACCEPTED = 202; + const NON_AUTHORITATIVE_INFORMATION = 203; + const NO_CONTENT = 204; + const RESET_CONTENT = 205; + const PARTIAL_CONTENT = 206; + const MULTI_STATUS = 207; + const ALREADY_REPORTED = 208; + const IM_USED = 226; + const MULTIPLE_CHOICES = 300; + const MOVED_PERMANENTLY = 301; + const FOUND = 302; + const SEE_OTHER = 303; + const NOT_MODIFIED = 304; + const USE_PROXY = 305; + const SWITCH_PROXY = 306; + const TEMPORARY_REDIRECT = 307; + const PERMANENT_REDIRECT = 308; + const BAD_REQUEST = 400; + const UNAUTHORIZED = 401; + const PAYMENT_REQUIRED = 402; + const FORBIDDEN = 403; + const NOT_FOUND = 404; + const METHOD_NOT_ALLOWED = 405; + const NOT_ACCEPTABLE = 406; + const PROXY_AUTHENTICATION_REQUIRED = 407; + const REQUEST_TIME_OUT = 408; + const CONFLICT = 409; + const GONE = 410; + const LENGTH_REQUIRED = 411; + const PRECONDITION_FAILED = 412; + const REQUEST_ENTITY_TOO_LARGE = 413; + const REQUEST_URI_TOO_LARGE = 414; + const UNSUPPORTED_MEDIA_TYPE = 415; + const REQUESTED_RANGE_NOT_SATISFIABLE = 416; + const EXPECTATION_FAILED = 417; + const MISDIRECTED_REQUEST = 421; + const UNPROCESSABLE_ENTITY = 422; + const LOCKED = 423; + const FAILED_DEPENDENCY = 424; + const UNORDERED_COLLECTION = 425; + const UPGRADE_REQUIRED = 426; + const PRECONDITION_REQUIRED = 428; + const TOO_MANY_REQUESTS = 429; + const REQUEST_HEADER_FIELDS_TOO_LARGE = 431; + const UNAVAILABLE_FOR_LEGAL_REASONS = 451; + const INTERNAL_SERVER_ERROR = 500; + const NOT_IMPLEMENTED = 501; + const BAD_GATEWAY = 502; + const SERVICE_UNAVAILABLE = 503; + const GATEWAY_TIME_OUT = 504; + const HTTP_VERSION_NOT_SUPPORTED = 505; + const VARIANT_ALSO_NEGOTIATES = 506; + const INSUFFICIENT_STORAGE = 507; + const LOOP_DETECTED = 508; + const NOT_EXTENDED = 510; + const NETWORK_AUTHENTICATION_REQUIRED = 511; /** * @var array diff --git a/src/YurunHttp/Http/Psr7/Request.php b/src/YurunHttp/Http/Psr7/Request.php index 68bd4c9..5a23db2 100644 --- a/src/YurunHttp/Http/Psr7/Request.php +++ b/src/YurunHttp/Http/Psr7/Request.php @@ -41,10 +41,12 @@ class Request extends AbstractMessage implements RequestInterface public function __construct($uri = null, array $headers = [], $body = '', $method = RequestMethod::GET, $version = '1.1') { parent::__construct($body); - if (!$uri instanceof UriInterface) { + if (!$uri instanceof UriInterface) + { $this->uri = new Uri($uri); } - elseif (null !== $uri) { + elseif (null !== $uri) + { $this->uri = $uri; } $this->setHeaders($headers); @@ -186,7 +188,8 @@ public function withUri(UriInterface $uri, $preserveHost = false): RequestInterf { $self = clone $this; $self->uri = $uri; - if (!$preserveHost) { + if (!$preserveHost) + { $self->headers = []; $self->headerNames = []; } diff --git a/src/YurunHttp/Http/Psr7/Response.php b/src/YurunHttp/Http/Psr7/Response.php index ea60075..4cf2ef4 100644 --- a/src/YurunHttp/Http/Psr7/Response.php +++ b/src/YurunHttp/Http/Psr7/Response.php @@ -73,10 +73,12 @@ public function withStatus($code, $reasonPhrase = ''): ResponseInterface { $self = clone $this; $self->statusCode = $code; - if ('' === $reasonPhrase) { + if ('' === $reasonPhrase) + { $self->reasonPhrase = StatusCode::getReasonPhrase($code); } - else { + else + { $self->reasonPhrase = $reasonPhrase; } diff --git a/src/YurunHttp/Http/Psr7/ServerRequest.php b/src/YurunHttp/Http/Psr7/ServerRequest.php index 3715995..c033948 100644 --- a/src/YurunHttp/Http/Psr7/ServerRequest.php +++ b/src/YurunHttp/Http/Psr7/ServerRequest.php @@ -260,21 +260,24 @@ public function withUploadedFiles(array $uploadedFiles): ServerRequestInterface public function getParsedBody() { $parsedBody = &$this->parsedBody; - if (null === $parsedBody) { + if (null === $parsedBody) + { $body = $this->body; $contentType = strtolower($this->getHeaderLine(RequestHeader::CONTENT_TYPE)); // post if ('POST' === $this->method && \in_array($contentType, [ MediaType::APPLICATION_FORM_URLENCODED, MediaType::MULTIPART_FORM_DATA, - ])) { + ])) + { $parsedBody = $this->post; } // json elseif (\in_array($contentType, [ MediaType::APPLICATION_JSON, MediaType::APPLICATION_JSON_UTF8, - ])) { + ])) + { $parsedBody = json_decode($body, true); } // xml @@ -284,12 +287,14 @@ public function getParsedBody() MediaType::APPLICATION_RSS_XML, MediaType::APPLICATION_XHTML_XML, MediaType::APPLICATION_XML, - ])) { + ])) + { $parsedBody = new \DOMDocument(); $parsedBody->loadXML($body); } // 其它 - else { + else + { $parsedBody = (object) (string) $body; } } @@ -371,10 +376,12 @@ public function getAttributes(): array public function getAttribute($name, $default = null) { $attributes = $this->attributes; - if (\array_key_exists($name, $attributes)) { + if (\array_key_exists($name, $attributes)) + { return $attributes[$name]; } - else { + else + { return YurunHttp::getAttribute($name, $default); } } @@ -423,7 +430,8 @@ public function withAttribute($name, $value): ServerRequestInterface public function withoutAttribute($name): ServerRequestInterface { $self = clone $this; - if (\array_key_exists($name, $self->attributes)) { + if (\array_key_exists($name, $self->attributes)) + { unset($self->attributes[$name]); } @@ -441,11 +449,14 @@ public function withoutAttribute($name): ServerRequestInterface protected function setUploadedFiles(self $object, array $files) { $object->files = []; - foreach ($files as $name => $file) { - if ($file instanceof UploadedFile) { + foreach ($files as $name => $file) + { + if ($file instanceof UploadedFile) + { $object->files[$name] = $file; } - else { + else + { $object->files[$name] = new UploadedFile($file['name'], $file['type'], $file['tmp_name'], $file['size'], $file['error']); } } diff --git a/src/YurunHttp/Http/Psr7/UploadedFile.php b/src/YurunHttp/Http/Psr7/UploadedFile.php index 947d8c1..34db06a 100644 --- a/src/YurunHttp/Http/Psr7/UploadedFile.php +++ b/src/YurunHttp/Http/Psr7/UploadedFile.php @@ -69,10 +69,12 @@ public function __construct($fileName, $mediaType, $tmpFileName, $size = null, $ $this->fileName = $fileName; $this->mediaType = $mediaType; $this->tmpFileName = $tmpFileName; - if (null === $size) { + if (null === $size) + { $this->size = filesize($tmpFileName); } - else { + else + { $this->size = $size; } $this->error = $error; @@ -97,7 +99,8 @@ public function __construct($fileName, $mediaType, $tmpFileName, $size = null, $ */ public function getStream(): StreamInterface { - if (null === $this->stream) { + if (null === $this->stream) + { $this->stream = new FileStream($this->tmpFileName); } @@ -142,19 +145,24 @@ public function getStream(): StreamInterface */ public function moveTo($targetPath): void { - if (!\is_string($targetPath)) { + if (!\is_string($targetPath)) + { throw new \InvalidArgumentException('targetPath specified is invalid'); } - if ($this->isMoved) { + if ($this->isMoved) + { throw new \RuntimeException('file can not be moved'); } - if (is_uploaded_file($this->tmpFileName)) { + if (is_uploaded_file($this->tmpFileName)) + { $this->isMoved = move_uploaded_file($this->tmpFileName, $targetPath); } - else { + else + { $this->isMoved = rename($this->tmpFileName, $targetPath); } - if (!$this->isMoved) { + if (!$this->isMoved) + { throw new \RuntimeException(sprintf('file %s move to %s fail', $this->tmpFileName, $targetPath)); } } diff --git a/src/YurunHttp/Http/Psr7/Uri.php b/src/YurunHttp/Http/Psr7/Uri.php index 692e770..aeb4135 100644 --- a/src/YurunHttp/Http/Psr7/Uri.php +++ b/src/YurunHttp/Http/Psr7/Uri.php @@ -73,14 +73,16 @@ class Uri implements UriInterface public function __construct($uri = '') { $uriOption = parse_url($uri); - if (false === $uriOption) { + if (false === $uriOption) + { throw new \InvalidArgumentException(sprintf('uri %s parse error', $uri)); } $this->scheme = isset($uriOption['scheme']) ? $uriOption['scheme'] : ''; $this->host = isset($uriOption['host']) ? $uriOption['host'] : ''; $this->port = isset($uriOption['port']) ? $uriOption['port'] : null; $this->userInfo = isset($uriOption['user']) ? $uriOption['user'] : ''; - if (isset($uriOption['pass'])) { + if (isset($uriOption['pass'])) + { $this->userInfo .= ':' . $uriOption['pass']; } $this->path = isset($uriOption['path']) ? $uriOption['path'] : ''; @@ -105,11 +107,13 @@ public static function makeUriString($host, $path, $query = '', $port = null, $s { $uri = ''; // 协议 - if ('' !== $scheme) { + if ('' !== $scheme) + { $uri = $scheme . '://'; } // 用户信息 - if ('' !== $userInfo) { + if ('' !== $userInfo) + { $uri .= $userInfo . '@'; } // 主机+端口 @@ -152,7 +156,8 @@ public static function makeUri($host, $path, $query = '', $port = 80, $scheme = public static function getServerPort(UriInterface $uri) { $port = $uri->getPort(); - if (!$port) { + if (!$port) + { $scheme = $uri->getScheme(); $port = isset(static::$schemePorts[$scheme]) ? static::$schemePorts[$scheme] : null; } @@ -171,7 +176,8 @@ public static function getServerPort(UriInterface $uri) public static function getDomain(UriInterface $uri) { $result = $uri->getHost(); - if (null !== ($port = $uri->getPort())) { + if (null !== ($port = $uri->getPort())) + { $result .= ':' . $port; } @@ -220,10 +226,12 @@ public function getScheme(): string public function getAuthority(): string { $result = $this->host; - if ('' !== $this->userInfo) { + if ('' !== $this->userInfo) + { $result = $this->userInfo . '@' . $result; } - if (null !== $this->port) { + if (null !== $this->port) + { $result .= ':' . $this->port; } @@ -385,7 +393,8 @@ public function getFragment(): string */ public function withScheme($scheme): UriInterface { - if (!\is_string($scheme)) { + if (!\is_string($scheme)) + { throw new \InvalidArgumentException('invalid or unsupported schemes'); } $self = clone $this; @@ -413,7 +422,8 @@ public function withUserInfo($user, $password = null): UriInterface { $self = clone $this; $self->userInfo = $user; - if (null !== $password) { + if (null !== $password) + { $self->userInfo .= ':' . $password; } diff --git a/src/YurunHttp/Http/Response.php b/src/YurunHttp/Http/Response.php index 705ae2f..f2b6835 100644 --- a/src/YurunHttp/Http/Response.php +++ b/src/YurunHttp/Http/Response.php @@ -110,7 +110,8 @@ public function withCookieOriginParams(array $cookiesOrigin) $self = clone $this; $self->cookiesOrigin = $cookiesOrigin; $self->cookies = []; - foreach ($cookiesOrigin as $name => $value) { + foreach ($cookiesOrigin as $name => $value) + { $self->cookies[$name] = $value['value']; } @@ -161,10 +162,12 @@ public function __construct($body = '', $statusCode = StatusCode::OK, $reasonPhr */ public function body($fromEncoding = null, $toEncoding = 'UTF-8') { - if (null === $fromEncoding) { + if (null === $fromEncoding) + { return (string) $this->getBody(); } - else { + else + { return mb_convert_encoding((string) $this->getBody(), $toEncoding, $fromEncoding); } } @@ -181,7 +184,8 @@ public function body($fromEncoding = null, $toEncoding = 'UTF-8') public function xml($assoc = false, $fromEncoding = null, $toEncoding = 'UTF-8') { $xml = simplexml_load_string($this->body($fromEncoding, $toEncoding), 'SimpleXMLElement', \LIBXML_NOCDATA | \LIBXML_COMPACT); - if ($assoc) { + if ($assoc) + { $xml = (array) $xml; } @@ -214,11 +218,14 @@ public function json($assoc = false, $fromEncoding = null, $toEncoding = 'UTF-8' public function jsonp($assoc = false, $fromEncoding = null, $toEncoding = 'UTF-8') { $jsonp = trim($this->body($fromEncoding, $toEncoding)); - if (isset($jsonp[0]) && '[' !== $jsonp[0] && '{' !== $jsonp[0]) { + if (isset($jsonp[0]) && '[' !== $jsonp[0] && '{' !== $jsonp[0]) + { $begin = strpos($jsonp, '('); - if (false !== $begin) { + if (false !== $begin) + { $end = strrpos($jsonp, ')'); - if (false !== $end) { + if (false !== $end) + { $jsonp = substr($jsonp, $begin + 1, $end - $begin - 1); } } diff --git a/src/YurunHttp/Http2/SwooleClient.php b/src/YurunHttp/Http2/SwooleClient.php index f3e3f21..8226e70 100644 --- a/src/YurunHttp/Http2/SwooleClient.php +++ b/src/YurunHttp/Http2/SwooleClient.php @@ -90,10 +90,12 @@ public function __construct($host, $port, $ssl, $handler = null) $this->host = $host; $this->port = $port; $this->ssl = $ssl; - if ($handler) { + if ($handler) + { $this->handler = $handler; } - else { + else + { $this->handler = new \Yurun\Util\YurunHttp\Handler\Swoole(); } } @@ -107,9 +109,11 @@ public function connect() { $url = ($this->ssl ? 'https://' : 'http://') . $this->host . ':' . $this->port; $client = $this->handler->getHttp2ConnectionManager()->getConnection($url); - if ($client) { + if ($client) + { $this->http2Client = $client; - if ($this->timeout) { + if ($this->timeout) + { $client->set([ 'timeout' => $this->timeout, ]); @@ -117,7 +121,8 @@ public function connect() return true; } - else { + else + { return false; } } @@ -141,7 +146,8 @@ public function close() { $this->recvCo = false; $recvChannels = &$this->recvChannels; - foreach ($recvChannels as $channel) { + foreach ($recvChannels as $channel) + { $channel->close(); } $recvChannels = []; @@ -164,24 +170,29 @@ public function close() */ public function send($request, $pipeline = false, $dropRecvResponse = false) { - if ('2.0' !== $request->getProtocolVersion()) { + if ('2.0' !== $request->getProtocolVersion()) + { $request = $request->withProtocolVersion('2.0'); } $uri = $request->getUri(); - if ($this->host != $uri->getHost() || $this->port != Uri::getServerPort($uri) || $this->ssl != ('https' === $uri->getScheme() || 'wss' === $uri->getScheme())) { + if ($this->host != $uri->getHost() || $this->port != Uri::getServerPort($uri) || $this->ssl != ('https' === $uri->getScheme() || 'wss' === $uri->getScheme())) + { throw new \RuntimeException(sprintf('Current http2 connection instance just support %s://%s:%s, does not support %s', $this->ssl ? 'https' : 'http', $this->host, $this->port, $uri->__toString())); } $http2Client = $this->http2Client; $request = $request->withAttribute(Attributes::HTTP2_PIPELINE, $pipeline); $this->handler->buildRequest($request, $http2Client, $http2Request); $streamId = $http2Client->send($http2Request); - if ($streamId) { - if (!$dropRecvResponse) { + if ($streamId) + { + if (!$dropRecvResponse) + { $this->recvChannels[$streamId] = new Channel(1); $this->requestMap[$streamId] = $request; } } - else { + else + { $this->close(); } @@ -225,27 +236,34 @@ public function end($streamId) public function recv($streamId = -1, $timeout = null) { $recvCo = $this->recvCo; - if (!$recvCo || !Coroutine::exists($recvCo)) { + if (!$recvCo || !Coroutine::exists($recvCo)) + { $this->startRecvCo(); } $recvChannels = &$this->recvChannels; - if (isset($recvChannels[$streamId])) { + if (isset($recvChannels[$streamId])) + { $channel = $recvChannels[$streamId]; } - else { + else + { $recvChannels[$streamId] = $channel = new Channel(-1 === $streamId ? $this->serverPushQueueLength : 1); } $requestMap = &$this->requestMap; - if (isset($requestMap[$streamId])) { + if (isset($requestMap[$streamId])) + { $request = $requestMap[$streamId]; unset($requestMap[$streamId]); } - else { + else + { $request = null; } $swooleResponse = $channel->pop(null === $timeout ? -1 : $timeout); - if ($this->recvCo === $recvCo) { - if (-1 !== $streamId) { + if ($this->recvCo === $recvCo) + { + if (-1 !== $streamId) + { unset($recvChannels[$streamId]); $channel->close(); } @@ -273,7 +291,8 @@ public function isConnected() */ private function startRecvCo() { - if (!$this->isConnected()) { + if (!$this->isConnected()) + { return false; } @@ -281,18 +300,24 @@ private function startRecvCo() $this->recvCo = $coid = Coroutine::getCid(); $http2Client = &$this->http2Client; $recvChannels = &$this->recvChannels; - while ($coid === $this->recvCo && $this->isConnected()) { - if ($this->timeout > 0) { + while ($coid === $this->recvCo && $this->isConnected()) + { + if ($this->timeout > 0) + { $swooleResponse = $http2Client->recv($this->timeout); } - else { + else + { $swooleResponse = $http2Client->recv(); } - if ($coid !== $this->recvCo) { + if ($coid !== $this->recvCo) + { return; } - if (!$swooleResponse) { - if ($this->ping()) { + if (!$swooleResponse) + { + if ($this->ping()) + { continue; } $this->close(); @@ -300,7 +325,8 @@ private function startRecvCo() return; } $streamId = $swooleResponse->streamId; - if (isset($recvChannels[$streamId]) || (0 === ($streamId & 1) && isset($recvChannels[$streamId = -1]))) { + if (isset($recvChannels[$streamId]) || (0 === ($streamId & 1) && isset($recvChannels[$streamId = -1]))) + { $recvChannels[$streamId]->push($swooleResponse); } } @@ -382,7 +408,8 @@ public function setTimeout($timeout) { $this->timeout = $timeout; $http2Client = $this->http2Client; - if ($http2Client) { + if ($http2Client) + { $http2Client->set([ 'timeout' => $timeout, ]); diff --git a/src/YurunHttp/Pool/Traits/TConnectionPoolConfigs.php b/src/YurunHttp/Pool/Traits/TConnectionPoolConfigs.php index dada6a3..df8acba 100644 --- a/src/YurunHttp/Pool/Traits/TConnectionPoolConfigs.php +++ b/src/YurunHttp/Pool/Traits/TConnectionPoolConfigs.php @@ -24,14 +24,16 @@ trait TConnectionPoolConfigs */ public function setConfig($url, $maxConnections = 0, $waitTimeout = 30) { - if (isset($this->connectionPoolConfigs[$url])) { + if (isset($this->connectionPoolConfigs[$url])) + { $config = $this->connectionPoolConfigs[$url]; $config->setMaxConnections($maxConnections); $config->setWaitTimeout($waitTimeout); return $config; } - else { + else + { return $this->connectionPoolConfigs[$url] = new PoolConfig($url, $maxConnections, $waitTimeout); } } @@ -45,10 +47,12 @@ public function setConfig($url, $maxConnections = 0, $waitTimeout = 30) */ public function getConfig($url) { - if (isset($this->connectionPoolConfigs[$url])) { + if (isset($this->connectionPoolConfigs[$url])) + { return $this->connectionPoolConfigs[$url]; } - else { + else + { return null; } } diff --git a/src/YurunHttp/Random.php b/src/YurunHttp/Random.php index ee056fa..9caf1ee 100644 --- a/src/YurunHttp/Random.php +++ b/src/YurunHttp/Random.php @@ -45,7 +45,8 @@ public static function text($chars, $min, $max) $length = mt_rand($min, $max); $charLength = mb_strlen($chars); $result = ''; - for ($i = 0; $i < $length; ++$i) { + for ($i = 0; $i < $length; ++$i) + { $result .= mb_substr($chars, mt_rand(1, $charLength) - 1, 1); } diff --git a/src/YurunHttp/Stream/FileStream.php b/src/YurunHttp/Stream/FileStream.php index 0be6f8c..4fb68d4 100644 --- a/src/YurunHttp/Stream/FileStream.php +++ b/src/YurunHttp/Stream/FileStream.php @@ -35,18 +35,22 @@ class FileStream implements StreamInterface */ public function __construct($uri, $mode = StreamMode::READ_WRITE) { - if (\is_string($uri)) { + if (\is_string($uri)) + { $this->uri = $uri = new Uri($uri); } - elseif ($uri instanceof UriInterface) { + elseif ($uri instanceof UriInterface) + { $this->uri = $uri; } - else { + else + { $uri = $this->uri; } $this->mode = $mode; $stream = fopen($uri, $mode); - if (false === $stream) { + if (false === $stream) + { throw new \RuntimeException(sprintf('Open stream %s error', (string) $uri)); } $this->stream = $stream; @@ -54,7 +58,8 @@ public function __construct($uri, $mode = StreamMode::READ_WRITE) public function __destruct() { - if ($this->stream) { + if ($this->stream) + { $this->close(); } } @@ -76,12 +81,14 @@ public function __destruct() */ public function __toString(): string { - try { + try + { $this->rewind(); return stream_get_contents($this->stream); } - catch (\Throwable $ex) { + catch (\Throwable $ex) + { return ''; } } @@ -120,7 +127,8 @@ public function detach() public function getSize(): ?int { $stat = fstat($this->stream); - if (false === $stat) { + if (false === $stat) + { throw new \RuntimeException('get stream size error'); } @@ -137,7 +145,8 @@ public function getSize(): ?int public function tell(): int { $result = ftell($this->stream); - if (false === $result) { + if (false === $result) + { throw new \RuntimeException('stream tell error'); } @@ -182,7 +191,8 @@ public function isSeekable(): bool */ public function seek($offset, $whence = \SEEK_SET): void { - if (-1 === fseek($this->stream, $offset, $whence)) { + if (-1 === fseek($this->stream, $offset, $whence)) + { throw new \RuntimeException('seek stream error'); } } @@ -202,7 +212,8 @@ public function seek($offset, $whence = \SEEK_SET): void */ public function rewind(): void { - if (!rewind($this->stream)) { + if (!rewind($this->stream)) + { throw new \RuntimeException('rewind stream failed'); } } @@ -237,7 +248,8 @@ public function isWritable(): bool public function write($string): int { $result = fwrite($this->stream, $string); - if (false === $result) { + if (false === $result) + { throw new \RuntimeException('write stream failed'); } @@ -275,7 +287,8 @@ public function isReadable(): bool public function read($length): string { $result = fread($this->stream, $length); - if (false === $result) { + if (false === $result) + { throw new \RuntimeException('read stream error'); } @@ -293,7 +306,8 @@ public function read($length): string public function getContents(): string { $result = stream_get_contents($this->stream); - if (false === $result) { + if (false === $result) + { throw new \RuntimeException('stream getContents error'); } @@ -318,16 +332,20 @@ public function getMetadata($key = null) { $result = stream_get_meta_data($this->stream); /* @phpstan-ignore-next-line */ - if (!$result) { + if (!$result) + { throw new \RuntimeException('stream getMetadata error'); } - if (null === $key) { + if (null === $key) + { return $result; } - elseif (isset($result[$key])) { + elseif (isset($result[$key])) + { return $result[$key]; } - else { + else + { return null; } } diff --git a/src/YurunHttp/Stream/MemoryStream.php b/src/YurunHttp/Stream/MemoryStream.php index 845993d..42cf9c1 100644 --- a/src/YurunHttp/Stream/MemoryStream.php +++ b/src/YurunHttp/Stream/MemoryStream.php @@ -139,9 +139,11 @@ public function isSeekable(): bool */ public function seek(int $offset, int $whence = \SEEK_SET): void { - switch ($whence) { + switch ($whence) + { case \SEEK_SET: - if ($offset < 0) { + if ($offset < 0) + { throw new \RuntimeException('offset failure'); } $this->position = $offset; @@ -246,12 +248,14 @@ public function read(int $length): string public function getContents(): string { $position = &$this->position; - if (0 === $position) { + if (0 === $position) + { $position = $this->size; return $this->content; } - else { + else + { return $this->read($this->size - $position); } } diff --git a/src/YurunHttp/Stream/StreamMode.php b/src/YurunHttp/Stream/StreamMode.php index 3e77695..05c997b 100644 --- a/src/YurunHttp/Stream/StreamMode.php +++ b/src/YurunHttp/Stream/StreamMode.php @@ -10,44 +10,44 @@ abstract class StreamMode /** * 只读方式打开,指针指向开头. */ - public const READONLY = 'r'; + const READONLY = 'r'; /** * 读写方式打开,指针指向开头. */ - public const READ_WRITE = 'r+'; + const READ_WRITE = 'r+'; /** * 写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。 */ - public const WRITE_CLEAN = 'w'; + const WRITE_CLEAN = 'w'; /** * 读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。 */ - public const READ_WRITE_CLEAN = 'w+'; + const READ_WRITE_CLEAN = 'w+'; /** * 写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。 */ - public const WRITE_END = 'a'; + const WRITE_END = 'a'; /** * 读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。 */ - public const READ_WRITE_END = 'a+'; + const READ_WRITE_END = 'a+'; /** * 创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。 * 这和给底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。 * 仅能用于本地文件。 */ - public const CREATE_WRITE = 'x'; + const CREATE_WRITE = 'x'; /** * 创建并以读写方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。 * 这和给底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。 * 仅能用于本地文件。 */ - public const CREATE_READ_WRITE = 'x+'; + const CREATE_READ_WRITE = 'x+'; } diff --git a/src/YurunHttp/Traits/TCookieManager.php b/src/YurunHttp/Traits/TCookieManager.php index 1d5c0f4..319fe9c 100644 --- a/src/YurunHttp/Traits/TCookieManager.php +++ b/src/YurunHttp/Traits/TCookieManager.php @@ -28,7 +28,8 @@ trait TCookieManager private function initCookieManager() { $this->cookieJar = $cookieJar = new CookieJar($this->cookieManager = new CookieManager()); - if (isset($this->options[HandlerOptions::COOKIE_JAR]) && \is_string($this->options[HandlerOptions::COOKIE_JAR])) { + if (isset($this->options[HandlerOptions::COOKIE_JAR]) && \is_string($this->options[HandlerOptions::COOKIE_JAR])) + { $cookieJar->load($this->options[HandlerOptions::COOKIE_JAR]); } } @@ -60,7 +61,8 @@ public function getCookieJar() */ protected function saveCookieJar() { - if (isset($this->options[HandlerOptions::COOKIE_JAR]) && \is_string($this->options[HandlerOptions::COOKIE_JAR])) { + if (isset($this->options[HandlerOptions::COOKIE_JAR]) && \is_string($this->options[HandlerOptions::COOKIE_JAR])) + { $this->cookieJar->save($this->options[HandlerOptions::COOKIE_JAR]); } } diff --git a/src/YurunHttp/Traits/THandler.php b/src/YurunHttp/Traits/THandler.php index e9cd104..ec3309e 100644 --- a/src/YurunHttp/Traits/THandler.php +++ b/src/YurunHttp/Traits/THandler.php @@ -18,17 +18,22 @@ trait THandler public function parseRedirectLocation($location, $currentUri) { $locationUri = new Uri($location); - if ('' === $locationUri->getHost()) { - if (!isset($location[0])) { + if ('' === $locationUri->getHost()) + { + if (!isset($location[0])) + { throw new \InvalidArgumentException(sprintf('Invalid $location: %s', $location)); } - if ('/' === $location[0]) { + if ('/' === $location[0]) + { $uri = $currentUri->withQuery('')->withPath($location); } - else { + else + { $uri = $currentUri; $path = $currentUri->getPath(); - if ('/' !== substr($path, -1, 1)) { + if ('/' !== substr($path, -1, 1)) + { $path .= '/'; } $path .= $location; @@ -36,7 +41,8 @@ public function parseRedirectLocation($location, $currentUri) } $uri = $uri->withHost($currentUri->getHost())->withPort($currentUri->getPort()); } - else { + else + { $uri = $locationUri; } @@ -52,8 +58,10 @@ public function parseRedirectLocation($location, $currentUri) */ protected function checkRequests($requests) { - foreach ($requests as $request) { - if (!$request instanceof \Yurun\Util\YurunHttp\Http\Request) { + foreach ($requests as $request) + { + if (!$request instanceof \Yurun\Util\YurunHttp\Http\Request) + { throw new \InvalidArgumentException('Request must be instance of \Yurun\Util\YurunHttp\Http\Request'); } } diff --git a/src/YurunHttp/Traits/TLogger.php b/src/YurunHttp/Traits/TLogger.php index b56368b..c085c53 100644 --- a/src/YurunHttp/Traits/TLogger.php +++ b/src/YurunHttp/Traits/TLogger.php @@ -24,13 +24,16 @@ protected function getLogger() protected function logRequest($request, $response) { $logger = $this->getLogger(); - if (!$logger) { + if (!$logger) + { return; } - if (isset($this->options[HandlerOptions::REQUEST_LOG_FORMAT])) { + if (isset($this->options[HandlerOptions::REQUEST_LOG_FORMAT])) + { $requestLogFormat = $this->options[HandlerOptions::REQUEST_LOG_FORMAT]; } - else { + else + { $requestLogFormat = <<<'STR' Request: [{method}] {url} Response: statusCode: [{status_code}], contentLength: {content_length}, errno: {errno}, error: {error}, useTime: {time} @@ -38,7 +41,8 @@ protected function logRequest($request, $response) } $message = preg_replace_callback('/\{([^\}]+)\}/', function ($matches) use ($request, $response) { - switch ($matches[1]) { + switch ($matches[1]) + { case 'method': return $request->getMethod(); case 'url': @@ -47,7 +51,8 @@ protected function logRequest($request, $response) return $request->getBody()->__toString(); case 'request_headers': $headers = []; - foreach ($request->getHeaders() as $name => $value) { + foreach ($request->getHeaders() as $name => $value) + { $headers[] = $name . ': ' . implode(',', $value); } @@ -62,7 +67,8 @@ protected function logRequest($request, $response) return $response->getError(); case 'response_headers': $headers = []; - foreach ($response->getHeaders() as $name => $value) { + foreach ($response->getHeaders() as $name => $value) + { $headers[] = $name . ': ' . implode(',', $value); } diff --git a/src/YurunHttp/WebSocket/Swoole.php b/src/YurunHttp/WebSocket/Swoole.php index ce0c09b..3d273ba 100644 --- a/src/YurunHttp/WebSocket/Swoole.php +++ b/src/YurunHttp/WebSocket/Swoole.php @@ -124,7 +124,8 @@ public function send($data) { $handler = $this->handler; $result = $handler->push($data); - if (!$result) { + if (!$result) + { $errCode = $handler->errCode; throw new WebSocketException(sprintf('Send Failed, error: %s, errorCode: %s', swoole_strerror($errCode), $errCode), $errCode); } @@ -142,7 +143,8 @@ public function send($data) public function recv($timeout = null) { $result = $this->handler->recv((float) $timeout); - if (!$result) { + if (!$result) + { return false; } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 13ff73d..68b37de 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -13,7 +13,8 @@ function testEnv($name, $default = null) { $result = getenv($name); - if (false === $result) { + if (false === $result) + { return $default; } @@ -25,39 +26,48 @@ function testEnv($name, $default = null) echo 'Starting Http server...', \PHP_EOL; echo `{$cmd}`, \PHP_EOL; $serverStarted = false; -for ($i = 0; $i < 10; ++$i) { +for ($i = 0; $i < 10; ++$i) +{ $context = stream_context_create(['http' => ['timeout' => 1]]); - if ('YurunHttp' === @file_get_contents(testEnv('HTTP_SERVER_HOST', 'http://127.0.0.1:8898/'), false, $context)) { + if ('YurunHttp' === @file_get_contents(testEnv('HTTP_SERVER_HOST', 'http://127.0.0.1:8898/'), false, $context)) + { $serverStarted = true; break; } sleep(1); } -if ($serverStarted) { +if ($serverStarted) +{ echo 'Http server started!', \PHP_EOL; } -else { +else +{ throw new \RuntimeException('Http server start failed'); } -if (SWOOLE_ON) { +if (SWOOLE_ON) +{ // WebSocket Server $cmd = __DIR__ . '/server/WebSocket/start-server.sh'; echo 'Starting WebSocket server...', \PHP_EOL; echo `{$cmd}`, \PHP_EOL; $serverStarted = false; - for ($i = 0; $i < 10; ++$i) { + for ($i = 0; $i < 10; ++$i) + { @file_get_contents(str_replace('ws://', 'http://', testEnv('WS_SERVER_HOST', 'ws://127.0.0.1:8900/'))); - if (isset($http_response_header[0]) && 'HTTP/1.1 400 Bad Request' === $http_response_header[0]) { + if (isset($http_response_header[0]) && 'HTTP/1.1 400 Bad Request' === $http_response_header[0]) + { $serverStarted = true; break; } sleep(1); } - if ($serverStarted) { + if ($serverStarted) + { echo 'WebSocekt server started!', \PHP_EOL; } - else { + else + { throw new \RuntimeException('WebSocekt server start failed'); } @@ -66,18 +76,22 @@ function testEnv($name, $default = null) echo 'Starting Http2 server...', \PHP_EOL; echo `{$cmd}`, \PHP_EOL; $serverStarted = false; - for ($i = 0; $i < 10; ++$i) { + for ($i = 0; $i < 10; ++$i) + { @file_get_contents(testEnv('HTTP2_SERVER_HOST', 'http://127.0.0.1:8901/')); - if (isset($http_response_header[0]) && 'HTTP/1.1 200 OK' === $http_response_header[0]) { + if (isset($http_response_header[0]) && 'HTTP/1.1 200 OK' === $http_response_header[0]) + { $serverStarted = true; break; } sleep(1); } - if ($serverStarted) { + if ($serverStarted) + { echo 'Http2 server started!', \PHP_EOL; } - else { + else + { throw new \RuntimeException('Http2 server start failed'); } } @@ -89,7 +103,8 @@ function testEnv($name, $default = null) echo `{$cmd}`, \PHP_EOL; echo 'Http Server stoped!', \PHP_EOL; - if (SWOOLE_ON) { + if (SWOOLE_ON) + { $cmd = __DIR__ . '/server/WebSocket/stop-server.sh'; echo 'Stoping WebSocket server...', \PHP_EOL; echo `{$cmd}`, \PHP_EOL; diff --git a/tests/server/Http/WorkermanHttp.php b/tests/server/Http/WorkermanHttp.php index f444314..e556dac 100644 --- a/tests/server/Http/WorkermanHttp.php +++ b/tests/server/Http/WorkermanHttp.php @@ -59,7 +59,8 @@ class WorkermanHttp */ public static function sessionName($name = null) { - if (null !== $name && '' !== $name) { + if (null !== $name && '' !== $name) + { static::$_sessionName = (string) $name; } @@ -75,7 +76,8 @@ public static function sessionName($name = null) */ public static function requestClass($class_name = null) { - if ($class_name) { + if ($class_name) + { static::$_requestClass = $class_name; } @@ -105,13 +107,16 @@ public static function enableCache($value) public static function input($recv_buffer, TcpConnection $connection) { static $input = []; - if (!isset($recv_buffer[512]) && isset($input[$recv_buffer])) { + if (!isset($recv_buffer[512]) && isset($input[$recv_buffer])) + { return $input[$recv_buffer]; } $crlf_pos = strpos($recv_buffer, "\r\n\r\n"); - if (false === $crlf_pos) { + if (false === $crlf_pos) + { // Judge whether the package length exceeds the limit. - if ($recv_len = strlen($recv_buffer) >= 16384) { + if ($recv_len = strlen($recv_buffer) >= 16384) + { $connection->close("HTTP/1.1 413 Request Entity Too Large\r\n\r\n"); return 0; @@ -123,34 +128,43 @@ public static function input($recv_buffer, TcpConnection $connection) $head_len = $crlf_pos + 4; $method = strstr($recv_buffer, ' ', true); - if ('GET' === $method || 'OPTIONS' === $method || 'HEAD' === $method || 'DELETE' === $method) { - if (!isset($recv_buffer[512])) { + if ('GET' === $method || 'OPTIONS' === $method || 'HEAD' === $method || 'DELETE' === $method) + { + if (!isset($recv_buffer[512])) + { $input[$recv_buffer] = $head_len; - if (count($input) > 512) { + if (count($input) > 512) + { unset($input[key($input)]); } } } - elseif ('POST' !== $method && 'PUT' !== $method) { + elseif ('POST' !== $method && 'PUT' !== $method) + { $connection->close("HTTP/1.1 400 Bad Request\r\n\r\n", true); return 0; } $header = substr($recv_buffer, 0, $crlf_pos); - if ($pos = strpos($header, "\r\nContent-Length: ")) { + if ($pos = strpos($header, "\r\nContent-Length: ")) + { $length = $head_len + (int) substr($header, $pos + 18, 10); } - elseif (preg_match("/\r\ncontent-length: ?(\d+)/i", $header, $match)) { + elseif (preg_match("/\r\ncontent-length: ?(\d+)/i", $header, $match)) + { $length = $head_len + (int) $match[1]; } - else { + else + { $length = $head_len; } - if (!isset($recv_buffer[512])) { + if (!isset($recv_buffer[512])) + { $input[$recv_buffer] = $length; - if (count($input) > 512) { + if (count($input) > 512) + { unset($input[key($input)]); } } @@ -170,7 +184,8 @@ public static function decode($recv_buffer, TcpConnection $connection) { static $requests = []; $cacheable = static::$_enableCache && !isset($recv_buffer[512]); - if (true === $cacheable && isset($requests[$recv_buffer])) { + if (true === $cacheable && isset($requests[$recv_buffer])) + { $request = $requests[$recv_buffer]; $request->connection = $connection; $connection->__request = $request; @@ -181,9 +196,11 @@ public static function decode($recv_buffer, TcpConnection $connection) $request = new static::$_requestClass($recv_buffer); $request->connection = $connection; $connection->__request = $request; - if (true === $cacheable) { + if (true === $cacheable) + { $requests[$recv_buffer] = $request; - if (count($requests) > 512) { + if (count($requests) > 512) + { unset($requests[key($requests)]); } } @@ -201,21 +218,28 @@ public static function decode($recv_buffer, TcpConnection $connection) */ public static function encode($response, TcpConnection $connection) { - if (isset($connection->__request)) { + if (isset($connection->__request)) + { $connection->__request->session = null; $connection->__request->connection = null; $connection->__request = null; } - if (is_scalar($response) || null === $response) { + if (is_scalar($response) || null === $response) + { $ext_header = ''; - if (isset($connection->__header)) { - foreach ($connection->__header as $name => $value) { - if (is_array($value)) { - foreach ($value as $item) { + if (isset($connection->__header)) + { + foreach ($connection->__header as $name => $value) + { + if (is_array($value)) + { + foreach ($value as $item) + { $ext_header = "$name: $item\r\n"; } } - else { + else + { $ext_header = "$name: $value\r\n"; } } @@ -226,13 +250,15 @@ public static function encode($response, TcpConnection $connection) return "HTTP/1.1 200 OK\r\nServer: workerman\r\n{$ext_header}Connection: keep-alive\r\nContent-Type: text/html;charset=utf-8\r\nContent-Length: $body_len\r\n\r\n$response"; } - if (isset($connection->__header)) { + if (isset($connection->__header)) + { $response->withHeaders($connection->__header); unset($connection->__header); } // @phpstan-ignore-next-line - if (isset($response->file)) { + if (isset($response->file)) + { $file = $response->file['file']; $offset = $response->file['offset']; $length = $response->file['length']; @@ -242,17 +268,20 @@ public static function encode($response, TcpConnection $connection) 'Content-Length' => $body_len, 'Accept-Ranges' => 'bytes', ]); - if ($offset || $length) { + if ($offset || $length) + { $offset_end = $offset + $body_len - 1; $response->header('Content-Range', "bytes $offset-$offset_end/$file_size"); } - if ($body_len < 2 * 1024 * 1024) { + if ($body_len < 2 * 1024 * 1024) + { $connection->send((string) $response . file_get_contents($file, false, null, $offset, $body_len), true); return ''; } $handler = fopen($file, 'r'); - if (false === $handler) { + if (false === $handler) + { $connection->close(new Response(403, [], '403 Forbidden')); return ''; @@ -280,20 +309,24 @@ protected static function sendStream(TcpConnection $connection, $handler, $offse { /* @phpstan-ignore-next-line */ $connection->bufferFull = false; - if (0 !== $offset) { + if (0 !== $offset) + { fseek($handler, $offset); } $offset_end = $offset + $length; // Read file content from disk piece by piece and send to client. $do_write = function () use ($connection, $handler, $length, $offset_end) { // Send buffer not full. - while (false === $connection->bufferFull) { + while (false === $connection->bufferFull) + { // Read from disk. $size = 1024 * 1024; - if (0 !== $length) { + if (0 !== $length) + { $tell = ftell($handler); $remain_size = $offset_end - $tell; - if ($remain_size <= 0) { + if ($remain_size <= 0) + { fclose($handler); /* @phpstan-ignore-next-line */ $connection->onBufferDrain = null; @@ -305,7 +338,8 @@ protected static function sendStream(TcpConnection $connection, $handler, $offse $buffer = fread($handler, $size); // Read eof. - if ('' === $buffer || false === $buffer) { + if ('' === $buffer || false === $buffer) + { fclose($handler); /* @phpstan-ignore-next-line */ $connection->onBufferDrain = null; @@ -336,14 +370,18 @@ protected static function sendStream(TcpConnection $connection, $handler, $offse */ public static function uploadTmpDir($dir = null) { - if (null !== $dir) { + if (null !== $dir) + { static::$_uploadTmpDir = $dir; } - if ('' === static::$_uploadTmpDir) { - if ($upload_tmp_dir = ini_get('upload_tmp_dir')) { + if ('' === static::$_uploadTmpDir) + { + if ($upload_tmp_dir = ini_get('upload_tmp_dir')) + { static::$_uploadTmpDir = $upload_tmp_dir; } - elseif ($upload_tmp_dir = sys_get_temp_dir()) { + elseif ($upload_tmp_dir = sys_get_temp_dir()) + { static::$_uploadTmpDir = $upload_tmp_dir; } } diff --git a/tests/server/Http/server.php b/tests/server/Http/server.php index 9f57130..aeeb806 100644 --- a/tests/server/Http/server.php +++ b/tests/server/Http/server.php @@ -19,10 +19,12 @@ // Emitted when data received $http_worker->onMessage = function (TcpConnection $connection, Request $request) { // var_dump($request->method(), $request->get('a')); - switch ($request->get('a')) { + switch ($request->get('a')) + { case 'info': $files = $request->file(); - foreach ($files as &$file) { + foreach ($files as &$file) + { $file['hash'] = md5(file_get_contents($file['tmp_name'])); } $connection->send(new Response(200, [ @@ -90,7 +92,8 @@ $connection->send($response); break; case 'download1': - if ('nb' === $request->post('yurunhttp') && 'POST' === $request->method()) { + if ('nb' === $request->post('yurunhttp') && 'POST' === $request->method()) + { $response = new Response(200, [ 'Content-Type' => 'text/html; charset=UTF-8', ], 'YurunHttp Hello World'); @@ -99,7 +102,8 @@ } break; case 'download2': - if ('nb' === $request->post('yurunhttp') && 'POST' === $request->method()) { + if ('nb' === $request->post('yurunhttp') && 'POST' === $request->method()) + { $connection->send('

YurunHttp Hello World

'); } break; diff --git a/tests/server/Http2/http2-server.php b/tests/server/Http2/http2-server.php index c433c29..0aaae95 100644 --- a/tests/server/Http2/http2-server.php +++ b/tests/server/Http2/http2-server.php @@ -8,7 +8,8 @@ 'worker_num' => 1, ]); $http->on('request', function (Swoole\Http\Request $request, Swoole\Http\Response $response) { - switch ($request->server['path_info']) { + switch ($request->server['path_info']) + { case '/': $response->header('trailer', 'yurun'); $response->trailer('yurun', 'niubi'); diff --git a/tests/server/WebSocket/ws-server.php b/tests/server/WebSocket/ws-server.php index 57b393c..def046d 100644 --- a/tests/server/WebSocket/ws-server.php +++ b/tests/server/WebSocket/ws-server.php @@ -9,7 +9,8 @@ $server->on('message', function (Swoole\WebSocket\Server $server, $frame) use (&$userNameStore) { $data = json_decode($frame->data, true); - switch ($data['action']) { + switch ($data['action']) + { case 'login': $userNameStore[$frame->fd] = $data['username']; $server->push($frame->fd, json_encode(['success' => true])); @@ -21,7 +22,8 @@ }); $server->on('close', function ($ser, $fd) use (&$userNameStore) { - if (isset($userNameStore[$fd])) { + if (isset($userNameStore[$fd])) + { unset($userNameStore[$fd]); } }); diff --git a/tests/unit/DefaultHandlerTest.php b/tests/unit/DefaultHandlerTest.php index 867c1e6..78ca411 100644 --- a/tests/unit/DefaultHandlerTest.php +++ b/tests/unit/DefaultHandlerTest.php @@ -12,7 +12,8 @@ class DefaultHandlerTest extends BaseTest public function testCurl(): void { - if (\extension_loaded('swoole')) { + if (\extension_loaded('swoole')) + { $this->assertEquals(-1, Coroutine::getuid()); } YurunHttp::setDefaultHandler(null); @@ -37,7 +38,8 @@ public function testSetDefaultHandler(): void YurunHttp::setDefaultHandler(\Yurun\Util\YurunHttp\Handler\Curl::class); $this->assertInstanceOf(\Yurun\Util\YurunHttp\Handler\Curl::class, YurunHttp::getHandler()); - if (\PHP_VERSION_ID >= 50600) { + if (\PHP_VERSION_ID >= 50600) + { YurunHttp::setDefaultHandler(null); $this->assertNull(YurunHttp::getDefaultHandler()); YurunHttp::setDefaultHandler(\Exception::class); diff --git a/tests/unit/Http2/SwooleHttp2Test.php b/tests/unit/Http2/SwooleHttp2Test.php index ec10abe..56fef05 100644 --- a/tests/unit/Http2/SwooleHttp2Test.php +++ b/tests/unit/Http2/SwooleHttp2Test.php @@ -105,7 +105,8 @@ public function testMuiltCo(): void $count = 10; $channel = new Channel($count); - for ($i = 0; $i < $count; ++$i) { + for ($i = 0; $i < $count; ++$i) + { go(function () use ($i, $client, $channel, $httpRequest, $fd) { $request = $httpRequest->buildRequest($this->http2Host, [ 'date' => $i, @@ -120,8 +121,10 @@ public function testMuiltCo(): void }); } $returnCount = 0; - do { - if ($channel->pop()) { + do + { + if ($channel->pop()) + { ++$returnCount; } } @@ -163,11 +166,13 @@ public function testPipeline1(): void $this->assertEquals('yurun', $response->getHeaderLine('trailer')); $client->close(); /* @phpstan-ignore-next-line */ - if (version_compare(\SWOOLE_VERSION, '4.4.13', '<')) { + if (version_compare(\SWOOLE_VERSION, '4.4.13', '<')) + { // Swoole <= 4.4.12 BUG $this->markTestSkipped(sprintf('Swoole version %s < 4.4.13', \SWOOLE_VERSION)); } - else { + else + { $this->assertEquals('niubi', $response->getHeaderLine('yurun')); } }); @@ -204,11 +209,13 @@ public function testPipeline2(): void $this->assertEquals('yurun', $response->getHeaderLine('trailer')); $client->close(); /* @phpstan-ignore-next-line */ - if (version_compare(\SWOOLE_VERSION, '4.4.13', '<')) { + if (version_compare(\SWOOLE_VERSION, '4.4.13', '<')) + { // Swoole <= 4.4.12 BUG $this->markTestSkipped(sprintf('Swoole version %s < 4.4.13', \SWOOLE_VERSION)); } - else { + else + { $this->assertEquals('niubi', $response->getHeaderLine('yurun')); } }); diff --git a/tests/unit/HttpRequestTest/CurlPoolTest.php b/tests/unit/HttpRequestTest/CurlPoolTest.php index cd9a25e..89852f3 100644 --- a/tests/unit/HttpRequestTest/CurlPoolTest.php +++ b/tests/unit/HttpRequestTest/CurlPoolTest.php @@ -15,7 +15,8 @@ public function test(): void // 启用连接池 ConnectionPool::enable(); - try { + try + { // 为这个地址设置限制连接池连接数量3个 // 一定不要有 / 及后续参数等 $url = rtrim($this->host, '/'); @@ -43,7 +44,8 @@ public function test(): void $this->assertEquals(1, $pool->getFree()); $this->assertEquals(0, $pool->getUsed()); } - finally { + finally + { ConnectionPool::disable(); } }); diff --git a/tests/unit/HttpRequestTest/HttpRequestTest.php b/tests/unit/HttpRequestTest/HttpRequestTest.php index c21c451..17f9282 100644 --- a/tests/unit/HttpRequestTest/HttpRequestTest.php +++ b/tests/unit/HttpRequestTest/HttpRequestTest.php @@ -216,14 +216,16 @@ public function testCookieManager(): void ]; $data = null; - for ($i = 0; $i < 2; ++$i) { + for ($i = 0; $i < 2; ++$i) + { sleep(1); $response = $http->get($this->host . '?a=info'); $this->assertResponse($response); $data = $response->json(true); - if ($compareCookie === $data['cookie']) { + if ($compareCookie === $data['cookie']) + { break; } } @@ -253,14 +255,16 @@ public function testAutoRedirect(): void $this->call(function () { $http = new HttpRequest(); - foreach ([301, 302] as $statusCode) { + foreach ([301, 302] as $statusCode) + { $response = $http->post($this->host . '?a=redirect' . $statusCode); $this->assertResponse($response); $data = $response->json(true); $this->assertEquals('GET', $data['method'], $statusCode . ' method error'); } - foreach ([307, 308] as $statusCode) { + foreach ([307, 308] as $statusCode) + { $response = $http->post($this->host . '?a=redirect' . $statusCode); $this->assertResponse($response); $data = $response->json(true); @@ -447,7 +451,8 @@ public function test304(): void { $this->call(function () { /* @phpstan-ignore-next-line */ - if (method_exists(Coroutine::class, 'getuid') && Coroutine::getuid() > 0 && version_compare(\SWOOLE_VERSION, '4.4.17', '<')) { + if (method_exists(Coroutine::class, 'getuid') && Coroutine::getuid() > 0 && version_compare(\SWOOLE_VERSION, '4.4.17', '<')) + { $this->markTestSkipped('Swoole must >= 4.4.17'); } $http = new HttpRequest(); @@ -479,7 +484,8 @@ public function testDownload(): void $this->call(function () { $http = new HttpRequest(); $fileName = __DIR__ . '/download.txt'; - if (is_file($fileName)) { + if (is_file($fileName)) + { unlink($fileName); } $this->assertFalse(is_file($fileName)); @@ -500,7 +506,8 @@ public function testDownloadAutoExt(): void $this->call(function () { $http = new HttpRequest(); $fileName = __DIR__ . '/download.html'; - if (is_file($fileName)) { + if (is_file($fileName)) + { unlink($fileName); } $this->assertFalse(is_file($fileName)); @@ -521,7 +528,8 @@ public function testDownloadWithRedirect(): void $this->call(function () { $http = new HttpRequest(); $fileName = __DIR__ . '/download.html'; - if (is_file($fileName)) { + if (is_file($fileName)) + { unlink($fileName); } $this->assertFalse(is_file($fileName)); @@ -558,19 +566,22 @@ public function testCoBatch(): void $this->call(function () { $time = time(); $fileName = __DIR__ . '/download.txt'; - if (is_file($fileName)) { + if (is_file($fileName)) + { unlink($fileName); } $this->assertFalse(is_file($fileName)); $fileName2Temp = __DIR__ . '/download2.*'; $fileName2 = __DIR__ . '/download2.html'; - if (is_file($fileName2)) { + if (is_file($fileName2)) + { unlink($fileName2); } $this->assertFalse(is_file($fileName2)); $fileName3Temp = __DIR__ . '/download3.*'; $fileName3 = __DIR__ . '/download3.html'; - if (is_file($fileName3)) { + if (is_file($fileName3)) + { unlink($fileName3); } $this->assertFalse(is_file($fileName3)); @@ -582,39 +593,46 @@ public function testCoBatch(): void 'a' => (new HttpRequest())->url($this->host . '?a=redirect&url=/?a=download3')->requestBody('yurunhttp=nb')->saveFile($fileName3Temp), ]); - foreach ($result as $i => $response) { - if (0 === $i) { + foreach ($result as $i => $response) + { + if (0 === $i) + { $this->assertResponse($response); $this->assertEquals('YurunHttp', $response->body()); $this->assertNotNull($response->getRequest()); } - elseif (1 === $i) { + elseif (1 === $i) + { $data = $response->json(true); $this->assertEquals('GET', isset($data['method']) ? $data['method'] : null); $this->assertEquals($time, isset($data['get']['time']) ? $data['get']['time'] : null); $this->assertNotNull($response->getRequest()); } - elseif (2 === $i) { + elseif (2 === $i) + { $this->assertTrue(is_file($fileName)); $this->assertEquals('YurunHttp Hello World', file_get_contents($fileName)); $this->assertNotNull($response->getRequest()); $this->assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type')); $this->assertEquals('1', $response->getCookie('a')); } - elseif (3 === $i) { + elseif (3 === $i) + { $this->assertTrue(is_file($fileName2)); $this->assertEquals('YurunHttp Hello World', file_get_contents($fileName2)); $this->assertNotNull($response->getRequest()); $this->assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type')); $this->assertEquals('1', $response->getCookie('a')); } - elseif ('a' === $i) { + elseif ('a' === $i) + { $this->assertTrue(is_file($fileName3)); $this->assertEquals('download3', file_get_contents($fileName3)); $this->assertNotNull($response->getRequest()); $this->assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type')); } - else { + else + { throw new \RuntimeException(sprintf('Unknown %s', $i)); } } @@ -641,7 +659,8 @@ public function testMemoryLeak(): void { $this->call(function () { $memorys = [1, 2, 3, 4, 5]; - for ($i = 0; $i < 5; ++$i) { + for ($i = 0; $i < 5; ++$i) + { $http = new HttpRequest(); $http->get($this->host); $memorys[$i] = memory_get_usage(); @@ -650,7 +669,8 @@ public function testMemoryLeak(): void $this->assertCount(1, array_unique($memorys)); $memorys = [1, 2, 3, 4, 5]; - for ($i = 0; $i < 5; ++$i) { + for ($i = 0; $i < 5; ++$i) + { YurunHttp::send(new Request($this->host)); $memorys[$i] = memory_get_usage(); } @@ -659,7 +679,8 @@ public function testMemoryLeak(): void $memorys = [1, 2, 3, 4, 5]; $time = time(); - for ($i = 0; $i < 5; ++$i) { + for ($i = 0; $i < 5; ++$i) + { Batch::run([ (new HttpRequest())->url($this->host), (new HttpRequest())->url($this->host . '?a=info&time=' . $time), diff --git a/tests/unit/HttpRequestTest/SwoolePoolTest.php b/tests/unit/HttpRequestTest/SwoolePoolTest.php index a9cc9af..94588c7 100644 --- a/tests/unit/HttpRequestTest/SwoolePoolTest.php +++ b/tests/unit/HttpRequestTest/SwoolePoolTest.php @@ -18,7 +18,8 @@ public function test(): void // 启用连接池 ConnectionPool::enable(); - try { + try + { // 为这个地址设置限制连接池连接数量3个 // 一定不要有 / 及后续参数等 $url = rtrim($this->host, '/'); @@ -46,7 +47,8 @@ public function test(): void $this->assertEquals(1, $pool->getFree()); $this->assertEquals(0, $pool->getUsed()); } - finally { + finally + { ConnectionPool::disable(); } }); diff --git a/tests/unit/Traits/TSwooleHandlerTest.php b/tests/unit/Traits/TSwooleHandlerTest.php index 1c04823..e7f4789 100644 --- a/tests/unit/Traits/TSwooleHandlerTest.php +++ b/tests/unit/Traits/TSwooleHandlerTest.php @@ -13,41 +13,50 @@ trait TSwooleHandlerTest */ protected function call($callable) { - if (!\extension_loaded('swoole')) { + if (!\extension_loaded('swoole')) + { $this->markTestSkipped('Does not installed ext/swoole'); } - if (\defined('SWOOLE_HOOK_ALL')) { + if (\defined('SWOOLE_HOOK_ALL')) + { $flags = \SWOOLE_HOOK_ALL; - if (\defined('SWOOLE_HOOK_NATIVE_CURL')) { + if (\defined('SWOOLE_HOOK_NATIVE_CURL')) + { $flags ^= \SWOOLE_HOOK_NATIVE_CURL; } } - else { + else + { $flags = true; } \Swoole\Runtime::enableCoroutine($flags); $throwable = null; $end = false; go(function () use ($callable, &$throwable, &$end) { - try { + try + { YurunHttp::setDefaultHandler(\Yurun\Util\YurunHttp\Handler\Swoole::class); $callable(); } - catch (\Throwable $th) { + catch (\Throwable $th) + { $throwable = $th; } $end = true; }); // @phpstan-ignore-next-line - while (!$end) { + while (!$end) + { swoole_event_dispatch(); } // @phpstan-ignore-next-line \Swoole\Runtime::enableCoroutine(false); - if ($throwable) { + if ($throwable) + { throw $throwable; } - else { + else + { $this->assertEquals(1, 1); } } diff --git a/tests/unit/WebSocketTest/WebSocketTest.php b/tests/unit/WebSocketTest/WebSocketTest.php index 45d2360..e632737 100644 --- a/tests/unit/WebSocketTest/WebSocketTest.php +++ b/tests/unit/WebSocketTest/WebSocketTest.php @@ -60,7 +60,8 @@ public function testMemoryLeak(): void { $this->call(function () { $memorys = [1, 2, 3, 4, 5]; - for ($i = 0; $i < 5; ++$i) { + for ($i = 0; $i < 5; ++$i) + { $http = new HttpRequest(); $client = $http->websocket($this->wsHost); $client->close(); From 891c0b982f99701597c01d2b7dcd4c19245a56ec Mon Sep 17 00:00:00 2001 From: Yurun Date: Fri, 13 Oct 2023 16:15:24 +0800 Subject: [PATCH 03/12] test --- .github/workflows/ci.yml | 20 +++++ .php-cs-fixer.dist.php | 113 +++++++++++++++++++++++++ src/YurunHttp/Http/Psr7/Uri.php | 2 +- src/YurunHttp/Stream/FileStream.php | 2 +- src/YurunHttp/Stream/MemoryStream.php | 2 +- tests/server/Http/start-server.sh | 2 +- tests/server/Http2/start-server.sh | 2 +- tests/server/WebSocket/start-server.sh | 2 +- 8 files changed, 139 insertions(+), 6 deletions(-) create mode 100644 .php-cs-fixer.dist.php diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c3b6911..c6f6284 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,6 +24,16 @@ jobs: - name: test run: docker exec php composer test + - name: Print logs + if: failure() + run: | + echo "Http" + cat tests/server/Http/log.log + echo "Http2" + cat tests/server/Http2/log.log + echo "WebSocket" + cat tests/server/WebSocket/log.log + ci-curl-swoole: runs-on: ubuntu-20.04 @@ -57,3 +67,13 @@ jobs: - name: test run: docker exec swoole composer test + + - name: Print logs + if: failure() + run: | + echo "Http" + cat tests/server/Http/log.log + echo "Http2" + cat tests/server/Http2/log.log + echo "WebSocket" + cat tests/server/WebSocket/log.log diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 0000000..19c5186 --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,113 @@ +setRules([ + '@Symfony' => true, + '@Symfony:risky' => true, + 'php_unit_dedicate_assert' => ['target' => '5.6'], + 'array_syntax' => ['syntax' => 'short'], + 'array_indentation' => true, + 'binary_operator_spaces' => [ + 'operators' => [ + '=>' => 'align_single_space', + ], + ], + 'concat_space' => [ + 'spacing' => 'one', + ], + 'fopen_flags' => false, + 'protected_to_private' => false, + 'native_constant_invocation' => true, + 'single_quote' => true, + 'single_space_around_construct' => [ + 'constructs_followed_by_a_single_space' => [ + 'abstract', + 'as', + 'attribute', + 'break', + 'case', + 'catch', + 'class', + 'clone', + 'comment', + 'const', + 'const_import', + 'continue', + 'do', + 'echo', + 'else', + 'elseif', + 'enum', + 'extends', + 'final', + 'finally', + 'for', + 'foreach', + 'function', + 'function_import', + 'global', + 'goto', + 'if', + 'implements', + 'include', + 'include_once', + 'instanceof', + 'insteadof', + 'interface', + 'match', + 'named_argument', + // 'namespace', // 兼容性移除 + 'new', + 'open_tag_with_echo', + 'php_doc', + 'php_open', + 'print', + 'private', + 'protected', + 'public', + 'readonly', + 'require', + 'require_once', + 'return', + 'static', + 'switch', + 'throw', + 'trait', + 'try', + 'type_colon', + 'use', + 'use_lambda', + 'use_trait', + 'var', + 'while', + 'yield', + 'yield_from', + ], + ], + 'control_structure_continuation_position' => [ + 'position' => 'next_line', + ], + 'curly_braces_position' => [ + 'control_structures_opening_brace' => 'next_line_unless_newline_at_signature_end', + ], + 'no_superfluous_phpdoc_tags' => false, + 'single_line_comment_style' => false, + 'combine_nested_dirname' => false, + 'backtick_to_shell_exec' => false, + 'visibility_required' => false, + ]) + ->setRiskyAllowed(true) + ->setFinder( + PhpCsFixer\Finder::create() + ->exclude(__DIR__ . '/vendor') + ->in(__DIR__ . '/src') + ->in(__DIR__ . '/examples') + ->in(__DIR__ . '/tests') + ->append([__FILE__]) + ) +; diff --git a/src/YurunHttp/Http/Psr7/Uri.php b/src/YurunHttp/Http/Psr7/Uri.php index aeb4135..91ca35e 100644 --- a/src/YurunHttp/Http/Psr7/Uri.php +++ b/src/YurunHttp/Http/Psr7/Uri.php @@ -583,7 +583,7 @@ public function withFragment($fragment): UriInterface * * @return string */ - public function __toString(): string + public function __toString() { return static::makeUriString($this->host, $this->path, $this->query, $this->port, $this->scheme, $this->fragment, $this->userInfo); } diff --git a/src/YurunHttp/Stream/FileStream.php b/src/YurunHttp/Stream/FileStream.php index 4fb68d4..902b911 100644 --- a/src/YurunHttp/Stream/FileStream.php +++ b/src/YurunHttp/Stream/FileStream.php @@ -79,7 +79,7 @@ public function __destruct() * * @return string */ - public function __toString(): string + public function __toString() { try { diff --git a/src/YurunHttp/Stream/MemoryStream.php b/src/YurunHttp/Stream/MemoryStream.php index 42cf9c1..952ecdc 100644 --- a/src/YurunHttp/Stream/MemoryStream.php +++ b/src/YurunHttp/Stream/MemoryStream.php @@ -137,7 +137,7 @@ public function isSeekable(): bool * * @throws \RuntimeException on failure */ - public function seek(int $offset, int $whence = \SEEK_SET): void + public function seek($offset, $whence = \SEEK_SET): void { switch ($whence) { diff --git a/tests/server/Http/start-server.sh b/tests/server/Http/start-server.sh index e2acbb1..ad8e124 100755 --- a/tests/server/Http/start-server.sh +++ b/tests/server/Http/start-server.sh @@ -4,4 +4,4 @@ __DIR__=$(cd `dirname $0`; pwd) ${__DIR__}/stop-server.sh -/usr/bin/env php $__DIR__/server.php start -d > /dev/null \ No newline at end of file +/usr/bin/env php $__DIR__/server.php start -d > log.log \ No newline at end of file diff --git a/tests/server/Http2/start-server.sh b/tests/server/Http2/start-server.sh index b33b77d..1b05c5f 100755 --- a/tests/server/Http2/start-server.sh +++ b/tests/server/Http2/start-server.sh @@ -10,4 +10,4 @@ else phpPath="/usr/bin/env php" fi -nohup $phpPath $__DIR__/http2-server.php > /dev/null 2>&1 & echo $! > "$__DIR__/server.pid" +nohup $phpPath $__DIR__/http2-server.php > log.log 2>&1 & echo $! > "$__DIR__/server.pid" diff --git a/tests/server/WebSocket/start-server.sh b/tests/server/WebSocket/start-server.sh index a675a8e..b226ff3 100755 --- a/tests/server/WebSocket/start-server.sh +++ b/tests/server/WebSocket/start-server.sh @@ -10,4 +10,4 @@ else phpPath="/usr/bin/env php" fi -nohup $phpPath $__DIR__/ws-server.php > /dev/null 2>&1 & echo $! > "$__DIR__/server.pid" +nohup $phpPath $__DIR__/ws-server.php > log.log 2>&1 & echo $! > "$__DIR__/server.pid" From 7007e812f360cb952bc2462c089444bb344d3117 Mon Sep 17 00:00:00 2001 From: Yurun Date: Fri, 13 Oct 2023 16:27:23 +0800 Subject: [PATCH 04/12] test --- .github/workflows/ci.yml | 2 +- .php-cs-fixer.dist.php | 1 + src/YurunHttp/Stream/MemoryStream.php | 4 ++-- tests/server/Http/start-server.sh | 2 +- tests/server/Http2/start-server.sh | 2 +- tests/server/WebSocket/start-server.sh | 2 +- 6 files changed, 7 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c6f6284..575db1d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,7 +9,7 @@ jobs: strategy: fail-fast: false matrix: - php: [7.0, 7.1] + php: ["7.0", "7.1"] env: PHP_DOCKER_VERSION: ${{ matrix.php }} diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 19c5186..df45a53 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -105,6 +105,7 @@ ->setFinder( PhpCsFixer\Finder::create() ->exclude(__DIR__ . '/vendor') + ->in(__DIR__ . '/.github') ->in(__DIR__ . '/src') ->in(__DIR__ . '/examples') ->in(__DIR__ . '/tests') diff --git a/src/YurunHttp/Stream/MemoryStream.php b/src/YurunHttp/Stream/MemoryStream.php index 952ecdc..91c272a 100644 --- a/src/YurunHttp/Stream/MemoryStream.php +++ b/src/YurunHttp/Stream/MemoryStream.php @@ -228,7 +228,7 @@ public function isReadable(): bool * * @throws \RuntimeException if an error occurs */ - public function read(int $length): string + public function read($length): string { $position = &$this->position; $result = substr($this->content, $position, $length); @@ -274,7 +274,7 @@ public function getContents(): string * provided. Returns a specific key value if a key is provided and the * value is found, or null if the key is not found. */ - public function getMetadata(string $key = null) + public function getMetadata($key = null) { return null; } diff --git a/tests/server/Http/start-server.sh b/tests/server/Http/start-server.sh index ad8e124..188dcaa 100755 --- a/tests/server/Http/start-server.sh +++ b/tests/server/Http/start-server.sh @@ -4,4 +4,4 @@ __DIR__=$(cd `dirname $0`; pwd) ${__DIR__}/stop-server.sh -/usr/bin/env php $__DIR__/server.php start -d > log.log \ No newline at end of file +/usr/bin/env php $__DIR__/server.php start -d > ${__DIR__}/log.log \ No newline at end of file diff --git a/tests/server/Http2/start-server.sh b/tests/server/Http2/start-server.sh index 1b05c5f..1cbc227 100755 --- a/tests/server/Http2/start-server.sh +++ b/tests/server/Http2/start-server.sh @@ -10,4 +10,4 @@ else phpPath="/usr/bin/env php" fi -nohup $phpPath $__DIR__/http2-server.php > log.log 2>&1 & echo $! > "$__DIR__/server.pid" +nohup $phpPath $__DIR__/http2-server.php > ${__DIR__}/log.log 2>&1 & echo $! > "$__DIR__/server.pid" diff --git a/tests/server/WebSocket/start-server.sh b/tests/server/WebSocket/start-server.sh index b226ff3..d8404ce 100755 --- a/tests/server/WebSocket/start-server.sh +++ b/tests/server/WebSocket/start-server.sh @@ -10,4 +10,4 @@ else phpPath="/usr/bin/env php" fi -nohup $phpPath $__DIR__/ws-server.php > log.log 2>&1 & echo $! > "$__DIR__/server.pid" +nohup $phpPath $__DIR__/ws-server.php > ${__DIR__}/log.log 2>&1 & echo $! > "$__DIR__/server.pid" From 92a0163ca0a235820b1219bb64cf6fbbbfd1d7d1 Mon Sep 17 00:00:00 2001 From: Yurun Date: Fri, 13 Oct 2023 17:02:14 +0800 Subject: [PATCH 05/12] test --- .github/{php-5.dockerfile => php-low.dockerfile} | 0 .github/prepare-test.sh | 8 +++++--- .github/print-logs.php | 16 ++++++++++++++++ .github/workflows/ci.yml | 16 ++-------------- 4 files changed, 23 insertions(+), 17 deletions(-) rename .github/{php-5.dockerfile => php-low.dockerfile} (100%) create mode 100644 .github/print-logs.php diff --git a/.github/php-5.dockerfile b/.github/php-low.dockerfile similarity index 100% rename from .github/php-5.dockerfile rename to .github/php-low.dockerfile diff --git a/.github/prepare-test.sh b/.github/prepare-test.sh index 1960cf0..865098f 100755 --- a/.github/prepare-test.sh +++ b/.github/prepare-test.sh @@ -4,10 +4,10 @@ __DIR__=$(cd `dirname $0`; pwd) cd $__DIR__ -if [[ `expr $PHP_DOCKER_VERSION \< 7` -eq 0 ]]; then +if [[ `expr $PHP_DOCKER_VERSION \< 7.1` -eq 0 ]]; then export PHP_DOCKER_FILE="php.dockerfile" else - export PHP_DOCKER_FILE="php-5.dockerfile" + export PHP_DOCKER_FILE="php-low.dockerfile" fi containerName=$1 @@ -15,7 +15,9 @@ containerName=$1 docker-compose up -d $containerName \ && docker exec $containerName php -v \ && docker exec $containerName php -m \ -&& docker exec $containerName composer -V \ +&& docker exec $containerName php --ri curl +docker exec $containerName php --ri swoole +docker exec $containerName composer -V \ && docker ps -a n=0 diff --git a/.github/print-logs.php b/.github/print-logs.php new file mode 100644 index 0000000..c71e79c --- /dev/null +++ b/.github/print-logs.php @@ -0,0 +1,16 @@ + Date: Fri, 13 Oct 2023 17:15:34 +0800 Subject: [PATCH 06/12] PHP >= 7.1 --- .github/workflows/ci.yml | 2 +- composer.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b7e6e76..2f0bbbc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,7 +9,7 @@ jobs: strategy: fail-fast: false matrix: - php: ["7.0", "7.1"] + php: ["7.1"] env: PHP_DOCKER_VERSION: ${{ matrix.php }} diff --git a/composer.json b/composer.json index 4ce2fed..e9e0cbc 100644 --- a/composer.json +++ b/composer.json @@ -2,7 +2,7 @@ "name": "yurunsoft/yurun-http", "description": "YurunHttp 是开源的 PHP HTTP 类库,支持链式操作,简单易用。支持 Curl、Swoole,支持 Http、Http2、WebSocket!", "require": { - "php": ">=7.0", + "php": ">=7.1", "psr/http-message": "~1.0|~2.0", "psr/log": "~1.0|~2.0|~3.0" }, From 142e214b88f5fa06b1cbebd24b1890f1af5d74a2 Mon Sep 17 00:00:00 2001 From: Yurun Date: Fri, 13 Oct 2023 17:26:43 +0800 Subject: [PATCH 07/12] test --- composer.json | 2 +- tests/unit/HttpRequestTest/HttpRequestTest.php | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/composer.json b/composer.json index e9e0cbc..f023e07 100644 --- a/composer.json +++ b/composer.json @@ -3,7 +3,7 @@ "description": "YurunHttp 是开源的 PHP HTTP 类库,支持链式操作,简单易用。支持 Curl、Swoole,支持 Http、Http2、WebSocket!", "require": { "php": ">=7.1", - "psr/http-message": "~1.0|~2.0", + "psr/http-message": "~1.0", "psr/log": "~1.0|~2.0|~3.0" }, "require-dev": { diff --git a/tests/unit/HttpRequestTest/HttpRequestTest.php b/tests/unit/HttpRequestTest/HttpRequestTest.php index 17f9282..635f6f4 100644 --- a/tests/unit/HttpRequestTest/HttpRequestTest.php +++ b/tests/unit/HttpRequestTest/HttpRequestTest.php @@ -94,7 +94,7 @@ public function testPostParams(): void { $this->call(function () { $http = new HttpRequest(); - $time = time(); + $time = (string) time(); $response = $http->post($this->host . '?a=info', [ 'time' => $time, ]); @@ -104,7 +104,7 @@ public function testPostParams(): void $this->assertEquals($time, isset($data['post']['time']) ? $data['post']['time'] : null); $http = new HttpRequest(); - $time = time(); + $time = (string) time(); $params = new \stdClass(); $params->time = $time; $this->assertResponse($response); @@ -710,9 +710,9 @@ public function testBug19(): void { $this->call(function () { $http = new HttpRequest(); - $response = $http->head('https://www.baidu.com'); + $response = $http->head('https://www.bing.com'); $this->assertResponse($response); - $response = $http->get('https://www.baidu.com'); + $response = $http->get('https://www.bing.com'); $this->assertResponse($response); $this->assertTrue('' != $response->body()); }); From a0e24103d525f62369570fd8086083255a80bd99 Mon Sep 17 00:00:00 2001 From: Yurun Date: Fri, 13 Oct 2023 17:31:45 +0800 Subject: [PATCH 08/12] test --- composer.json | 2 +- src/YurunHttp/Http/Psr7/Uri.php | 2 +- src/YurunHttp/Stream/FileStream.php | 2 +- src/YurunHttp/Stream/MemoryStream.php | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/composer.json b/composer.json index f023e07..e9e0cbc 100644 --- a/composer.json +++ b/composer.json @@ -3,7 +3,7 @@ "description": "YurunHttp 是开源的 PHP HTTP 类库,支持链式操作,简单易用。支持 Curl、Swoole,支持 Http、Http2、WebSocket!", "require": { "php": ">=7.1", - "psr/http-message": "~1.0", + "psr/http-message": "~1.0|~2.0", "psr/log": "~1.0|~2.0|~3.0" }, "require-dev": { diff --git a/src/YurunHttp/Http/Psr7/Uri.php b/src/YurunHttp/Http/Psr7/Uri.php index 91ca35e..72a704c 100644 --- a/src/YurunHttp/Http/Psr7/Uri.php +++ b/src/YurunHttp/Http/Psr7/Uri.php @@ -583,7 +583,7 @@ public function withFragment($fragment): UriInterface * * @return string */ - public function __toString() + public function __toString() :string { return static::makeUriString($this->host, $this->path, $this->query, $this->port, $this->scheme, $this->fragment, $this->userInfo); } diff --git a/src/YurunHttp/Stream/FileStream.php b/src/YurunHttp/Stream/FileStream.php index 902b911..de4acc1 100644 --- a/src/YurunHttp/Stream/FileStream.php +++ b/src/YurunHttp/Stream/FileStream.php @@ -79,7 +79,7 @@ public function __destruct() * * @return string */ - public function __toString() + public function __toString() :string { try { diff --git a/src/YurunHttp/Stream/MemoryStream.php b/src/YurunHttp/Stream/MemoryStream.php index 91c272a..98be169 100644 --- a/src/YurunHttp/Stream/MemoryStream.php +++ b/src/YurunHttp/Stream/MemoryStream.php @@ -51,7 +51,7 @@ public function __construct($content = '') * * @return string */ - public function __toString() + public function __toString() :string { return $this->content; } From 324fc23cc7cec7ad2bdf2825c99dc9bf89b5c791 Mon Sep 17 00:00:00 2001 From: Yurun Date: Fri, 13 Oct 2023 18:56:29 +0800 Subject: [PATCH 09/12] test --- src/YurunHttp/Http/Psr7/ServerRequest.php | 2 +- src/YurunHttp/Http/Psr7/Uri.php | 2 +- src/YurunHttp/Stream/FileStream.php | 2 +- src/YurunHttp/Stream/MemoryStream.php | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/YurunHttp/Http/Psr7/ServerRequest.php b/src/YurunHttp/Http/Psr7/ServerRequest.php index c033948..65babbb 100644 --- a/src/YurunHttp/Http/Psr7/ServerRequest.php +++ b/src/YurunHttp/Http/Psr7/ServerRequest.php @@ -138,7 +138,7 @@ public function getCookieParams(): array * * @return static */ - public function withCookieParams(array $cookies): self + public function withCookieParams(array $cookies): ServerRequestInterface { $self = clone $this; $self->cookies = $cookies; diff --git a/src/YurunHttp/Http/Psr7/Uri.php b/src/YurunHttp/Http/Psr7/Uri.php index 72a704c..aeb4135 100644 --- a/src/YurunHttp/Http/Psr7/Uri.php +++ b/src/YurunHttp/Http/Psr7/Uri.php @@ -583,7 +583,7 @@ public function withFragment($fragment): UriInterface * * @return string */ - public function __toString() :string + public function __toString(): string { return static::makeUriString($this->host, $this->path, $this->query, $this->port, $this->scheme, $this->fragment, $this->userInfo); } diff --git a/src/YurunHttp/Stream/FileStream.php b/src/YurunHttp/Stream/FileStream.php index de4acc1..4fb68d4 100644 --- a/src/YurunHttp/Stream/FileStream.php +++ b/src/YurunHttp/Stream/FileStream.php @@ -79,7 +79,7 @@ public function __destruct() * * @return string */ - public function __toString() :string + public function __toString(): string { try { diff --git a/src/YurunHttp/Stream/MemoryStream.php b/src/YurunHttp/Stream/MemoryStream.php index 98be169..4f8604a 100644 --- a/src/YurunHttp/Stream/MemoryStream.php +++ b/src/YurunHttp/Stream/MemoryStream.php @@ -51,7 +51,7 @@ public function __construct($content = '') * * @return string */ - public function __toString() :string + public function __toString(): string { return $this->content; } From b8915fe231b455160d26e84d4fe9489333404d92 Mon Sep 17 00:00:00 2001 From: Yurun Date: Fri, 13 Oct 2023 19:54:27 +0800 Subject: [PATCH 10/12] =?UTF-8?q?=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/YurunHttp/Handler/Curl.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/YurunHttp/Handler/Curl.php b/src/YurunHttp/Handler/Curl.php index 2123376..d076821 100644 --- a/src/YurunHttp/Handler/Curl.php +++ b/src/YurunHttp/Handler/Curl.php @@ -678,7 +678,7 @@ private function parseNetwork(&$request, &$options) } else { - $userPwd = ''; + $userPwd = null; } // 连接超时 $options[\CURLOPT_CONNECTTIMEOUT_MS] = $request->getAttribute(Attributes::CONNECT_TIMEOUT, 30000); @@ -688,8 +688,11 @@ private function parseNetwork(&$request, &$options) $options[\CURLOPT_MAX_RECV_SPEED_LARGE] = $request->getAttribute(Attributes::DOWNLOAD_SPEED); // 上传限速 $options[\CURLOPT_MAX_SEND_SPEED_LARGE] = $request->getAttribute(Attributes::UPLOAD_SPEED); - // 连接中用到的用户名和密码 - $options[\CURLOPT_USERPWD] = $userPwd; + if (null !== $userPwd) + { + // 连接中用到的用户名和密码 + $options[\CURLOPT_USERPWD] = $userPwd; + } } /** From 327db5a4460ab5c2cf152d2bffac324ba4b1a719 Mon Sep 17 00:00:00 2001 From: Yurun Date: Mon, 16 Oct 2023 10:36:15 +0800 Subject: [PATCH 11/12] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/YurunHttp/Handler/Curl.php | 12 +++++++----- tests/unit/HttpRequestTest/HttpRequestTest.php | 4 ++-- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/YurunHttp/Handler/Curl.php b/src/YurunHttp/Handler/Curl.php index d076821..fbeb0ad 100644 --- a/src/YurunHttp/Handler/Curl.php +++ b/src/YurunHttp/Handler/Curl.php @@ -295,10 +295,10 @@ private function buildCurlHandlerBase(&$request, $handler, &$headers = null, &$s $options[\CURLOPT_RETURNTRANSFER] = true; } // 保存cookie - if (!isset($options[\CURLOPT_COOKIEJAR])) - { - $options[\CURLOPT_COOKIEJAR] = 'php://memory'; - } + // if (!isset($options[\CURLOPT_COOKIEJAR])) + // { + // $options[\CURLOPT_COOKIEJAR] = 'php://memory'; + // } // 允许复用连接 if (!isset($options[\CURLOPT_FORBID_REUSE])) { @@ -324,7 +324,6 @@ private function buildCurlHandlerBase(&$request, $handler, &$headers = null, &$s $this->parseSSL($request, $options); $this->parseProxy($request, $options); $this->parseHeaders($request, $options); - $this->parseCookies($request, $options); $this->parseNetwork($request, $options); curl_setopt_array($handler, $options); } @@ -387,6 +386,7 @@ private function buildCurlHandlerEx(&$request, $handler, $uri = null, $method = { $requestOptions[\CURLOPT_NOBODY] = true; } + $this->parseCookies($request, $requestOptions); curl_setopt_array($handler, $requestOptions); } @@ -649,9 +649,11 @@ private function parseHeadersFormat($request) private function parseCookies(&$request, &$options) { $cookieManager = $this->cookieManager; + $cookie = []; foreach ($request->getCookieParams() as $name => $value) { $cookieManager->setCookie($name, $value); + $cookie[] = $name . '=' . $value; } $cookie = $cookieManager->getRequestCookieString($request->getUri()); if ('' !== $cookie) diff --git a/tests/unit/HttpRequestTest/HttpRequestTest.php b/tests/unit/HttpRequestTest/HttpRequestTest.php index 635f6f4..e78a14a 100644 --- a/tests/unit/HttpRequestTest/HttpRequestTest.php +++ b/tests/unit/HttpRequestTest/HttpRequestTest.php @@ -710,9 +710,9 @@ public function testBug19(): void { $this->call(function () { $http = new HttpRequest(); - $response = $http->head('https://www.bing.com'); + $response = $http->head('https://www.baidu.com'); $this->assertResponse($response); - $response = $http->get('https://www.bing.com'); + $response = $http->get('https://www.baidu.com'); $this->assertResponse($response); $this->assertTrue('' != $response->body()); }); From 47adc92de1cefbf48fd20d27d8353ec3dabf72f6 Mon Sep 17 00:00:00 2001 From: Yurun Date: Mon, 16 Oct 2023 10:44:37 +0800 Subject: [PATCH 12/12] =?UTF-8?q?=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/YurunHttp/Handler/Curl.php | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/YurunHttp/Handler/Curl.php b/src/YurunHttp/Handler/Curl.php index fbeb0ad..e8911fa 100644 --- a/src/YurunHttp/Handler/Curl.php +++ b/src/YurunHttp/Handler/Curl.php @@ -294,11 +294,6 @@ private function buildCurlHandlerBase(&$request, $handler, &$headers = null, &$s { $options[\CURLOPT_RETURNTRANSFER] = true; } - // 保存cookie - // if (!isset($options[\CURLOPT_COOKIEJAR])) - // { - // $options[\CURLOPT_COOKIEJAR] = 'php://memory'; - // } // 允许复用连接 if (!isset($options[\CURLOPT_FORBID_REUSE])) { @@ -649,11 +644,9 @@ private function parseHeadersFormat($request) private function parseCookies(&$request, &$options) { $cookieManager = $this->cookieManager; - $cookie = []; foreach ($request->getCookieParams() as $name => $value) { $cookieManager->setCookie($name, $value); - $cookie[] = $name . '=' . $value; } $cookie = $cookieManager->getRequestCookieString($request->getUri()); if ('' !== $cookie)