-
-
Notifications
You must be signed in to change notification settings - Fork 868
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
feat(serializer): add ApiProperty::uriTemplate option #5675
Merged
soyuka
merged 2 commits into
api-platform:main
from
GregoireHebert:iri-only-collection-property
Sep 11, 2023
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
203 changes: 203 additions & 0 deletions
203
docs/guides/return-the-iri-of-your-resources-relations.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,203 @@ | ||
<?php | ||
// --- | ||
// slug: return-the-iri-of-your-resources-relations | ||
// name: How to return an IRI instead of an object for your resources relations ? | ||
// executable: true | ||
// tags: serialization | ||
// --- | ||
|
||
// This guide shows you how to expose the IRI of a related (sub)ressource relation instead of an object. | ||
|
||
namespace App\ApiResource { | ||
use ApiPlatform\Metadata\ApiProperty; | ||
use ApiPlatform\Metadata\ApiResource; | ||
use ApiPlatform\Metadata\Get; | ||
use ApiPlatform\Metadata\GetCollection; | ||
use ApiPlatform\Metadata\Link; | ||
use ApiPlatform\Metadata\Operation; | ||
|
||
#[ApiResource( | ||
operations: [ | ||
new Get(provider: Brand::class.'::provide'), | ||
], | ||
)] | ||
class Brand | ||
{ | ||
public function __construct( | ||
#[ApiProperty(identifier: true)] | ||
public readonly int $id = 1, | ||
|
||
public readonly string $name = 'Anon', | ||
|
||
// Setting uriTemplate on a relation with a resource collection will try to find the related operation. | ||
// It is based on the uriTemplate set on the operation defined on the Car resource (see below). | ||
/** | ||
* @var array<int, Car> $cars | ||
*/ | ||
#[ApiProperty(uriTemplate: '/brands/{brandId}/cars')] | ||
private array $cars = [], | ||
|
||
// Setting uriTemplate on a relation with a resource item will try to find the related operation. | ||
// It is based on the uriTemplate set on the operation defined on the Address resource (see below). | ||
#[ApiProperty(uriTemplate: '/brands/{brandId}/addresses/{id}')] | ||
private ?Address $headQuarters = null | ||
) | ||
{ | ||
} | ||
|
||
/** | ||
* @return array<int, Car> | ||
*/ | ||
public function getCars(): array | ||
{ | ||
return $this->cars; | ||
} | ||
|
||
public function addCar(Car $car): self | ||
{ | ||
$car->setBrand($this); | ||
$this->cars[] = $car; | ||
|
||
return $this; | ||
} | ||
|
||
public function getHeadQuarters(): ?Address | ||
{ | ||
return $this->headQuarters; | ||
} | ||
|
||
public function setHeadQuarters(?Address $headQuarters): self | ||
{ | ||
$headQuarters?->setBrand($this); | ||
$this->headQuarters = $headQuarters; | ||
|
||
return $this; | ||
} | ||
|
||
public static function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null | ||
{ | ||
return (new Brand(1, 'Ford')) | ||
->setHeadQuarters(new Address(1, 'One American Road near Michigan Avenue, Dearborn, Michigan')) | ||
->addCar(new Car(1, 'Torpedo Roadster')); | ||
} | ||
} | ||
|
||
#[ApiResource( | ||
operations: [ | ||
new Get, | ||
// Without the use of uriTemplate on the property this would be used coming from the Brand resource, but not anymore. | ||
new GetCollection(uriTemplate: '/cars'), | ||
// This operation will be used to create the IRI instead since the uriTemplate matches. | ||
new GetCollection( | ||
uriTemplate: '/brands/{brandId}/cars', | ||
uriVariables: [ | ||
'brandId' => new Link(toProperty: 'brand', fromClass: Brand::class), | ||
] | ||
), | ||
], | ||
)] | ||
class Car | ||
{ | ||
public function __construct( | ||
#[ApiProperty(identifier: true)] | ||
public readonly int $id = 1, | ||
public readonly string $name = 'Anon', | ||
private ?Brand $brand = null | ||
) | ||
{ | ||
} | ||
|
||
public function getBrand(): Brand | ||
{ | ||
return $this->brand; | ||
} | ||
|
||
public function setBrand(Brand $brand): void | ||
{ | ||
$this->brand = $brand; | ||
} | ||
} | ||
|
||
#[ApiResource( | ||
operations: [ | ||
// Without the use of uriTemplate on the property this would be used coming from the Brand resource, but not anymore. | ||
new Get(uriTemplate: '/addresses/{id}'), | ||
// This operation will be used to create the IRI instead since the uriTemplate matches. | ||
new Get( | ||
uriTemplate: '/brands/{brandId}/addresses/{id}', | ||
uriVariables: [ | ||
'brandId' => new Link(toProperty: 'brand', fromClass: Brand::class), | ||
'id' => new Link(fromClass: Address::class), | ||
] | ||
) | ||
], | ||
)] | ||
class Address | ||
{ | ||
public function __construct( | ||
#[ApiProperty(identifier: true)] | ||
public readonly int $id = 1, | ||
public readonly string $name = 'Anon', | ||
private ?Brand $brand = null | ||
) | ||
{ | ||
} | ||
|
||
public function getBrand(): Brand | ||
{ | ||
return $this->brand; | ||
} | ||
|
||
public function setBrand(Brand $brand): void | ||
{ | ||
$this->brand = $brand; | ||
} | ||
} | ||
} | ||
|
||
// If API Platform does not find any `GetCollection` operation on the target resource, it will result in a `NotFoundException`. | ||
// | ||
// The **OpenAPI** documentation will set the properties as `read-only` of type `string` in the format `iri-reference` for `JSON-LD`, `JSON:API` and `HAL` formats. | ||
// | ||
// The **Hydra** documentation will set the properties as `hydra:Link` with the right domain, with `hydra:readable` to `true` but `hydra:writable` to `false`. | ||
// | ||
// When using JSON:API or HAL formats, the IRI will be used and set links, embedded and relationship. | ||
// | ||
// *Additional Note:* If you are using the default doctrine provider, this will prevent unnecessary sql join and related processing. | ||
|
||
namespace App\Playground { | ||
use Symfony\Component\HttpFoundation\Request; | ||
|
||
function request(): Request | ||
{ | ||
return Request::create(uri: '/brands/1', method: 'GET', server: ['HTTP_ACCEPT' => 'application/ld+json']); | ||
} | ||
} | ||
|
||
|
||
namespace App\Tests { | ||
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase; | ||
use App\ApiResource\Brand; | ||
|
||
final class BrandTest extends ApiTestCase | ||
{ | ||
|
||
public function testResourceExposeIRI(): void | ||
{ | ||
static::createClient()->request('GET', '/brands/1', ['headers' => [ | ||
'Accept: application/ld+json' | ||
]]); | ||
|
||
$this->assertResponseIsSuccessful(); | ||
$this->assertMatchesResourceCollectionJsonSchema(Brand::class, '_api_/brands/{id}{._format}_get'); | ||
$this->assertJsonContains([ | ||
"@context" => "/contexts/Brand", | ||
"@id" => "/brands/1", | ||
"@type" => "Brand", | ||
"name"=> "Ford", | ||
"cars" => "/brands/1/cars", | ||
"headQuarters" => "/brands/1/addresses/1" | ||
]); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
@php8 | ||
@v3 | ||
Feature: Exposing a property being a collection of resources | ||
can return an IRI instead of an array | ||
when the uriTemplate is set on the ApiProperty attribute | ||
|
||
@createSchema | ||
Scenario: Retrieve Resource with uriTemplate collection Property | ||
Given there are propertyCollectionIriOnly with relations | ||
When I add "Accept" header equal to "application/hal+json" | ||
And I send a "GET" request to "/property_collection_iri_onlies/1" | ||
Then the response status code should be 200 | ||
And the response should be in JSON | ||
And the JSON should be valid according to the JSON HAL schema | ||
And the header "Content-Type" should be equal to "application/hal+json; charset=utf-8" | ||
And the JSON should be equal to: | ||
""" | ||
{ | ||
"_links": { | ||
"self": { | ||
"href": "/property_collection_iri_onlies/1" | ||
}, | ||
"propertyCollectionIriOnlyRelation": { | ||
"href": "/property-collection-relations" | ||
}, | ||
"iterableIri": { | ||
"href": "/parent/1/another-collection-operations" | ||
}, | ||
"toOneRelation": { | ||
"href": "/parent/1/property-uri-template/one-to-ones/1" | ||
} | ||
}, | ||
"_embedded": { | ||
"propertyCollectionIriOnlyRelation": [ | ||
{ | ||
"_links": { | ||
"self": { | ||
"href": "/property_collection_iri_only_relations/1" | ||
} | ||
}, | ||
"name": "asb" | ||
} | ||
], | ||
"iterableIri": [ | ||
{ | ||
"_links": { | ||
"self": { | ||
"href": "/property_collection_iri_only_relations/9999" | ||
} | ||
}, | ||
"name": "Michel" | ||
} | ||
], | ||
"toOneRelation": { | ||
"_links": { | ||
"self": { | ||
"href": "/parent/1/property-uri-template/one-to-ones/1" | ||
} | ||
}, | ||
"name": "xarguš" | ||
} | ||
} | ||
} | ||
""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
@php8 | ||
@v3 | ||
Feature: Exposing a property being a collection of resources | ||
can return an IRI instead of an array | ||
when the uriTemplate is set on the ApiProperty attribute | ||
|
||
Background: | ||
Given I add "Accept" header equal to "application/vnd.api+json" | ||
And I add "Content-Type" header equal to "application/vnd.api+json" | ||
|
||
@createSchema | ||
Scenario: Retrieve Resource with uriTemplate collection Property | ||
Given there are propertyCollectionIriOnly with relations | ||
And I send a "GET" request to "/property_collection_iri_onlies/1" | ||
Then the response status code should be 200 | ||
And the response should be in JSON | ||
And the JSON should be valid according to the JSON HAL schema | ||
And the header "Content-Type" should be equal to "application/vnd.api+json; charset=utf-8" | ||
And the JSON should be equal to: | ||
""" | ||
{ | ||
"links": { | ||
"propertyCollectionIriOnlyRelation": "/property-collection-relations", | ||
"iterableIri": "/parent/1/another-collection-operations", | ||
"toOneRelation": "/parent/1/property-uri-template/one-to-ones/1" | ||
}, | ||
"data": { | ||
"id": "/property_collection_iri_onlies/1", | ||
"type": "PropertyCollectionIriOnly", | ||
"relationships": { | ||
"propertyCollectionIriOnlyRelation": { | ||
"data": [ | ||
{ | ||
"type": "PropertyCollectionIriOnlyRelation", | ||
"id": "/property_collection_iri_only_relations/1" | ||
} | ||
] | ||
}, | ||
"iterableIri": { | ||
"data": [ | ||
{ | ||
"type": "PropertyCollectionIriOnlyRelation", | ||
"id": "/property_collection_iri_only_relations/9999" | ||
} | ||
] | ||
}, | ||
"toOneRelation": { | ||
"data": { | ||
"type": "PropertyUriTemplateOneToOneRelation", | ||
"id": "/parent/1/property-uri-template/one-to-ones/1" | ||
} | ||
} | ||
} | ||
} | ||
} | ||
""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -155,8 +155,9 @@ private function joinRelations(QueryBuilder $queryBuilder, QueryNameGeneratorInt | |
} | ||
|
||
$fetchEager = $propertyMetadata->getFetchEager(); | ||
$uriTemplate = $propertyMetadata->getUriTemplate(); | ||
|
||
if (false === $fetchEager) { | ||
if (false === $fetchEager || null !== $uriTemplate) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. When items are embedded, they should still be fetched. Should we change as following? if (false === $fetchEager || (null !== $uriTemplate && !$propertyMetadata->isReadableLink() )) { There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'll try this |
||
continue; | ||
} | ||
|
||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@GregoireHebert This causes an issue here.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
weird, it's initialized to
null
inside the constructor. Can you provide a reproducer an open a new issue please?