From e97d9d05b741d4ee7ef58824a280acf983354d5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B2=88=E5=94=81?= <52o@qq52o.cn> Date: Sat, 15 Aug 2020 18:36:45 +0800 Subject: [PATCH] fix: undefined offset (#4) * fix: undefined offset close https://github.com/swlib/saber/issues/100 * add getLastKey * refactor: getRedirectsTrace * fix typo * fix typo * fix typo --- src/Exception/TooManyRedirectsException.php | 10 +++++++--- src/Util.php | 12 ++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/Exception/TooManyRedirectsException.php b/src/Exception/TooManyRedirectsException.php index 557a28c..d5491a2 100644 --- a/src/Exception/TooManyRedirectsException.php +++ b/src/Exception/TooManyRedirectsException.php @@ -10,6 +10,7 @@ use Exception; use Swlib\Http\Request; use Swlib\Http\Response; +use Swlib\Http\Util; class TooManyRedirectsException extends RequestException { @@ -24,7 +25,7 @@ public function __construct( ) { $this->redirect_headers = $redirects; $times = count($redirects); - $location = $this->redirect_headers[$times - 1]; + $location = Util::getLastKey($this->redirect_headers); $message = "Too many redirects! more than {$times} times to {$location} !"; parent::__construct($request, $response, $code, $message, $previous); } @@ -37,8 +38,11 @@ public function getRedirectHeaders(): array public function getRedirectsTrace(): string { $trace = ''; - foreach (array_keys($this->redirect_headers) as $index => $location) { - $trace .= "#$index $location\n"; + $index = 0; + + foreach ($this->redirect_headers as $location => $redirect_headers) { + $trace .= "#{$index} {$location}\n"; + $index++; } return $trace; diff --git a/src/Util.php b/src/Util.php index 1ac6b4e..fba383e 100755 --- a/src/Util.php +++ b/src/Util.php @@ -101,4 +101,16 @@ public static function parseHeaders(string $raw_header): array return self::parseHeader($raw_header[0]); } } + + /** + * 获取数组最后一个键名 + * + * @param array $array + * @return int|string|null + */ + public static function getLastKey(array $array) + { + end($array); + return key($array); + } }