Skip to content

Commit d16028d

Browse files
eyupcanakmantharropoulos
authored andcommitted
feat(filter_by): add helper to escape filter string values
1 parent a4c8d0a commit d16028d

3 files changed

Lines changed: 50 additions & 0 deletions

File tree

README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,17 @@ Read the documentation here: [https://typesense.org/api/](https://typesense.org/
1818

1919
Here are some examples that walk you through how to use the client: [doc/examples](examples)
2020

21+
### Escaping filter values
22+
23+
Use `Typesense\FilterBy::escapeString()` to safely use string values in `filter_by`:
24+
25+
```php
26+
use Typesense\FilterBy;
27+
28+
$filterValue = "The 17\" O'Conner && O`Series \n OR a || 1%2 book? (draft), [alpha]";
29+
$filterBy = 'tags:=' . FilterBy::escapeString($filterValue);
30+
```
31+
2132
## Compatibility
2233

2334
| Typesense Server | typesense-php |

src/FilterBy.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php
2+
3+
namespace Typesense;
4+
5+
class FilterBy
6+
{
7+
public static function escapeString(string $value): string
8+
{
9+
return '`' . str_replace('`', '\\`', $value) . '`';
10+
}
11+
}

tests/Feature/FilterByTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
3+
namespace Feature;
4+
5+
use PHPUnit\Framework\TestCase;
6+
use Typesense\FilterBy;
7+
8+
class FilterByTest extends TestCase
9+
{
10+
public function testEscapesSpecialCharactersByWrappingInBackticks(): void
11+
{
12+
$rawFilterValue = "The 17\" O'Conner && O`Series \n OR a || 1%2 book? (draft), [alpha]";
13+
14+
$escapedFilterValue = FilterBy::escapeString($rawFilterValue);
15+
16+
$this->assertSame(
17+
"`The 17\" O'Conner && O\\`Series \n OR a || 1%2 book? (draft), [alpha]`",
18+
$escapedFilterValue
19+
);
20+
}
21+
22+
public function testEscapesMultipleBackticksWithinAFilterString(): void
23+
{
24+
$escapedFilterValue = FilterBy::escapeString('`left` and `right`');
25+
26+
$this->assertSame('`\\`left\\` and \\`right\\``', $escapedFilterValue);
27+
}
28+
}

0 commit comments

Comments
 (0)