Skip to content

Commit e65d2c3

Browse files
feat(serializer): add ApiProperty::uriTemplate option (#5675)
* feat(serializer): add ApiProperty::uriTemplate option This feature gives control over the operation used for *toOne and *toMany relations IRI generation. When defined, API Platform will use the operation declared on the related resource that matches the uriTemplate string. In addition, this will override the value returned to be the IRI string only, not an object in JSONLD formats. For HAL and JSON:API format, the IRI will be used in links properties, and in the objects embedded or in relationship properties. * fix: update for guide
1 parent 80cb5eb commit e65d2c3

31 files changed

+1448
-92
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,203 @@
1+
<?php
2+
// ---
3+
// slug: return-the-iri-of-your-resources-relations
4+
// name: How to return an IRI instead of an object for your resources relations ?
5+
// executable: true
6+
// tags: serialization
7+
// ---
8+
9+
// This guide shows you how to expose the IRI of a related (sub)ressource relation instead of an object.
10+
11+
namespace App\ApiResource {
12+
use ApiPlatform\Metadata\ApiProperty;
13+
use ApiPlatform\Metadata\ApiResource;
14+
use ApiPlatform\Metadata\Get;
15+
use ApiPlatform\Metadata\GetCollection;
16+
use ApiPlatform\Metadata\Link;
17+
use ApiPlatform\Metadata\Operation;
18+
19+
#[ApiResource(
20+
operations: [
21+
new Get(provider: Brand::class.'::provide'),
22+
],
23+
)]
24+
class Brand
25+
{
26+
public function __construct(
27+
#[ApiProperty(identifier: true)]
28+
public readonly int $id = 1,
29+
30+
public readonly string $name = 'Anon',
31+
32+
// Setting uriTemplate on a relation with a resource collection will try to find the related operation.
33+
// It is based on the uriTemplate set on the operation defined on the Car resource (see below).
34+
/**
35+
* @var array<int, Car> $cars
36+
*/
37+
#[ApiProperty(uriTemplate: '/brands/{brandId}/cars')]
38+
private array $cars = [],
39+
40+
// Setting uriTemplate on a relation with a resource item will try to find the related operation.
41+
// It is based on the uriTemplate set on the operation defined on the Address resource (see below).
42+
#[ApiProperty(uriTemplate: '/brands/{brandId}/addresses/{id}')]
43+
private ?Address $headQuarters = null
44+
)
45+
{
46+
}
47+
48+
/**
49+
* @return array<int, Car>
50+
*/
51+
public function getCars(): array
52+
{
53+
return $this->cars;
54+
}
55+
56+
public function addCar(Car $car): self
57+
{
58+
$car->setBrand($this);
59+
$this->cars[] = $car;
60+
61+
return $this;
62+
}
63+
64+
public function getHeadQuarters(): ?Address
65+
{
66+
return $this->headQuarters;
67+
}
68+
69+
public function setHeadQuarters(?Address $headQuarters): self
70+
{
71+
$headQuarters?->setBrand($this);
72+
$this->headQuarters = $headQuarters;
73+
74+
return $this;
75+
}
76+
77+
public static function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
78+
{
79+
return (new Brand(1, 'Ford'))
80+
->setHeadQuarters(new Address(1, 'One American Road near Michigan Avenue, Dearborn, Michigan'))
81+
->addCar(new Car(1, 'Torpedo Roadster'));
82+
}
83+
}
84+
85+
#[ApiResource(
86+
operations: [
87+
new Get,
88+
// Without the use of uriTemplate on the property this would be used coming from the Brand resource, but not anymore.
89+
new GetCollection(uriTemplate: '/cars'),
90+
// This operation will be used to create the IRI instead since the uriTemplate matches.
91+
new GetCollection(
92+
uriTemplate: '/brands/{brandId}/cars',
93+
uriVariables: [
94+
'brandId' => new Link(toProperty: 'brand', fromClass: Brand::class),
95+
]
96+
),
97+
],
98+
)]
99+
class Car
100+
{
101+
public function __construct(
102+
#[ApiProperty(identifier: true)]
103+
public readonly int $id = 1,
104+
public readonly string $name = 'Anon',
105+
private ?Brand $brand = null
106+
)
107+
{
108+
}
109+
110+
public function getBrand(): Brand
111+
{
112+
return $this->brand;
113+
}
114+
115+
public function setBrand(Brand $brand): void
116+
{
117+
$this->brand = $brand;
118+
}
119+
}
120+
121+
#[ApiResource(
122+
operations: [
123+
// Without the use of uriTemplate on the property this would be used coming from the Brand resource, but not anymore.
124+
new Get(uriTemplate: '/addresses/{id}'),
125+
// This operation will be used to create the IRI instead since the uriTemplate matches.
126+
new Get(
127+
uriTemplate: '/brands/{brandId}/addresses/{id}',
128+
uriVariables: [
129+
'brandId' => new Link(toProperty: 'brand', fromClass: Brand::class),
130+
'id' => new Link(fromClass: Address::class),
131+
]
132+
)
133+
],
134+
)]
135+
class Address
136+
{
137+
public function __construct(
138+
#[ApiProperty(identifier: true)]
139+
public readonly int $id = 1,
140+
public readonly string $name = 'Anon',
141+
private ?Brand $brand = null
142+
)
143+
{
144+
}
145+
146+
public function getBrand(): Brand
147+
{
148+
return $this->brand;
149+
}
150+
151+
public function setBrand(Brand $brand): void
152+
{
153+
$this->brand = $brand;
154+
}
155+
}
156+
}
157+
158+
// If API Platform does not find any `GetCollection` operation on the target resource, it will result in a `NotFoundException`.
159+
//
160+
// 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.
161+
//
162+
// The **Hydra** documentation will set the properties as `hydra:Link` with the right domain, with `hydra:readable` to `true` but `hydra:writable` to `false`.
163+
//
164+
// When using JSON:API or HAL formats, the IRI will be used and set links, embedded and relationship.
165+
//
166+
// *Additional Note:* If you are using the default doctrine provider, this will prevent unnecessary sql join and related processing.
167+
168+
namespace App\Playground {
169+
use Symfony\Component\HttpFoundation\Request;
170+
171+
function request(): Request
172+
{
173+
return Request::create(uri: '/brands/1', method: 'GET', server: ['HTTP_ACCEPT' => 'application/ld+json']);
174+
}
175+
}
176+
177+
178+
namespace App\Tests {
179+
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
180+
use App\ApiResource\Brand;
181+
182+
final class BrandTest extends ApiTestCase
183+
{
184+
185+
public function testResourceExposeIRI(): void
186+
{
187+
static::createClient()->request('GET', '/brands/1', ['headers' => [
188+
'Accept: application/ld+json'
189+
]]);
190+
191+
$this->assertResponseIsSuccessful();
192+
$this->assertMatchesResourceCollectionJsonSchema(Brand::class, '_api_/brands/{id}{._format}_get');
193+
$this->assertJsonContains([
194+
"@context" => "/contexts/Brand",
195+
"@id" => "/brands/1",
196+
"@type" => "Brand",
197+
"name"=> "Ford",
198+
"cars" => "/brands/1/cars",
199+
"headQuarters" => "/brands/1/addresses/1"
200+
]);
201+
}
202+
}
203+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
@php8
2+
@v3
3+
Feature: Exposing a property being a collection of resources
4+
can return an IRI instead of an array
5+
when the uriTemplate is set on the ApiProperty attribute
6+
7+
@createSchema
8+
Scenario: Retrieve Resource with uriTemplate collection Property
9+
Given there are propertyCollectionIriOnly with relations
10+
When I add "Accept" header equal to "application/hal+json"
11+
And I send a "GET" request to "/property_collection_iri_onlies/1"
12+
Then the response status code should be 200
13+
And the response should be in JSON
14+
And the JSON should be valid according to the JSON HAL schema
15+
And the header "Content-Type" should be equal to "application/hal+json; charset=utf-8"
16+
And the JSON should be equal to:
17+
"""
18+
{
19+
"_links": {
20+
"self": {
21+
"href": "/property_collection_iri_onlies/1"
22+
},
23+
"propertyCollectionIriOnlyRelation": {
24+
"href": "/property-collection-relations"
25+
},
26+
"iterableIri": {
27+
"href": "/parent/1/another-collection-operations"
28+
},
29+
"toOneRelation": {
30+
"href": "/parent/1/property-uri-template/one-to-ones/1"
31+
}
32+
},
33+
"_embedded": {
34+
"propertyCollectionIriOnlyRelation": [
35+
{
36+
"_links": {
37+
"self": {
38+
"href": "/property_collection_iri_only_relations/1"
39+
}
40+
},
41+
"name": "asb"
42+
}
43+
],
44+
"iterableIri": [
45+
{
46+
"_links": {
47+
"self": {
48+
"href": "/property_collection_iri_only_relations/9999"
49+
}
50+
},
51+
"name": "Michel"
52+
}
53+
],
54+
"toOneRelation": {
55+
"_links": {
56+
"self": {
57+
"href": "/parent/1/property-uri-template/one-to-ones/1"
58+
}
59+
},
60+
"name": "xarguš"
61+
}
62+
}
63+
}
64+
"""

features/hal/hal.feature

-3
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,6 @@ Feature: HAL support
170170
}
171171
"""
172172

173-
174173
Scenario: Embed a relation in a parent object
175174
When I add "Content-Type" header equal to "application/json"
176175
And I send a "POST" request to "/relation_embedders" with body:
@@ -180,8 +179,6 @@ Feature: HAL support
180179
}
181180
"""
182181
Then the response status code should be 201
183-
184-
Scenario: Get the object with the embedded relation
185182
When I add "Accept" header equal to "application/hal+json"
186183
And I send a "GET" request to "/relation_embedders/1"
187184
Then the response status code should be 200
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
@php8
2+
@v3
3+
Feature: Exposing a property being a collection of resources
4+
can return an IRI instead of an array
5+
when the uriTemplate is set on the ApiProperty attribute
6+
7+
Background:
8+
Given I add "Accept" header equal to "application/vnd.api+json"
9+
And I add "Content-Type" header equal to "application/vnd.api+json"
10+
11+
@createSchema
12+
Scenario: Retrieve Resource with uriTemplate collection Property
13+
Given there are propertyCollectionIriOnly with relations
14+
And I send a "GET" request to "/property_collection_iri_onlies/1"
15+
Then the response status code should be 200
16+
And the response should be in JSON
17+
And the JSON should be valid according to the JSON HAL schema
18+
And the header "Content-Type" should be equal to "application/vnd.api+json; charset=utf-8"
19+
And the JSON should be equal to:
20+
"""
21+
{
22+
"links": {
23+
"propertyCollectionIriOnlyRelation": "/property-collection-relations",
24+
"iterableIri": "/parent/1/another-collection-operations",
25+
"toOneRelation": "/parent/1/property-uri-template/one-to-ones/1"
26+
},
27+
"data": {
28+
"id": "/property_collection_iri_onlies/1",
29+
"type": "PropertyCollectionIriOnly",
30+
"relationships": {
31+
"propertyCollectionIriOnlyRelation": {
32+
"data": [
33+
{
34+
"type": "PropertyCollectionIriOnlyRelation",
35+
"id": "/property_collection_iri_only_relations/1"
36+
}
37+
]
38+
},
39+
"iterableIri": {
40+
"data": [
41+
{
42+
"type": "PropertyCollectionIriOnlyRelation",
43+
"id": "/property_collection_iri_only_relations/9999"
44+
}
45+
]
46+
},
47+
"toOneRelation": {
48+
"data": {
49+
"type": "PropertyUriTemplateOneToOneRelation",
50+
"id": "/parent/1/property-uri-template/one-to-ones/1"
51+
}
52+
}
53+
}
54+
}
55+
}
56+
"""

features/jsonld/iri_only.feature

+37
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,40 @@ Feature: JSON-LD using iri_only parameter
5656
"hydra:totalItems": 3
5757
}
5858
"""
59+
60+
@createSchema
61+
Scenario: Retrieve Resource with uriTemplate collection Property
62+
Given there are propertyCollectionIriOnly with relations
63+
When I send a "GET" request to "/property_collection_iri_onlies"
64+
Then the response status code should be 200
65+
And the response should be in JSON
66+
And the header "Content-Type" should be equal to "application/ld+json; charset=utf-8"
67+
And the JSON should be a superset of:
68+
"""
69+
{
70+
"hydra:member": [
71+
{
72+
"@id": "/property_collection_iri_onlies/1",
73+
"@type": "PropertyCollectionIriOnly",
74+
"propertyCollectionIriOnlyRelation": "/property-collection-relations",
75+
"iterableIri": "/parent/1/another-collection-operations",
76+
"toOneRelation": "/parent/1/property-uri-template/one-to-ones/1"
77+
}
78+
]
79+
}
80+
"""
81+
When I send a "GET" request to "/property_collection_iri_onlies/1"
82+
Then the response status code should be 200
83+
And the response should be in JSON
84+
And the header "Content-Type" should be equal to "application/ld+json; charset=utf-8"
85+
And the JSON should be a superset of:
86+
"""
87+
{
88+
"@context": "/contexts/PropertyCollectionIriOnly",
89+
"@id": "/property_collection_iri_onlies/1",
90+
"@type": "PropertyCollectionIriOnly",
91+
"propertyCollectionIriOnlyRelation": "/property-collection-relations",
92+
"iterableIri": "/parent/1/another-collection-operations",
93+
"toOneRelation": "/parent/1/property-uri-template/one-to-ones/1"
94+
}
95+
"""

src/Doctrine/Orm/Extension/EagerLoadingExtension.php

+2-1
Original file line numberDiff line numberDiff line change
@@ -155,8 +155,9 @@ private function joinRelations(QueryBuilder $queryBuilder, QueryNameGeneratorInt
155155
}
156156

157157
$fetchEager = $propertyMetadata->getFetchEager();
158+
$uriTemplate = $propertyMetadata->getUriTemplate();
158159

159-
if (false === $fetchEager) {
160+
if (false === $fetchEager || null !== $uriTemplate) {
160161
continue;
161162
}
162163

0 commit comments

Comments
 (0)