3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\View\Strategy
;
12 use Zend\EventManager\AbstractListenerAggregate
;
13 use Zend\EventManager\EventManagerInterface
;
14 use Zend\Http\Request
as HttpRequest
;
16 use Zend\View\Renderer\JsonRenderer
;
17 use Zend\View\ViewEvent
;
19 class JsonStrategy
extends AbstractListenerAggregate
22 * Character set for associated content-type
26 protected $charset = 'utf-8';
29 * Multibyte character sets that will trigger a binary content-transfer-encoding
33 protected $multibyteCharsets = array(
46 * @param JsonRenderer $renderer
48 public function __construct(JsonRenderer
$renderer)
50 $this->renderer
= $renderer;
56 public function attach(EventManagerInterface
$events, $priority = 1)
58 $this->listeners
[] = $events->attach(ViewEvent
::EVENT_RENDERER
, array($this, 'selectRenderer'), $priority);
59 $this->listeners
[] = $events->attach(ViewEvent
::EVENT_RESPONSE
, array($this, 'injectResponse'), $priority);
63 * Set the content-type character set
65 * @param string $charset
66 * @return JsonStrategy
68 public function setCharset($charset)
70 $this->charset
= (string) $charset;
75 * Retrieve the current character set
79 public function getCharset()
81 return $this->charset
;
85 * Detect if we should use the JsonRenderer based on model type and/or
89 * @return null|JsonRenderer
91 public function selectRenderer(ViewEvent
$e)
93 $model = $e->getModel();
95 if (!$model instanceof Model\JsonModel
) {
96 // no JsonModel; do nothing
101 return $this->renderer
;
105 * Inject the response with the JSON payload and appropriate Content-Type header
107 * @param ViewEvent $e
110 public function injectResponse(ViewEvent
$e)
112 $renderer = $e->getRenderer();
113 if ($renderer !== $this->renderer
) {
114 // Discovered renderer is not ours; do nothing
118 $result = $e->getResult();
119 if (!is_string($result)) {
120 // We don't have a string, and thus, no JSON
125 $response = $e->getResponse();
126 $response->setContent($result);
127 $headers = $response->getHeaders();
129 if ($this->renderer
->hasJsonpCallback()) {
130 $contentType = 'application/javascript';
132 $contentType = 'application/json';
135 $contentType .= '; charset=' . $this->charset
;
136 $headers->addHeaderLine('content-type', $contentType);
138 if (in_array(strtoupper($this->charset
), $this->multibyteCharsets
)) {
139 $headers->addHeaderLine('content-transfer-encoding', 'BINARY');