Skip to content

Commit

Permalink
🚀
Browse files Browse the repository at this point in the history
  • Loading branch information
someniatko committed Apr 27, 2020
0 parents commit c9988fa
Show file tree
Hide file tree
Showing 6 changed files with 166 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/vendor/
/composer.lock
.phpunit.result.cache
7 changes: 7 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2020 someniatko

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Json Decode Middleware

Simple PSR-15 middleware, which decodes JSON body of a PSR-7 Server Request,
if it has a `Content-Type: application/json` header, into array, which you can
obtain via `getParsedBody()` call on the Server Request.
32 changes: 32 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "someniatko/json-decode-middleware",
"description": "Simple PSR-15 middleware for decoding JSON body of a server request when given respective Content-Type header",
"type": "library",
"require": {
"php": "^7.3",
"ext-json": "*",
"psr/http-message": "^1.0",
"psr/http-server-middleware": "^1.0",
"psr/http-server-handler": "^1.0"
},
"require-dev": {
"phpunit/phpunit": "^9.1",
"nyholm/psr7": "^1.2"
},
"autoload": {
"psr-4": {
"Someniatko\\JsonDecodeMiddleware\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Test\\": "test"
}
},
"config": {
"platform": {
"php": "7.3.0"
}
},
"license": "MIT"
}
40 changes: 40 additions & 0 deletions src/JsonDecodeMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);

namespace Someniatko\JsonDecodeMiddleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

final class JsonDecodeMiddleware implements MiddlewareInterface
{
private const DEFAULT_JSON_DEPTH = 512;

/** @throws \JsonException */
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
return $handler->handle($request->withParsedBody($this->parseBody($request)));
}

/** @throws \JsonException */
private function parseBody(ServerRequestInterface $request)
{
if (! $request->hasHeader('Content-Type')) {
return $request->getParsedBody();
}

if (strpos($request->getHeaderLine('Content-Type'), 'application/json') === false) {
return $request->getParsedBody();
}

return json_decode(
(string)$request->getBody(),
true,
self::DEFAULT_JSON_DEPTH,
JSON_THROW_ON_ERROR
);
}
}
79 changes: 79 additions & 0 deletions test/JsonDecodeMiddlewareTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

declare(strict_types=1);

namespace Test;

use Nyholm\Psr7\Factory\Psr17Factory;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Someniatko\JsonDecodeMiddleware\JsonDecodeMiddleware;

final class JsonDecodeMiddlewareTest extends TestCase
{
/** @dataProvider requestProvider */
public function testWithJsonContentType(ServerRequestInterface $request, $expectedBody): void
{
$handler = $this->createMock(RequestHandlerInterface::class);
$handler
->method('handle')
->with($this->callback(function (ServerRequestInterface $request) use ($expectedBody): bool {
return ($request->getMethod() === 'POST')
&& ((string)$request->getUri() === '/some/uri')
&& ($request->getParsedBody() === $expectedBody);
}))
->willReturn($response = $this->createMock(ResponseInterface::class));

$middleware = new JsonDecodeMiddleware();

$this->assertSame($response, $middleware->process($request, $handler));
}

public function requestProvider(): iterable
{
$httpFactory = new Psr17Factory();

yield 'application/json Content-Type' => [
$httpFactory
->createServerRequest('POST', '/some/uri')
->withBody($httpFactory->createStream('{"some":"json"}'))
->withHeader('Content-Type', 'application/json'),
[ 'some' => 'json' ]
];

yield 'unknown Content-Type' => [
$httpFactory
->createServerRequest('POST', '/some/uri')
->withBody($httpFactory->createStream('{"some":"json"}'))
->withHeader('Content-Type', 'application/xml'),
null
];

yield 'missing Content-Type' => [
$httpFactory
->createServerRequest('POST', '/some/uri')
->withBody($httpFactory->createStream('{"some":"json"}'))
->withoutHeader('Content-Type'),
null
];

yield 'missing Content-Type, parsed body already given' => [
$httpFactory
->createServerRequest('POST', '/some/uri')
->withBody($httpFactory->createStream('{"some":"json"}'))
->withParsedBody($c = new \stdClass())
->withoutHeader('Content-Type'),
$c
];

yield 'application/json;charset=UTF-8 Content-Type' => [
$httpFactory
->createServerRequest('POST', '/some/uri')
->withBody($httpFactory->createStream('{"some":"json"}'))
->withHeader('Content-Type', 'application/json;charset=UTF-8'),
[ 'some' => 'json' ]
];
}
}

0 comments on commit c9988fa

Please sign in to comment.