Skip to content

Commit

Permalink
Code optimization (step 1).
Browse files Browse the repository at this point in the history
  • Loading branch information
twose committed Apr 18, 2019
1 parent b4d4eca commit b845add
Show file tree
Hide file tree
Showing 9 changed files with 58 additions and 57 deletions.
2 changes: 1 addition & 1 deletion examples/download.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
'https://ws1.sinaimg.cn/large/006DQdzWly1fsr8jt2botj31hc0wxqfs.jpg',
$download_dir
);
if ($response->success) {
if ($response->getSuccess()) {
exec('open ' . $download_dir);
}
});
4 changes: 2 additions & 2 deletions examples/interceptor.php
Original file line number Diff line number Diff line change
Expand Up @@ -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";
}
]);
});
2 changes: 1 addition & 1 deletion examples/multi-vs-single.php
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down
12 changes: 6 additions & 6 deletions examples/pool.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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);

Expand Down
2 changes: 1 addition & 1 deletion examples/redirect.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@
go(function () {
$uri = 'http://t.cn/Rn3tRyK';
$res = SaberGM::get($uri);
var_dump($res->redirect_headers);
var_dump($res->getRedirectHeaders());
});
4 changes: 2 additions & 2 deletions src/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
64 changes: 32 additions & 32 deletions src/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,28 @@

namespace Swlib\Saber;

use Psr\Http\Message\UriInterface;
use Swlib\Http\BufferStream;
use Swlib\Http\CookiesManagerTrait;
use Swlib\Http\Exception\BadResponseException;
use Swlib\Http\Exception\ClientException;
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.
Expand All @@ -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;

Expand All @@ -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)) {
Expand Down Expand Up @@ -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;
}
Expand All @@ -155,4 +150,9 @@ public function getRedirectHeaders(): array
return $this->redirect_headers;
}

public function getException(): TransferException
{
return $this->exception;
}

}
7 changes: 4 additions & 3 deletions src/ResponseMap.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
18 changes: 9 additions & 9 deletions tests/SaberTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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 ?? '');
Expand Down Expand Up @@ -212,7 +212,7 @@ public function testRetryInterceptor()
}
]
);
$this->assertEquals(false, $res->success);
$this->assertEquals(false, $res->getSuccess());
$this->assertEquals(1, $count);
}

Expand All @@ -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);
}

Expand All @@ -244,7 +244,7 @@ public function testRetryAndAuth()
}
]
);
$this->assertEquals(true, $res->success, (string)$res);
$this->assertEquals(true, $res->getSuccess(), (string)$res);
}

public function testIconv()
Expand All @@ -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);
}
}
Expand All @@ -277,7 +277,7 @@ public function testBeforeRedirect()
}
]
);
$this->assertTrue($response->success);
$this->assertTrue($response->getSuccess());
$this->assertContains('www.qq.com', (string)$response->body);
}

Expand Down

0 comments on commit b845add

Please sign in to comment.