BitmaskedBehavior.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 http://opensource.org/licenses/mit-license.php MIT
  20. * @link http://www.dereuromark.de/2012/02/26/bitmasked-using-bitmasks-in-cakephp/
  21. */
  22. class BitmaskedBehavior extends ModelBehavior {
  23. /**
  24. * Default config
  25. *
  26. * @var array
  27. */
  28. protected $_defaultConfig = [
  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 = []) {
  43. $config += $this->_defaultConfig;
  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. * @param Model $Model
  62. * @param array $query
  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. * @param Model $Model
  74. * @param array $results
  75. * @param bool $primary
  76. * @return array
  77. */
  78. public function afterFind(Model $Model, $results, $primary = false) {
  79. $field = $this->settings[$Model->alias]['field'];
  80. if (!($mappedField = $this->settings[$Model->alias]['mappedField'])) {
  81. $mappedField = $field;
  82. }
  83. foreach ($results as $key => $result) {
  84. if (isset($result[$Model->alias][$field])) {
  85. $results[$key][$Model->alias][$mappedField] = $this->decodeBitmask($Model, $result[$Model->alias][$field]);
  86. }
  87. }
  88. return $results;
  89. }
  90. /**
  91. * @param Model $Model
  92. * @param array $options
  93. * @return bool Success
  94. */
  95. public function beforeValidate(Model $Model, $options = []) {
  96. if ($this->settings[$Model->alias]['before'] !== 'validate') {
  97. return true;
  98. }
  99. $this->encodeBitmaskData($Model);
  100. return true;
  101. }
  102. /**
  103. * @param Model $Model
  104. * @param array $options
  105. * @return bool Success
  106. */
  107. public function beforeSave(Model $Model, $options = []) {
  108. if ($this->settings[$Model->alias]['before'] !== 'save') {
  109. return true;
  110. }
  111. $this->encodeBitmaskData($Model);
  112. return true;
  113. }
  114. /**
  115. * @param Model $Model
  116. * @param int $value Bitmask.
  117. * @return array Bitmask array (from DB to APP).
  118. */
  119. public function decodeBitmask(Model $Model, $value) {
  120. $res = [];
  121. $value = (int)$value;
  122. foreach ($this->settings[$Model->alias]['bits'] as $key => $val) {
  123. $val = (($value & $key) !== 0) ? true : false;
  124. if ($val) {
  125. $res[] = $key;
  126. }
  127. }
  128. return $res;
  129. }
  130. /**
  131. * @param Model $Model
  132. * @param array $value Bitmask array.
  133. * @param array $defaultValue Default bitmask array.
  134. * @return int Bitmask (from APP to DB).
  135. */
  136. public function encodeBitmask(Model $Model, $value, $defaultValue = null) {
  137. $res = 0;
  138. if (empty($value)) {
  139. return $defaultValue;
  140. }
  141. foreach ((array)$value as $key => $val) {
  142. $res |= (int)$val;
  143. }
  144. if ($res === 0) {
  145. return $defaultValue; // make sure notEmpty validation rule triggers
  146. }
  147. return $res;
  148. }
  149. /**
  150. * @param Model $Model
  151. * @param array $conditions
  152. * @return array Conditions.
  153. */
  154. public function encodeBitmaskConditions(Model $Model, $conditions) {
  155. $field = $this->settings[$Model->alias]['field'];
  156. if (!($mappedField = $this->settings[$Model->alias]['mappedField'])) {
  157. $mappedField = $field;
  158. }
  159. foreach ($conditions as $key => $val) {
  160. if ($key === $mappedField) {
  161. $conditions[$field] = $this->encodeBitmask($Model, $val);
  162. if ($field !== $mappedField) {
  163. unset($conditions[$mappedField]);
  164. }
  165. continue;
  166. } elseif ($key === $Model->alias . '.' . $mappedField) {
  167. $conditions[$Model->alias . '.' . $field] = $this->encodeBitmask($Model, $val);
  168. if ($field !== $mappedField) {
  169. unset($conditions[$Model->alias . '.' . $mappedField]);
  170. }
  171. continue;
  172. }
  173. if (!is_array($val)) {
  174. continue;
  175. }
  176. $conditions[$key] = $this->encodeBitmaskConditions($Model, $val);
  177. }
  178. return $conditions;
  179. }
  180. /**
  181. * @param Model $Model
  182. * @return void
  183. */
  184. public function encodeBitmaskData(Model $Model) {
  185. $field = $this->settings[$Model->alias]['field'];
  186. if (!($mappedField = $this->settings[$Model->alias]['mappedField'])) {
  187. $mappedField = $field;
  188. }
  189. $default = null;
  190. $schema = $Model->schema($field);
  191. if ($schema && isset($schema['default'])) {
  192. $default = $schema['default'];
  193. }
  194. if ($this->settings[$Model->alias]['defaultValue'] !== null) {
  195. $default = $this->settings[$Model->alias]['defaultValue'];
  196. }
  197. if (isset($Model->data[$Model->alias][$mappedField])) {
  198. $Model->data[$Model->alias][$field] = $this->encodeBitmask($Model, $Model->data[$Model->alias][$mappedField], $default);
  199. }
  200. if ($field !== $mappedField) {
  201. unset($Model->data[$Model->alias][$mappedField]);
  202. }
  203. }
  204. /**
  205. * @param Model $Model
  206. * @param mixed $bits (int, array)
  207. * @return array SQL snippet.
  208. */
  209. public function isBit(Model $Model, $bits) {
  210. $bits = (array)$bits;
  211. $bitmask = $this->encodeBitmask($Model, $bits);
  212. $field = $this->settings[$Model->alias]['field'];
  213. return [$Model->alias . '.' . $field => $bitmask];
  214. }
  215. /**
  216. * @param Model $Model
  217. * @param mixed $bits (int, array)
  218. * @return array SQL snippet.
  219. */
  220. public function isNotBit(Model $Model, $bits) {
  221. return ['NOT' => $this->isBit($Model, $bits)];
  222. }
  223. /**
  224. * @param Model $Model
  225. * @param mixed $bits (int, array)
  226. * @return array SQL snippet.
  227. */
  228. public function containsBit(Model $Model, $bits) {
  229. return $this->_containsBit($Model, $bits);
  230. }
  231. /**
  232. * @param Model $Model
  233. * @param mixed $bits (int, array)
  234. * @return array SQL snippet.
  235. */
  236. public function containsNotBit(Model $Model, $bits) {
  237. return $this->_containsBit($Model, $bits, false);
  238. }
  239. /**
  240. * @param Model $Model
  241. * @param mixed $bits (int, array)
  242. * @param bool $contain
  243. * @return array SQL snippet.
  244. */
  245. protected function _containsBit(Model $Model, $bits, $contain = true) {
  246. $bits = (array)$bits;
  247. $bitmask = $this->encodeBitmask($Model, $bits);
  248. $field = $this->settings[$Model->alias]['field'];
  249. $contain = $contain ? ' & ? = ?' : ' & ? != ?';
  250. return ['(' . $Model->alias . '.' . $field . $contain . ')' => [$bitmask, $bitmask]];
  251. }
  252. }