Skip to content
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
merged 2 commits into from
Sep 11, 2023
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
203 changes: 203 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,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"
]);
}
}
}
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();
Copy link
Contributor

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.

Error: Typed property ApiPlatform\Metadata\ApiProperty::$uriTemplate must not be accessed before initialization
#32 /vendor/api-platform/core/src/Metadata/ApiProperty.php(477): ApiPlatform\Metadata\ApiProperty::getUriTemplate
#31 /vendor/api-platform/core/src/Doctrine/Orm/Extension/EagerLoadingExtension.php(158): ApiPlatform\Doctrine\Orm\Extension\EagerLoadingExtension::joinRelations
#30 /vendor/api-platform/core/src/Doctrine/Orm/Extension/EagerLoadingExtension.php(98): ApiPlatform\Doctrine\Orm\Extension\EagerLoadingExtension::apply
#29 /vendor/api-platform/core/src/Doctrine/Orm/Extension/EagerLoadingExtension.php(61): ApiPlatform\Doctrine\Orm\Extension\EagerLoadingExtension::applyToItem

Copy link
Member

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?


if (false === $fetchEager) {
if (false === $fetchEager || null !== $uriTemplate) {
Copy link
Contributor

Choose a reason for hiding this comment

The 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() )) {

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'll try this

continue;
}

Expand Down
Loading
Loading