diff --git a/src/BodyParser/BodyParserInterface.php b/src/BodyParser/BodyParserInterface.php index 878701f..aa21ae1 100644 --- a/src/BodyParser/BodyParserInterface.php +++ b/src/BodyParser/BodyParserInterface.php @@ -1,6 +1,9 @@ + */ +class FormData implements BodyParserInterface +{ + /** + * FIXME: This should not use $_POST + */ + public static function parseBody(Request $request): Request + { + $request = $request->withParsedBody($_POST); + + return $request; + } +} \ No newline at end of file diff --git a/src/BodyParser/Json.php b/src/BodyParser/Json.php index 081da2a..292ced6 100644 --- a/src/BodyParser/Json.php +++ b/src/BodyParser/Json.php @@ -1,9 +1,11 @@ getBody()->getContents(); + if (!$body) { + return $request; + } - public static function parse($source): array - { try { $result = json_decode( - $source, + $body, associative: true, flags: JSON_THROW_ON_ERROR ); @@ -29,13 +31,15 @@ public static function parse($source): array // Lo rethrowamos if (class_exists(VendimiaException::class)) { throw new VendimiaException("Error parsing JSON body: " . $e->getMessage(), - original_body: $source, + original_body: $body, ); } else { throw new Exception("Error parsing JSON body: " . $e->getMessage()); } } - return $result; + $request = $request->withParsedBody($result); + + return $request; } } \ No newline at end of file diff --git a/src/BodyParser/Url.php b/src/BodyParser/Url.php index 5b2a34f..10fd793 100644 --- a/src/BodyParser/Url.php +++ b/src/BodyParser/Url.php @@ -1,6 +1,9 @@ getBody()->getContents(), $parsed_body); + $request = $request->withParsedBody($parsed_body); - public static function parse($source): array - { - parse_str($source, $parsed_body); - return $parsed_body; + return $request; } } \ No newline at end of file diff --git a/src/Request.php b/src/Request.php index f7f5655..bdfb564 100644 --- a/src/Request.php +++ b/src/Request.php @@ -13,9 +13,10 @@ class Request extends Psr\ServerRequest /** * Default Body parsers */ - const REGISTERED_PARSERS = [ - BodyParser\Url::class, - BodyParser\Json::class, + private static $REGISTERED_PARSERS = [ + 'application/x-www-form-urlencoded' => BodyParser\Url::class, + 'application/json' => BodyParser\Json::class, + 'multipart/form-data' => BodyParser\FormData::class, ]; // Shortcut to $this->getParsedBody(), in a Vendimia\Collection\Collection @@ -69,7 +70,11 @@ public static function fromPHP(): self // Ignoramos los parĂ¡metros extras $content_type = trim(explode(';', $content_type)[0]); - foreach (self::REGISTERED_PARSERS as $parse_class) { + if ($parser_class = self::$REGISTERED_PARSERS[$content_type] ?? null) { + $server_request = $parser_class::parseBody($server_request); + } + + /*foreach (self::$REGISTERED_PARSERS as $mime => $parse_class) { if ($parse_class::canDecode($content_type)) { $body_content = $body->getContents(); @@ -82,7 +87,7 @@ public static function fromPHP(): self break; } - } + }*/ } $server_request->parsed_body = $server_request->getParsedBody();