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

Skip to content

Commit 0ccff59

Browse files
committed
Add a Controller function to make it easy to return json
If the serializer component is enabled it is used to generate the json data, if not the standard `json_encode` function is used
1 parent 83b53f4 commit 0ccff59

File tree

4 files changed

+185
-0
lines changed

4 files changed

+185
-0
lines changed

src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,10 @@
1111

1212
namespace Symfony\Bundle\FrameworkBundle\Controller;
1313

14+
use Symfony\Bundle\FrameworkBundle\Response\JsonSerializedResponse;
1415
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
1516
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
17+
use Symfony\Component\HttpFoundation\JsonResponse;
1618
use Symfony\Component\HttpFoundation\Response;
1719
use Symfony\Component\HttpFoundation\RedirectResponse;
1820
use Symfony\Component\HttpFoundation\StreamedResponse;
@@ -97,6 +99,23 @@ protected function redirectToRoute($route, array $parameters = array(), $status
9799
return $this->redirect($this->generateUrl($route, $parameters), $status);
98100
}
99101

102+
/**
103+
* Returns a JsonResponse that uses the serializer component if enabled, or json_encode
104+
*
105+
* @param mixed $data The response data
106+
* @param int $status The status code to use for the Response
107+
* @param array $headers Array of extra headers to add
108+
* @param array $context Context to pass to serializer when using serializer component
109+
* @return JsonResponse
110+
*/
111+
protected function json($data, $status = 200, $headers = array(), $context = array())
112+
{
113+
if ($this->container->has('serializer')) {
114+
return new JsonSerializedResponse($data, $this->container->get('serializer'), $status, $headers, $context);
115+
}
116+
return new JsonResponse($data, $status);
117+
}
118+
100119
/**
101120
* Adds a flash message to the current session for type.
102121
*
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Bundle\FrameworkBundle\Response;
13+
14+
use Symfony\Component\HttpFoundation\JsonResponse;
15+
use Symfony\Component\Serializer\SerializerInterface;
16+
17+
/**
18+
* A response that makes it easy to use the Serializer component to generate json responses
19+
*
20+
* @author Fred Cox <[email protected]>
21+
*/
22+
class JsonSerializedResponse extends JsonResponse
23+
{
24+
/**
25+
* @var SerializerInterface
26+
*/
27+
private $serializer;
28+
29+
/**
30+
* @var array
31+
*/
32+
private $context;
33+
34+
/**
35+
* {@inheritdoc}
36+
*
37+
* @param SerializerInterface $serializer
38+
* @param array $context Context to pass to the serializer
39+
*/
40+
public function __construct($data = null, SerializerInterface $serializer, $status = 200, $headers = array(), $context = array())
41+
{
42+
$this->setSerializer($serializer);
43+
$this->setContext($context);
44+
parent::__construct($data, $status, $headers);
45+
}
46+
47+
/**
48+
* Set the serializer to use
49+
*
50+
* @param SerializerInterface $serializer
51+
*/
52+
public function setSerializer(SerializerInterface $serializer)
53+
{
54+
$this->serializer = $serializer;
55+
}
56+
57+
/**
58+
* Set the context to pass to the serializer
59+
*
60+
* @param array $context
61+
*/
62+
public function setContext(array $context)
63+
{
64+
$this->context = $context;
65+
}
66+
67+
/**
68+
* {@inheritdoc}
69+
*/
70+
public function setData($data = array())
71+
{
72+
$this->data = $this->serializer->serialize($data, 'json', array_merge(array('json_encode_options' => $this->encodingOptions), $this->context));
73+
return $this->update();
74+
}
75+
}

src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerTest.php

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,18 @@
1111

1212
namespace Symfony\Bundle\FrameworkBundle\Tests\Controller;
1313

14+
use Symfony\Bundle\FrameworkBundle\Response\JsonSerializedResponse;
1415
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
1516
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
1617
use Symfony\Component\DependencyInjection\ContainerInterface;
18+
use Symfony\Component\HttpFoundation\JsonResponse;
1719
use Symfony\Component\HttpFoundation\Request;
1820
use Symfony\Component\HttpFoundation\RequestStack;
1921
use Symfony\Component\HttpFoundation\Response;
2022
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
2123
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
2224
use Symfony\Component\Security\Core\User\User;
25+
use Symfony\Component\Serializer\SerializerInterface;
2326

2427
class ControllerTest extends TestCase
2528
{
@@ -124,6 +127,52 @@ private function getContainerWithTokenStorage($token = null)
124127

125128
return $container;
126129
}
130+
131+
public function testJson()
132+
{
133+
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
134+
$container
135+
->expects($this->once())
136+
->method('has')
137+
->with('serializer')
138+
->will($this->returnValue(false));
139+
140+
$controller = new TestController();
141+
$controller->setContainer($container);
142+
143+
$response = $controller->json(array());
144+
$this->assertInstanceOf(JsonResponse::class, $response);
145+
$this->assertEquals('[]', $response->getContent());
146+
}
147+
148+
public function testJsonWithSerializer()
149+
{
150+
$container = $this->getMock(ContainerInterface::class);
151+
$container
152+
->expects($this->once())
153+
->method('has')
154+
->with('serializer')
155+
->will($this->returnValue(true));
156+
157+
$serializer = $this->getMock(SerializerInterface::class);
158+
$serializer
159+
->expects($this->once())
160+
->method('serialize')
161+
->will($this->returnValue('[]'));
162+
163+
$container
164+
->expects($this->once())
165+
->method('get')
166+
->with('serializer')
167+
->will($this->returnValue($serializer));
168+
169+
$controller = new TestController();
170+
$controller->setContainer($container);
171+
172+
$response = $controller->json(array());
173+
$this->assertInstanceOf(JsonSerializedResponse::class, $response);
174+
$this->assertEquals('[]', $response->getContent());
175+
}
127176
}
128177

129178
class TestController extends Controller
@@ -137,4 +186,9 @@ public function getUser()
137186
{
138187
return parent::getUser();
139188
}
189+
190+
public function json($data, $status = 200, $headers = array(), $context = array())
191+
{
192+
return parent::json($data, $status, $headers, $context);
193+
}
140194
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
/**
3+
* Created by mcfedr on 2/1/16 18:22
4+
*/
5+
6+
7+
namespace Symfony\Bundle\FrameworkBundle\Tests\Response;
8+
9+
10+
use Symfony\Bundle\FrameworkBundle\Response\JsonSerializedResponse;
11+
use Symfony\Component\HttpFoundation\JsonResponse;
12+
use Symfony\Component\Serializer\SerializerInterface;
13+
14+
class JsonSerializedResponseTest extends \PHPUnit_Framework_TestCase
15+
{
16+
public function testJsonSerializedResponse()
17+
{
18+
$object = array(
19+
'object' => 'object'
20+
);
21+
22+
$serializer = $this->getMock(SerializerInterface::class);
23+
$serializer
24+
->expects($this->once())
25+
->method('serialize')
26+
->with($object, 'json', array(
27+
'some_context' => 'some_context',
28+
'json_encode_options' => 15 //Default json encoding options from JsonResponse
29+
))
30+
->will($this->returnValue('[]'));
31+
32+
$response = new JsonSerializedResponse($object, $serializer, 200, array(), array(
33+
'some_context' => 'some_context'
34+
));
35+
$this->assertEquals('[]', $response->getContent());
36+
}
37+
}

0 commit comments

Comments
 (0)