api platform, can't add a custom search filter to an abstract class using symfony 4

581 Views Asked by At

I'm trying to create a custom search filter to an abstract class, i want to be able to search by one keyword .

The search filter code :

public function getDescription(string $resourceClass): array
    {
        $reader = new AnnotationReader();
        $annotation = $reader->getClassAnnotation(new \ReflectionClass(new $resourceClass), SearchAnnotation::class);

        $description['search'] = [
            'property' => 'search',
            'type' => 'string',
            'required' => false,
            'swagger' => ['description' => 'FullTextFilter on ' . implode(', ', $annotation->fields)],
        ];

        return $description;
    }

The custom search try to get a new instance of the resource class but in my case it's an abstract class and i got an error about :

Cannot instantiate abstract class.

In the filterProperty function i need to fetch fields from annotation :

$reader = new AnnotationReader();
        $annotation = $reader->getClassAnnotation(new \ReflectionClass(new $resourceClass), SearchAnnotation::class);

        if (!$annotation) {
            throw new \HttpInvalidParamException('No Search implemented.');
        }

        $parameterName = $queryNameGenerator->generateParameterName($property);
        $search = [];
        $mappedJoins = [];

        foreach ($annotation->fields as $field)
        {
            $joins = explode(".", $field);
            for ($lastAlias = 'o', $i = 0, $num = count($joins); $i < $num; $i++) {
                $currentAlias = $joins[$i];
                if ($i === $num - 1) {
                    $search[] = "{$lastAlias}.{$currentAlias} = :{$parameterName}";
                } else {
                    $join = "{$lastAlias}.{$currentAlias}";
                    if (false === array_search($join, $mappedJoins)) {
                        $queryBuilder->leftJoin($join, $currentAlias);
                        $mappedJoins[] = $join;
                    }
                }

                $lastAlias = $currentAlias;
            }
        }

I need to fetch fields without instantiate the abstract class .

I tried to remove the new resource class by calling :

 $reader = new AnnotationReader();
        $annotation = $reader->getClassAnnotation(new \ReflectionClass(AbstractContact::class), SearchAnnotation::class);

I got : Trying to get property 'fields' of non-object

1

There are 1 best solutions below

5
On BEST ANSWER

No need to instantiate the class, you have access to $this->properties

Reference : https://api-platform.com/docs/core/filters/#creating-custom-filters