Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 9 additions & 12 deletions src/Model/Behavior/TrashBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
use ArrayObject;
use Cake\Core\Configure;
use Cake\Core\Exception\CakeException;
use Cake\Database\Expression\BetweenExpression;
use Cake\Database\Expression\ComparisonExpression;
use Cake\Database\Expression\FieldInterface;
use Cake\Database\Expression\IdentifierExpression;
use Cake\Database\Expression\QueryExpression;
use Cake\Database\Expression\UnaryExpression;
Expand Down Expand Up @@ -184,41 +183,39 @@ public function beforeFind(EventInterface $event, SelectQuery $query, ArrayObjec
return;
}

$field = $this->getTrashField();

if ($this->shouldAddTrashCondition($query, $field)) {
$query->andWhere([$field . ' IS' => null]);
if ($this->shouldAddTrashCondition($query)) {
$query->andWhere([$this->getTrashField() . ' IS' => null]);
}
}

/**
* Whether we need to add the trash condition to the query
*
* @param \Cake\ORM\Query\SelectQuery $query Query.
* @param string $field Trash field
* @return bool
*/
protected function shouldAddTrashCondition(SelectQuery $query, string $field): bool
protected function shouldAddTrashCondition(SelectQuery $query): bool
{
$fieldIdentifiers = [$this->getTrashField(false), $this->getTrashField()];
$addCondition = true;

$query->traverseExpressions(function ($expression) use (&$addCondition, $field): void {
$query->traverseExpressions(function ($expression) use (&$addCondition, $fieldIdentifiers): void {
if (!$addCondition) {
return;
}

if (
$expression instanceof IdentifierExpression
&& $expression->getIdentifier() === $field
&& in_array($expression->getIdentifier(), $fieldIdentifiers, true)
) {
$addCondition = false;

return;
}

if (
($expression instanceof ComparisonExpression || $expression instanceof BetweenExpression)
&& $expression->getField() === $field
$expression instanceof FieldInterface
&& in_array($expression->getField(), $fieldIdentifiers, true)
) {
$addCondition = false;
}
Expand Down
11 changes: 11 additions & 0 deletions tests/TestCase/Model/Behavior/TrashBehaviorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,17 @@ public function testTrashNonAccessibleProperty()
$this->assertCount(3, $this->Articles->find('withTrashed'));
}

public function testFindWithImplicitCondition()
{
$this->assertCount(2, $this->Articles->find()->where([
'trashed IS NOT' => null,
]));

$this->assertCount(2, $this->Articles->find()->where([
'Articles.trashed IS NOT' => null,
]));
}

/**
* Test it can find only trashed records.
*
Expand Down