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

Support parsing urlencoded request body (RequestBodyParserMiddleware) #220

Merged
merged 4 commits into from
Sep 25, 2017
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
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Event-driven, streaming plaintext HTTP and secure HTTPS server for [ReactPHP](ht
* [Response](#response)
* [Middleware](#middleware)
* [RequestBodyBufferMiddleware](#requestbodybuffermiddleware)
* [RequestBodyParserMiddleware](#requestbodyparsermiddleware)
* [Install](#install)
* [Tests](#tests)
* [License](#license)
Expand Down Expand Up @@ -725,6 +726,39 @@ $middlewares = new MiddlewareRunner([
]);
```

#### RequestBodyParserMiddleware

The `RequestBodyParserMiddleware` takes a fully buffered request body (generally from [`RequestBodyBufferMiddleware`](#requestbodybuffermiddleware)),
and parses the forms and uploaded files from the request body.

Parsed submitted forms will be available from `$request->getParsedBody()` as array. For example the following submitted body:

`bar[]=beer&bar[]=wine`

Results in the following parsed body:

```php
$parsedBody = [
'bar' => [
'beer',
'wine',
],
];
```

Usage:

```php
$middlewares = new MiddlewareRunner([
new RequestBodyBufferMiddleware(16 * 1024 * 1024), // 16 MiB
new RequestBodyParserMiddleware(),
function (ServerRequestInterface $request, callable $next) {
// If any, parsed form fields are now available from $request->getParsedBody()
return new Response(200);
},
]);
```

## Install

The recommended way to install this library is [through Composer](http://getcomposer.org).
Expand Down
27 changes: 27 additions & 0 deletions src/Middleware/RequestBodyParserMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace React\Http\Middleware;

use Psr\Http\Message\ServerRequestInterface;

final class RequestBodyParserMiddleware

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would like to not see final in this case. There are literally a metric ton of different request body formats and this is rather limiting (from the perspective of a http framework). XML, Json, form-urlencoded are only the most popular however there are many custom encodings as well.
For framework usage it would be nice to be able extend.

Also it's possible to have a mixture of encoding types inside an application (I know it sounds weird, but it happens... a lot).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@geggleto going to provide a third party middleware that allows this as I also have a use for it 😄

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See #225 :-)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@geggleto We've decided to provide only some core middleware which are required to build a standard PHP/PSR-7 request. Everything else can be easily provided third-party middleware packages. See #221 for reference.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

{
public function __invoke(ServerRequestInterface $request, $next)
{
$type = strtolower($request->getHeaderLine('Content-Type'));

if ($type === 'application/x-www-form-urlencoded') {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See #225 :-)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return $next($this->parseFormUrlencoded($request));
}

return $next($request);
}

private function parseFormUrlencoded(ServerRequestInterface $request)
{
$ret = array();
parse_str((string)$request->getBody(), $ret);

return $request->withParsedBody($ret);
}
}
136 changes: 136 additions & 0 deletions tests/Middleware/RequestBodyParserMiddlewareTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
<?php

namespace React\Tests\Http\Middleware;

use Psr\Http\Message\ServerRequestInterface;
use React\Http\Middleware\RequestBodyParserMiddleware;
use React\Http\ServerRequest;
use React\Tests\Http\TestCase;

final class RequestBodyParserMiddlewareTest extends TestCase
{
public function testFormUrlencodedParsing()
{
$middleware = new RequestBodyParserMiddleware();
$request = new ServerRequest(
'POST',
'https://example.com/',
array(
'Content-Type' => 'application/x-www-form-urlencoded',
),
'hello=world'
);

/** @var ServerRequestInterface $parsedRequest */
$parsedRequest = $middleware(
$request,
function (ServerRequestInterface $request) {
return $request;
}
);

$this->assertSame(
array('hello' => 'world'),
$parsedRequest->getParsedBody()
);
$this->assertSame('hello=world', (string)$parsedRequest->getBody());
}

public function testFormUrlencodedParsingIgnoresCaseForHeadersButRespectsContentCase()
{
$middleware = new RequestBodyParserMiddleware();
$request = new ServerRequest(
'POST',
'https://example.com/',
array(
'CONTENT-TYPE' => 'APPLICATION/X-WWW-Form-URLEncoded',
),
'Hello=World'
);

/** @var ServerRequestInterface $parsedRequest */
$parsedRequest = $middleware(
$request,
function (ServerRequestInterface $request) {
return $request;
}
);

$this->assertSame(
array('Hello' => 'World'),
$parsedRequest->getParsedBody()
);
$this->assertSame('Hello=World', (string)$parsedRequest->getBody());
}

public function testFormUrlencodedParsingNestedStructure()
{
$middleware = new RequestBodyParserMiddleware();
$request = new ServerRequest(
'POST',
'https://example.com/',
array(
'Content-Type' => 'application/x-www-form-urlencoded',
),
'foo=bar&baz[]=cheese&bar[]=beer&bar[]=wine&market[fish]=salmon&market[meat][]=beef&market[meat][]=chicken&market[]=bazaar'
);

/** @var ServerRequestInterface $parsedRequest */
$parsedRequest = $middleware(
$request,
function (ServerRequestInterface $request) {
return $request;
}
);

$this->assertSame(
array(
'foo' => 'bar',
'baz' => array(
'cheese',
),
'bar' => array(
'beer',
'wine',
),
'market' => array(
'fish' => 'salmon',
'meat' => array(
'beef',
'chicken',
),
0 => 'bazaar',
),
),
$parsedRequest->getParsedBody()
);
$this->assertSame('foo=bar&baz[]=cheese&bar[]=beer&bar[]=wine&market[fish]=salmon&market[meat][]=beef&market[meat][]=chicken&market[]=bazaar', (string)$parsedRequest->getBody());
}

public function testDoesNotParseJsonByDefault()
{
$middleware = new RequestBodyParserMiddleware();
$request = new ServerRequest(
'POST',
'https://example.com/',
array(
'Content-Type' => 'application/json',
),
'{"hello":"world"}'
);

/** @var ServerRequestInterface $parsedRequest */
$parsedRequest = $middleware(
$request,
function (ServerRequestInterface $request) {
return $request;
}
);

$this->assertSame(
null,
$parsedRequest->getParsedBody()
);
$this->assertSame('{"hello":"world"}', (string)$parsedRequest->getBody());
}
}