Skip to content

Commit

Permalink
FilterProcessor: Escape literal percent signs
Browse files Browse the repository at this point in the history
fixes #71
  • Loading branch information
nilmerg committed Jun 23, 2023
1 parent 39d2c60 commit 10d3053
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/Compat/FilterProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,11 @@ public static function assemblePredicate(Filter\Condition $filter)
if ($expression === '*') {
return ["$column IS " . ($filter instanceof Filter\Like ? 'NOT ' : '') . 'NULL'];
} elseif ($filter instanceof Filter\Unlike) {
return ["($column NOT LIKE ? OR $column IS NULL)" => str_replace('*', '%', $expression)];
return [
"($column NOT LIKE ? OR $column IS NULL)" => str_replace(['%', '*'], ['\\%', '%'], $expression)
];
} else {
return ["$column LIKE ?" => str_replace('*', '%', $expression)];
return ["$column LIKE ?" => str_replace(['%', '*'], ['\\%', '%'], $expression)];
}
} elseif ($filter instanceof Filter\Unequal || $filter instanceof Filter\Unlike) {
return ["($column != ? OR $column IS NULL)" => $expression];
Expand Down
41 changes: 41 additions & 0 deletions tests/FilterProcessorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace ipl\Tests\Sql;

use ipl\Sql\Compat\FilterProcessor;
use ipl\Stdlib\Filter;

class FilterProcessorTest extends TestCase
{
public function testLikeToSql()
{
$this->assertSame(
['foo IS NOT NULL'],
FilterProcessor::assemblePredicate(Filter::like('foo', '*'))
);
$this->assertSame(
['foo LIKE ?' => '%bar%'],
FilterProcessor::assemblePredicate(Filter::like('foo', '*bar*'))
);
$this->assertSame(
['foo LIKE ?' => '%\\%%'],
FilterProcessor::assemblePredicate(Filter::like('foo', '*%*'))
);
}

public function testUnlikeToSql()
{
$this->assertSame(
['foo IS NULL'],
FilterProcessor::assemblePredicate(Filter::unlike('foo', '*'))
);
$this->assertSame(
['(foo NOT LIKE ? OR foo IS NULL)' => '%bar%'],
FilterProcessor::assemblePredicate(Filter::unlike('foo', '*bar*'))
);
$this->assertSame(
['(foo NOT LIKE ? OR foo IS NULL)' => '%\\%%'],
FilterProcessor::assemblePredicate(Filter::unlike('foo', '*%*'))
);
}
}

0 comments on commit 10d3053

Please sign in to comment.