scout
scout copied to clipboard
fix(typesense): properly format boolean filters in Typesense
Rationale
This change addresses an issue where boolean filters were not properly handled in the TypesenseEngine for Laravel Scout. When users attempted to search with a boolean filter (e.g., Model::search($query)->where('myFilter', true)->get()), the engine was incorrectly transforming boolean values to integers before passing them to the Typesense SDK. This resulted in a Typesense\Exceptions\RequestMalformed exception with the message "Value of filter field myFilter must be true or false."
By implementing this fix, we ensure that boolean filters are correctly formatted and passed to Typesense, allowing users to perform searches with boolean conditions as expected.
Changes
Code Changes:
- In
src/Engines/TypesenseEngine.php:- Modified the
filtersmethod to use a newparseFilterValuemethod when processingwheresandwhereIns. - Added a new
parseFilterValuemethod to handle various data types, including booleans:protected function parseFilterValue(array|string|bool|int|float $value) { if (is_array($value)) { return array_map([$this, 'parseFilterValue'], $value); } if (gettype($value) == 'boolean') { return $value ? 'true' : 'false'; } return $value; } - Updated
parseWhereInFiltermethod to use string interpolation for better readability.
- Modified the
Test Updates:
- In
tests/Unit/TypesenseEngineTest.php:- Added new test methods to cover the changes:
test_filters_method: Ensures thefiltersmethod correctly formats multiple conditions.test_parse_filter_value_method: Verifies the newparseFilterValuemethod handles various input types correctly.test_parse_where_filter_method: Checks theparseWhereFiltermethod's output for different inputs.test_parse_where_in_filter_method: Validates theparseWhereInFiltermethod's formatting.
- Implemented a helper method
invokeMethodto test protected methods.
- Added new test methods to cover the changes:
Context
This change was prompted by #873. @bredmor encountered a RequestMalformed exception when attempting to use boolean filters with Typesense in Laravel Scout. The problem was traced to the TypesenseEngine::filters() method, which was not properly handling boolean values.
This fix ensures that boolean values are correctly formatted as strings ('true' or 'false') before being sent to Typesense, resolving the exception and allowing users to successfully perform searches with boolean filters.