<?php
declare(strict_types=1);

namespace App\Doctrine;

use ApiPlatform\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
use ApiPlatform\Doctrine\Orm\Extension\QueryItemExtensionInterface;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\Operation;
use Doctrine\ORM\QueryBuilder;
use Exception;

/**
 * Base class for custom doctrine extensions
 */
abstract class AbstractExtension implements QueryCollectionExtensionInterface, QueryItemExtensionInterface
{
    /**
     * Called by doctrine when getting a collection
     *
     * @param QueryBuilder $queryBuilder
     * @param QueryNameGeneratorInterface $queryNameGenerator
     * @param string $resourceClass
     * @param Operation|null $operation
     * @param mixed[] $context
     * @return void
     * @throws Exception
     */
    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, Operation $operation = null, array $context = []): void
    {
        $this->apply($queryBuilder, $resourceClass, $operation);
    }

    /**
     * Called by doctrine when getting an item
     *
     * @param QueryBuilder $queryBuilder
     * @param QueryNameGeneratorInterface $queryNameGenerator
     * @param string $resourceClass
     * @param list<int> $identifiers
     * @param Operation|null $operation
     * @param mixed[] $context
     * @return void
     * @throws Exception
     */
    public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, Operation $operation = null, array $context = []): void
    {
        $this->apply($queryBuilder, $resourceClass, $operation);
    }

    /**
     * Generic application of the extension
     *
     * @param $queryBuilder
     * @param $resourceClass
     * @return void
     */
    protected function apply(QueryBuilder $queryBuilder, string $resourceClass, ?Operation $operation): void {
        if (!$this->supports($resourceClass, $operation)) {
            return;
        }
        $this->addWhere($queryBuilder, $resourceClass, $operation);
    }

    /**
     * Returns true if the extension supports the given resource
     *
     * @param string $resourceClass
     * @return bool
     */
    abstract protected function supports(string $resourceClass, ?Operation $operation): bool;

    /**
     * Add one or more filters to the query
     *
     * @param QueryBuilder $queryBuilder
     * @param string $resourceClass
     * @return void
     */
    abstract protected function addWhere(QueryBuilder $queryBuilder, string $resourceClass, ?Operation $operation): void;
}
