Skip to content

Commit

Permalink
Add contain mode AND.
Browse files Browse the repository at this point in the history
  • Loading branch information
dereuromark committed Dec 2, 2021
1 parent 62b7437 commit d81e04e
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/Model/Behavior/BitmaskedBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ class BitmaskedBehavior extends Behavior {
'implementedFinders' => [
'bits' => 'findBitmasked',
],
'type' => null, // Auto-defaults to current default "exact", set to "contain" for contain mode
'containMode' => 'or', // Use "and" when a record must match all bits
];

/**
Expand All @@ -58,7 +60,10 @@ public function findBitmasked(Query $query, array $options) {
if (!isset($options['bits'])) {
throw new InvalidArgumentException("The 'bits' key is required for find('bits')");
}
$options += ['type' => 'exact'];
$options += [
'type' => $this->_config['type'] ?? 'exact',
'containMode' => $this->_config['containMode'],
];

if ($options['type'] === 'contain') {
$bits = (array)$options['bits'];
Expand All @@ -68,6 +73,12 @@ public function findBitmasked(Query $query, array $options) {
return $query->where([$this->_table->getAlias() . '.' . $field => $this->_getDefaultValue($field)]);
}

if ($options['containMode'] === 'and') {
$bits = $this->encodeBitmask($options['bits']);

return $query->where($this->containsBit($bits));
}

$conditions = [];
foreach ($bits as $bit) {
$conditions[] = $this->containsBit($bit);
Expand Down
30 changes: 30 additions & 0 deletions tests/TestCase/Model/Behavior/BitmaskedBehaviorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,36 @@ public function testFindBitmaskedContain() {
$this->assertCount(5, $res);
}

/**
* @return void
*/
public function testFindBitmaskedContainAnd() {
$options = [
'bits' => [],
'type' => 'contain',
'containMode' => 'and',
];
$res = $this->Comments->find('bits', $options)->toArray();
$this->assertCount(1, $res);
$this->assertSame([], $res[0]->statuses);

$options = [
'bits' => [BitmaskedComment::STATUS_APPROVED],
'type' => 'contain',
'containMode' => 'and',
];
$res = $this->Comments->find('bits', $options)->toArray();
$this->assertCount(3, $res);

$options = [
'bits' => [BitmaskedComment::STATUS_APPROVED, BitmaskedComment::STATUS_PUBLISHED],
'type' => 'contain',
'containMode' => 'and',
];
$res = $this->Comments->find('bits', $options)->toArray();
$this->assertCount(1, $res);
}

/**
* @return void
*/
Expand Down

0 comments on commit d81e04e

Please sign in to comment.