JsonableBehavior.php 6.9 KB

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