Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[FrameworkBundle] [DX] Add Controller::json method to make it easy to send json #17642

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

Merged
merged 1 commit into from
Mar 3, 2016
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
5 changes: 5 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

3.1.0
-----

* Added `Controller::json` to simplify creating JSON responses when using the Serializer component
Copy link
Contributor

Choose a reason for hiding this comment

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

Missing [BC break] ?

Copy link
Member

Choose a reason for hiding this comment

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

AFAIK, it's not a BC break.

Copy link
Contributor

Choose a reason for hiding this comment

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

Agreed, sorry I got confused by #18373.


3.0.0
-----

Expand Down
24 changes: 24 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;
Expand Down Expand Up @@ -97,6 +98,29 @@ protected function redirectToRoute($route, array $parameters = array(), $status
return $this->redirect($this->generateUrl($route, $parameters), $status);
}

/**
* Returns a JsonResponse that uses the serializer component if enabled, or json_encode.
*
* @param mixed $data The response data
* @param int $status The status code to use for the Response
* @param array $headers Array of extra headers to add
* @param array $context Context to pass to serializer when using serializer component
*
* @return JsonResponse
*/
protected function json($data, $status = 200, $headers = array(), $context = array())
Copy link
Member

Choose a reason for hiding this comment

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

What about renderJson or something similar to existing methods?

Copy link
Member

Choose a reason for hiding this comment

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

json is consistent with stream to return a stream response.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I was looking at redirect and stream as similar names, also renderView for example returns a string, not a Response

Copy link
Member

Choose a reason for hiding this comment

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

ok :)

{
if ($this->container->has('serializer')) {
Copy link
Member

Choose a reason for hiding this comment

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

I'm not a fan of having 2 different behaviors depending of the configuration. What do you think about splitting this method in 2 separates methods and throw an error in the method using the serializer if it is not available?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I do understand this point, but then again, looking at render/renderView, changes according to whether you have templating or twig enabled.

Also if #17603 is merged the result would be the same after you enable the serializer.

$json = $this->container->get('serializer')->serialize($data, 'json', array_merge(array(
'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS,
), $context));

return new JsonResponse($json, $status, $headers, true);
Copy link
Member

Choose a reason for hiding this comment

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

The fourth argument should be removed.

Sorry, I missed the change below.

Copy link
Member

Choose a reason for hiding this comment

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

But you now have to increase the required version of symfony/http-foundation.

}

return new JsonResponse($data, $status, $headers);
}

/**
* Adds a flash message to the current session for type.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Serializer\SerializerInterface;

class ControllerTest extends TestCase
{
Expand Down Expand Up @@ -124,6 +126,85 @@ private function getContainerWithTokenStorage($token = null)

return $container;
}

public function testJson()
{
$container = $this->getMock(ContainerInterface::class);
$container
->expects($this->once())
->method('has')
->with('serializer')
->will($this->returnValue(false));

$controller = new TestController();
$controller->setContainer($container);

$response = $controller->json(array());
$this->assertInstanceOf(JsonResponse::class, $response);
$this->assertEquals('[]', $response->getContent());
}

public function testJsonWithSerializer()
{
$container = $this->getMock(ContainerInterface::class);
$container
->expects($this->once())
->method('has')
->with('serializer')
->will($this->returnValue(true));

$serializer = $this->getMock(SerializerInterface::class);
$serializer
->expects($this->once())
->method('serialize')
->with(array(), 'json', array('json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS))
->will($this->returnValue('[]'));

$container
->expects($this->once())
->method('get')
->with('serializer')
->will($this->returnValue($serializer));

$controller = new TestController();
$controller->setContainer($container);

$response = $controller->json(array());
$this->assertInstanceOf(JsonResponse::class, $response);
$this->assertEquals('[]', $response->getContent());
}

public function testJsonWithSerializerContextOverride()
{
$container = $this->getMock(ContainerInterface::class);
$container
->expects($this->once())
->method('has')
->with('serializer')
->will($this->returnValue(true));

$serializer = $this->getMock(SerializerInterface::class);
$serializer
->expects($this->once())
->method('serialize')
->with(array(), 'json', array('json_encode_options' => 0, 'other' => 'context'))
->will($this->returnValue('[]'));

$container
->expects($this->once())
->method('get')
->with('serializer')
->will($this->returnValue($serializer));

$controller = new TestController();
$controller->setContainer($container);

$response = $controller->json(array(), 200, array(), array('json_encode_options' => 0, 'other' => 'context'));
$this->assertInstanceOf(JsonResponse::class, $response);
$this->assertEquals('[]', $response->getContent());
$response->setEncodingOptions(JSON_FORCE_OBJECT);
$this->assertEquals('{}', $response->getContent());
}
}

class TestController extends Controller
Expand All @@ -137,4 +218,9 @@ public function getUser()
{
return parent::getUser();
}

public function json($data, $status = 200, $headers = array(), $context = array())
{
return parent::json($data, $status, $headers, $context);
}
}
2 changes: 1 addition & 1 deletion src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"symfony/dependency-injection": "~2.8|~3.0",
"symfony/config": "~2.8|~3.0",
"symfony/event-dispatcher": "~2.8|~3.0",
"symfony/http-foundation": "~2.8|~3.0",
"symfony/http-foundation": "~3.1",
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@xabbuh is this the best way to do it? I see at least one other component has a ~3.0 requirement, I assume this is expected to change as new functionality is added to Symfony 3

Copy link
Member

Choose a reason for hiding this comment

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

yes, that's right

"symfony/http-kernel": "~2.8|~3.0",
"symfony/polyfill-mbstring": "~1.0",
"symfony/filesystem": "~2.8|~3.0",
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/HttpFoundation/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

3.1.0
-----

* Added support for creating `JsonResponse` with a string of JSON data

3.0.0
-----

Expand Down
54 changes: 30 additions & 24 deletions src/Symfony/Component/HttpFoundation/JsonResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,24 +29,27 @@ class JsonResponse extends Response

// Encode <, >, ', &, and " for RFC4627-compliant JSON, which may also be embedded into HTML.
// 15 === JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT
protected $encodingOptions = 15;
const DEFAULT_ENCODING_OPTIONS = 15;

protected $encodingOptions = self::DEFAULT_ENCODING_OPTIONS;
Copy link
Contributor

Choose a reason for hiding this comment

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

IRC, the possibility to assign a property from a constant value is available only on php >= 5.6, and Sf3 is php >= 5.5...

Copy link
Contributor Author

Choose a reason for hiding this comment

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

As far as I can tell this usage has always been part of PHP 5. It certainly works in 5.5. You made me doubt it and I ran the tests for this class in 5.5 to double check!

I know that from PHP 7 its possible to write this how I would have really liked

const DEFAULT_ENCODING_OPTIONS = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT

Copy link
Contributor

Choose a reason for hiding this comment

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

Ow, yeah I may have mistaken with arithmetics such as const DEFAULT_ENCODING_OPTIONS = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT indeed. My bad !


/**
* Constructor.
*
* @param mixed $data The response data
* @param int $status The response status code
* @param array $headers An array of response headers
* @param mixed $data The response data
* @param int $status The response status code
* @param array $headers An array of response headers
* @param bool $preEncoded If the data is already a JSON string
*/
public function __construct($data = null, $status = 200, $headers = array())
public function __construct($data = null, $status = 200, $headers = array(), $preEncoded = false)
{
parent::__construct('', $status, $headers);

if (null === $data) {
$data = new \ArrayObject();
}

$this->setData($data);
$this->setData($data, $preEncoded);
}

/**
Expand Down Expand Up @@ -88,34 +91,37 @@ public function setCallback($callback = null)
* Sets the data to be sent as JSON.
*
* @param mixed $data
* @param bool $preEncoded If the data is already a JSON string
*
* @return JsonResponse
*
* @throws \InvalidArgumentException
*/
public function setData($data = array())
public function setData($data = array(), $preEncoded = false)
Copy link
Contributor

Choose a reason for hiding this comment

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

Breaks BC.

{
if (defined('HHVM_VERSION')) {
// HHVM does not trigger any warnings and let exceptions
// thrown from a JsonSerializable object pass through.
// If only PHP did the same...
$data = json_encode($data, $this->encodingOptions);
} else {
try {
// PHP 5.4 and up wrap exceptions thrown by JsonSerializable
// objects in a new exception that needs to be removed.
// Fortunately, PHP 5.5 and up do not trigger any warning anymore.
if (!$preEncoded) {
if (defined('HHVM_VERSION')) {
// HHVM does not trigger any warnings and let exceptions
// thrown from a JsonSerializable object pass through.
// If only PHP did the same...
$data = json_encode($data, $this->encodingOptions);
} catch (\Exception $e) {
if ('Exception' === get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling ')) {
throw $e->getPrevious() ?: $e;
} else {
try {
// PHP 5.4 and up wrap exceptions thrown by JsonSerializable
// objects in a new exception that needs to be removed.
// Fortunately, PHP 5.5 and up do not trigger any warning anymore.
$data = json_encode($data, $this->encodingOptions);
} catch (\Exception $e) {
if ('Exception' === get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling ')) {
throw $e->getPrevious() ?: $e;
}
throw $e;
}
throw $e;
}
}

if (JSON_ERROR_NONE !== json_last_error()) {
throw new \InvalidArgumentException(json_last_error_msg());
if (JSON_ERROR_NONE !== json_last_error()) {
throw new \InvalidArgumentException(json_last_error_msg());
}
}

$this->data = $data;
Expand Down
12 changes: 12 additions & 0 deletions src/Symfony/Component/HttpFoundation/Tests/JsonResponseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,18 @@ public function testConstructorWithCustomContentType()
$this->assertSame('application/vnd.acme.blog-v1+json', $response->headers->get('Content-Type'));
}

public function testConstructorWithPreEncoded()
{
$response = new JsonResponse('1', 200, array(), true);
$this->assertEquals('1', $response->getContent());

$response = new JsonResponse('[1]', 200, array(), true);
$this->assertEquals('[1]', $response->getContent());

$response = new JsonResponse('true', 200, array(), true);
$this->assertEquals('true', $response->getContent());
}

public function testCreate()
{
$response = JsonResponse::create(array('foo' => 'bar'), 204);
Expand Down