<?php
declare(strict_types=1);

namespace App\Filter\Person;

use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\AbstractFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use Doctrine\ORM\QueryBuilder;

class FullNameFilter extends AbstractFilter{
    protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
    {
        if ($property !== 'fullname') {
            return;
        }
        $alias = $queryBuilder->getRootAliases()[0];
        $queryBuilder
            ->innerJoin(sprintf('%s.person', $alias), 'person')
            ->andWhere(sprintf('person.name LIKE :search OR person.givenName LIKE :search', $alias, $alias))
            ->setParameter('search', '%'.$value.'%');
    }

    /**
     * API docs
     * @param string $resourceClass
     * @return array[]
     */
    public function getDescription(string $resourceClass): array
    {
        return [
            'fullname' => [
                'property' => null,
                'type' => 'string',
                'required' => false,
                'openapi' => [
                    'description' => 'Rechercher parmi les champs name et givenName',
                ],
            ]
        ];
    }
}