Created
March 18, 2025 10:26
-
-
Save soyuka/5a6e7ac20a3737bc2c9553a899a2fd28 to your computer and use it in GitHub Desktop.
Text search filter for JSON:API API Platform
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use ApiPlatform\Metadata\OpenApiParameterFilterInterface; | |
use ApiPlatform\Metadata\Parameter; | |
use ApiPlatform\OpenApi\Model\Parameter as OpenApiParameter; | |
use Illuminate\Database\Eloquent\Builder; | |
use Illuminate\Database\Eloquent\Model; | |
final class PartialSearchFilter implements FilterInterface, OpenApiParameterFilterInterface | |
{ | |
use QueryPropertyTrait; | |
/** | |
* @param Builder<Model> $builder | |
* @param array<string, mixed> $context | |
*/ | |
public function apply(Builder $builder, mixed $values, Parameter $parameter, array $context = []): Builder | |
{ | |
if (!\is_string($values)) { | |
$properties = $parameter->getExtraProperties()['_properties'] ?? []; | |
foreach ($values as $key => $value) { | |
if (!isset($properties[$key])) { | |
continue; | |
} | |
$builder = $builder->where($properties[$key], 'like', '%'.$value.'%'); | |
} | |
return $builder; | |
} | |
return $builder->{$context['whereClause'] ?? 'where'}($this->getQueryProperty($parameter), 'like', '%'.$values.'%'); | |
} | |
/** | |
* @return OpenApiParameter[]|null | |
*/ | |
public function getOpenApiParameters(Parameter $parameter): ?array | |
{ | |
if (str_contains($parameter->getKey(), ':property')) { | |
$parameters = []; | |
$key = str_replace('[:property]', '', $parameter->getKey()); | |
foreach (array_keys($parameter->getExtraProperties()['_properties'] ?? []) as $property) { | |
$parameters[] = new OpenApiParameter(name: \sprintf('%s[%s]', $key, $property), in: 'query'); | |
} | |
return $parameters; | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment