Make building LIKE expression with escaping easier

It was possible to provide escaping through the second argument but that
was more like a hack.
parent 1bc05367
......@@ -20,6 +20,9 @@
namespace Doctrine\DBAL\Query\Expression;
use Doctrine\DBAL\Connection;
use function func_get_args;
use function func_num_args;
use function sprintf;
/**
* ExpressionBuilder class is responsible to dynamically create SQL query parts.
......@@ -256,7 +259,8 @@ class ExpressionBuilder
*/
public function like($x, $y)
{
return $this->comparison($x, 'LIKE', $y);
return $this->comparison($x, 'LIKE', $y) .
(func_num_args() >= 3 ? sprintf(" ESCAPE '%s'", func_get_args()[2]) : '');
}
/**
......@@ -269,7 +273,8 @@ class ExpressionBuilder
*/
public function notLike($x, $y)
{
return $this->comparison($x, 'NOT LIKE', $y);
return $this->comparison($x, 'NOT LIKE', $y) .
(func_num_args() >= 3 ? sprintf(" ESCAPE '%s'", func_get_args()[2]) : '');
}
/**
......
......@@ -219,4 +219,33 @@ class ExpressionBuilderTest extends \Doctrine\Tests\DbalTestCase
{
self::assertEquals('u.groups NOT IN (:values)', $this->expr->notIn('u.groups', ':values'));
}
public function testLikeWithoutEscape()
{
self::assertEquals("a.song LIKE 'a virgin'", $this->expr->like('a.song', "'a virgin'"));
}
public function testLikeWithEscape()
{
self::assertEquals(
"a.song LIKE 'a virgin' ESCAPE '💩'",
$this->expr->like('a.song', "'a virgin'", '💩')
);
}
public function testNotLikeWithoutEscape()
{
self::assertEquals(
"s.last_words NOT LIKE 'this'",
$this->expr->notLike('s.last_words', "'this'")
);
}
public function testNotLikeWithEscape()
{
self::assertEquals(
"p.description NOT LIKE '20💩%' ESCAPE '💩'",
$this->expr->notLike('p.description', "'20💩%'", '💩')
);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment