BitmaskedBehavior.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. <?php
  2. namespace Tools\Model\Behavior;
  3. use Cake\Event\Event;
  4. use Cake\ORM\Behavior;
  5. use Cake\ORM\Entity;
  6. use Cake\Utility\Inflector;
  7. use Cake\Core\Configure;
  8. use Cake\ORM\Query;
  9. use Cake\Utility\String;
  10. /**
  11. * BitmaskedBehavior
  12. *
  13. * An implementation of bitwise masks for row-level operations.
  14. * You can submit/register flags in different ways. The easiest way is using a static model function.
  15. * It should contain the bits like so (starting with 1):
  16. * 1 => w, 2 => x, 4 => y, 8 => z, ... (bits as keys - names as values)
  17. * The order doesn't matter, as long as no bit is used twice.
  18. *
  19. * The theoretical limit for a 64-bit integer would be 64 bits (2^64).
  20. * But if you actually seem to need more than a hand full you
  21. * obviously do something wrong and should better use a joined table etc.
  22. *
  23. * @author Mark Scherer
  24. * @license MIT
  25. * @link http://www.dereuromark.de/2012/02/26/bitmasked-using-bitmasks-in-cakephp/
  26. */
  27. class BitmaskedBehavior extends Behavior {
  28. /**
  29. * Default config
  30. *
  31. * @var array
  32. */
  33. protected $_defaultConfig = array(
  34. 'field' => 'status',
  35. 'mappedField' => null, // NULL = same as above
  36. 'bits' => null, // Method or callback to get the bits data
  37. 'on' => 'beforeValidate', // beforeSave or beforeValidate
  38. 'defaultValue' => null, // NULL = auto (use empty string to trigger "notEmpty" rule for "default NOT NULL" db fields)
  39. );
  40. /**
  41. * Behavior configuration
  42. *
  43. * @param array $config
  44. * @return void
  45. */
  46. public function initialize(array $config = array()) {
  47. $config = $this->_config;
  48. if (empty($config['bits'])) {
  49. $config['bits'] = Inflector::pluralize($config['field']);
  50. }
  51. $entity = $this->_table->newEntity();
  52. if (is_callable($config['bits'])) {
  53. $config['bits'] = call_user_func($config['bits']);
  54. } elseif (is_string($config['bits']) && method_exists($entity, $config['bits'])) {
  55. $config['bits'] = $entity->{$config['bits']}();
  56. } elseif (is_string($config['bits']) && method_exists($this->_table, $config['bits'])) {
  57. $config['bits'] = $this->_table->{$config['bits']}();
  58. } elseif (!is_array($config['bits'])) {
  59. $config['bits'] = false;
  60. }
  61. if (empty($config['bits'])) {
  62. throw new \Exception('Bits not found');
  63. }
  64. ksort($config['bits'], SORT_NUMERIC);
  65. $this->_config = $config;
  66. }
  67. /**
  68. * @param Event $event
  69. * @param Query $query
  70. * @return void
  71. */
  72. public function beforeFind(Event $event, Query $query) {
  73. $this->encodeBitmaskConditions($query);
  74. $field = $this->_config['field'];
  75. if (!($mappedField = $this->_config['mappedField'])) {
  76. $mappedField = $field;
  77. }
  78. $mapper = function ($row, $key, $mr) use ($field, $mappedField) {
  79. $row->set($mappedField, $this->decodeBitmask($row->get($field)));
  80. $mr->emit($row);
  81. };
  82. $query->mapReduce($mapper);
  83. }
  84. /**
  85. * @param Event $event
  86. * @param Entity $entity
  87. * @param \ArrayObject $options
  88. * @return void
  89. */
  90. public function beforeValidate(Event $event, Entity $entity, \ArrayObject $options) {
  91. if ($this->_config['on'] !== 'beforeValidate' || !$options['validate']) {
  92. return;
  93. }
  94. $this->encodeBitmaskData($entity);
  95. }
  96. /**
  97. * @param Event $event
  98. * @param Entity $entity
  99. * @param \ArrayObject $options
  100. * @return void
  101. */
  102. public function beforeSave(Event $event, Entity $entity, \ArrayObject $options) {
  103. if ($this->_config['on'] !== 'beforeSave') {
  104. return;
  105. }
  106. $this->encodeBitmaskData($entity);
  107. }
  108. /**
  109. * @param int $value Bitmask.
  110. * @return array Bitmask array (from DB to APP).
  111. */
  112. public function decodeBitmask($value) {
  113. $res = array();
  114. $value = (int)$value;
  115. foreach ($this->_config['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 $value Bitmask array.
  125. * @param mixed $defaultValue Default bitmask value.
  126. * @return int Bitmask (from APP to DB).
  127. */
  128. public function encodeBitmask($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. * @param Query $query
  143. * @return void
  144. */
  145. public function encodeBitmaskConditions(Query $query) {
  146. $field = $this->_config['field'];
  147. if (!($mappedField = $this->_config['mappedField'])) {
  148. $mappedField = $field;
  149. }
  150. $where = $query->clause('where');
  151. if (!$where) {
  152. return;
  153. }
  154. $callable = function ($foo) use ($field, $mappedField) {
  155. if (!$foo instanceof \Cake\Database\Expression\Comparison) {
  156. return $foo;
  157. }
  158. $key = $foo->getField();
  159. if ($key === $mappedField || $key === $this->_table->alias() . '.' . $mappedField) {
  160. $foo->value($this->encodeBitmask($foo->getValue()));
  161. }
  162. if ($field !== $mappedField) {
  163. $foo->field($field);
  164. }
  165. return $foo;
  166. };
  167. $where->iterateParts($callable);
  168. }
  169. /**
  170. * @param Entity $entity
  171. * @return void
  172. */
  173. public function encodeBitmaskData(Entity $entity) {
  174. $field = $this->_config['field'];
  175. if (!($mappedField = $this->_config['mappedField'])) {
  176. $mappedField = $field;
  177. }
  178. $default = null;
  179. $schema = $this->_table->schema()->column($field);
  180. if ($schema && isset($schema['default'])) {
  181. $default = $schema['default'];
  182. }
  183. if ($this->_config['defaultValue'] !== null) {
  184. $default = $this->_config['defaultValue'];
  185. }
  186. if ($entity->get($mappedField) !== null) {
  187. $entity->set($field, $this->encodeBitmask($entity->get($mappedField), $default));
  188. }
  189. if ($field !== $mappedField) {
  190. $entity->unsetProperty($mappedField);
  191. }
  192. }
  193. /**
  194. * @param int|array $bits
  195. * @return array SQL snippet.
  196. */
  197. public function isBit($bits) {
  198. $bits = (array)$bits;
  199. $bitmask = $this->encodeBitmask($bits);
  200. $field = $this->_config['field'];
  201. return array($this->_table->alias() . '.' . $field => $bitmask);
  202. }
  203. /**
  204. * @param int|array $bits
  205. * @return array SQL snippet.
  206. */
  207. public function isNotBit($bits) {
  208. return array('NOT' => $this->isBit($bits));
  209. }
  210. /**
  211. * @param int|array $bits
  212. * @return array SQL snippet.
  213. */
  214. public function containsBit($bits) {
  215. return $this->_containsBit($bits);
  216. }
  217. /**
  218. * @param int|array $bits
  219. * @return array SQL snippet.
  220. */
  221. public function containsNotBit($bits) {
  222. return $this->_containsBit($bits, false);
  223. }
  224. /**
  225. * @param int|array $bits
  226. * @param bool $contain
  227. * @return array SQL snippet.
  228. */
  229. protected function _containsBit($bits, $contain = true) {
  230. $bits = (array)$bits;
  231. $bitmask = $this->encodeBitmask($bits);
  232. $field = $this->_config['field'];
  233. $contain = $contain ? ' & ? = ?' : ' & ? != ?';
  234. $contain = String::insert($contain, array($bitmask, $bitmask));
  235. return array('(' . $this->_table->alias() . '.' . $field . $contain . ')');
  236. }
  237. }