BitmaskedBehavior.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. * Setup example:
  38. * <code>
  39. * public $actsAs = array(
  40. * 'Tools.Bitmasked' => [
  41. * [
  42. * 'mappedField' => 'weekdays',
  43. * 'field' => 'weekday'
  44. * ],
  45. * [
  46. * 'mappedField' => 'monthdays',
  47. * 'field' => 'monthday'
  48. * ]
  49. * ]
  50. * ];
  51. * </code>
  52. *
  53. * @param Model $Model
  54. * @param array $config
  55. * @return void
  56. */
  57. public function setup(Model $Model, $config = []) {
  58. if (is_array(reset($config))) {
  59. // Setup example:
  60. foreach ($config as $fieldConfig) {
  61. $fieldName = $fieldConfig['field'];
  62. $this->settings[$Model->alias][$fieldName] = $this->_getFieldConfig($Model, $fieldConfig);
  63. }
  64. } else {
  65. $fieldName = $config['field'];
  66. $this->settings[$Model->alias][$fieldName] = $this->_getFieldConfig($Model, $config);
  67. }
  68. }
  69. private function _getFieldConfig(Model $Model, $config) {
  70. $config += $this->_defaultConfig;
  71. if (empty($config['bits'])) {
  72. $config['bits'] = Inflector::pluralize($config['field']);
  73. }
  74. if (is_callable($config['bits'])) {
  75. $config['bits'] = call_user_func($config['bits']);
  76. } elseif (is_string($config['bits']) && method_exists($Model, $config['bits'])) {
  77. $config['bits'] = $Model->{$config['bits']}();
  78. } elseif (!is_array($config['bits'])) {
  79. $config['bits'] = false;
  80. }
  81. if (empty($config['bits'])) {
  82. throw new InternalErrorException('Bits not found');
  83. }
  84. ksort($config['bits'], SORT_NUMERIC);
  85. return $config;
  86. }
  87. /**
  88. * @param Model $Model
  89. * @param array $query
  90. * @return array
  91. */
  92. public function beforeFind(Model $Model, $query) {
  93. if (isset($query['conditions']) && is_array($query['conditions'])) {
  94. $query['conditions'] = $this->encodeBitmaskConditions($Model, $query['conditions']);
  95. }
  96. return $query;
  97. }
  98. /**
  99. * @param Model $Model
  100. * @param array $results
  101. * @param bool $primary
  102. * @return array
  103. */
  104. public function afterFind(Model $Model, $results, $primary = false) {
  105. foreach ($this->settings[$Model->alias] as $fieldConfig) {
  106. $field = $fieldConfig['field'];
  107. if (!($mappedField = $fieldConfig['mappedField'])) {
  108. $mappedField = $field;
  109. }
  110. foreach ($results as $key => $result) {
  111. if (isset($result[$Model->alias][$field])) {
  112. $results[$key][$Model->alias][$mappedField] = $this->decodeBitmask($Model, $result[$Model->alias][$field], $field);
  113. }
  114. }
  115. }
  116. return $results;
  117. }
  118. /**
  119. * @param Model $Model
  120. * @param array $options
  121. * @return bool Success
  122. */
  123. public function beforeValidate(Model $Model, $options = []) {
  124. foreach ($this->settings[$Model->alias] as $fieldConfig) {
  125. if ($fieldConfig['before'] === 'validate') {
  126. $this->encodeBitmaskData($Model);
  127. }
  128. }
  129. return true;
  130. }
  131. /**
  132. * @param Model $Model
  133. * @param array $options
  134. * @return bool Success
  135. */
  136. public function beforeSave(Model $Model, $options = []) {
  137. foreach ($this->settings[$Model->alias] as $fieldConfig) {
  138. if ($fieldConfig['before'] === 'save') {
  139. $this->encodeBitmaskData($Model);
  140. }
  141. }
  142. return true;
  143. }
  144. /**
  145. * @param Model $Model
  146. * @param int $value Bitmask.
  147. * @param string $fieldName field name.
  148. * @return array Bitmask array (from DB to APP).
  149. */
  150. public function decodeBitmask(Model $Model, $value, $fieldName) {
  151. $res = [];
  152. $value = (int)$value;
  153. foreach ($this->settings[$Model->alias][$fieldName]['bits'] as $key => $val) {
  154. $val = (($value & $key) !== 0) ? true : false;
  155. if ($val) {
  156. $res[] = $key;
  157. }
  158. }
  159. return $res;
  160. }
  161. /**
  162. * @param Model $Model
  163. * @param array $value Bitmask array.
  164. * @param array $defaultValue Default bitmask array.
  165. * @return int Bitmask (from APP to DB).
  166. */
  167. public function encodeBitmask(Model $Model, $value, $defaultValue = null) {
  168. $res = 0;
  169. if (empty($value)) {
  170. return $defaultValue;
  171. }
  172. foreach ((array)$value as $key => $val) {
  173. $res |= (int)$val;
  174. }
  175. if ($res === 0) {
  176. return $defaultValue; // make sure notEmpty validation rule triggers
  177. }
  178. return $res;
  179. }
  180. /**
  181. * @param Model $Model
  182. * @param array $conditions
  183. * @return array Conditions.
  184. */
  185. public function encodeBitmaskConditions(Model $Model, $conditions) {
  186. foreach ($this->settings[$Model->alias] as $fieldConfig) {
  187. $field = $fieldConfig['field'];
  188. if (!($mappedField = $fieldConfig['mappedField'])) {
  189. $mappedField = $field;
  190. }
  191. foreach ($conditions as $key => $val) {
  192. if ($key === $mappedField) {
  193. $conditions[$field] = $this->encodeBitmask($Model, $val);
  194. if ($field !== $mappedField) {
  195. unset($conditions[$mappedField]);
  196. }
  197. continue;
  198. } elseif ($key === $Model->alias . '.' . $mappedField) {
  199. $conditions[$Model->alias . '.' . $field] = $this->encodeBitmask($Model, $val);
  200. if ($field !== $mappedField) {
  201. unset($conditions[$Model->alias . '.' . $mappedField]);
  202. }
  203. continue;
  204. }
  205. if (!is_array($val)) {
  206. continue;
  207. }
  208. $conditions[$key] = $this->encodeBitmaskConditions($Model, $val);
  209. }
  210. }
  211. return $conditions;
  212. }
  213. /**
  214. * @param Model $Model
  215. * @return void
  216. */
  217. public function encodeBitmaskData(Model $Model) {
  218. foreach ($this->settings[$Model->alias] as $fieldConfig) {
  219. $field = $fieldConfig['field'];
  220. if (!($mappedField = $fieldConfig['mappedField'])) {
  221. $mappedField = $field;
  222. }
  223. $default = null;
  224. $schema = $Model->schema($field);
  225. if ($schema && isset($schema['default'])) {
  226. $default = $schema['default'];
  227. }
  228. if ($fieldConfig['defaultValue'] !== null) {
  229. $default = $fieldConfig['defaultValue'];
  230. }
  231. if (isset($Model->data[$Model->alias][$mappedField])) {
  232. $Model->data[$Model->alias][$field] = $this->encodeBitmask($Model, $Model->data[$Model->alias][$mappedField], $default);
  233. }
  234. if ($field !== $mappedField) {
  235. unset($Model->data[$Model->alias][$mappedField]);
  236. }
  237. }
  238. }
  239. /**
  240. * @param Model $Model
  241. * @param mixed $bits (int, array)
  242. * @param string $fieldName field name.
  243. * @return array SQL snippet.
  244. */
  245. public function isBit(Model $Model, $bits, $fieldName) {
  246. $bits = (array)$bits;
  247. $bitmask = $this->encodeBitmask($Model, $bits);
  248. return array($Model->alias . '.' . $fieldName => $bitmask);
  249. }
  250. /**
  251. * @param Model $Model
  252. * @param mixed $bits (int, array)
  253. * @param string $fieldName field name.
  254. * @return array SQL snippet.
  255. */
  256. public function isNotBit(Model $Model, $bits, $fieldName) {
  257. return ['NOT' => $this->isBit($Model, $bits, $fieldName)];
  258. }
  259. /**
  260. * @param Model $Model
  261. * @param mixed $bits (int, array)
  262. * @param string $fieldName field name.
  263. * @return array SQL snippet.
  264. */
  265. public function containsBit(Model $Model, $bits, $fieldName) {
  266. return $this->_containsBit($Model, $bits, $fieldName);
  267. }
  268. /**
  269. * @param Model $Model
  270. * @param mixed $bits (int, array)
  271. * @param string $fieldName field name.
  272. * @return array SQL snippet.
  273. */
  274. public function containsNotBit(Model $Model, $bits, $fieldName) {
  275. return $this->_containsBit($Model, $bits, $fieldName, false);
  276. }
  277. /**
  278. * @param Model $Model
  279. * @param mixed $bits (int, array)
  280. * @param string $fieldName field name.
  281. * @param bool $contain
  282. * @return array SQL snippet.
  283. */
  284. protected function _containsBit(Model $Model, $bits, $fieldName, $contain = true) {
  285. $bits = (array)$bits;
  286. $bitmask = $this->encodeBitmask($Model, $bits);
  287. $contain = $contain ? ' & ? = ?' : ' & ? != ?';
  288. return array['(' . $Model->alias . '.' . $fieldName . $contain . ')' => [$bitmask, $bitmask]];
  289. }
  290. }