AbstractExtension.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Doctrine;
  4. use ApiPlatform\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
  5. use ApiPlatform\Doctrine\Orm\Extension\QueryItemExtensionInterface;
  6. use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
  7. use ApiPlatform\Metadata\Operation;
  8. use Doctrine\ORM\QueryBuilder;
  9. /**
  10. * Base class for custom doctrine extensions.
  11. */
  12. abstract class AbstractExtension implements QueryCollectionExtensionInterface, QueryItemExtensionInterface
  13. {
  14. /**
  15. * Called by doctrine when getting a collection.
  16. *
  17. * @param mixed[] $context
  18. *
  19. * @throws \Exception
  20. */
  21. public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, array $context = []): void
  22. {
  23. $this->apply($queryBuilder, $resourceClass, $operation);
  24. }
  25. /**
  26. * Called by doctrine when getting an item.
  27. *
  28. * @param array<string, mixed> $identifiers
  29. * @param mixed[] $context
  30. *
  31. * @throws \Exception
  32. */
  33. public function applyToItem(
  34. QueryBuilder $queryBuilder,
  35. QueryNameGeneratorInterface $queryNameGenerator,
  36. string $resourceClass,
  37. array $identifiers,
  38. ?Operation $operation = null,
  39. array $context = []
  40. ): void
  41. {
  42. $this->apply($queryBuilder, $resourceClass, $operation);
  43. }
  44. /**
  45. * Generic application of the extension.
  46. */
  47. protected function apply(QueryBuilder $queryBuilder, string $resourceClass, ?Operation $operation): void
  48. {
  49. if (!$this->supports($resourceClass, $operation)) {
  50. return;
  51. }
  52. $this->addWhere($queryBuilder, $resourceClass, $operation);
  53. }
  54. /**
  55. * Returns true if the extension supports the given resource.
  56. */
  57. abstract protected function supports(string $resourceClass, ?Operation $operation): bool;
  58. /**
  59. * Add one or more filters to the query.
  60. */
  61. abstract protected function addWhere(QueryBuilder $queryBuilder, string $resourceClass, ?Operation $operation): void;
  62. }