/lib/Cake/View/JsonView.php

https://gitlab.com/grlopez90/servipro · PHP · 175 lines · 71 code · 13 blank · 91 comment · 20 complexity · a6b72cae17715697773062d8d279930a MD5 · raw file

  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. App::uses('View', 'View');
  15. /**
  16. * A view class that is used for JSON responses.
  17. *
  18. * By setting the '_serialize' key in your controller, you can specify a view variable
  19. * that should be serialized to JSON and used as the response for the request.
  20. * This allows you to omit views and layouts if you just need to emit a single view
  21. * variable as the JSON response.
  22. *
  23. * In your controller, you could do the following:
  24. *
  25. * `$this->set(array('posts' => $posts, '_serialize' => 'posts'));`
  26. *
  27. * When the view is rendered, the `$posts` view variable will be serialized
  28. * into JSON.
  29. *
  30. * You can also define `'_serialize'` as an array. This will create a top level object containing
  31. * all the named view variables:
  32. *
  33. * ```
  34. * $this->set(compact('posts', 'users', 'stuff'));
  35. * $this->set('_serialize', array('posts', 'users'));
  36. * ```
  37. *
  38. * The above would generate a JSON object that looks like:
  39. *
  40. * `{"posts": [...], "users": [...]}`
  41. *
  42. * If you don't use the `_serialize` key, you will need a view. You can use extended
  43. * views to provide layout-like functionality.
  44. *
  45. * You can also enable JSONP support by setting parameter `_jsonp` to true or a string to specify
  46. * custom query string paramater name which will contain the callback function name.
  47. *
  48. * @package Cake.View
  49. * @since CakePHP(tm) v 2.1.0
  50. */
  51. class JsonView extends View {
  52. /**
  53. * JSON views are always located in the 'json' sub directory for
  54. * controllers' views.
  55. *
  56. * @var string
  57. */
  58. public $subDir = 'json';
  59. /**
  60. * Constructor
  61. *
  62. * @param Controller $controller Controller instance.
  63. */
  64. public function __construct(Controller $controller = null) {
  65. parent::__construct($controller);
  66. if (isset($controller->response) && $controller->response instanceof CakeResponse) {
  67. $controller->response->type('json');
  68. }
  69. }
  70. /**
  71. * Skip loading helpers if this is a _serialize based view.
  72. *
  73. * @return void
  74. */
  75. public function loadHelpers() {
  76. if (isset($this->viewVars['_serialize'])) {
  77. return;
  78. }
  79. parent::loadHelpers();
  80. }
  81. /**
  82. * Render a JSON view.
  83. *
  84. * ### Special parameters
  85. * `_serialize` To convert a set of view variables into a JSON response.
  86. * Its value can be a string for single variable name or array for multiple names.
  87. * You can omit the`_serialize` parameter, and use a normal view + layout as well.
  88. * `_jsonp` Enables JSONP support and wraps response in callback function provided in query string.
  89. * - Setting it to true enables the default query string parameter "callback".
  90. * - Setting it to a string value, uses the provided query string parameter for finding the
  91. * JSONP callback name.
  92. *
  93. * @param string $view The view being rendered.
  94. * @param string $layout The layout being rendered.
  95. * @return string The rendered view.
  96. */
  97. public function render($view = null, $layout = null) {
  98. $return = null;
  99. if (isset($this->viewVars['_serialize'])) {
  100. $return = $this->_serialize($this->viewVars['_serialize']);
  101. } elseif ($view !== false && $this->_getViewFileName($view)) {
  102. $return = parent::render($view, false);
  103. }
  104. if (!empty($this->viewVars['_jsonp'])) {
  105. $jsonpParam = $this->viewVars['_jsonp'];
  106. if ($this->viewVars['_jsonp'] === true) {
  107. $jsonpParam = 'callback';
  108. }
  109. if (isset($this->request->query[$jsonpParam])) {
  110. $return = sprintf('%s(%s)', h($this->request->query[$jsonpParam]), $return);
  111. $this->response->type('js');
  112. }
  113. }
  114. return $return;
  115. }
  116. /**
  117. * Serialize view vars
  118. *
  119. * ### Special parameters
  120. * `_jsonOptions` You can set custom options for json_encode() this way,
  121. * e.g. `JSON_HEX_TAG | JSON_HEX_APOS`.
  122. *
  123. * @param array $serialize The viewVars that need to be serialized
  124. * @throws CakeException
  125. * @return string The serialized data
  126. */
  127. protected function _serialize($serialize) {
  128. if (is_array($serialize)) {
  129. $data = array();
  130. foreach ($serialize as $alias => $key) {
  131. if (is_numeric($alias)) {
  132. $alias = $key;
  133. }
  134. if (array_key_exists($key, $this->viewVars)) {
  135. $data[$alias] = $this->viewVars[$key];
  136. }
  137. }
  138. $data = !empty($data) ? $data : null;
  139. } else {
  140. $data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null;
  141. }
  142. $jsonOptions = 0;
  143. if (isset($this->viewVars['_jsonOptions'])) {
  144. if ($this->viewVars['_jsonOptions'] === false) {
  145. $jsonOptions = 0;
  146. } else {
  147. $jsonOptions = $this->viewVars['_jsonOptions'];
  148. }
  149. }
  150. if (version_compare(PHP_VERSION, '5.4.0', '>=') && Configure::read('debug')) {
  151. $jsonOptions = $jsonOptions | JSON_PRETTY_PRINT;
  152. }
  153. $json = json_encode($data, $jsonOptions);
  154. if (function_exists('json_last_error') && json_last_error() !== JSON_ERROR_NONE) {
  155. throw new CakeException(json_last_error_msg());
  156. }
  157. if ($json === false) {
  158. throw new CakeException('Failed to parse JSON');
  159. }
  160. return $json;
  161. }
  162. }