BitmaskedBehavior.php 8.7 KB

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