Skip to content
Open
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
51 changes: 48 additions & 3 deletions src/Doctrine/Orm/State/ItemProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,8 @@ public function provide(Operation $operation, array $uriVariables = [], array $c
}

$fetchData = $context['fetch_data'] ?? true;
if (!$fetchData && \array_key_exists('id', $uriVariables)) {
// todo : if uriVariables don't contain the id, this fails. This should behave like it does in the following code
return $manager->getReference($entityClass, $uriVariables);
if (!$fetchData && null !== ($identifiers = $this->getReferenceIdentifiers($manager, $entityClass, $operation, $uriVariables, $context))) {
return $manager->getReference($entityClass, $identifiers);
}

$repository = $manager->getRepository($entityClass);
Expand All @@ -88,4 +87,50 @@ public function provide(Operation $operation, array $uriVariables = [], array $c

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

/**
* Builds the [identifierField => value] map for getReference() from the resource's own identifier
* links, ignoring parent/relation links a subresource carries (e.g. "companyId") which are not
* identifiers of the entity and would make getReference() throw UnrecognizedIdentifierFields.
*
* Returns null (so the caller falls through to the link-resolving query) when an own identifier
* value is missing, or when a resource identifier is not a Doctrine identifier of the entity
* (e.g. a uuid exposed as the API identifier while the table key is "id") and therefore cannot be
* turned into a reference.
*
* @param array<string, mixed> $uriVariables
* @param array<string, mixed> $context
*
* @return array<string, mixed>|null
*/
private function getReferenceIdentifiers(EntityManagerInterface $manager, string $entityClass, Operation $operation, array $uriVariables, array $context): ?array
{
$identifierFields = array_flip($manager->getClassMetadata($entityClass)->getIdentifierFieldNames());

$identifiers = [];
foreach ($this->getLinks($entityClass, $operation, $context) as $parameterName => $link) {
// Mirrors LinksHandlerTrait: the identifier-self link has no relation property and points to the entity itself.
if ($entityClass !== $link->getFromClass() || $link->getFromProperty() || $link->getToProperty()) {
continue;
}

$identifierProperties = $link->getIdentifiers();
$hasCompositeIdentifiers = 1 < \count($identifierProperties);
foreach ($identifierProperties as $identifierProperty) {
if (!isset($identifierFields[$identifierProperty])) {
return null;
}

// Composite identifiers are exploded by field name upstream; a single identifier is keyed by its uriVariable name.
$key = $hasCompositeIdentifiers ? $identifierProperty : $parameterName;
if (!\array_key_exists($key, $uriVariables)) {
return null;
}

$identifiers[$identifierProperty] = $uriVariables[$key];
}
}

return $identifiers ?: null;
}
}
140 changes: 140 additions & 0 deletions src/Doctrine/Orm/Tests/State/ItemProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,146 @@ public function testGetItemDoubleIdentifier(): void
$this->assertEquals($returnObject, $dataProvider->provide($operation, ['ida' => 1, 'idb' => 2], $context));
}

public function testGetItemWithFetchDataFalseOnSubresourceFiltersParentLink(): void
{
$reference = new Employee();

$classMetadataMock = $this->createMock(ClassMetadata::class);
$classMetadataMock->method('getIdentifierFieldNames')->willReturn(['id']);

$managerMock = $this->createMock(EntityManagerInterface::class);
$managerMock->method('getClassMetadata')->with(Employee::class)->willReturn($classMetadataMock);
$managerMock->expects($this->once())
->method('getReference')
->with(Employee::class, ['id' => 2])
->willReturn($reference);

$managerRegistryMock = $this->createMock(ManagerRegistry::class);
$managerRegistryMock->method('getManagerForClass')->with(Employee::class)->willReturn($managerMock);

$operation = (new Get())->withUriVariables([
'companyId' => (new Link())->withFromClass(Company::class)->withToProperty('company'),
'id' => (new Link())->withFromClass(Employee::class)->withIdentifiers(['id']),
])->withName('get')->withClass(Employee::class);

$dataProvider = new ItemProvider(
$this->createStub(ResourceMetadataCollectionFactoryInterface::class),
$managerRegistryMock,
);

$this->assertSame($reference, $dataProvider->provide($operation, ['companyId' => 1, 'id' => 2], ['fetch_data' => false]));
}

public function testGetItemWithFetchDataFalseMapsRenamedIdentifierUriVariable(): void
{
$reference = new Employee();

$classMetadataMock = $this->createMock(ClassMetadata::class);
$classMetadataMock->method('getIdentifierFieldNames')->willReturn(['id']);

$managerMock = $this->createMock(EntityManagerInterface::class);
$managerMock->method('getClassMetadata')->with(Employee::class)->willReturn($classMetadataMock);
$managerMock->expects($this->once())
->method('getReference')
->with(Employee::class, ['id' => 2])
->willReturn($reference);

$managerRegistryMock = $this->createMock(ManagerRegistry::class);
$managerRegistryMock->method('getManagerForClass')->with(Employee::class)->willReturn($managerMock);

// The identifier uriVariable is named "employeeId" while the entity's own identifier field is "id".
$operation = (new Get())->withUriVariables([
'companyId' => (new Link())->withFromClass(Company::class)->withToProperty('company'),
'employeeId' => (new Link())->withFromClass(Employee::class)->withIdentifiers(['id'])->withParameterName('employeeId'),
])->withName('get')->withClass(Employee::class);

$dataProvider = new ItemProvider(
$this->createStub(ResourceMetadataCollectionFactoryInterface::class),
$managerRegistryMock,
);

$this->assertSame($reference, $dataProvider->provide($operation, ['companyId' => 1, 'employeeId' => 2], ['fetch_data' => false]));
}

public function testGetItemWithFetchDataFalseFallsBackToQueryWhenOwnIdentifierMissing(): void
{
$returnObject = new \stdClass();

$queryMock = $this->createMock($this->getQueryClass());
$queryMock->method('getOneOrNullResult')->willReturn($returnObject);

$queryBuilderMock = $this->createMock(QueryBuilder::class);
$queryBuilderMock->method('getQuery')->willReturn($queryMock);
$queryBuilderMock->method('getRootAliases')->willReturn(['o']);

$classMetadataMock = $this->createMock(ClassMetadata::class);
$classMetadataMock->method('getIdentifierFieldNames')->willReturn(['id']);

$repositoryMock = $this->createMock(EntityRepository::class);
$repositoryMock->method('createQueryBuilder')->with('o')->willReturn($queryBuilderMock);

$managerMock = $this->createMock(EntityManagerInterface::class);
$managerMock->method('getClassMetadata')->willReturn($classMetadataMock);
$managerMock->method('getRepository')->willReturn($repositoryMock);
// Only the parent link is provided: the own identifier cannot be resolved to a reference,
// so we must fall back to the query that resolves the link instead of calling getReference().
$managerMock->expects($this->never())->method('getReference');

$managerRegistryMock = $this->createMock(ManagerRegistry::class);
$managerRegistryMock->method('getManagerForClass')->willReturn($managerMock);

$operation = (new Get())->withUriVariables([
'companyId' => (new Link())->withFromClass(Company::class)->withToProperty('company')->withIdentifiers(['id']),
'id' => (new Link())->withFromClass(Employee::class)->withIdentifiers(['id']),
])->withName('get')->withClass(Employee::class);

$dataProvider = new ItemProvider(
$this->createStub(ResourceMetadataCollectionFactoryInterface::class),
$managerRegistryMock,
);

$this->assertSame($returnObject, $dataProvider->provide($operation, ['companyId' => 1], ['fetch_data' => false]));
}

public function testGetItemWithFetchDataFalseFallsBackToQueryWhenIdentifierIsNotADoctrineIdentifier(): void
{
$returnObject = new \stdClass();

$queryMock = $this->createMock($this->getQueryClass());
$queryMock->method('getOneOrNullResult')->willReturn($returnObject);

$queryBuilderMock = $this->createMock(QueryBuilder::class);
$queryBuilderMock->method('getQuery')->willReturn($queryMock);
$queryBuilderMock->method('getRootAliases')->willReturn(['o']);

// The Doctrine identifier is "id" while the resource exposes "uuid" as its API identifier:
// getReference() cannot be built from "uuid", so we must fall back to the query.
$classMetadataMock = $this->createMock(ClassMetadata::class);
$classMetadataMock->method('getIdentifierFieldNames')->willReturn(['id']);

$repositoryMock = $this->createMock(EntityRepository::class);
$repositoryMock->method('createQueryBuilder')->with('o')->willReturn($queryBuilderMock);

$managerMock = $this->createMock(EntityManagerInterface::class);
$managerMock->method('getClassMetadata')->willReturn($classMetadataMock);
$managerMock->method('getRepository')->willReturn($repositoryMock);
$managerMock->expects($this->never())->method('getReference');

$managerRegistryMock = $this->createMock(ManagerRegistry::class);
$managerRegistryMock->method('getManagerForClass')->willReturn($managerMock);

$operation = (new Get())->withUriVariables([
'uuid' => (new Link())->withFromClass(Employee::class)->withIdentifiers(['uuid'])->withParameterName('uuid'),
])->withName('get')->withClass(Employee::class);

$dataProvider = new ItemProvider(
$this->createStub(ResourceMetadataCollectionFactoryInterface::class),
$managerRegistryMock,
);

$this->assertSame($returnObject, $dataProvider->provide($operation, ['uuid' => '61817181-0ecc-42fb-a6e7-d97f2ddcb344'], ['fetch_data' => false]));
}

public function testQueryResultExtension(): void
{
$returnObject = new \stdClass();
Expand Down
72 changes: 72 additions & 0 deletions tests/Functional/Doctrine/FetchDataFalseSubresourceTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

/*
* 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.
*/

declare(strict_types=1);

namespace ApiPlatform\Tests\Functional\Doctrine;

use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\Company;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\Employee;
use ApiPlatform\Tests\RecreateSchemaTrait;
use ApiPlatform\Tests\SetupClassResourcesTrait;

final class FetchDataFalseSubresourceTest extends ApiTestCase
{
use RecreateSchemaTrait;
use SetupClassResourcesTrait;

protected static ?bool $alwaysBootKernel = false;

/**
* @return class-string[]
*/
public static function getResources(): array
{
return [Company::class, Employee::class];
}

public function testGetResourceFromSubresourceIriWithFetchDataFalseReturnsReference(): void
{
$container = static::getContainer();
if ('mongodb' === $container->getParameter('kernel.environment')) {
$this->markTestSkipped('getReference()/UnrecognizedIdentifierFields is ORM specific.');
}

$this->recreateSchema([Company::class, Employee::class]);

$manager = $this->getManager();
$company = new Company();
$company->name = 'test';
$manager->persist($company);

$employees = [];
for ($i = 0; $i < 3; ++$i) {
$employee = new Employee();
$employee->name = "Employee number $i";
$employee->company = $company;
$manager->persist($employee);
$employees[] = $employee;
}
$manager->flush();

$employee = $employees[1];
$iri = \sprintf('/companies/%d/employees/%d', $company->getId(), $employee->getId());

// fetch_data=false short-circuits to EntityManager::getReference(); the subresource IRI carries the
// parent link "companyId" which is not an identifier of Employee and used to raise
// Doctrine\ORM\Exception\UnrecognizedIdentifierFields ('companyId'). See #8124.
$reference = $container->get('api_platform.iri_converter')->getResourceFromIri($iri, ['fetch_data' => false]);

$this->assertInstanceOf(Employee::class, $reference);
$this->assertSame($employee->getId(), $reference->getId());
}
}
Loading