diff --git a/src/Common/Mvc/View/PrettyPrintJsonListener.php b/src/Common/Mvc/View/PrettyPrintJsonListener.php new file mode 100644 index 0000000..08bcfa7 --- /dev/null +++ b/src/Common/Mvc/View/PrettyPrintJsonListener.php @@ -0,0 +1,99 @@ + + * @copyright 2014 Jurian Sluiman. + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @link http://soflomo.com + */ + +namespace Soflomo\Common\Mvc\View; + +use Zend\Mvc\MvcEvent; +use Zend\Json\Json; + +/** + * Pretty-Print JSON responses + * + * Attach this listener to the MvcEvent::EVENT_FINISH event to + * modify the reponse. The listener will check whether the type + * of the response is application/json. If so, a requets header + * X-Pretty-Json must be send by the client. If both are true, + * the response will be modified to pretty print the JSON string. + * + * Usage: + * + * public function onBootstrap(MvcEvent $e) + * { + * $app = $e->getApplication(); + * $em = $app->getEventManager(); + * + * $listener = new PrettyPrintJsonListener; + * $em->attach(MvcEvent::EVENT_FINISH, $listener); + * } + * + */ +class PrettyPrintJsonListener +{ + /** + * Invoked by event manager + * + * @param MvcEvent $e + * @return void + */ + public function __invoke(MvcEvent $e) + { + $response = $e->getResponse(); + $headers = $response->getHeaders(); + if (!$headers->has('Content-Type')) { + return; + } + + $contentType = $headers->get('Content-Type'); + if (false !== strpos('application/json', $contentType->getFieldValue())) { + return; + } + + $request = $e->getRequest(); + $headers = $request->getHeaders(); + if (!$headers->has('X-Pretty-Json')) { + return; + } + + $body = $response->getContent(); + $body = Json::prettyPrint($body, array('indent' => ' ')); + $body = $body . "\n"; + $response->setContent($body); + } +} \ No newline at end of file