From b845addb719d561c2d80c565241dfcf70e46052c Mon Sep 17 00:00:00 2001 From: twosee Date: Thu, 18 Apr 2019 12:09:33 +0800 Subject: [PATCH] Code optimization (step 1). --- examples/download.php | 2 +- examples/interceptor.php | 4 +-- examples/multi-vs-single.php | 2 +- examples/pool.php | 12 +++---- examples/redirect.php | 2 +- src/Request.php | 4 +-- src/Response.php | 64 ++++++++++++++++++------------------ src/ResponseMap.php | 7 ++-- tests/SaberTest.php | 18 +++++----- 9 files changed, 58 insertions(+), 57 deletions(-) diff --git a/examples/download.php b/examples/download.php index 89fe68f..7a6f820 100644 --- a/examples/download.php +++ b/examples/download.php @@ -14,7 +14,7 @@ 'https://ws1.sinaimg.cn/large/006DQdzWly1fsr8jt2botj31hc0wxqfs.jpg', $download_dir ); - if ($response->success) { + if ($response->getSuccess()) { exec('open ' . $download_dir); } }); diff --git a/examples/interceptor.php b/examples/interceptor.php index 67f64c8..c4660ce 100644 --- a/examples/interceptor.php +++ b/examples/interceptor.php @@ -17,12 +17,12 @@ echo "log: request $uri now...\n"; }, 'after' => function (Saber\Response $response) { - if ($response->success) { + if ($response->getSuccess()) { echo "log: success!\n"; } else { echo "log: failed\n"; } - echo "use {$response->time}s"; + echo "use {$response->getTime()}s"; } ]); }); diff --git a/examples/multi-vs-single.php b/examples/multi-vs-single.php index 5afa000..53faab8 100644 --- a/examples/multi-vs-single.php +++ b/examples/multi-vs-single.php @@ -14,7 +14,7 @@ $response = SaberGM::request(['uri' => 'https://github.com/']); echo "single-request [ status: {$response->statusCode} ]: \n" . - "consuming-time: {$response->time}s\n"; + "consuming-time: {$response->getTime()}s\n"; echo str_repeat("=", 20) . "\n"; diff --git a/examples/pool.php b/examples/pool.php index a362652..c51f058 100644 --- a/examples/pool.php +++ b/examples/pool.php @@ -15,9 +15,9 @@ 'use_pool' => true ]); $start = microtime(true); - assert($pool->get('/')->success, true); - assert($pool->get('/contract.shtml')->success, true); - assert($pool->get('/dzwfggcns.htm')->success, true); + assert($pool->get('/')->getSuccess(), true); + assert($pool->get('/contract.shtml')->getSuccess(), true); + assert($pool->get('/dzwfggcns.htm')->getSuccess(), true); $pool_time = microtime(true) - $start; var_dump($pool_time); @@ -26,9 +26,9 @@ 'use_pool' => false ]); $start = microtime(true); - assert($not_pool->get('/')->success, true); - assert($not_pool->get('/contract.shtml')->success, true); - assert($not_pool->get('/dzwfggcns.htm')->success, true); + assert($not_pool->get('/')->getSuccess(), true); + assert($not_pool->get('/contract.shtml')->getSuccess(), true); + assert($not_pool->get('/dzwfggcns.htm')->getSuccess(), true); $not_pool_time = microtime(true) - $start; var_dump($not_pool_time); diff --git a/examples/redirect.php b/examples/redirect.php index 86aedf1..1f97e9f 100644 --- a/examples/redirect.php +++ b/examples/redirect.php @@ -12,5 +12,5 @@ go(function () { $uri = 'http://t.cn/Rn3tRyK'; $res = SaberGM::get($uri); - var_dump($res->redirect_headers); + var_dump($res->getRedirectHeaders()); }); diff --git a/src/Request.php b/src/Request.php index 77fa8f1..20ab317 100755 --- a/src/Request.php +++ b/src/Request.php @@ -690,7 +690,7 @@ public function recv() * just return a bool type value */ $allow_redirect = true; - $ret = $this->callInterceptor('before_redirect', $this, $response); + $ret = $this->callInterceptor('before_redirect', $this); if ($ret !== null) { if (is_bool($ret)) { $allow_redirect = $ret; @@ -726,7 +726,7 @@ public function recv() } /** auto retry */ - while (!$response->success && $this->_retried_time++ < $this->retry_time) { + while (!$response->getSuccess() && $this->_retried_time++ < $this->retry_time) { $ret = $this->callInterceptor('before_retry', $this, $response); if ($ret === false) { break; diff --git a/src/Response.php b/src/Response.php index c7c1a6f..a314bd5 100755 --- a/src/Response.php +++ b/src/Response.php @@ -7,7 +7,6 @@ namespace Swlib\Saber; -use Psr\Http\Message\UriInterface; use Swlib\Http\BufferStream; use Swlib\Http\CookiesManagerTrait; use Swlib\Http\Exception\BadResponseException; @@ -15,15 +14,21 @@ use Swlib\Http\Exception\HttpExceptionMask; use Swlib\Http\Exception\ServerException; use Swlib\Http\Exception\TooManyRedirectsException; +use Swlib\Http\Exception\TransferException; use Swlib\Http\StreamInterface; use Swlib\Util\StringDataParserTrait; use Swlib\Util\SpecialMarkTrait; class Response extends \Swlib\Http\Response { - - public $redirect_headers = []; - public $success = false; + /** @var array */ + protected $redirect_headers = []; + /** @var TransferException */ + protected $exception = null; + /** @var bool */ + protected $success = false; + /** @var float */ + protected $time; /** * @var int $statusCode * Http status code, such as 200, 404 and so on. If the status code is negative, there is a problem with the connection. @@ -32,10 +37,10 @@ class Response extends \Swlib\Http\Response * -3: After the client sends a request, the server forcibly cuts off the connection */ public $statusCode = 0; + /** @var string */ public $reasonPhrase = 'Failed'; - public $time; /** @var StreamInterface */ - public $body; + public $body = null; use CookiesManagerTrait; @@ -48,18 +53,10 @@ function __construct(Request $request) { /** consuming time */ $this->time = $request->_time; - /** status code */ - $this->withStatus($request->client->statusCode ?: 0); - /** 设定uri */ - $this->uri = $request->getUri(); - - /** 初始化 */ + $this->withStatus($request->client->statusCode); + $this->withUri($request->getUri()); $this->withHeaders($request->client->headers ?: []); - - /** 记录重定向头 */ - $this->redirect_headers = $request->_redirect_headers; //记录重定向前的headers - - /** 置Cookie对象 */ + $this->redirect_headers = $request->_redirect_headers; // record headers before redirect $this->cookies = $request->incremental_cookies; if (!empty($body = $request->client->body)) { @@ -105,42 +102,40 @@ function __construct(Request $request) $e_level = $request->getExceptionReport(); $exception = null; + $should_be_thrown = false; $status = ($this->statusCode / 100) % 10; switch ($status) { case 2: $this->success = true; break; case 3: - if ($e_level & HttpExceptionMask::E_REDIRECT) { - $exception = - new TooManyRedirectsException($request, $this, $this->statusCode, $this->redirect_headers); - } + $should_be_thrown = !!($e_level & HttpExceptionMask::E_REDIRECT); + $exception = new TooManyRedirectsException($request, $this, $this->statusCode, $this->redirect_headers); break; case 4: - if ($e_level & HttpExceptionMask::E_CLIENT) { - $exception = new ClientException($request, $this, $this->statusCode); - } + $should_be_thrown = !!($e_level & HttpExceptionMask::E_CLIENT); + $exception = new ClientException($request, $this, $this->statusCode); break; case 5: - if ($e_level & HttpExceptionMask::E_SERVER) { - $exception = new ServerException($request, $this, $this->statusCode); - } + $should_be_thrown = !!($e_level & HttpExceptionMask::E_SERVER); + $exception = new ServerException($request, $this, $this->statusCode); break; default: - if ($e_level & HttpExceptionMask::E_BAD_RESPONSE) { - $exception = new BadResponseException($request, $this, $this->statusCode); - } + $should_be_thrown = !!($e_level & HttpExceptionMask::E_BAD_RESPONSE); + $exception = new BadResponseException($request, $this, $this->statusCode); } if ($exception) { $ret = $request->callInterceptor('exception', $exception); - if (!$ret) { + if ($should_be_thrown && !$ret) { $request->tryToRevertClientToPool(); throw $exception; + } else { + $this->exception = $exception; } } } - public function isSuccess(): bool + public function getSuccess(): bool { return $this->success; } @@ -155,4 +150,9 @@ public function getRedirectHeaders(): array return $this->redirect_headers; } + public function getException(): TransferException + { + return $this->exception; + } + } diff --git a/src/ResponseMap.php b/src/ResponseMap.php index 3a293b7..d969ee2 100644 --- a/src/ResponseMap.php +++ b/src/ResponseMap.php @@ -30,10 +30,11 @@ public function offsetSet($index, $response) throw new InvalidArgumentException("Value must be instance of " . Response::class); } parent::offsetSet($index, $response); - $this->time = $this->time ?: max($this->time, $response->time); + $this->time = $this->time ?: max($this->time, $response->getTime()); $this->status_map[$index] = $response->getStatusCode(); - $this->success_map[$index] = $response->success; - $response->success ? $this->success_num++ : $this->error_num++; + $success = $response->getSuccess(); + $this->success_map[$index] = $success; + $success ? $this->success_num++ : $this->error_num++; } public function __toString() diff --git a/tests/SaberTest.php b/tests/SaberTest.php index 36404ec..fb0b6c0 100644 --- a/tests/SaberTest.php +++ b/tests/SaberTest.php @@ -79,8 +79,8 @@ public function testDataParser() 'http://www.httpbin.org/html' ] ]); - $this->assertEquals((string)$json->uri, $json->getParsedJsonArray()['url']); - $this->assertEquals((string)$json->uri, $json->getParsedJsonObject()->url); + $this->assertEquals((string)$json->getUri(), $json->getParsedJsonArray()['url']); + $this->assertEquals((string)$json->getUri(), $json->getParsedJsonObject()->url); $this->assertEquals('Everyday Italian', $xml->getParsedXmlObject()->book[0]->title); $this->assertStringStartsWith( 'Herman', @@ -180,7 +180,7 @@ public function testInterceptor() $uri = $request->getUri(); }, 'after' => function (Saber\Response $response) use (&$success) { - $success = $response->success; + $success = $response->getSuccess(); } ]); $this->assertEquals($target, $uri ?? ''); @@ -212,7 +212,7 @@ public function testRetryInterceptor() } ] ); - $this->assertEquals(false, $res->success); + $this->assertEquals(false, $res->getSuccess()); $this->assertEquals(1, $count); } @@ -229,7 +229,7 @@ public function testRetryTime() } ] ); - $this->assertEquals(false, $res->success); + $this->assertEquals(false, $res->getSuccess()); $this->assertEquals(['retry 1', 'retry 2', 'retry 3'], $log); } @@ -244,7 +244,7 @@ public function testRetryAndAuth() } ] ); - $this->assertEquals(true, $res->success, (string)$res); + $this->assertEquals(true, $res->getSuccess(), (string)$res); } public function testIconv() @@ -262,8 +262,8 @@ public function testDownload() 'https://ws1.sinaimg.cn/large/006DQdzWly1fsr8jt2botj31hc0wxqfs.jpg', $download_dir ); - $this->assertTrue($response->success); - if ($response->success) { + $this->assertTrue($response->getSuccess()); + if ($response->getSuccess()) { unlink($download_dir); } } @@ -277,7 +277,7 @@ public function testBeforeRedirect() } ] ); - $this->assertTrue($response->success); + $this->assertTrue($response->getSuccess()); $this->assertContains('www.qq.com', (string)$response->body); }