JsonableBehavior.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. * @var array
  35. */
  36. public $_defaultSettings = array(
  37. 'fields' => array(), # empty => autodetect - 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. */
  66. public function afterFind(Model $Model, $results, $primary) {
  67. $results = $this->decodeItems($Model, $results);
  68. return $results;
  69. }
  70. /**
  71. * Decodes the fields of an array (if the value itself was encoded)
  72. *
  73. * @param array $arr
  74. * @return array
  75. */
  76. public function decodeItems(Model $Model, $arr) {
  77. foreach ($arr as $akey => $val) {
  78. if (!isset($val[$Model->alias])) {
  79. return $arr;
  80. }
  81. $fields = $this->settings[$Model->alias]['fields'];
  82. foreach ($val[$Model->alias] as $key => $v) {
  83. if (empty($fields) && !is_array($v) || !in_array($key, $fields)) {
  84. continue;
  85. }
  86. if ($this->isEncoded($Model, $v)) {
  87. if (!empty($this->settings[$Model->alias]['map'])) {
  88. $keys = array_keys($this->settings[$Model->alias]['fields'], $key);
  89. if (!empty($keys)) {
  90. $key = $this->settings[$Model->alias]['map'][array_shift($keys)];
  91. }
  92. }
  93. $arr[$akey][$Model->alias][$key] = $this->decoded;
  94. }
  95. }
  96. }
  97. return $arr;
  98. }
  99. /**
  100. * Saves all fields that do not belong to the current Model into 'with' helper model.
  101. *
  102. * @param object $Model
  103. * @return boolean Success
  104. */
  105. public function beforeSave(Model $Model) {
  106. $data = $Model->data[$Model->alias];
  107. $usedFields = $this->settings[$Model->alias]['fields'];
  108. $mappedFields = $this->settings[$Model->alias]['map'];
  109. if (empty($mappedFields)) {
  110. $mappedFields = $usedFields;
  111. }
  112. $fields = array();
  113. foreach ($mappedFields as $index => $map) {
  114. if (empty($map) || $map == $usedFields[$index]) {
  115. $fields[$usedFields[$index]] = $usedFields[$index];
  116. continue;
  117. }
  118. $fields[$map] = $usedFields[$index];
  119. }
  120. foreach ($data as $key => $val) {
  121. if (!empty($fields) && !array_key_exists($key, $fields)) {
  122. continue;
  123. }
  124. if (!empty($fields)) {
  125. $key = $fields[$key];
  126. }
  127. if (!empty($this->settings[$Model->alias]['fields']) || is_array($val)) {
  128. $Model->data[$Model->alias][$key] = $this->_encode($Model, $val);
  129. }
  130. }
  131. return true;
  132. }
  133. /**
  134. * JsonableBehavior::_encode()
  135. *
  136. * @param Model $Model
  137. * @param mixed $val
  138. * @return string
  139. */
  140. public function _encode(Model $Model, $val) {
  141. if (!empty($this->settings[$Model->alias]['fields'])) {
  142. if ($this->settings[$Model->alias]['input'] === 'param') {
  143. $val = $this->_fromParam($Model, $val);
  144. } elseif ($this->settings[$Model->alias]['input'] === 'list') {
  145. $val = $this->_fromList($Model, $val);
  146. if ($this->settings[$Model->alias]['unique']) {
  147. $val = array_unique($val);
  148. }
  149. if ($this->settings[$Model->alias]['sort']) {
  150. sort($val);
  151. }
  152. }
  153. }
  154. if (is_array($val)) {
  155. $val = json_encode($val);
  156. }
  157. return $val;
  158. }
  159. /**
  160. * fields are absolutely necessary to function properly!
  161. *
  162. * @param Model $Model
  163. * @param mixed $val
  164. * @return mixed
  165. * 2011-06-18 ms
  166. */
  167. public function _decode(Model $Model, $val) {
  168. $decoded = json_decode($val);
  169. if ($decoded === false) {
  170. return false;
  171. }
  172. $decoded = (array)$decoded;
  173. if ($this->settings[$Model->alias]['output'] === 'param') {
  174. $decoded = $this->_toParam($Model, $decoded);
  175. } elseif ($this->settings[$Model->alias]['output'] === 'list') {
  176. $decoded = $this->_toList($Model, $decoded);
  177. }
  178. return $decoded;
  179. }
  180. /**
  181. * array() => param1:value1|param2:value2|...
  182. */
  183. public function _toParam(Model $Model, $val) {
  184. $res = array();
  185. foreach ($val as $key => $v) {
  186. $res[] = $key.$this->settings[$Model->alias]['keyValueSeparator'].$v;
  187. }
  188. return implode($this->settings[$Model->alias]['separator'], $res);
  189. }
  190. public function _fromParam(Model $Model, $val) {
  191. $leftBound = $this->settings[$Model->alias]['leftBound'];
  192. $rightBound = $this->settings[$Model->alias]['rightBound'];
  193. $separator = $this->settings[$Model->alias]['separator'];
  194. $res = array();
  195. $pieces = String::tokenize($val, $separator, $leftBound, $rightBound);
  196. foreach ($pieces as $piece) {
  197. $subpieces = String::tokenize($piece, $this->settings[$Model->alias]['keyValueSeparator'], $leftBound, $rightBound);
  198. if (count($subpieces) < 2) {
  199. continue;
  200. }
  201. $res[$subpieces[0]] = $subpieces[1];
  202. }
  203. return $res;
  204. }
  205. /**
  206. * array() => value1|value2|value3|...
  207. */
  208. public function _toList(Model $Model, $val) {
  209. return implode($this->settings[$Model->alias]['separator'], $val);
  210. }
  211. public function _fromList(Model $Model, $val) {
  212. extract($this->settings[$Model->alias]);
  213. return String::tokenize($val, $separator, $leftBound, $rightBound);
  214. }
  215. /**
  216. * Checks if string is encoded array/object
  217. *
  218. * @param string string to check
  219. * @return boolean
  220. */
  221. public function isEncoded(Model $Model, $str) {
  222. $this->decoded = $this->_decode($Model, $str);
  223. if ($this->decoded !== false) {
  224. return true;
  225. }
  226. return false;
  227. }
  228. }