1<?php 2/** 3 * Zend Framework (http://framework.zend.com/) 4 * 5 * @link http://github.com/zendframework/zf2 for the canonical source repository 6 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) 7 * @license http://framework.zend.com/license/new-bsd New BSD License 8 */ 9 10namespace Zend\View\Model; 11 12use Traversable; 13use Zend\Json\Json; 14use Zend\Stdlib\ArrayUtils; 15 16class JsonModel extends ViewModel 17{ 18 /** 19 * JSON probably won't need to be captured into a 20 * a parent container by default. 21 * 22 * @var string 23 */ 24 protected $captureTo = null; 25 26 /** 27 * JSONP callback (if set, wraps the return in a function call) 28 * 29 * @var string 30 */ 31 protected $jsonpCallback = null; 32 33 /** 34 * JSON is usually terminal 35 * 36 * @var bool 37 */ 38 protected $terminate = true; 39 40 /** 41 * Set the JSONP callback function name 42 * 43 * @param string $callback 44 * @return JsonModel 45 */ 46 public function setJsonpCallback($callback) 47 { 48 $this->jsonpCallback = $callback; 49 return $this; 50 } 51 52 /** 53 * Serialize to JSON 54 * 55 * @return string 56 */ 57 public function serialize() 58 { 59 $variables = $this->getVariables(); 60 if ($variables instanceof Traversable) { 61 $variables = ArrayUtils::iteratorToArray($variables); 62 } 63 64 $options = array( 65 'prettyPrint' => $this->getOption('prettyPrint'), 66 ); 67 68 if (null !== $this->jsonpCallback) { 69 return $this->jsonpCallback.'('.Json::encode($variables, false, $options).');'; 70 } 71 return Json::encode($variables, false, $options); 72 } 73} 74