BitmaskedBehavior.php 8.8 KB

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