BitmaskedBehavior.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. * @link http://www.dereuromark.de/2012/02/26/bitmasked-using-bitmasks-in-cakephp/
  21. */
  22. class BitmaskedBehavior extends ModelBehavior {
  23. /**
  24. * Settings defaults
  25. *
  26. * @var array
  27. */
  28. protected $_defaults = array(
  29. 'field' => 'status',
  30. 'mappedField' => null, // NULL = same as above
  31. 'bits' => null,
  32. 'before' => 'validate', // on: save or validate
  33. 'defaultValue' => null, // NULL = auto (use empty string to trigger "notEmpty" rule for "default NOT NULL" db fields)
  34. );
  35. /**
  36. * Behavior configuration
  37. *
  38. * @param Model $Model
  39. * @param array $config
  40. * @return void
  41. */
  42. public function setup(Model $Model, $config = array()) {
  43. $config = array_merge($this->_defaults, $config);
  44. if (empty($config['bits'])) {
  45. $config['bits'] = Inflector::pluralize($config['field']);
  46. }
  47. if (is_callable($config['bits'])) {
  48. $config['bits'] = call_user_func($config['bits']);
  49. } elseif (is_string($config['bits']) && method_exists($Model, $config['bits'])) {
  50. $config['bits'] = $Model->{$config['bits']}();
  51. } elseif (!is_array($config['bits'])) {
  52. $config['bits'] = false;
  53. }
  54. if (empty($config['bits'])) {
  55. throw new InternalErrorException('Bits not found');
  56. }
  57. ksort($config['bits'], SORT_NUMERIC);
  58. $this->settings[$Model->alias] = $config;
  59. }
  60. /**
  61. * @return array
  62. */
  63. public function beforeFind(Model $Model, $query) {
  64. $field = $this->settings[$Model->alias]['field'];
  65. if (isset($query['conditions']) && is_array($query['conditions'])) {
  66. $query['conditions'] = $this->encodeBitmaskConditions($Model, $query['conditions']);
  67. }
  68. return $query;
  69. }
  70. /**
  71. * @return array
  72. */
  73. public function afterFind(Model $Model, $results, $primary = false) {
  74. $field = $this->settings[$Model->alias]['field'];
  75. if (!($mappedField = $this->settings[$Model->alias]['mappedField'])) {
  76. $mappedField = $field;
  77. }
  78. foreach ($results as $key => $result) {
  79. if (isset($result[$Model->alias][$field])) {
  80. $results[$key][$Model->alias][$mappedField] = $this->decodeBitmask($Model, $result[$Model->alias][$field]);
  81. }
  82. }
  83. return $results;
  84. }
  85. /**
  86. * @return boolean Success
  87. */
  88. public function beforeValidate(Model $Model, $options = array()) {
  89. if ($this->settings[$Model->alias]['before'] !== 'validate') {
  90. return true;
  91. }
  92. $this->encodeBitmaskData($Model);
  93. return true;
  94. }
  95. /**
  96. * @return boolean Success
  97. */
  98. public function beforeSave(Model $Model, $options = array()) {
  99. if ($this->settings[$Model->alias]['before'] !== 'save') {
  100. return true;
  101. }
  102. $this->encodeBitmaskData($Model);
  103. return true;
  104. }
  105. /**
  106. * @param integer $bitmask
  107. * @return array bitmaskArray
  108. * from DB to APP
  109. */
  110. public function decodeBitmask(Model $Model, $value) {
  111. $res = array();
  112. $value = (int)$value;
  113. foreach ($this->settings[$Model->alias]['bits'] as $key => $val) {
  114. $val = (($value & $key) !== 0) ? true : false;
  115. if ($val) {
  116. $res[] = $key;
  117. }
  118. }
  119. return $res;
  120. }
  121. /**
  122. * @param array $bitmaskArray
  123. * @return integer bitmask
  124. * from APP to DB
  125. */
  126. public function encodeBitmask(Model $Model, $value, $defaultValue = null) {
  127. $res = 0;
  128. if (empty($value)) {
  129. return $defaultValue;
  130. }
  131. foreach ((array)$value as $key => $val) {
  132. $res |= (int)$val;
  133. }
  134. if ($res === 0) {
  135. return $defaultValue; // make sure notEmpty validation rule triggers
  136. }
  137. return $res;
  138. }
  139. /**
  140. * @return array conditions
  141. */
  142. public function encodeBitmaskConditions(Model $Model, $conditions) {
  143. $field = $this->settings[$Model->alias]['field'];
  144. if (!($mappedField = $this->settings[$Model->alias]['mappedField'])) {
  145. $mappedField = $field;
  146. }
  147. foreach ($conditions as $key => $val) {
  148. if ($key === $mappedField) {
  149. $conditions[$field] = $this->encodeBitmask($Model, $val);
  150. if ($field !== $mappedField) {
  151. unset($conditions[$mappedField]);
  152. }
  153. continue;
  154. } elseif ($key === $Model->alias . '.' . $mappedField) {
  155. $conditions[$Model->alias . '.' . $field] = $this->encodeBitmask($Model, $val);
  156. if ($field !== $mappedField) {
  157. unset($conditions[$Model->alias . '.' . $mappedField]);
  158. }
  159. continue;
  160. }
  161. if (!is_array($val)) {
  162. continue;
  163. }
  164. $conditions[$key] = $this->encodeBitmaskConditions($Model, $val);
  165. }
  166. return $conditions;
  167. }
  168. /**
  169. * @return void
  170. */
  171. public function encodeBitmaskData(Model $Model) {
  172. $field = $this->settings[$Model->alias]['field'];
  173. if (!($mappedField = $this->settings[$Model->alias]['mappedField'])) {
  174. $mappedField = $field;
  175. }
  176. $default = null;
  177. $schema = $Model->schema($field);
  178. if ($schema && isset($schema['default'])) {
  179. $default = $schema['default'];
  180. }
  181. if ($this->settings[$Model->alias]['defaultValue'] !== null) {
  182. $default = $this->settings[$Model->alias]['defaultValue'];
  183. }
  184. if (isset($Model->data[$Model->alias][$mappedField])) {
  185. $Model->data[$Model->alias][$field] = $this->encodeBitmask($Model, $Model->data[$Model->alias][$mappedField], $default);
  186. }
  187. if ($field !== $mappedField) {
  188. unset($Model->data[$Model->alias][$mappedField]);
  189. }
  190. }
  191. /**
  192. * @param mixed bits (int, array)
  193. * @return array sqlSnippet
  194. */
  195. public function isBit(Model $Model, $bits) {
  196. $bits = (array)$bits;
  197. $bitmask = $this->encodeBitmask($Model, $bits);
  198. $field = $this->settings[$Model->alias]['field'];
  199. return array($Model->alias . '.' . $field => $bitmask);
  200. }
  201. /**
  202. * @param mixed bits (int, array)
  203. * @return array sqlSnippet
  204. */
  205. public function isNotBit(Model $Model, $bits) {
  206. $bits = (array)$bits;
  207. $bitmask = $this->encodeBitmask($Model, $bits);
  208. $field = $this->settings[$Model->alias]['field'];
  209. return array('NOT' => array($Model->alias . '.' . $field => $bitmask));
  210. }
  211. /**
  212. * @param mixed bits (int, array)
  213. * @return array sqlSnippet
  214. */
  215. public function containsBit(Model $Model, $bits) {
  216. $bits = (array)$bits;
  217. $bitmask = $this->encodeBitmask($Model, $bits);
  218. $field = $this->settings[$Model->alias]['field'];
  219. return array('(' . $Model->alias . '.' . $field . ' & ? = ?)' => array($bitmask, $bitmask));
  220. }
  221. /**
  222. * @param mixed bits (int, array)
  223. * @return array sqlSnippet
  224. */
  225. public function containsNotBit(Model $Model, $bits) {
  226. $bits = (array)$bits;
  227. $bitmask = $this->encodeBitmask($Model, $bits);
  228. $field = $this->settings[$Model->alias]['field'];
  229. return array('(' . $Model->alias . '.' . $field . ' & ? != ?)' => array($bitmask, $bitmask));
  230. }
  231. }