api platform, custom search filter doesn’t work with an abstract class

I tried to add a custom search filter to make possible searching by one word from many class attributes : i want to be able to search my abstract class by name, description and other properties by one word .

In my abstract class i added the custom search filter :

/**
 * A Contact
 *
 * @ApiResource(attributes={
 *     "normalization_context"={"groups"={"contact:read"}},
 *     "denormalization_context"={"groups"={"contact:write"}},
 *     "filters"={"custom.discriminator_filter", "custom.search_filter"}
 * })

In services :

 custom.search_filter:
        class: AppFilterSearchFilter
        autowire: true
        tags: [ { name: 'api_platform.filter', id: 'search' } ]

The search filter :

protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
    {
        if ($property === 'search') {
            $this->logger->info('Search for: ' . $value);
        } else {
            return;
        }

        $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;
            }
        }

        $queryBuilder->andWhere(implode(' OR ', $search));
        $queryBuilder->setParameter($parameterName, '%' . $value . '%');
    }

i got an error about abstract class instantiation when i call new ReflectionClass(new $resourceClass) .

How can i edit this code to correctly add my filter.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *