Skip to content
Permalink
Browse files

Refactoring whereNotNull() and whereNull()

  • Loading branch information...
burzum committed Apr 4, 2018
1 parent cd2c34a commit 39bf33303d099d9b5228e7fd8574b4a03d9eccdc
Showing with 41 additions and 25 deletions.
  1. +23 −25 src/Database/Query.php
  2. +18 −0 tests/TestCase/Database/QueryTest.php
@@ -882,47 +882,45 @@ public function where($conditions = null, $types = [], $overwrite = false)
}
/**
* Adds a NOT NULL or IS NULL expression to the query
* Convenience method that adds a NOT NULL condition to the query
*
* @param array $fields A list of fields that should be not null
* @param bool $isNull Toggles between NOT NULL and NULL checks
* @param array|string|\Cake\Database\ExpressionInterface $fields A single field or expressions or a list of them that should be not null
* @return $this
*/
protected function whereNullOrNotNull($fields, $isNull = true)
public function whereNotNull($fields)
{
foreach ($fields as $condition) {
$this->where(function ($exp) use ($condition, $isNull) {
if ($isNull) {
return $exp->isNull($condition);
}
return $exp->isNotNull($condition);
});
if (!is_array($fields)) {
$fields = [$fields];
}
return $this;
}
$exp = $this->newExpr();
/**
* Convenience method that adds a NOT NULL condition to the query
*
* @param array $fields A list of fields that should be not null
* @return $this
*/
public function whereNotNull($fields)
{
return $this->whereNullOrNotNull($fields, false);
foreach ($fields as $field) {
$exp->isNotNull($field);
}
return $this->where($exp);
}
/**
* Convenience method that adds a IS NULL condition to the query
*
* @param array $fields A list of fields that should be not null
* @param array|string|\Cake\Database\ExpressionInterface $fields A single field or expressions or a list of them that should be null
* @return $this
*/
public function whereNull($fields)
{
return $this->whereNullOrNotNull($fields, true);
if (!is_array($fields)) {
$fields = [$fields];
}
$exp = $this->newExpr();
foreach ($fields as $field) {
$exp->isNull($field);
}
return $this->where($exp);
}
/**
@@ -765,6 +765,15 @@ public function testSelectWhereNull()
->execute();
$this->assertCount(5, $result);
$result->closeCursor();
$query = new Query($this->connection);
$result = $query
->select(['id'])
->from('menu_link_trees')
->whereNull($this->connection->newQuery()->select('parent_id'))
->execute();
$this->assertCount(5, $result);
$result->closeCursor();
}
/**
@@ -784,6 +793,15 @@ public function testSelectWhereNotNull()
->execute();
$this->assertCount(13, $result);
$result->closeCursor();
$query = new Query($this->connection);
$result = $query
->select(['id'])
->from('menu_link_trees')
->whereNotNull($this->connection->newQuery()->select('parent_id'))
->execute();
$this->assertCount(13, $result);
$result->closeCursor();
}
/**

0 comments on commit 39bf333

Please sign in to comment.
You can’t perform that action at this time.