Skip to content
This repository was archived by the owner on Aug 22, 2023. It is now read-only.

Commit 4a491f6

Browse files
committed
Fix support for % and _ in like expression
1 parent 34a6085 commit 4a491f6

File tree

3 files changed

+12
-2
lines changed

3 files changed

+12
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ All notable changes to this project will be documented in this file.
1111
- Throw an exception when `Query\Builder::orderBy()` is used with invalid direction [#7](https://github.com/GromNaN/laravel-mongodb-private/pull/7) by [@GromNaN](https://github.com/GromNaN).
1212
- Throw an exception when `Query\Builder::push()` is used incorrectly [#5](https://github.com/GromNaN/laravel-mongodb-private/pull/5) by [@GromNaN](https://github.com/GromNaN).
1313
- Remove public property `Query\Builder::$paginating` [#15](https://github.com/GromNaN/laravel-mongodb-private/pull/15) by [@GromNaN](https://github.com/GromNaN).
14+
- Fix support for `%` and `_` in `like` expression [#17](https://github.com/GromNaN/laravel-mongodb-private/pull/17) by [@GromNaN](https://github.com/GromNaN).
1415
- Remove `ilike` and `regexp` operators, use `like` and `regex` instead [#17](https://github.com/GromNaN/laravel-mongodb-private/pull/17) by [@GromNaN](https://github.com/GromNaN).
1516

1617
## [3.9.2] - 2022-09-01

src/Query/Builder.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1073,8 +1073,12 @@ protected function compileWhereBasic(array $where): array
10731073
$operator = 'not';
10741074
}
10751075

1076-
// Convert to regular expression.
1077-
$regex = preg_replace(['#(^|[^\\\])%#', '#(^|[^\\\])_#'], ['$1.*', '$1.'], preg_quote($value));
1076+
// Convert % and _ to regex, and unescape \% and \_
1077+
$regex = preg_replace(
1078+
['#(^|[^\\\])%#', '#(^|[^\\\])_#', '#\\\\\\\(%|_)#'],
1079+
['$1.*', '$1.', '$1'],
1080+
preg_quote($value),
1081+
);
10781082
$value = new Regex('^'.$regex.'$', 'i');
10791083
} // Manipulate regex operations.
10801084
elseif (in_array($operator, ['regex', 'not regex'])) {

tests/Query/BuilderTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,11 @@ function (Builder $builder) {
450450
fn (Builder $builder) => $builder->where('name', 'like', '^ac.me$'),
451451
];
452452

453+
yield 'where like unescaped \% \_' => [
454+
['find' => [['name' => new Regex('^a%cm_e$', 'i')], []]],
455+
fn (Builder $builder) => $builder->where('name', 'like', 'a\%cm\_e'),
456+
];
457+
453458
yield 'where like %' => [
454459
['find' => [['name' => new Regex('^.*ac.*me.*$', 'i')], []]],
455460
fn (Builder $builder) => $builder->where('name', 'like', '%ac%me%'),

0 commit comments

Comments
 (0)