Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Instruct Doctrine Orm Bridge to use result cache or second level cache #2789

Closed
wants to merge 15 commits into from
8 changes: 8 additions & 0 deletions src/Annotation/ApiResource.php
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
* @Attribute("denormalizationContext", type="array"),
* @Attribute("deprecationReason", type="string"),
* @Attribute("description", type="string"),
* @Attribute("doctrineCache", type="array"),
* @Attribute("elasticsearch", type="bool"),
* @Attribute("fetchPartial", type="bool"),
* @Attribute("forceEager", type="bool"),
Expand Down Expand Up @@ -138,6 +139,13 @@ final class ApiResource
*/
private $deprecationReason;

/**
* @see https://github.com/Haehnchen/idea-php-annotation-plugin/issues/112
*
* @var array
*/
private $doctrineCache;

/**
* @see https://github.com/Haehnchen/idea-php-annotation-plugin/issues/112
*
Expand Down
112 changes: 112 additions & 0 deletions src/Bridge/Doctrine/Orm/Cache/QueryExpander.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This class should be an extension that alters the query probably implementing QueryResult{Collection|Item}ExtensionInterface.


/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Core\Bridge\Doctrine\Orm\Cache;

use ApiPlatform\Core\Exception\ResourceClassNotFoundException;
use ApiPlatform\Core\Exception\RuntimeException;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use Doctrine\ORM\AbstractQuery;

/**
* Class QueryExpander.
*
* Expands Query settings with Second Level Cache and Result Cache settings from attributes.
*
* @author st-it <[email protected]>
*/
class QueryExpander
{
public const DOCTRINE_CACHE_CONFIG_ATTR = 'doctrine_cache';
public const CACHEABLE_ATTR = 'cacheable';
public const CACHE_HINT_ATTR = 'cache_hint';
public const CACHE_MODE_ATTR = 'cache_mode';
public const USE_RESULT_CACHE_ATTR = 'use_result_cache';

private $resourceMetadataFactory;

public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory)
{
$this->resourceMetadataFactory = $resourceMetadataFactory;
}

/**
* @throws ResourceClassNotFoundException
*/
public function expand(string $resourceClass, AbstractQuery $query)
{
$cacheConfig = $this->getDoctrineCacheConfig($resourceClass);
if (null !== $cacheConfig) {
$this->processCacheable($cacheConfig, $query);
$this->processCacheHint($cacheConfig, $query);
$this->processCacheMode($cacheConfig, $query);
$this->processResultCache($cacheConfig, $query);
}
}

/**
* @throws ResourceClassNotFoundException
*/
private function getDoctrineCacheConfig(string $resourceClass): ?array
{
$resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
$config = $resourceMetadata->getAttribute(self::DOCTRINE_CACHE_CONFIG_ATTR, null);

return \is_array($config) ? $config : null;
}

private function processCacheable(array $cacheConfig, AbstractQuery $query)
{
if (false !== ($cacheConfig[self::CACHEABLE_ATTR] ?? false)) {
$query->setCacheable(true);
}
}

/**
* @throws RuntimeException
*/
private function processCacheHint(array $cacheConfig, AbstractQuery $query)
{
if (null !== $cacheHint = $cacheConfig[self::CACHE_HINT_ATTR] ?? null) {
if (!\is_array($cacheHint)) {
throw new RuntimeException(sprintf('Attribute value %s should be an array', self::CACHE_HINT_ATTR));
}
foreach ($cacheHint as $name => $value) {
$query->setHint($name, $value);
}
}
}

private function processCacheMode(array $cacheConfig, AbstractQuery $query)
{
if (null !== $cacheMode = $cacheConfig[self::CACHE_MODE_ATTR] ?? null) {
$query->setCacheMode($cacheMode);
}
}

/**
* @throws RuntimeException
*/
private function processResultCache(array $cacheConfig, AbstractQuery $query)
{
if (null !== $useResultCache = $cacheConfig[self::USE_RESULT_CACHE_ATTR] ?? null) {
if (!\is_array($useResultCache)) {
throw new RuntimeException(sprintf('Attribute value %s should be an array', self::USE_RESULT_CACHE_ATTR));
}
if (empty($useResultCache) || 3 < \count($useResultCache)) {
throw new RuntimeException(sprintf('Attribute %s should at least contain one item for use. Other options are lifetime and and result cache id', self::USE_RESULT_CACHE_ATTR));
}
$query->useResultCache(...$useResultCache);
}
}
}
11 changes: 9 additions & 2 deletions src/Bridge/Doctrine/Orm/CollectionDataProvider.php
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@

namespace ApiPlatform\Core\Bridge\Doctrine\Orm;

use ApiPlatform\Core\Bridge\Doctrine\Orm\Cache\QueryExpander;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\ContextAwareQueryCollectionExtensionInterface;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryResultCollectionExtensionInterface;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGenerator;
use ApiPlatform\Core\DataProvider\ContextAwareCollectionDataProviderInterface;
use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
use ApiPlatform\Core\Exception\ResourceClassNotFoundException;
use ApiPlatform\Core\Exception\RuntimeException;
use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\Common\Persistence\ObjectManager;
Expand All @@ -34,14 +36,16 @@ class CollectionDataProvider implements ContextAwareCollectionDataProviderInterf
{
private $managerRegistry;
private $collectionExtensions;
private $queryExpander;

/**
* @param QueryCollectionExtensionInterface[]|ContextAwareQueryCollectionExtensionInterface[] $collectionExtensions
*/
public function __construct(ManagerRegistry $managerRegistry, /* iterable */ $collectionExtensions = [])
public function __construct(ManagerRegistry $managerRegistry, QueryExpander $queryExpander, /* iterable */ $collectionExtensions = [])
{
$this->managerRegistry = $managerRegistry;
$this->collectionExtensions = $collectionExtensions;
$this->queryExpander = $queryExpander;
}

public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
Expand All @@ -53,6 +57,7 @@ public function supports(string $resourceClass, string $operationName = null, ar
* {@inheritdoc}
*
* @throws RuntimeException
* @throws ResourceClassNotFoundException
*/
public function getCollection(string $resourceClass, string $operationName = null, array $context = [])
{
Expand All @@ -73,7 +78,9 @@ public function getCollection(string $resourceClass, string $operationName = nul
return $extension->getResult($queryBuilder, $resourceClass, $operationName, $context);
}
}
$query = $queryBuilder->getQuery();
$this->queryExpander->expand($resourceClass, $query);

return $queryBuilder->getQuery()->getResult();
return $query->getResult();
}
}
18 changes: 17 additions & 1 deletion src/Bridge/Doctrine/Orm/Extension/PaginationExtension.php
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace ApiPlatform\Core\Bridge\Doctrine\Orm\Extension;

use ApiPlatform\Core\Bridge\Doctrine\Orm\AbstractPaginator;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Cache\QueryExpander;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryChecker;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
Expand Down Expand Up @@ -51,12 +52,14 @@ final class PaginationExtension implements ContextAwareQueryResultCollectionExte
private $clientPartial;
private $partialParameterName;
private $pagination;
private $queryExpander;

/**
* @param ResourceMetadataFactoryInterface|RequestStack $resourceMetadataFactory
* @param Pagination|ResourceMetadataFactoryInterface $pagination
* @param mixed|null $queryExpander
*/
public function __construct(ManagerRegistry $managerRegistry, /* ResourceMetadataFactoryInterface */ $resourceMetadataFactory, /* Pagination */ $pagination)
public function __construct(ManagerRegistry $managerRegistry, /* ResourceMetadataFactoryInterface */ $resourceMetadataFactory, /* Pagination */ $pagination, /* ?QueryExpander */ $queryExpander = null)
{
if ($resourceMetadataFactory instanceof RequestStack && $pagination instanceof ResourceMetadataFactoryInterface) {
@trigger_error(sprintf('Passing an instance of "%s" as second argument of "%s" is deprecated since API Platform 2.4 and will not be possible anymore in API Platform 3. Pass an instance of "%s" instead.', RequestStack::class, self::class, ResourceMetadataFactoryInterface::class), E_USER_DEPRECATED);
Expand Down Expand Up @@ -105,6 +108,7 @@ public function __construct(ManagerRegistry $managerRegistry, /* ResourceMetadat
$this->managerRegistry = $managerRegistry;
$this->resourceMetadataFactory = $resourceMetadataFactory;
$this->pagination = $pagination;
$this->queryExpander = $queryExpander;
}

/**
Expand Down Expand Up @@ -145,6 +149,10 @@ public function supportsResult(string $resourceClass, string $operationName = nu
public function getResult(QueryBuilder $queryBuilder, string $resourceClass = null, string $operationName = null, array $context = [])
{
$query = $queryBuilder->getQuery();
$queryExpanderResourceClass = $resourceClass ?? $this->getResourceClassFromQueryBuilder($queryBuilder);
if (null !== $this->queryExpander && null !== $queryExpanderResourceClass) {
$this->queryExpander->expand($queryExpanderResourceClass, $query);
}

// Only one alias, without joins, disable the DISTINCT on the COUNT
if (1 === \count($queryBuilder->getAllAliases())) {
Expand Down Expand Up @@ -236,6 +244,14 @@ private function getPagination(QueryBuilder $queryBuilder, string $resourceClass
return [$firstResult, $itemsPerPage];
}

private function getResourceClassFromQueryBuilder(QueryBuilder $queryBuilder): ?string
{
$fromPart = $queryBuilder->getDQLPart('from');
if (1 === \count($fromPart)) {
return $fromPart[0]->getFrom();
}
}

private function isPartialPaginationEnabled(Request $request = null, ResourceMetadata $resourceMetadata = null, string $operationName = null): bool
{
$enabled = $this->partial;
Expand Down
9 changes: 7 additions & 2 deletions src/Bridge/Doctrine/Orm/ItemDataProvider.php
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace ApiPlatform\Core\Bridge\Doctrine\Orm;

use ApiPlatform\Core\Bridge\Doctrine\Common\Util\IdentifierManagerTrait;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Cache\QueryExpander;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryItemExtensionInterface;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryResultItemExtensionInterface;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGenerator;
Expand Down Expand Up @@ -42,16 +43,18 @@ class ItemDataProvider implements DenormalizedIdentifiersAwareItemDataProviderIn

private $managerRegistry;
private $itemExtensions;
private $queryExpander;

/**
* @param QueryItemExtensionInterface[] $itemExtensions
*/
public function __construct(ManagerRegistry $managerRegistry, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, /* iterable */ $itemExtensions = [])
public function __construct(ManagerRegistry $managerRegistry, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, QueryExpander $queryExpander, /* iterable */ $itemExtensions = [])
{
$this->managerRegistry = $managerRegistry;
$this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
$this->propertyMetadataFactory = $propertyMetadataFactory;
$this->itemExtensions = $itemExtensions;
$this->queryExpander = $queryExpander;
}

public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
Expand Down Expand Up @@ -98,8 +101,10 @@ public function getItem(string $resourceClass, $id, string $operationName = null
return $extension->getResult($queryBuilder, $resourceClass, $operationName, $context);
}
}
$query = $queryBuilder->getQuery();
$this->queryExpander->expand($resourceClass, $query);

return $queryBuilder->getQuery()->getOneOrNullResult();
return $query->getOneOrNullResult();
}

/**
Expand Down
7 changes: 6 additions & 1 deletion src/Bridge/Doctrine/Orm/SubresourceDataProvider.php
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace ApiPlatform\Core\Bridge\Doctrine\Orm;

use ApiPlatform\Core\Bridge\Doctrine\Common\Util\IdentifierManagerTrait;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Cache\QueryExpander;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\FilterEagerLoadingExtension;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryItemExtensionInterface;
Expand Down Expand Up @@ -43,18 +44,20 @@ final class SubresourceDataProvider implements SubresourceDataProviderInterface
private $managerRegistry;
private $collectionExtensions;
private $itemExtensions;
private $queryExpander;

/**
* @param QueryCollectionExtensionInterface[] $collectionExtensions
* @param QueryItemExtensionInterface[] $itemExtensions
*/
public function __construct(ManagerRegistry $managerRegistry, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, /* iterable */ $collectionExtensions = [], /* iterable */ $itemExtensions = [])
public function __construct(ManagerRegistry $managerRegistry, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, QueryExpander $queryExpander, /* iterable */ $collectionExtensions = [], /* iterable */ $itemExtensions = [])
{
$this->managerRegistry = $managerRegistry;
$this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
$this->propertyMetadataFactory = $propertyMetadataFactory;
$this->collectionExtensions = $collectionExtensions;
$this->itemExtensions = $itemExtensions;
$this->queryExpander = $queryExpander;
}

/**
Expand Down Expand Up @@ -116,6 +119,8 @@ public function getSubresource(string $resourceClass, array $identifiers, array

$query = $queryBuilder->getQuery();

$this->queryExpander->expand($resourceClass, $query);

return $context['collection'] ? $query->getResult() : $query->getOneOrNullResult();
}

Expand Down
9 changes: 9 additions & 0 deletions src/Bridge/Symfony/Bundle/Resources/config/doctrine_orm.xml
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,30 @@
<tag name="api_platform.data_persister" priority="-1000" />
</service>

<service id="api_platform.doctrine.orm.cache.query_expander" class="ApiPlatform\Core\Bridge\Doctrine\Orm\Cache\QueryExpander" public="false">
<argument type="service" id="api_platform.metadata.resource.metadata_factory" />
</service>
<service id="ApiPlatform\Core\Bridge\Doctrine\Orm\Cache\QueryExpander" alias="api_platform.doctrine.orm.cache.query_expander" />

<service id="api_platform.doctrine.orm.collection_data_provider" public="false" abstract="true">
<argument type="service" id="doctrine" />
<argument type="service" id="api_platform.doctrine.orm.cache.query_expander" />
<argument type="tagged" tag="api_platform.doctrine.orm.query_extension.collection" />
</service>

<service id="api_platform.doctrine.orm.item_data_provider" public="false" abstract="true">
<argument type="service" id="doctrine" />
<argument type="service" id="api_platform.metadata.property.name_collection_factory" />
<argument type="service" id="api_platform.metadata.property.metadata_factory" />
<argument type="service" id="api_platform.doctrine.orm.cache.query_expander" />
<argument type="tagged" tag="api_platform.doctrine.orm.query_extension.item" />
</service>

<service id="api_platform.doctrine.orm.subresource_data_provider" public="false" abstract="true">
<argument type="service" id="doctrine" />
<argument type="service" id="api_platform.metadata.property.name_collection_factory" />
<argument type="service" id="api_platform.metadata.property.metadata_factory" />
<argument type="service" id="api_platform.doctrine.orm.cache.query_expander" />
<argument type="tagged" tag="api_platform.doctrine.orm.query_extension.collection" />
<argument type="tagged" tag="api_platform.doctrine.orm.query_extension.item" />
</service>
Expand Down Expand Up @@ -158,6 +166,7 @@
<argument type="service" id="doctrine" />
<argument type="service" id="api_platform.metadata.resource.metadata_factory" />
<argument type="service" id="api_platform.pagination" />
<argument type="service" id="api_platform.doctrine.orm.cache.query_expander" />

<tag name="api_platform.doctrine.orm.query_extension.collection" priority="-64" />
</service>
Expand Down
Loading