JsonableBehavior.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. *
  25. * Also automatically cleans lists and works with custom separators etc
  26. *
  27. * @link http://www.dereuromark.de/2011/07/05/introducing-two-cakephp-behaviors/
  28. * 2011-07-04 ms
  29. */
  30. class JsonableBehavior extends ModelBehavior {
  31. public $decoded = null;
  32. /**
  33. * //TODO: json input/ouput directly, clean
  34. * @access protected
  35. */
  36. public $_defaultSettings = array(
  37. 'fields' => array(), # empty => only works with array!!!
  38. 'input' => 'array', # json, array, param, list (param/list only works with specific fields)
  39. 'output' => 'array', # json, array, param, list (param/list only works with specific fields)
  40. 'separator' => '|', # only for param or list
  41. 'keyValueSeparator' => ':', # only for param
  42. 'leftBound' => '{', # only for list
  43. 'rightBound' => '}', # only for list
  44. 'clean' => true, # only for param or list (autoclean values on insert)
  45. 'sort' => false, # only for list
  46. 'unique' => true, # only for list (autoclean values on insert),
  47. 'map' => array(), # map on a different DB field
  48. );
  49. public function setup(Model $Model, $config = array()) {
  50. $this->settings[$Model->alias] = Set::merge($this->_defaultSettings, $config);
  51. //extract ($this->settings[$Model->alias]);
  52. if (!is_array($this->settings[$Model->alias]['fields'])) {
  53. $this->settings[$Model->alias]['fields'] = (array)$this->settings[$Model->alias]['fields'];
  54. }
  55. if (!is_array($this->settings[$Model->alias]['map'])) {
  56. $this->settings[$Model->alias]['map'] = (array)$this->settings[$Model->alias]['map'];
  57. }
  58. }
  59. /**
  60. * Decodes the fields
  61. *
  62. * @param object $Model
  63. * @param array $results
  64. * @return array
  65. * @access public
  66. */
  67. public function afterFind(Model $Model, $results, $primary) {
  68. $results = $this->decodeItems($Model, $results);
  69. return $results;
  70. }
  71. /**
  72. * Decodes the fields of an array (if the value itself was encoded)
  73. *
  74. * @param array $arr
  75. * @return array
  76. * @access public
  77. */
  78. public function decodeItems(Model $Model, $arr) {
  79. foreach ($arr as $akey => $val) {
  80. if (!isset($val[$Model->alias])) {
  81. return $arr;
  82. }
  83. $fields = $this->settings[$Model->alias]['fields'];
  84. foreach ($val[$Model->alias] as $key => $v) {
  85. if (empty($fields) && !is_array($v) || !in_array($key, $fields)) {
  86. continue;
  87. }
  88. if ($this->isEncoded($Model, $v)) {
  89. if (!empty($this->settings[$Model->alias]['map'])) {
  90. $keys = array_keys($this->settings[$Model->alias]['fields'], $key);
  91. if (!empty($keys)) {
  92. $key = $this->settings[$Model->alias]['map'][array_shift($keys)];
  93. }
  94. }
  95. $arr[$akey][$Model->alias][$key] = $this->decoded;
  96. }
  97. }
  98. }
  99. return $arr;
  100. }
  101. /**
  102. * Saves all fields that do not belong to the current Model into 'with' helper model.
  103. *
  104. * @param object $Model
  105. * @access public
  106. */
  107. public function beforeSave(Model $Model) {
  108. $data = $Model->data[$Model->alias];
  109. $usedFields = $this->settings[$Model->alias]['fields'];
  110. $mappedFields = $this->settings[$Model->alias]['map'];
  111. if (empty($mappedFields)) {
  112. $mappedFields = $usedFields;
  113. }
  114. $fields = array();
  115. foreach ($mappedFields as $index => $map) {
  116. if (empty($map) || $map == $usedFields[$index]) {
  117. $fields[$usedFields[$index]] = $usedFields[$index];
  118. continue;
  119. }
  120. $fields[$map] = $usedFields[$index];
  121. }
  122. foreach ($data as $key => $val) {
  123. if (!empty($fields) && !array_key_exists($key, $fields)) {
  124. continue;
  125. }
  126. if (!empty($fields)) {
  127. $key = $fields[$key];
  128. }
  129. if (!empty($this->settings[$Model->alias]['fields']) || is_array($val)) {
  130. $Model->data[$Model->alias][$key] = $this->_encode($Model, $val);
  131. }
  132. }
  133. return true;
  134. }
  135. public function _encode(Model $Model, $val) {
  136. if (!empty($this->settings[$Model->alias]['fields'])) {
  137. if ($this->settings[$Model->alias]['input'] === 'param') {
  138. $val = $this->_fromParam($Model, $val);
  139. } elseif ($this->settings[$Model->alias]['input'] === 'list') {
  140. $val = $this->_fromList($Model, $val);
  141. if ($this->settings[$Model->alias]['unique']) {
  142. $val = array_unique($val);
  143. }
  144. if ($this->settings[$Model->alias]['sort']) {
  145. sort($val);
  146. }
  147. }
  148. }
  149. if (is_array($val)) {
  150. $val = json_encode($val);
  151. }
  152. return $val;
  153. }
  154. /**
  155. * fields are absolutely necessary to function properly!
  156. * 2011-06-18 ms
  157. */
  158. public function _decode(Model $Model, $val) {
  159. $decoded = json_decode($val);
  160. if ($decoded === false) {
  161. return false;
  162. }
  163. $decoded = (array)$decoded;
  164. if ($this->settings[$Model->alias]['output'] === 'param') {
  165. $decoded = $this->_toParam($Model, $decoded);
  166. } elseif ($this->settings[$Model->alias]['output'] === 'list') {
  167. $decoded = $this->_toList($Model, $decoded);
  168. }
  169. return $decoded;
  170. }
  171. /**
  172. * array() => param1:value1|param2:value2|...
  173. */
  174. public function _toParam(Model $Model, $val) {
  175. $res = array();
  176. foreach ($val as $key => $v) {
  177. $res[] = $key.$this->settings[$Model->alias]['keyValueSeparator'].$v;
  178. }
  179. return implode($this->settings[$Model->alias]['separator'], $res);
  180. }
  181. public function _fromParam(Model $Model, $val) {
  182. $leftBound = $this->settings[$Model->alias]['leftBound'];
  183. $rightBound = $this->settings[$Model->alias]['rightBound'];
  184. $separator = $this->settings[$Model->alias]['separator'];
  185. $res = array();
  186. $pieces = String::tokenize($val, $separator, $leftBound, $rightBound);
  187. foreach ($pieces as $piece) {
  188. $subpieces = String::tokenize($piece, $this->settings[$Model->alias]['keyValueSeparator'], $leftBound, $rightBound);
  189. if (count($subpieces) < 2) {
  190. continue;
  191. }
  192. $res[$subpieces[0]] = $subpieces[1];
  193. }
  194. return $res;
  195. }
  196. /**
  197. * array() => value1|value2|value3|...
  198. */
  199. public function _toList(Model $Model, $val) {
  200. return implode($this->settings[$Model->alias]['separator'], $val);
  201. }
  202. public function _fromList(Model $Model, $val) {
  203. extract($this->settings[$Model->alias]);
  204. return String::tokenize($val, $separator, $leftBound, $rightBound);
  205. }
  206. /**
  207. * Checks if string is encoded array/object
  208. *
  209. * @param string string to check
  210. * @access public
  211. * @return boolean
  212. */
  213. public function isEncoded(Model $Model, $str) {
  214. $this->decoded = $this->_decode($Model, $str);
  215. if ($this->decoded !== false) {
  216. return true;
  217. }
  218. return false;
  219. }
  220. }