From e73604c8c0c07d3da12c762d4ef8a46a98f664e3 Mon Sep 17 00:00:00 2001 From: BadJacky <113529280+BadJacky@users.noreply.github.com> Date: Thu, 20 Feb 2025 01:01:13 +0800 Subject: [PATCH] feature: refactor `\Ripple\Http\Server\Connection` to use `\Ripple\Http\Enum` enum's `hasBody` method - Updated Connection class to use Method enum's hasBody method - Simplified request body handling logic in Connection class - Improved code readability and maintainability --- src/Enum/Method.php | 29 +++++++++++++++++++---------- src/Server/Connection.php | 19 +++++++++++-------- 2 files changed, 30 insertions(+), 18 deletions(-) diff --git a/src/Enum/Method.php b/src/Enum/Method.php index b430782..75c3317 100644 --- a/src/Enum/Method.php +++ b/src/Enum/Method.php @@ -12,15 +12,24 @@ namespace Ripple\Http\Enum; -enum Method +use function in_array; + +enum Method: string { - public const GET = 'GET'; - public const POST = 'POST'; - public const PUT = 'PUT'; - public const DELETE = 'DELETE'; - public const PATCH = 'PATCH'; - public const OPTIONS = 'OPTIONS'; - public const HEAD = 'HEAD'; - public const TRACE = 'TRACE'; - public const CONNECT = 'CONNECT'; + case GET = 'GET'; + case POST = 'POST'; + case PUT = 'PUT'; + case DELETE = 'DELETE'; + case PATCH = 'PATCH'; + case OPTIONS = 'OPTIONS'; + case HEAD = 'HEAD'; + case TRACE = 'TRACE'; + case CONNECT = 'CONNECT'; + + private const METHOD_WITH_BODY = [self::POST, self::PUT, self::DELETE, self::PATCH]; + + public function hasBody(): bool + { + return in_array($this, self::METHOD_WITH_BODY, true); + } } diff --git a/src/Server/Connection.php b/src/Server/Connection.php index d8a9be7..574ba23 100644 --- a/src/Server/Connection.php +++ b/src/Server/Connection.php @@ -13,6 +13,7 @@ namespace Ripple\Http\Server; use Closure; +use Ripple\Http\Enum\Method; use Ripple\Http\Server\Exception\FormatException; use Ripple\Http\Server\Upload\MultipartHandler; use Ripple\Socket; @@ -301,14 +302,16 @@ private function parseHeaders(): void */ private function handleRequestBody(string $method, string $body): void { - if (in_array($method, ['GET', 'HEAD'])) { - $this->bodyLength = 0; - $this->step = 2; - } elseif ($method === 'POST') { - $this->handlePostRequest($body); - } elseif (in_array($method, ['PUT', 'DELETE', 'PATCH', 'OPTIONS', 'TRACE', 'CONNECT'])) { - $this->handleOtherMethods(); - } + $methodEnum = Method::tryFrom($method); + + if (null === $methodEnum) { + $this->handleOtherMethods(); + } elseif ($methodEnum->hasBody()) { + $this->handlePostRequest($body); + } else { + $this->bodyLength = 0; + $this->step = 2; + } } /**