Skip to content

Commit

Permalink
Merge pull request #11 from lucasmezencio/master
Browse files Browse the repository at this point in the history
Improve code quality/readability and PHPUnit version
  • Loading branch information
benji07 authored Jul 6, 2020
2 parents 6185bc5 + f7e63a0 commit c3bdb2c
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 92 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@

namespace Elao\Bundle\JsonHttpFormBundle\DependencyInjection\Compiler;

use Elao\Bundle\JsonHttpFormBundle\Form\RequestHandler\JsonHttpFoundationRequestHandler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class OverrideRequestHandlerCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
public function process(ContainerBuilder $container): void
{
$container
->getDefinition('form.type_extension.form.request_handler')
->setClass('Elao\Bundle\JsonHttpFormBundle\Form\RequestHandler\JsonHttpFoundationRequestHandler');
->setClass(JsonHttpFoundationRequestHandler::class);
}
}
4 changes: 2 additions & 2 deletions ElaoJsonHttpFormBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@

namespace Elao\Bundle\JsonHttpFormBundle;

use Elao\Bundle\JsonHttpFormBundle\DependencyInjection\Compiler\OverrideRequestHandlerCompilerPass;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Elao\Bundle\JsonHttpFormBundle\DependencyInjection\Compiler\OverrideRequestHandlerCompilerPass;

class ElaoJsonHttpFormBundle extends Bundle
{
public function build(ContainerBuilder $container)
public function build(ContainerBuilder $container): void
{
parent::build($container);

Expand Down
65 changes: 34 additions & 31 deletions Form/RequestHandler/JsonHttpFoundationRequestHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@
*/
class JsonHttpFoundationRequestHandler extends HttpFoundationRequestHandler
{
/**
* @var ServerParams
*/
/** @var ServerParams */
private $serverParams;

/**
Expand All @@ -29,30 +27,29 @@ class JsonHttpFoundationRequestHandler extends HttpFoundationRequestHandler
*/
private static $bodyMethods = ['POST', 'PUT', 'PATCH', 'DELETE'];

/**
* {@inheritdoc}
*/
public function __construct(ServerParams $serverParams = null)
{
parent::__construct($serverParams);

$this->serverParams = $serverParams ?: new ServerParams();
}

/**
* {@inheritdoc}
*/
public function handleRequest(FormInterface $form, $request = null)
public function handleRequest(FormInterface $form, $request = null): void
{
if (!$request instanceof Request) {
throw new UnexpectedTypeException($request, 'Symfony\Component\HttpFoundation\Request');
throw new UnexpectedTypeException($request, Request::class);
}

if ($request->getContentType() === 'json' && in_array($request->getMethod(), static::$bodyMethods)) {
return $this->handleJsonRequest($form, $request);
} else {
return parent::handleRequest($form, $request);
if (
'json' === $request->getContentType()
&& in_array($request->getMethod(), static::$bodyMethods, false)
) {
$this->handleJsonRequest($form, $request);

return;
}

parent::handleRequest($form, $request);
}

/**
Expand All @@ -61,23 +58,27 @@ public function handleRequest(FormInterface $form, $request = null)
* @param FormInterface $form
* @param Request $request
*/
protected function handleJsonRequest(FormInterface $form, Request $request)
protected function handleJsonRequest(FormInterface $form, Request $request): void
{
if ($this->isContentSizeValid($form)) {
$name = $form->getName();
$name = $form->getName();
$content = json_decode($request->getContent(), true);

if (json_last_error() !== JSON_ERROR_NONE) {
$form->submit(null, false);
$form->addError(new FormError(sprintf(
'The given JSON content could not be parsed: %s',
json_last_error_msg()
)));
$form->addError(
new FormError(
sprintf(
'The given JSON content could not be parsed: %s',
json_last_error_msg()
)
)
);

return;
}

if ('' === $name || $request->getMethod() === 'DELETE') {
if ('' === $name || 'DELETE' === $request->getMethod()) {
$data = $content;
} else {
// Don't submit if the form's name does not exist in the request
Expand All @@ -96,29 +97,31 @@ protected function handleJsonRequest(FormInterface $form, Request $request)
* Check content size
*
* Code from {@link HttpFoundationRequestHandler} max size verification.
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @param FormInterface $form
*
* @return boolean
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
protected function isContentSizeValid(FormInterface $form)
protected function isContentSizeValid(FormInterface $form): bool
{
// Mark the form with an error if the uploaded size was too large
// This is done here and not in FormValidator because $_POST is
// empty when that error occurs. Hence the form is never submitted.
$contentLength = $this->serverParams->getContentLength();
$maxContentLength = $this->serverParams->getPostMaxSize();

if (!empty($maxContentLength) && $contentLength > $maxContentLength) {
if (null !== $maxContentLength && $contentLength > $maxContentLength) {
// Submit the form, but don't clear the default values
$form->submit(null, false);

$form->addError(new FormError(
$form->getConfig()->getOption('post_max_size_message'),
null,
array('{{ max }}' => $this->serverParams->getNormalizedIniPostMaxSize())
));
$form->addError(
new FormError(
$form->getConfig()->getOption('post_max_size_message'),
null,
['{{ max }}' => $this->serverParams->getNormalizedIniPostMaxSize()]
)
);

return false;
}
Expand Down
97 changes: 42 additions & 55 deletions Tests/Form/RequestHandler/RequestHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,91 +2,78 @@

namespace Elao\Bundle\JsonHttpFormBundle\Tests\Form\RequestHandler;

use Symfony\Component\Form\FormFactory;
use Elao\Bundle\JsonHttpFormBundle\Form\RequestHandler\JsonHttpFoundationRequestHandler;
use Symfony\Component\Form\Extension\Core\Type\{FormType, TextType, ChoiceType};
use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\Forms;
use Symfony\Component\Form\Util\ServerParams;
use Symfony\Component\HttpFoundation\Request;
use Elao\Bundle\JsonHttpFormBundle\Form\RequestHandler\JsonHttpFoundationRequestHandler;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

class RequestHandlerTest extends \PHPUnit_Framework_TestCase
class RequestHandlerTest extends TestCase
{
/**
* {@inheritdoc}
*/
protected function setUp()
private $requestHandler;
private $factory;

protected function setUp(): void
{
$this->serverParams = $this->getMock(
'Symfony\Component\Form\Util\ServerParams',
['getNormalizedIniPostMaxSize', 'getContentLength']
);
$this->requestHandler = new JsonHttpFoundationRequestHandler($this->serverParams);
$this->factory = Forms::createFormFactoryBuilder()->getFormFactory();
$serverParams = $this->createMock(ServerParams::class);
$this->requestHandler = new JsonHttpFoundationRequestHandler($serverParams);
$this->factory = Forms::createFormFactoryBuilder()->getFormFactory();
}

/**
* Test JSON POST request
*/
public function testJsonPostRequest()
public function testJsonPostRequest(): void
{
$form = $this->getSampleForm();
$data = $this->getSampleData();
$request = new Request([], [], [], [], [], [
'REQUEST_METHOD' => 'POST',
$form = $this->getSampleForm();
$data = $this->getSampleData();
$request = new Request(
[], [], [], [], [], [
'REQUEST_METHOD' => 'POST',
'HTTP_CONTENT_TYPE' => 'application/json',
], json_encode(['rocket' => $data]));
], json_encode(['rocket' => $data])
);

$this->requestHandler->handleRequest($form, $request);
$this->assertEquals($data, $form->getData());
}

/**
* Test Classic POST request
*/
public function testClassicPostRequest()
public function testClassicPostRequest(): void
{
$form = $this->getSampleForm();
$data = $this->getSampleData();
$form = $this->getSampleForm();
$data = $this->getSampleData();
$request = new Request([], ['rocket' => $data], [], [], [], ['REQUEST_METHOD' => 'POST']);

$this->requestHandler->handleRequest($form, $request);
$this->assertEquals($data, $form->getData());
}

/**
* Get sample data
*
* @return array
*/
private function getSampleData()
private function getSampleData(): array
{
return [
'name' => "Méliès",
'colors' => ['brown', 'pink']
'name' => 'Méliès',
'colors' => ['brown', 'pink'],
];
}

/**
* Get sample form
*
* @return Form
*/
private function getSampleForm()
private function getSampleForm(): FormInterface
{
return $this->factory
->createNamed('rocket', FormType::class, [], [])
->add('name', TextType::class)
->add('colors', ChoiceType::class, [
'multiple' => true,
'choices' => [
'White' => 'white',
'Orange' => 'orange',
'Blonde' => 'blonde',
'Pink' => 'pink',
'Blue' => 'blue',
'Brown' => 'brown',
->add(
'colors',
ChoiceType::class,
[
'multiple' => true,
'choices' => [
'White' => 'white',
'Orange' => 'orange',
'Blonde' => 'blonde',
'Pink' => 'pink',
'Blue' => 'blue',
'Brown' => 'brown',
],
]
]);
);
}
}
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,16 @@
"require": {
"php": "^7.1",
"symfony/framework-bundle": "~3.0|~4.0|~5.0",
"symfony/form": "~3.0|~4.0|~5.0"
"symfony/form": "~3.0|~4.0|~5.0",
"ext-json": "*"
},
"autoload": {
"psr-4": {
"Elao\\Bundle\\JsonHttpFormBundle\\": "."
}
},
"require-dev": {
"phpunit/phpunit": "~4.5"
"phpunit/phpunit": "^7.5"
},
"extra": {
"branch-alias": {
Expand Down

0 comments on commit c3bdb2c

Please sign in to comment.