add JSONP support to JsonResponse

This commit is contained in:
Toni Uebernickel 2012-03-19 18:27:08 +01:00
parent 05c523a7de
commit 678822459b
2 changed files with 24 additions and 5 deletions

View File

@ -24,26 +24,37 @@ class JsonResponse extends Response
* @param mixed $data The response data
* @param integer $status The response status code
* @param array $headers An array of response headers
* @param string $jsonp A JSONP callback name
*/
public function __construct($data = array(), $status = 200, $headers = array())
public function __construct($data = array(), $status = 200, $headers = array(), $jsonp = '')
{
// root should be JSON object, not array
if (is_array($data) && 0 === count($data)) {
$data = new \ArrayObject();
}
$content = json_encode($data);
$contentType = 'application/json';
if (!empty($jsonp)) {
$content = sprintf('%s(%s);', $jsonp, $content);
// Not using application/javascript for compatibility reasons with older browsers.
$contentType = 'text/javascript';
}
parent::__construct(
json_encode($data),
$content,
$status,
array_merge(array('Content-Type' => 'application/json'), $headers)
array_merge(array('Content-Type' => $contentType), $headers)
);
}
/**
* {@inheritDoc}
*
* @param string $jsonp A JSONP callback name.
*/
static public function create($data = array(), $status = 200, $headers = array())
static public function create($data = array(), $status = 200, $headers = array(), $jsonp = '')
{
return new static($data, $status, $headers);
return new static($data, $status, $headers, $jsonp = '');
}
}

View File

@ -86,4 +86,12 @@ class JsonResponseTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('{"foo":"bar"}', $response->getContent());
$this->assertEquals(204, $response->getStatusCode());
}
public function testJsonp()
{
$response = new JsonResponse(array('foo' => 'bar'), 200, array(), 'callback');
$this->assertEquals('callback({"foo":"bar"});', $response->getContent());
$this->assertEquals('text/javascript', $response->headers->get('Content-Type'));
}
}