Skip to content
This repository has been archived by the owner on Jan 21, 2020. It is now read-only.

BodyParams middleware stolen w/permission from mwop.net #3

Merged
merged 3 commits into from
Dec 22, 2015
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
78 changes: 78 additions & 0 deletions src/BodyParamsMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php
/**
* @see http://github.com/zendframework/zend-expressive for the canonical source repository
* @copyright Copyright (c) 2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-expressive/blob/master/LICENSE.md New BSD License
*/

namespace Zend\Expressive\Helper;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class BodyParamsMiddleware
{
/**
* List of request methods that do not have any defined body semantics, and thus
* will not have the body parsed.
*
* @see https://tools.ietf.org/html/rfc7231
*
* @var array
*/
private $nonBodyRequests = [
'GET',
'HEAD',
'OPTIONS',
];

/**
* Adds JSON decoded request body to the request, where appropriate.
*
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param callable $next
*
* @return ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
{
if (in_array($request->getMethod(), $this->nonBodyRequests)) {
return $next($request, $response);
}

$header = $request->getHeaderLine('Content-Type');
$priorities = [
'form' => 'application/x-www-form-urlencoded',
'json' => '[/+]json',
];

$matched = false;
foreach ($priorities as $type => $pattern) {
$pattern = sprintf('#%s#', $pattern);
if (! preg_match($pattern, $header)) {
continue;
}
$matched = $type;
break;
}

switch ($matched) {
case 'form':
// $_POST is injected by default into the request body parameters.
break;
case 'json':
$rawBody = $request->getBody()->getContents();
return $next(
$request
->withAttribute('rawBody', $rawBody)
->withParsedBody(json_decode($rawBody, true)),
$response
);
default:
break;
}

return $next($request, $response);
}
}
93 changes: 93 additions & 0 deletions test/BodyParamsMiddlewareTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @see https://github.com/zendframework/zend-expressive for the canonical source repository
* @copyright Copyright (c) 2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-expressive/blob/master/LICENSE.md New BSD License
*/

namespace ZendTest\Expressive\Helper;

use PHPUnit_Framework_TestCase as TestCase;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequest;
use Zend\Diactoros\Stream;
use Zend\Expressive\Helper\BodyParamsMiddleware;

class BodyParamsMiddlewareTest extends TestCase
{
/**
* @var Stream
*/
protected $body;

/**
* @var BodyParamsMiddleware
*/
protected $bodyParams;

public function setUp()
{
$this->bodyParams = new BodyParamsMiddleware();

$stream = fopen('php://memory', 'r+');
fwrite($stream, json_encode(['foo' => 'bar']));

$this->body = new Stream($stream);
$this->body->rewind();
}

public function testParsesRawBodyAndPreservesRawBodyInRequestAttribute()
{
$serverRequest = new ServerRequest([], [], '', 'PUT', $this->body, ['Content-type' => 'application/json']);

$this->bodyParams->__invoke(
$serverRequest,
new Response(),
function ($request, $response) use (&$serverRequest) {
$serverRequest = $request;

return $response;
}
);

$this->assertSame(
json_encode(['foo' => 'bar']),
$serverRequest->getAttribute('rawBody')
);
$this->assertSame(['foo' => 'bar'], $serverRequest->getParsedBody());
}

public function notApplicableProvider()
{
return [
['GET', 'application/json'],
['HEAD', 'application/json'],
['OPTIONS', 'application/json'],
['POST', 'application/x-www-form-urlencoded'],
['DELETE', 'this-isnt-a-real-content-type'],
];
}

/**
* @dataProvider notApplicableProvider
*/
public function testRequestIsUnchangedWhenBodyParamsMiddlewareIsNotApplicable($method, $contentType)
{
$originalRequest = new ServerRequest([], [], '', $method, $this->body, ['Content-type' => $contentType]);
$finalRequest = null;

$this->bodyParams->__invoke(
$originalRequest,
new Response(),
function ($request, $response) use (&$finalRequest) {
$finalRequest = $request;

return $response;
}
);

$this->assertSame($originalRequest, $finalRequest);
}
}