Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code optimization #114

Merged
merged 4 commits into from
Dec 10, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"php" : ">=7.0",
"ext-mbstring" : "*",
"ext-ctype" : "*",
"ext-curl" : "*",
"sabre/event" : ">=4.0 <6.0",
"sabre/uri" : "^2.0"
},
Expand Down
8 changes: 4 additions & 4 deletions lib/Auth/AWS.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,14 @@ public function init(): bool
{
$authHeader = $this->request->getHeader('Authorization');

if (is_null($authHeader)) {
if (null === $authHeader) {
$this->errorCode = self::ERR_NOAWSHEADER;

return false;
}
$authHeader = explode(' ', $authHeader);

if ('AWS' != $authHeader[0] || !isset($authHeader[1])) {
if ('AWS' !== $authHeader[0] || !isset($authHeader[1])) {
$this->errorCode = self::ERR_NOAWSHEADER;

return false;
Expand Down Expand Up @@ -93,7 +93,7 @@ public function validate(string $secretKey): bool
$body = $this->request->getBody();
$this->request->setBody($body);

if ($contentMD5 != base64_encode(md5((string) $body, true))) {
if ($contentMD5 !== base64_encode(md5((string) $body, true))) {
// content-md5 header did not match md5 signature of body
$this->errorCode = self::ERR_MD5CHECKSUMWRONG;

Expand Down Expand Up @@ -122,7 +122,7 @@ public function validate(string $secretKey): bool
)
);

if ($this->signature != $signature) {
if ($this->signature !== $signature) {
$this->errorCode = self::ERR_INVALIDSIGNATURE;

return false;
Expand Down
13 changes: 5 additions & 8 deletions lib/Auth/Digest.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ protected function validate(): bool
{
$A2 = $this->request->getMethod().':'.$this->digestParts['uri'];

if ('auth-int' == $this->digestParts['qop']) {
if ('auth-int' === $this->digestParts['qop']) {
// Making sure we support this qop value
if (!($this->qop & self::QOP_AUTHINT)) {
return false;
Expand All @@ -132,18 +132,15 @@ protected function validate(): bool
$body = $this->request->getBody($asString = true);
$this->request->setBody($body);
$A2 .= ':'.md5($body);
} else {
// We need to make sure we support this qop value
if (!($this->qop & self::QOP_AUTH)) {
return false;
}
} elseif (!($this->qop & self::QOP_AUTH)) {
return false;
}

$A2 = md5($A2);

$validResponse = md5("{$this->A1}:{$this->digestParts['nonce']}:{$this->digestParts['nc']}:{$this->digestParts['cnonce']}:{$this->digestParts['qop']}:{$A2}");

return $this->digestParts['response'] == $validResponse;
return $this->digestParts['response'] === $validResponse;
}

/**
Expand Down Expand Up @@ -200,7 +197,7 @@ protected function parseDigest(string $digest)
preg_match_all('@(\w+)=(?:(?:")([^"]+)"|([^\s,$]+))@', $digest, $matches, PREG_SET_ORDER);

foreach ($matches as $m) {
$data[$m[1]] = $m[2] ? $m[2] : $m[3];
$data[$m[1]] = $m[2] ?: $m[3];
unset($needed_parts[$m[1]]);
}

Expand Down
12 changes: 6 additions & 6 deletions lib/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,14 +96,14 @@ public function send(RequestInterface $request): ResponseInterface
try {
$response = $this->doRequest($request);

$code = (int) $response->getStatus();
$code = $response->getStatus();

// We are doing in-PHP redirects, because curl's
// FOLLOW_LOCATION throws errors when PHP is configured with
// open_basedir.
//
// https://github.com/fruux/sabre-http/issues/12
if (in_array($code, [301, 302, 307, 308]) && $redirects < $this->maxRedirects) {
if ($redirects < $this->maxRedirects && in_array($code, [301, 302, 307, 308])) {
$oldLocation = $request->getUrl();

// Creating a new instance of the request object.
Expand Down Expand Up @@ -196,7 +196,7 @@ public function poll(): bool
);

if ($status && CURLMSG_DONE === $status['msg']) {
$resourceId = intval($status['handle']);
$resourceId = (int) $status['handle'];
list(
$request,
$successCallback,
Expand Down Expand Up @@ -454,14 +454,14 @@ protected function parseCurlResult(string $response, $curlHandle): array

foreach ($headerBlob as $header) {
$parts = explode(':', $header, 2);
if (2 == count($parts)) {
if (2 === count($parts)) {
$response->addHeader(trim($parts[0]), trim($parts[1]));
}
}

$response->setBody($responseBody);

$httpCode = intval($response->getStatus());
$httpCode = $response->getStatus();

return [
'status' => $httpCode >= 400 ? self::STATUS_HTTPERROR : self::STATUS_SUCCESS,
Expand All @@ -487,7 +487,7 @@ protected function sendAsyncInternal(RequestInterface $request, callable $succes
$this->createCurlSettingsArray($request)
);
curl_multi_add_handle($this->curlMultiHandle, $curl);
$this->curlMultiMap[intval($curl)] = [
$this->curlMultiMap[(int) $curl] = [
$request,
$success,
$error,
Expand Down
13 changes: 8 additions & 5 deletions lib/Message.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public function getBodyAsStream()
if (is_callable($this->body)) {
$body = $this->getBodyAsString();
}
if (is_string($body) || is_null($body)) {
if (is_string($body) || null === $body) {
$stream = fopen('php://temp', 'r+');
fwrite($stream, (string) $body);
rewind($stream);
Expand All @@ -75,7 +75,7 @@ public function getBodyAsString(): string
if (is_string($body)) {
return $body;
}
if (is_null($body)) {
if (null === $body) {
return '';
}
if (is_callable($body)) {
Expand All @@ -84,12 +84,15 @@ public function getBodyAsString(): string

return ob_get_clean();
}
/**
* @var string|int|null
*/
$contentLength = $this->getHeader('Content-Length');
if (is_int($contentLength) || ctype_digit($contentLength)) {
return stream_get_contents($body, (int) $contentLength);
} else {
return stream_get_contents($body);
}

return stream_get_contents($body);
}

/**
Expand Down Expand Up @@ -220,7 +223,7 @@ public function setHeaders(array $headers)
* another value. Individual values can be retrieved with
* getHeadersAsArray.
*
* @param scalar $value
* @param string|string[] $value
*/
public function addHeader(string $name, $value)
{
Expand Down
2 changes: 1 addition & 1 deletion lib/MessageDecoratorTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ public function setHeaders(array $headers)
* another value. Individual values can be retrieved with
* getHeadersAsArray.
*
* @param scalar $value
* @param string|string[] $value
*/
public function addHeader(string $name, $value)
{
Expand Down
2 changes: 1 addition & 1 deletion lib/MessageInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ public function setHeaders(array $headers);
* another value. Individual values can be retrieved with
* getHeadersAsArray.
*
* @param scalar $value
* @param string|string[] $value
*/
public function addHeader(string $name, $value);

Expand Down
21 changes: 10 additions & 11 deletions lib/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,11 @@ public function getQueryParameters(): array
$url = $this->getUrl();
if (false === ($index = strpos($url, '?'))) {
return [];
} else {
parse_str(substr($url, $index + 1), $queryParams);

return $queryParams;
}

parse_str(substr($url, $index + 1), $queryParams);

return $queryParams;
}

protected $absoluteUrl;
Expand Down Expand Up @@ -174,11 +174,12 @@ public function getPath(): string

return trim(decodePath(substr($uri, strlen($baseUri))), '/');
}
// A special case, if the baseUri was accessed without a trailing
// slash, we'll accept it as well.
elseif ($uri.'/' === $baseUri) {

if ($uri.'/' === $baseUri) {
return '';
}
// A special case, if the baseUri was accessed without a trailing
// slash, we'll accept it as well.

throw new \LogicException('Requested uri ('.$this->getUrl().') is out of base uri ('.$this->getBaseUrl().')');
}
Expand Down Expand Up @@ -229,9 +230,7 @@ public function getPostData(): array
*/
public function getRawServerValue(string $valueName)
{
if (isset($this->rawServerData[$valueName])) {
return $this->rawServerData[$valueName];
}
return $this->rawServerData[$valueName] ?? null;
}

/**
Expand All @@ -249,7 +248,7 @@ public function setRawServerData(array $data)
*/
public function __toString(): string
{
$out = $this->getMethod().' '.$this->getUrl().' HTTP/'.$this->getHTTPVersion()."\r\n";
$out = $this->getMethod().' '.$this->getUrl().' HTTP/'.$this->getHttpVersion()."\r\n";

foreach ($this->getHeaders() as $key => $value) {
foreach ($value as $v) {
Expand Down
11 changes: 6 additions & 5 deletions lib/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,13 +105,13 @@ class Response extends Message implements ResponseInterface
*/
public function __construct($status = 500, array $headers = null, $body = null)
{
if (!is_null($status)) {
if (null !== $status) {
$this->setStatus($status);
}
if (!is_null($headers)) {
if (null !== $headers) {
$this->setHeaders($headers);
}
if (!is_null($body)) {
if (null !== $body) {
$this->setBody($body);
}
}
Expand Down Expand Up @@ -151,18 +151,19 @@ public function setStatus($status)
{
if (ctype_digit($status) || is_int($status)) {
$statusCode = $status;
$statusText = isset(self::$statusCodes[$status]) ? self::$statusCodes[$status] : 'Unknown';
$statusText = self::$statusCodes[$status] ?? 'Unknown';
} else {
list(
$statusCode,
$statusText
) = explode(' ', $status, 2);
$statusCode = (int) $statusCode;
}
if ($statusCode < 100 || $statusCode > 999) {
throw new \InvalidArgumentException('The HTTP status code must be exactly 3 digits');
}

$this->status = (int) $statusCode;
$this->status = $statusCode;
$this->statusText = $statusText;
}

Expand Down
8 changes: 4 additions & 4 deletions lib/Sapi.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public static function getRequest(): Request
{
$serverArr = $_SERVER;

if ('cli' === php_sapi_name()) {
if ('cli' === PHP_SAPI) {
// If we're running off the CLI, we're going to set some default
// settings.
$serverArr['REQUEST_URI'] = $_SERVER['REQUEST_URI'] ?? '/';
Expand Down Expand Up @@ -75,7 +75,7 @@ public static function sendResponse(ResponseInterface $response)
}

$body = $response->getBody();
if (is_null($body)) {
if (null === $body) {
return;
}

Expand Down Expand Up @@ -199,11 +199,11 @@ public static function createFromServerArray(array $serverArray): Request
}
}

if (is_null($url)) {
if (null === $url) {
throw new InvalidArgumentException('The _SERVER array must have a REQUEST_URI key');
}

if (is_null($method)) {
if (null === $method) {
throw new InvalidArgumentException('The _SERVER array must have a REQUEST_METHOD key');
}
$r = new Request($method, $url, $headers);
Expand Down
2 changes: 1 addition & 1 deletion lib/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ function negotiateContentType($acceptHeaderValue, array $availableOptions)

foreach ($proposals as $proposal) {
// Ignoring broken values.
if (is_null($proposal)) {
if (null === $proposal) {
continue;
}

Expand Down