JsonableBehavior.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. <?php
  2. /**
  3. * Copyright 2011, PJ Hile (http://www.pjhile.com)
  4. *
  5. * Licensed under The MIT License
  6. * Redistributions of files must retain the above copyright notice.
  7. *
  8. * @version 0.1
  9. * @license http://www.opensource.org/licenses/mit-license.php The MIT License
  10. */
  11. App::uses('ModelBehavior', 'Model');
  12. /**
  13. * A behavior that will json_encode (and json_decode) fields if they contain an array or specific pattern.
  14. *
  15. * Requres: PHP 5 >= 5.2.0 or PECL json >= 1.2.0
  16. *
  17. * This is a port of the Serializeable behavior by Matsimitsu (http://www.matsimitsu.nl)
  18. * Modified by Mark Scherer (http://www.dereuromark.de)
  19. *
  20. * Now supports different input/output formats:
  21. * - "list" is useful as some kind of pseudo enums or simple lists
  22. * - "params" is useful for multiple key/value pairs
  23. * - can be used to create dynamic forms (and tables)
  24. * Also automatically cleans lists and works with custom separators etc
  25. *
  26. * Tip: If you have other behaviors that might modify the array data prior to saving, better use a higher priority:
  27. * public $actsAs = array('Tools.Jsonable' => array('priority' => 11, ...));
  28. * So that it is run last.
  29. *
  30. * @link http://www.dereuromark.de/2011/07/05/introducing-two-cakephp-behaviors/
  31. */
  32. class JsonableBehavior extends ModelBehavior {
  33. public $decoded = null;
  34. /**
  35. * //TODO: json input/ouput directly, clean
  36. * @var array
  37. */
  38. protected $_defaultConfig = array(
  39. 'fields' => array(), // empty => autodetect - only works with array!
  40. 'input' => 'array', // json, array, param, list (param/list only works with specific fields)
  41. 'output' => 'array', // json, array, param, list (param/list only works with specific fields)
  42. 'separator' => '|', // only for param or list
  43. 'keyValueSeparator' => ':', // only for param
  44. 'leftBound' => '{', // only for list
  45. 'rightBound' => '}', // only for list
  46. 'clean' => true, // only for param or list (autoclean values on insert)
  47. 'sort' => false, // only for list
  48. 'unique' => true, // only for list (autoclean values on insert),
  49. 'map' => array(), // map on a different DB field
  50. 'encodeParams' => array( // params for json_encode
  51. 'options' => 0,
  52. 'depth' => 512,
  53. ),
  54. 'decodeParams' => array( // params for json_decode
  55. 'assoc' => false, // useful when working with multidimensional arrays
  56. 'depth' => 512,
  57. 'options' => 0
  58. )
  59. );
  60. public function setup(Model $Model, $config = array()) {
  61. $this->settings[$Model->alias] = Hash::merge($this->_defaultConfig, $config);
  62. //extract($this->settings[$Model->alias]);
  63. if (!is_array($this->settings[$Model->alias]['fields'])) {
  64. $this->settings[$Model->alias]['fields'] = (array)$this->settings[$Model->alias]['fields'];
  65. }
  66. if (!is_array($this->settings[$Model->alias]['map'])) {
  67. $this->settings[$Model->alias]['map'] = (array)$this->settings[$Model->alias]['map'];
  68. }
  69. }
  70. /**
  71. * Decodes the fields
  72. *
  73. * @param object $Model
  74. * @param array $results
  75. * @return array
  76. */
  77. public function afterFind(Model $Model, $results, $primary = false) {
  78. $results = $this->decodeItems($Model, $results);
  79. return $results;
  80. }
  81. /**
  82. * Decodes the fields of an array (if the value itself was encoded)
  83. *
  84. * @param array $arr
  85. * @return array
  86. */
  87. public function decodeItems(Model $Model, $arr) {
  88. foreach ($arr as $akey => $val) {
  89. if (!isset($val[$Model->alias])) {
  90. return $arr;
  91. }
  92. $fields = $this->settings[$Model->alias]['fields'];
  93. foreach ($val[$Model->alias] as $key => $v) {
  94. if (empty($fields) && !is_array($v) || !in_array($key, $fields)) {
  95. continue;
  96. }
  97. if ($this->isEncoded($Model, $v)) {
  98. if (!empty($this->settings[$Model->alias]['map'])) {
  99. $keys = array_keys($this->settings[$Model->alias]['fields'], $key);
  100. if (!empty($keys)) {
  101. $key = $this->settings[$Model->alias]['map'][array_shift($keys)];
  102. }
  103. }
  104. $arr[$akey][$Model->alias][$key] = $this->decoded;
  105. }
  106. }
  107. }
  108. return $arr;
  109. }
  110. /**
  111. * Saves all fields that do not belong to the current Model into 'with' helper model.
  112. *
  113. * @param object $Model
  114. * @return bool Success
  115. */
  116. public function beforeSave(Model $Model, $options = array()) {
  117. $data = $Model->data[$Model->alias];
  118. $usedFields = $this->settings[$Model->alias]['fields'];
  119. $mappedFields = $this->settings[$Model->alias]['map'];
  120. if (empty($mappedFields)) {
  121. $mappedFields = $usedFields;
  122. }
  123. $fields = array();
  124. foreach ($mappedFields as $index => $map) {
  125. if (empty($map) || $map == $usedFields[$index]) {
  126. $fields[$usedFields[$index]] = $usedFields[$index];
  127. continue;
  128. }
  129. $fields[$map] = $usedFields[$index];
  130. }
  131. foreach ($data as $key => $val) {
  132. if (!empty($fields) && !array_key_exists($key, $fields)) {
  133. continue;
  134. }
  135. if (!empty($fields)) {
  136. $key = $fields[$key];
  137. }
  138. if (!empty($this->settings[$Model->alias]['fields']) || is_array($val)) {
  139. $Model->data[$Model->alias][$key] = $this->_encode($Model, $val);
  140. }
  141. }
  142. return true;
  143. }
  144. /**
  145. * JsonableBehavior::_encode()
  146. *
  147. * @param Model $Model
  148. * @param mixed $val
  149. * @return string
  150. */
  151. public function _encode(Model $Model, $val) {
  152. if (!empty($this->settings[$Model->alias]['fields'])) {
  153. if ($this->settings[$Model->alias]['input'] === 'param') {
  154. $val = $this->_fromParam($Model, $val);
  155. } elseif ($this->settings[$Model->alias]['input'] === 'list') {
  156. $val = $this->_fromList($Model, $val);
  157. if ($this->settings[$Model->alias]['unique']) {
  158. $val = array_unique($val);
  159. }
  160. if ($this->settings[$Model->alias]['sort']) {
  161. sort($val);
  162. }
  163. }
  164. }
  165. if (is_array($val)) {
  166. // $depth param added in php 5.5
  167. if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
  168. $val = json_encode($val, $this->settings[$Model->alias]['encodeParams']['options'], $this->settings[$Model->alias]['encodeParams']['depth']);
  169. } else {
  170. $val = json_encode($val, $this->settings[$Model->alias]['encodeParams']['options']);
  171. }
  172. }
  173. return $val;
  174. }
  175. /**
  176. * Fields are absolutely necessary to function properly!
  177. *
  178. * @param Model $Model
  179. * @param mixed $val
  180. * @return mixed
  181. */
  182. public function _decode(Model $Model, $val) {
  183. // $options param added in php 5.4
  184. if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
  185. $decoded = json_decode($val, $this->settings[$Model->alias]['decodeParams']['assoc'], $this->settings[$Model->alias]['decodeParams']['depth'], $this->settings[$Model->alias]['decodeParams']['options']);
  186. } else {
  187. $decoded = json_decode($val, $this->settings[$Model->alias]['decodeParams']['assoc'], $this->settings[$Model->alias]['decodeParams']['depth']);
  188. }
  189. if ($decoded === false) {
  190. return false;
  191. }
  192. $decoded = (array)$decoded;
  193. if ($this->settings[$Model->alias]['output'] === 'param') {
  194. $decoded = $this->_toParam($Model, $decoded);
  195. } elseif ($this->settings[$Model->alias]['output'] === 'list') {
  196. $decoded = $this->_toList($Model, $decoded);
  197. }
  198. return $decoded;
  199. }
  200. /**
  201. * array() => param1:value1|param2:value2|...
  202. */
  203. public function _toParam(Model $Model, $val) {
  204. $res = array();
  205. foreach ($val as $key => $v) {
  206. $res[] = $key . $this->settings[$Model->alias]['keyValueSeparator'] . $v;
  207. }
  208. return implode($this->settings[$Model->alias]['separator'], $res);
  209. }
  210. public function _fromParam(Model $Model, $val) {
  211. $leftBound = $this->settings[$Model->alias]['leftBound'];
  212. $rightBound = $this->settings[$Model->alias]['rightBound'];
  213. $separator = $this->settings[$Model->alias]['separator'];
  214. $res = array();
  215. $pieces = String::tokenize($val, $separator, $leftBound, $rightBound);
  216. foreach ($pieces as $piece) {
  217. $subpieces = String::tokenize($piece, $this->settings[$Model->alias]['keyValueSeparator'], $leftBound, $rightBound);
  218. if (count($subpieces) < 2) {
  219. continue;
  220. }
  221. $res[$subpieces[0]] = $subpieces[1];
  222. }
  223. return $res;
  224. }
  225. /**
  226. * array() => value1|value2|value3|...
  227. */
  228. public function _toList(Model $Model, $val) {
  229. return implode($this->settings[$Model->alias]['separator'], $val);
  230. }
  231. public function _fromList(Model $Model, $val) {
  232. extract($this->settings[$Model->alias]);
  233. return String::tokenize($val, $separator, $leftBound, $rightBound);
  234. }
  235. /**
  236. * Checks if string is encoded array/object
  237. *
  238. * @param string string to check
  239. * @return bool
  240. */
  241. public function isEncoded(Model $Model, $str) {
  242. $this->decoded = $this->_decode($Model, $str);
  243. if ($this->decoded !== false) {
  244. return true;
  245. }
  246. return false;
  247. }
  248. }