From 5c40369ac912879bdc9758c13df76e93909f9e3e Mon Sep 17 00:00:00 2001 From: Jurian Sluiman Date: Wed, 5 Feb 2014 11:39:05 +0100 Subject: [PATCH] Add listener to print JSON to Pretty Print --- .../Mvc/View/PrettyPrintJsonListener.php | 99 +++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 src/Common/Mvc/View/PrettyPrintJsonListener.php 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