BitmaskedBehavior.php 7.0 KB

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