Skip to content

Commit

Permalink
Merge pull request #1 from ferfabricio/hotfix/empty-null-values
Browse files Browse the repository at this point in the history
Fix empty null values
  • Loading branch information
ferfabricio authored Aug 15, 2020
2 parents 4de95dc + 0ceb539 commit 65f51f5
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 2 deletions.
13 changes: 12 additions & 1 deletion src/Filters/AbstractFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,24 @@ public function apply(Builder $query, string $column, array $filter): Builder
{
$operator = $this->identifyOperator($column, $filter);
$key = $this->identifyKey($column, $filter);
if (array_key_exists($key, $filter)) {

if (array_key_exists($key, $filter) && !$this->checkEmptyOrNull($filter[$key])) {
$query->where($column, $operator, $filter[$key]);
}

return $query;
}

/**
* @param mixed $value
*
* @return bool
*/
protected function checkEmptyOrNull($value): bool
{
return null === $value || empty($value);
}

/**
* @param string $identifier
* @param string $column
Expand Down
4 changes: 3 additions & 1 deletion src/Filters/Like.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ public function apply(Builder $query, string $column, array $filter): Builder
{
$value = $filter[$column] ?? '';

$query->where($column, 'like', "%{$value}%");
if (!$this->checkEmptyOrNull($value)) {
$query->where($column, 'like', "%{$value}%");
}

return $query;
}
Expand Down
32 changes: 32 additions & 0 deletions tests/Unit/Filters/EqualTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,36 @@ public function testApplyInClass()
['test' => 'to equal']
);
}

/**
* @dataProvider nullAndEmptyScenario
*
* @param mixed $value
*/
public function testWithEmptyValue($value)
{
$exampleModel = new class() {
use Filterable;

protected $filters = [
'test' => Equal::IDENTIFIER,
];
};

$query = Mockery::spy(Builder::class);
$query->shouldNotReceive('where');

$exampleModel->scopeFilters(
$query,
['test' => $value]
);
}

public function nullAndEmptyScenario(): array
{
return [
[''],
[null],
];
}
}
19 changes: 19 additions & 0 deletions tests/Unit/Filters/LikeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,23 @@ public function testApplyInClass()
['test' => 'to like']
);
}

public function testWithEmptyValue()
{
$exampleModel = new class() {
use Filterable;

protected $filters = [
'test' => Like::IDENTIFIER,
];
};

$query = Mockery::spy(Builder::class);
$query->shouldNotReceive('where');

$exampleModel->scopeFilters(
$query,
['test' => '']
);
}
}

0 comments on commit 65f51f5

Please sign in to comment.