BitmaskedBehavior.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. <?php
  2. App::uses('ModelBehavior', 'Model');
  3. /**
  4. * BitmaskedBehavior
  5. *
  6. * An implementation of bitwise masks for row-level operations.
  7. * You can submit/register flags in different ways. The easiest way is using a static model function.
  8. * It should contain the bits like so (starting with 1):
  9. * 1 => w, 2 => x, 4 => y, 8 => z, ... (bits as keys - names as values)
  10. * The order doesn't matter, as long as no bit is used twice.
  11. *
  12. * The theoretical limit for a 64-bit integer would be 64 bits (2^64).
  13. * But if you actually seem to need more than a hand full you
  14. * obviously do something wrong and should better use a joined table etc.
  15. *
  16. * @version 1.1
  17. * @author Mark Scherer
  18. * @cake 2.x
  19. * @license MIT
  20. * @uses ModelBehavior
  21. * @link http://www.dereuromark.de/2012/02/26/bitmasked-using-bitmasks-in-cakephp/
  22. * 2012-02-24 ms
  23. */
  24. class BitmaskedBehavior extends ModelBehavior {
  25. /**
  26. * Settings defaults
  27. *
  28. * @var array
  29. */
  30. protected $_defaults = array(
  31. 'field' => 'status',
  32. 'mappedField' => null, // NULL = same as above
  33. 'bits' => null,
  34. 'before' => 'validate', // on: save or validate
  35. 'defaultValue' => null, // NULL = auto (use empty string to trigger "notEmpty" rule for "default NOT NULL" db fields)
  36. );
  37. /**
  38. * Behavior configuration
  39. *
  40. * @param Model $Model
  41. * @param array $config
  42. * @return void
  43. */
  44. public function setup(Model $Model, $config = array()) {
  45. $config = array_merge($this->_defaults, $config);
  46. if (empty($config['bits'])) {
  47. $config['bits'] = Inflector::pluralize($config['field']);
  48. }
  49. if (is_callable($config['bits'])) {
  50. $config['bits'] = call_user_func($config['bits']);
  51. } elseif (is_string($config['bits']) && method_exists($Model, $config['bits'])) {
  52. $config['bits'] = $Model->{$config['bits']}();
  53. } elseif (!is_array($config['bits'])) {
  54. $config['bits'] = false;
  55. }
  56. if (empty($config['bits'])) {
  57. throw new InternalErrorException('Bits not found');
  58. }
  59. ksort($config['bits'], SORT_NUMERIC);
  60. $this->settings[$Model->alias] = $config;
  61. }
  62. /**
  63. * @return array
  64. */
  65. public function beforeFind(Model $Model, $query) {
  66. $field = $this->settings[$Model->alias]['field'];
  67. if (isset($query['conditions']) && is_array($query['conditions'])) {
  68. $query['conditions'] = $this->encodeBitmaskConditions($Model, $query['conditions']);
  69. }
  70. return $query;
  71. }
  72. /**
  73. * @return array
  74. */
  75. public function afterFind(Model $Model, $results, $primary) {
  76. $field = $this->settings[$Model->alias]['field'];
  77. if (!($mappedField = $this->settings[$Model->alias]['mappedField'])) {
  78. $mappedField = $field;
  79. }
  80. foreach ($results as $key => $result) {
  81. if (isset($result[$Model->alias][$field])) {
  82. $results[$key][$Model->alias][$mappedField] = $this->decodeBitmask($Model, $result[$Model->alias][$field]);
  83. }
  84. }
  85. return $results;
  86. }
  87. /**
  88. * @return boolean Success
  89. */
  90. public function beforeValidate(Model $Model) {
  91. if ($this->settings[$Model->alias]['before'] !== 'validate') {
  92. return true;
  93. }
  94. $this->encodeBitmaskData($Model);
  95. return true;
  96. }
  97. /**
  98. * @return boolean Success
  99. */
  100. public function beforeSave(Model $Model) {
  101. if ($this->settings[$Model->alias]['before'] !== 'save') {
  102. return true;
  103. }
  104. $this->encodeBitmaskData($Model);
  105. return true;
  106. }
  107. /**
  108. * @param int $bitmask
  109. * @return array $bitmaskArray
  110. * from DB to APP
  111. */
  112. public function decodeBitmask(Model $Model, $value) {
  113. $res = array();
  114. $value = (int)$value;
  115. foreach ($this->settings[$Model->alias]['bits'] as $key => $val) {
  116. $val = (($value & $key) !== 0) ? true : false;
  117. if ($val) {
  118. $res[] = $key;
  119. }
  120. }
  121. return $res;
  122. }
  123. /**
  124. * @param array $bitmaskArray
  125. * @return int $bitmask
  126. * from APP to DB
  127. */
  128. public function encodeBitmask(Model $Model, $value, $defaultValue = null) {
  129. $res = 0;
  130. if (empty($value)) {
  131. return $defaultValue;
  132. }
  133. foreach ((array)$value as $key => $val) {
  134. $res |= (int)$val;
  135. }
  136. if ($res === 0) {
  137. return $defaultValue; // make sure notEmpty validation rule triggers
  138. }
  139. return $res;
  140. }
  141. /**
  142. * @return array $conditions
  143. */
  144. public function encodeBitmaskConditions(Model $Model, $conditions) {
  145. $field = $this->settings[$Model->alias]['field'];
  146. if (!($mappedField = $this->settings[$Model->alias]['mappedField'])) {
  147. $mappedField = $field;
  148. }
  149. foreach ($conditions as $key => $val) {
  150. if ($key === $mappedField) {
  151. $conditions[$field] = $this->encodeBitmask($Model, $val);
  152. if ($field !== $mappedField) {
  153. unset($conditions[$mappedField]);
  154. }
  155. continue;
  156. } elseif ($key === $Model->alias . '.' . $mappedField) {
  157. $conditions[$Model->alias . '.' .$field] = $this->encodeBitmask($Model, $val);
  158. if ($field !== $mappedField) {
  159. unset($conditions[$Model->alias . '.' .$mappedField]);
  160. }
  161. continue;
  162. }
  163. if (!is_array($val)) {
  164. continue;
  165. }
  166. $conditions[$key] = $this->encodeBitmaskConditions($Model, $val);
  167. }
  168. return $conditions;
  169. }
  170. /**
  171. * @return void
  172. */
  173. public function encodeBitmaskData(Model $Model) {
  174. $field = $this->settings[$Model->alias]['field'];
  175. if (!($mappedField = $this->settings[$Model->alias]['mappedField'])) {
  176. $mappedField = $field;
  177. }
  178. $default = null;
  179. $schema = $Model->schema($field);
  180. if ($schema && isset($schema['default'])) {
  181. $default = $schema['default'];
  182. }
  183. if ($this->settings[$Model->alias]['defaultValue'] !== null) {
  184. $default = $this->settings[$Model->alias]['defaultValue'];
  185. }
  186. if (isset($Model->data[$Model->alias][$mappedField])) {
  187. $Model->data[$Model->alias][$field] = $this->encodeBitmask($Model, $Model->data[$Model->alias][$mappedField], $default);
  188. }
  189. if ($field !== $mappedField) {
  190. unset($Model->data[$Model->alias][$mappedField]);
  191. }
  192. }
  193. /**
  194. * @param mixed bits (int, array)
  195. * @return array $sqlSnippet
  196. */
  197. public function isBit(Model $Model, $bits) {
  198. $bits = (array)$bits;
  199. $bitmask = $this->encodeBitmask($Model, $bits);
  200. $field = $this->settings[$Model->alias]['field'];
  201. return array($Model->alias.'.'.$field => $bitmask);
  202. }
  203. /**
  204. * @param mixed bits (int, array)
  205. * @return array $sqlSnippet
  206. */
  207. public function isNotBit(Model $Model, $bits) {
  208. $bits = (array)$bits;
  209. $bitmask = $this->encodeBitmask($Model, $bits);
  210. $field = $this->settings[$Model->alias]['field'];
  211. return array('NOT' => array($Model->alias.'.'.$field => $bitmask));
  212. }
  213. /**
  214. * @param mixed bits (int, array)
  215. * @return array $sqlSnippet
  216. */
  217. public function containsBit(Model $Model, $bits) {
  218. $bits = (array)$bits;
  219. $bitmask = $this->encodeBitmask($Model, $bits);
  220. $field = $this->settings[$Model->alias]['field'];
  221. return array('('.$Model->alias.'.'.$field.' & ? = ?)' => array($bitmask, $bitmask));
  222. }
  223. /**
  224. * @param mixed bits (int, array)
  225. * @return array $sqlSnippet
  226. */
  227. public function containsNotBit(Model $Model, $bits) {
  228. $bits = (array)$bits;
  229. $bitmask = $this->encodeBitmask($Model, $bits);
  230. $field = $this->settings[$Model->alias]['field'];
  231. return array('('.$Model->alias.'.'.$field.' & ? != ?)' => array($bitmask, $bitmask));
  232. }
  233. }