Skip to content

Commit

Permalink
feat(serializer): add ApiProperty::uriTemplate option
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
GregoireHebert committed Aug 28, 2023
1 parent b58ec12 commit d7eac24
Show file tree
Hide file tree
Showing 31 changed files with 1,451 additions and 92 deletions.
208 changes: 208 additions & 0 deletions docs/guides/return-the-iri-of-your-resources-relations.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
<?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;
use ApiPlatform\State\ProviderInterface;
use Symfony\Component\Serializer\Annotation\Groups;

#[ApiResource(
operations: [
new Get(normalizationContext: ['groups' => ['read']], provider: Brand::class),
],
)]
class Brand implements ProviderInterface
{
public function __construct(
#[ApiProperty(identifier: true)]
public readonly int $id = 1,

#[Groups('read')]
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')]
#[Groups('read')]
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}')]
#[Groups('read')]
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 function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
{
return (new self(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,
#[Groups('read')]
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('/brands/1.jsonld', 'GET');
}
}


namespace App\Tests {
use ApiPlatform\Playground\Test\TestGuideTrait;
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
use App\ApiResource\Brand;

final class BrandTest extends ApiTestCase
{
use TestGuideTrait;

public function testResourceExposeIRI(): void
{
static::createClient()->request('GET', '/brands/1.jsonld');

$this->assertResponseIsSuccessful();
$this->assertMatchesResourceCollectionJsonSchema(Brand::class, '_api_/brand{._format}_get_item');
$this->assertJsonContains([
"@context" => "/contexts/Brand",
"@id" => "/brands/1",
"@type" => "Brand",
"cars" => "/brands/1/cars",
"headQuarters" => "/brands/1/addresses/1"
]);
}
}
}
64 changes: 64 additions & 0 deletions features/hal/collection_uri_template.feature
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š"
}
}
}
"""
3 changes: 0 additions & 3 deletions features/hal/hal.feature
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,6 @@ Feature: HAL support
}
"""


Scenario: Embed a relation in a parent object
When I add "Content-Type" header equal to "application/json"
And I send a "POST" request to "/relation_embedders" with body:
Expand All @@ -180,8 +179,6 @@ Feature: HAL support
}
"""
Then the response status code should be 201

Scenario: Get the object with the embedded relation
When I add "Accept" header equal to "application/hal+json"
And I send a "GET" request to "/relation_embedders/1"
Then the response status code should be 200
Expand Down
56 changes: 56 additions & 0 deletions features/jsonapi/collection_uri_template.feature
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"
}
}
}
}
}
"""
37 changes: 37 additions & 0 deletions features/jsonld/iri_only.feature
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,40 @@ Feature: JSON-LD using iri_only parameter
"hydra:totalItems": 3
}
"""

@createSchema
Scenario: Retrieve Resource with uriTemplate collection Property
Given there are propertyCollectionIriOnly with relations
When I send a "GET" request to "/property_collection_iri_onlies"
Then the response status code should be 200
And the response should be in JSON
And the header "Content-Type" should be equal to "application/ld+json; charset=utf-8"
And the JSON should be a superset of:
"""
{
"hydra:member": [
{
"@id": "/property_collection_iri_onlies/1",
"@type": "PropertyCollectionIriOnly",
"propertyCollectionIriOnlyRelation": "/property-collection-relations",
"iterableIri": "/parent/1/another-collection-operations",
"toOneRelation": "/parent/1/property-uri-template/one-to-ones/1"
}
]
}
"""
When 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 header "Content-Type" should be equal to "application/ld+json; charset=utf-8"
And the JSON should be a superset of:
"""
{
"@context": "/contexts/PropertyCollectionIriOnly",
"@id": "/property_collection_iri_onlies/1",
"@type": "PropertyCollectionIriOnly",
"propertyCollectionIriOnlyRelation": "/property-collection-relations",
"iterableIri": "/parent/1/another-collection-operations",
"toOneRelation": "/parent/1/property-uri-template/one-to-ones/1"
}
"""
3 changes: 2 additions & 1 deletion src/Doctrine/Orm/Extension/EagerLoadingExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,9 @@ private function joinRelations(QueryBuilder $queryBuilder, QueryNameGeneratorInt
}

$fetchEager = $propertyMetadata->getFetchEager();
$uriTemplate = $propertyMetadata->getUriTemplate();

if (false === $fetchEager) {
if (false === $fetchEager || null !== $uriTemplate) {
continue;
}

Expand Down
Loading

0 comments on commit d7eac24

Please sign in to comment.