Skip to content

Commit

Permalink
Merge pull request #14 from kodedphp/http-status
Browse files Browse the repository at this point in the history
HTTP status codes refactor
  • Loading branch information
kodeart authored Apr 14, 2020
2 parents 4377fd4 + 5404830 commit 0fc6f6f
Show file tree
Hide file tree
Showing 16 changed files with 269 additions and 256 deletions.
5 changes: 3 additions & 2 deletions AcceptHeaderNegotiator.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@

use Generator;
use InvalidArgumentException;
use Koded\Http\Interfaces\HttpStatus;

class AcceptHeaderNegotiator
{
Expand Down Expand Up @@ -101,7 +102,7 @@ public function __construct(string $header)

if (!empty($type) && !preg_match('~^(\*|[a-z0-9._]+)([/|_-])?(\*|[a-z0-9.\-_+]+)?$~i', $type, $matches)) {
throw new InvalidArgumentException(sprintf('"%s" is not a valid Access header', $header),
StatusCode::NOT_ACCEPTABLE);
HttpStatus::NOT_ACCEPTABLE);
}

$this->separator = $matches[2] ?? '/';
Expand All @@ -110,7 +111,7 @@ public function __construct(string $header)
if ('*' === $type && '*' !== $subtype) {
// @see https://tools.ietf.org/html/rfc7231#section-5.3.2
throw new InvalidArgumentException(sprintf('"%s" is not a valid Access header', $header),
StatusCode::NOT_ACCEPTABLE);
HttpStatus::NOT_ACCEPTABLE);
}

// @see https://tools.ietf.org/html/rfc7540#section-8.1.2
Expand Down
12 changes: 6 additions & 6 deletions Client/CurlClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@

namespace Koded\Http\Client;

use Koded\Http\{ClientRequest, ServerResponse, StatusCode};
use Koded\Http\Interfaces\{HttpRequestClient, Response};
use Koded\Http\{ClientRequest, ServerResponse};
use Koded\Http\Interfaces\{HttpRequestClient, HttpStatus, Response};
use Throwable;
use function Koded\Http\create_stream;
use function Koded\Stdlib\json_serialize;
Expand Down Expand Up @@ -59,14 +59,14 @@ public function read(): Response
if (false === $resource = $this->createResource()) {
return new ServerResponse(
'The HTTP client is not created therefore cannot read anything',
StatusCode::PRECONDITION_FAILED);
HttpStatus::PRECONDITION_FAILED);
}

curl_setopt_array($resource, $this->options);
$response = curl_exec($resource);

if (true === $this->hasError($resource)) {
return (new ServerResponse($this->getCurlError($resource), StatusCode::FAILED_DEPENDENCY))
return (new ServerResponse($this->getCurlError($resource), HttpStatus::FAILED_DEPENDENCY))
->withHeader('Content-Type', 'application/json');
}

Expand All @@ -76,7 +76,7 @@ public function read(): Response
$this->responseHeaders
);
} catch (Throwable $e) {
return new ServerResponse($e->getMessage(), StatusCode::INTERNAL_SERVER_ERROR);
return new ServerResponse($e->getMessage(), HttpStatus::INTERNAL_SERVER_ERROR);
} finally {
unset($response);

Expand Down Expand Up @@ -193,7 +193,7 @@ protected function getCurlError($resource): string
'uri' => curl_getinfo($resource, CURLINFO_EFFECTIVE_URL),
'message' => curl_strerror(curl_errno($resource)),
'explain' => curl_error($resource),
'code' => StatusCode::FAILED_DEPENDENCY,
'code' => HttpStatus::FAILED_DEPENDENCY,
]);
}

Expand Down
5 changes: 2 additions & 3 deletions Client/EncodingTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@
namespace Koded\Http\Client;

use Exception;
use Koded\Http\Interfaces\HttpRequestClient;
use Koded\Http\StatusCode;
use Koded\Http\Interfaces\{HttpRequestClient, HttpStatus};
use Psr\Http\Client\ClientExceptionInterface;


Expand All @@ -32,7 +31,7 @@ public function withEncoding(int $type): HttpRequestClient

throw new class(
'Invalid encoding type. Expects 0, PHP_QUERY_RFC1738 or PHP_QUERY_RFC3986',
StatusCode::BAD_REQUEST
HttpStatus::BAD_REQUEST
) extends Exception implements ClientExceptionInterface {};
}
}
10 changes: 5 additions & 5 deletions Client/PhpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@

namespace Koded\Http\Client;

use Koded\Http\{ClientRequest, ServerResponse, StatusCode};
use Koded\Http\Interfaces\{HttpRequestClient, Response};
use Koded\Http\{ClientRequest, ServerResponse};
use Koded\Http\Interfaces\{HttpRequestClient, HttpStatus, Response};
use Throwable;
use function Koded\Http\create_stream;

Expand Down Expand Up @@ -56,7 +56,7 @@ public function read(): Response

try {
if (false === $resource = $this->createResource(stream_context_create(['http' => $this->options]))) {
return new ServerResponse(error_get_last()['message'], StatusCode::FAILED_DEPENDENCY);
return new ServerResponse(error_get_last()['message'], HttpStatus::FAILED_DEPENDENCY);
}

$this->extractFromResponseHeaders($resource, $headers, $statusCode);
Expand All @@ -67,7 +67,7 @@ public function read(): Response
$headers
);
} catch (Throwable $e) {
return new ServerResponse($e->getMessage(), StatusCode::INTERNAL_SERVER_ERROR);
return new ServerResponse($e->getMessage(), HttpStatus::INTERNAL_SERVER_ERROR);
} finally {
if (is_resource($resource)) {
fclose($resource);
Expand Down Expand Up @@ -174,7 +174,7 @@ protected function extractFromResponseHeaders($response, &$headers, &$statusCode
return false !== stripos($header, 'HTTP/', 0);
});
$statusCode = array_pop($statusCode) ?: 'HTTP/1.1 200 OK';
$statusCode = (int)(explode(' ', $statusCode)[1] ?? StatusCode::OK);
$statusCode = (int)(explode(' ', $statusCode)[1] ?? HttpStatus::OK);

foreach ($_headers as $header) {
[$k, $v] = explode(':', $header, 2) + [1 => null];
Expand Down
5 changes: 2 additions & 3 deletions Client/Psr18ClientTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@
namespace Koded\Http\Client;

use Exception;
use Koded\Http\Interfaces\Response;
use Koded\Http\StatusCode;
use Koded\Http\Interfaces\{HttpStatus, Response};
use Psr\Http\Client\{NetworkExceptionInterface, RequestExceptionInterface};
use Psr\Http\Message\{RequestInterface, ResponseInterface};

Expand All @@ -40,7 +39,7 @@ public function sendRequest(RequestInterface $request): ResponseInterface
->withBody($request->getBody())
->read();

if ($response->getStatusCode() >= StatusCode::BAD_REQUEST) {
if ($response->getStatusCode() >= HttpStatus::BAD_REQUEST) {
throw new Psr18Exception($response->getBody()->getContents(), $response->getStatusCode(), $this);
}

Expand Down
6 changes: 3 additions & 3 deletions ClientRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

use InvalidArgumentException;
use JsonSerializable;
use Koded\Http\Interfaces\Request;
use Koded\Http\Interfaces\{HttpStatus, Request};
use Psr\Http\Message\{RequestInterface, UriInterface};
use function Koded\Stdlib\json_serialize;

Expand Down Expand Up @@ -107,7 +107,7 @@ public function getRequestTarget(): string
public function withRequestTarget($requestTarget): ClientRequest
{
if (preg_match('/\s+/', $requestTarget)) {
throw new InvalidArgumentException(self::E_INVALID_REQUEST_TARGET, StatusCode::BAD_REQUEST);
throw new InvalidArgumentException(self::E_INVALID_REQUEST_TARGET, HttpStatus::BAD_REQUEST);
}

$instance = clone $this;
Expand Down Expand Up @@ -172,7 +172,7 @@ protected function setMethod(string $method, RequestInterface $instance): Reques
protected function assertSafeMethod(): ?ServerResponse
{
if ($this->isSafeMethod() && $this->getBody()->getSize() > 0) {
return new ServerResponse(self::E_SAFE_METHODS_WITH_BODY, StatusCode::BAD_REQUEST);
return new ServerResponse(self::E_SAFE_METHODS_WITH_BODY, HttpStatus::BAD_REQUEST);
}

return null;
Expand Down
9 changes: 5 additions & 4 deletions HeaderTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
namespace Koded\Http;

use InvalidArgumentException;
use Koded\Http\Interfaces\HttpStatus;
use Throwable;


Expand Down Expand Up @@ -198,12 +199,12 @@ protected function normalizeHeaderName($name): string
$name = str_replace(["\r", "\n", "\t"], '', trim($name));
} catch (Throwable $e) {
throw new InvalidArgumentException(
sprintf('Header name must be a string, %s given', gettype($name)), StatusCode::BAD_REQUEST
sprintf('Header name must be a string, %s given', gettype($name)), HttpStatus::BAD_REQUEST
);
}

if ('' === $name) {
throw new InvalidArgumentException('Empty header name', StatusCode::BAD_REQUEST);
throw new InvalidArgumentException('Empty header name', HttpStatus::BAD_REQUEST);
}

return $name;
Expand All @@ -227,15 +228,15 @@ protected function normalizeHeaderValue(string $name, $value): array
break;
default:
throw new InvalidArgumentException(
sprintf('Invalid header value, expects string or array, "%s" given', $type), StatusCode::BAD_REQUEST
sprintf('Invalid header value, expects string or array, "%s" given', $type), HttpStatus::BAD_REQUEST
);
}

if (empty($value = array_map(function($v) {
return trim(preg_replace('/\s+/', ' ', $v));
}, $value))) {
throw new InvalidArgumentException(
sprintf('The value for header "%s" cannot be empty', $name), StatusCode::BAD_REQUEST
sprintf('The value for header "%s" cannot be empty', $name), HttpStatus::BAD_REQUEST
);
}

Expand Down
Loading

0 comments on commit 0fc6f6f

Please sign in to comment.