Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 105 additions & 0 deletions src/Api/CachedIdentifiersExtractor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<?php

declare(strict_types=1);
Copy link
Member

Choose a reason for hiding this comment

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

Missing blank line


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

namespace ApiPlatform\Core\Api;

use ApiPlatform\Core\Util\ClassInfoTrait;
use Psr\Cache\CacheException;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;

/**
* {@inheritdoc}
*
* @author Antoine Bluchet <soyuka@gmail.com>
*/
final class CachedIdentifiersExtractor implements IdentifiersExtractorInterface
{
use ClassInfoTrait;

const CACHE_KEY_PREFIX = 'iri_identifiers';

private $cacheItemPool;
private $propertyAccessor;
private $decorated;

public function __construct(CacheItemPoolInterface $cacheItemPool, IdentifiersExtractorInterface $decorated, PropertyAccessorInterface $propertyAccessor = null)
{
$this->cacheItemPool = $cacheItemPool;
$this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
$this->decorated = $decorated;
}

/**
* {@inheritdoc}
*/
public function getIdentifiersFromItem($item): array
{
$identifiers = [];
$resourceClass = $this->getObjectClass($item);

$cacheKey = self::CACHE_KEY_PREFIX.md5($resourceClass);

// This is to avoid setting the cache twice in the case where the related item cache doesn't exist
$cacheIsHit = false;

try {
$cacheItem = $this->cacheItemPool->getItem($cacheKey);
$isRelationCached = true;

if ($cacheIsHit = $cacheItem->isHit()) {
foreach ($cacheItem->get() as $propertyName) {
$identifiers[$propertyName] = $this->propertyAccessor->getValue($item, $propertyName);

if (!is_object($identifiers[$propertyName])) {
continue;
}

$relatedItem = $identifiers[$propertyName];
$relatedCacheKey = self::CACHE_KEY_PREFIX.md5($this->getObjectClass($relatedItem));

$relatedCacheItem = $this->cacheItemPool->getItem($relatedCacheKey);

if (!$relatedCacheItem->isHit()) {
$isRelationCached = false;
break;
}

unset($identifiers[$propertyName]);

$identifiers[$propertyName] = $this->propertyAccessor->getValue($relatedItem, $relatedCacheItem->get()[0]);
}

if (true === $isRelationCached) {
return $identifiers;
}
}
} catch (CacheException $e) {
// do nothing
}

$identifiers = $this->decorated->getIdentifiersFromItem($item);

if (isset($cacheItem) && false === $cacheIsHit) {
try {
$cacheItem->set(array_keys($identifiers));
$this->cacheItemPool->save($cacheItem);
} catch (CacheException $e) {
// do nothing
}
}

return $identifiers;
}
}
89 changes: 89 additions & 0 deletions src/Api/IdentifiersExtractor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?php

declare(strict_types=1);
Copy link
Member

Choose a reason for hiding this comment

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

missing blank line


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

namespace ApiPlatform\Core\Api;

use ApiPlatform\Core\Exception\RuntimeException;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Core\Util\ClassInfoTrait;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;

/**
* {@inheritdoc}
*
* @author Antoine Bluchet <soyuka@gmail.com>
*/
final class IdentifiersExtractor implements IdentifiersExtractorInterface
{
use ClassInfoTrait;

private $propertyNameCollectionFactory;
private $propertyMetadataFactory;
private $propertyAccessor;

public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, PropertyAccessorInterface $propertyAccessor = null)
{
$this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
$this->propertyMetadataFactory = $propertyMetadataFactory;
$this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
}

/**
* {@inheritdoc}
*/
public function getIdentifiersFromItem($item): array
{
$identifiers = [];
$resourceClass = $this->getObjectClass($item);

foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $propertyName) {
$propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);

$identifier = $propertyMetadata->isIdentifier();
if (null === $identifier || false === $identifier) {
continue;
}

$identifiers[$propertyName] = $this->propertyAccessor->getValue($item, $propertyName);

if (!is_object($identifiers[$propertyName])) {
continue;
}

$relatedResourceClass = $this->getObjectClass($identifiers[$propertyName]);
$relatedItem = $identifiers[$propertyName];

unset($identifiers[$propertyName]);

foreach ($this->propertyNameCollectionFactory->create($relatedResourceClass) as $relatedPropertyName) {
$propertyMetadata = $this->propertyMetadataFactory->create($relatedResourceClass, $relatedPropertyName);

if ($propertyMetadata->isIdentifier()) {
if (isset($identifiers[$propertyName])) {
throw new RuntimeException(sprintf('Composite identifiers not supported in "%s" through relation "%s" of "%s" used as identifier', $relatedResourceClass, $propertyName, $resourceClass));
Copy link
Member Author

Choose a reason for hiding this comment

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

@teohhanhui I'm having a hard time trying to add test coverage on this one. IMO this is not a valid case, but maybe you can give me some more context/informations about the Exception? Origin commit you authored.

}

$identifiers[$propertyName] = $this->propertyAccessor->getValue($relatedItem, $relatedPropertyName);
}
}

if (!isset($identifiers[$propertyName])) {
throw new RuntimeException(sprintf('No identifier found in "%s" through relation "%s" of "%s" used as identifier', $relatedResourceClass, $propertyName, $resourceClass));
}
}

return $identifiers;
}
}
33 changes: 33 additions & 0 deletions src/Api/IdentifiersExtractorInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);
Copy link
Member

Choose a reason for hiding this comment

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

Missing blank line


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

namespace ApiPlatform\Core\Api;

/**
* Extracts identifiers for a given Resource according to the retrieved Metadata.
*
* @author Antoine Bluchet <soyuka@gmail.com>
*/
interface IdentifiersExtractorInterface
{
/**
* Finds identifiers from an Item (object).
*
* @param object $item
*
* @throws RuntimeException
*
* @return array
*/
public function getIdentifiersFromItem($item): array;
}
19 changes: 19 additions & 0 deletions src/Bridge/Symfony/Bundle/Resources/config/api.xml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
<argument type="service" id="api_platform.route_name_resolver" />
<argument type="service" id="api_platform.router" />
<argument type="service" id="api_platform.property_accessor" />
<argument type="service" id="api_platform.identifiers_extractor.cached" />
</service>

<!-- Serializer -->
Expand Down Expand Up @@ -165,11 +166,29 @@
<argument>%api_platform.exception_to_status%</argument>
</service>

<!-- Identifiers extractor -->

<service id="api_platform.identifiers_extractor" class="ApiPlatform\Core\Api\IdentifiersExtractor" public="false">
<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.property_accessor" />
</service>

<service id="api_platform.identifiers_extractor.cached" class="ApiPlatform\Core\Api\CachedIdentifiersExtractor" decorates="api_platform.identifiers_extractor" public="false">
<argument type="service" id="api_platform.cache.identifiers_extractor" />
<argument type="service" id="api_platform.identifiers_extractor.cached.inner" />
<argument type="service" id="api_platform.property_accessor" />
</service>

<!-- Cache -->

<service id="api_platform.cache.route_name_resolver" parent="cache.system" public="false">
<tag name="cache.pool" />
</service>

<service id="api_platform.cache.identifiers_extractor" parent="cache.system" public="false">
<tag name="cache.pool" />
</service>
</services>

</container>
70 changes: 13 additions & 57 deletions src/Bridge/Symfony/Routing/IriConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@

namespace ApiPlatform\Core\Bridge\Symfony\Routing;

use ApiPlatform\Core\Api\IdentifiersExtractor;
use ApiPlatform\Core\Api\IdentifiersExtractorInterface;
use ApiPlatform\Core\Api\IriConverterInterface;
use ApiPlatform\Core\Api\UrlGeneratorInterface;
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
use ApiPlatform\Core\Exception\InvalidArgumentException;
use ApiPlatform\Core\Exception\ItemNotFoundException;
use ApiPlatform\Core\Exception\RuntimeException;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Core\Util\ClassInfoTrait;
Expand All @@ -42,15 +43,23 @@ final class IriConverter implements IriConverterInterface
private $routeNameResolver;
private $router;
private $propertyAccessor;
private $identifiersExtractor;

public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouteNameResolverInterface $routeNameResolver, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null)
public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouteNameResolverInterface $routeNameResolver, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null, IdentifiersExtractorInterface $identifiersExtractor = null)
{
$this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
$this->propertyMetadataFactory = $propertyMetadataFactory;
$this->itemDataProvider = $itemDataProvider;
$this->routeNameResolver = $routeNameResolver;
$this->router = $router;
$this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
$this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();

if (null === $identifiersExtractor) {
@trigger_error('Not injecting ItemIdentifiersExtractor is deprecated since API Platform 2.1 and will not be possible anymore in API Platform 3');
$this->identifiersExtractor = new IdentifiersExtractor($this->propertyNameCollectionFactory, $this->propertyMetadataFactory, $this->propertyAccessor);
} else {
$this->identifiersExtractor = $identifiersExtractor;
}
}

/**
Expand Down Expand Up @@ -83,7 +92,7 @@ public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface
$resourceClass = $this->getObjectClass($item);
$routeName = $this->routeNameResolver->getRouteName($resourceClass, false);

$identifiers = $this->generateIdentifiersUrl($this->getIdentifiersFromItem($item));
$identifiers = $this->generateIdentifiersUrl($this->identifiersExtractor->getIdentifiersFromItem($item));

return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], $referenceType);
}
Expand All @@ -100,59 +109,6 @@ public function getIriFromResourceClass(string $resourceClass, int $referenceTyp
}
}

/**
* Find identifiers from an Item (Object).
*
* @param object $item
*
* @throws RuntimeException
*
* @return array
*/
private function getIdentifiersFromItem($item): array
{
$identifiers = [];
$resourceClass = $this->getObjectClass($item);

foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $propertyName) {
$propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);

$identifier = $propertyMetadata->isIdentifier();
if (null === $identifier || false === $identifier) {
continue;
}

$identifiers[$propertyName] = $this->propertyAccessor->getValue($item, $propertyName);

if (!is_object($identifiers[$propertyName])) {
continue;
}

$relatedResourceClass = $this->getObjectClass($identifiers[$propertyName]);
$relatedItem = $identifiers[$propertyName];

unset($identifiers[$propertyName]);

foreach ($this->propertyNameCollectionFactory->create($relatedResourceClass) as $relatedPropertyName) {
$propertyMetadata = $this->propertyMetadataFactory->create($relatedResourceClass, $relatedPropertyName);

if ($propertyMetadata->isIdentifier()) {
if (isset($identifiers[$propertyName])) {
throw new RuntimeException(sprintf('Composite identifiers not supported in "%s" through relation "%s" of "%s" used as identifier', $relatedResourceClass, $propertyName, $resourceClass));
}

$identifiers[$propertyName] = $this->propertyAccessor->getValue($relatedItem, $relatedPropertyName);
}
}

if (!isset($identifiers[$propertyName])) {
throw new RuntimeException(sprintf('No identifier found in "%s" through relation "%s" of "%s" used as identifier', $relatedResourceClass, $propertyName, $resourceClass));
}
}

return $identifiers;
}

/**
* Generate the identifier url.
*
Expand Down
Loading