From b32edd0c8881bd9d026e143e1a41c6a6ee76ea2b Mon Sep 17 00:00:00 2001 From: adriafigueres Date: Mon, 18 Nov 2024 11:09:40 +0000 Subject: [PATCH 1/2] feat: Adding boolean filter --- src/Laravel/Eloquent/Filter/BooleanFilter.php | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/Laravel/Eloquent/Filter/BooleanFilter.php diff --git a/src/Laravel/Eloquent/Filter/BooleanFilter.php b/src/Laravel/Eloquent/Filter/BooleanFilter.php new file mode 100644 index 00000000000..d378114149e --- /dev/null +++ b/src/Laravel/Eloquent/Filter/BooleanFilter.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace ApiPlatform\Laravel\Eloquent\Filter; + +use ApiPlatform\Metadata\Parameter; +use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\Model; + +final class BooleanFilter implements FilterInterface +{ + use QueryPropertyTrait; + + /** + * @param Builder $builder + * @param array $context + */ + public function apply(Builder $builder, mixed $values, Parameter $parameter, array $context = []): Builder + { + $booleanValues = [ + 'true' => true, + 'false' => false, + '1' => true, + '0' => false, + ]; + + if (array_key_exists($values, $booleanValues)) { + $values = $booleanValues[$values]; + } + + return $builder->{$context['whereClause'] ?? 'where'}($this->getQueryProperty($parameter), $values); + } +} From 108281d3dbac854ca55ce6a433f19c81dd793558 Mon Sep 17 00:00:00 2001 From: adriafigueres Date: Mon, 18 Nov 2024 13:48:13 +0000 Subject: [PATCH 2/2] refactor: return early if wrong values --- src/Laravel/Eloquent/Filter/BooleanFilter.php | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Laravel/Eloquent/Filter/BooleanFilter.php b/src/Laravel/Eloquent/Filter/BooleanFilter.php index d378114149e..3a869848239 100644 --- a/src/Laravel/Eloquent/Filter/BooleanFilter.php +++ b/src/Laravel/Eloquent/Filter/BooleanFilter.php @@ -21,21 +21,21 @@ final class BooleanFilter implements FilterInterface { use QueryPropertyTrait; + private const BOOLEAN_VALUES = [ + 'true' => true, + 'false' => false, + '1' => true, + '0' => false, + ]; + /** * @param Builder $builder * @param array $context */ public function apply(Builder $builder, mixed $values, Parameter $parameter, array $context = []): Builder { - $booleanValues = [ - 'true' => true, - 'false' => false, - '1' => true, - '0' => false, - ]; - - if (array_key_exists($values, $booleanValues)) { - $values = $booleanValues[$values]; + if (!is_string($values) || !array_key_exists($values, self::BOOLEAN_VALUES)) { + return $builder; } return $builder->{$context['whereClause'] ?? 'where'}($this->getQueryProperty($parameter), $values);