Skip to content

feat(doctrine): new hook for entity/document transformation #6919

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
64 changes: 64 additions & 0 deletions features/doctrine/transform_model.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
Feature: Use an entity or document transformer to return the correct ressource

@createSchema
@!mongodb
Scenario: Get transformed collection from entities
Given there is a TransformedDummy for date '2025-01-01'
When I send a "GET" request to "/transformed_dummy_entity_ressources"
Then the response status code should be 200
And the response should be in JSON
And the JSON node "hydra:totalItems" should be equal to 1

@!mongodb
Scenario: Get transform item from entity
Given there is a TransformedDummy for date '2025-01-01'
When I send a "GET" request to "/transformed_dummy_entity_ressources/1"
Then the response status code should be 200
And the response should be in JSON
And the JSON node "year" should exist
And the JSON node year should be equal to "2025"

@!mongodb
Scenario: Post new entity from transformed resource
Given I add "Content-type" header equal to "application/ld+json"
When I send a "POST" request to "/transformed_dummy_entity_ressources" with body:
"""
{
"year" : 2020
}
"""
Then the response status code should be 201
And the response should be in JSON
And the JSON node "year" should be equal to "2020"

@!mongodb
Scenario: Patch entity from transformed resource
Given there is a TransformedDummy for date '2025-01-01'
And I add "Content-type" header equal to "application/merge-patch+json"
When I send a "PATCH" request to "/transformed_dummy_entity_ressources/1" with body:
"""
{
"year" : 2020
}
"""
Then the response status code should be 200
And the response should be in JSON
And the JSON node "year" should be equal to "2020"

@createSchema
@mongodb
Scenario: Get collection from documents
Given there is a TransformedDummy for date '2025-01-01'
When I send a "GET" request to "/transformed_dummy_document_ressources"
Then the response status code should be 200
And the response should be in JSON
And the JSON node "hydra:totalItems" should be equal to 1

@mongodb
Scenario: Get item from document
Given there is a TransformedDummy for date '2025-01-01'
When I send a "GET" request to "/transformed_dummy_document_ressources/1"
Then the response status code should be 200
And the response should be in JSON
And the JSON node "year" should exist
And the JSON node year should be equal to "2025"
2 changes: 1 addition & 1 deletion features/hydra/error.feature
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Feature: Error handling
And the header "Content-Type" should be equal to "application/problem+json; charset=utf-8"
And the header "Link" should contain '<http://www.w3.org/ns/hydra/error>; rel="http://www.w3.org/ns/json-ld#error"'
And the JSON node "type" should exist
And the JSON node "title" should not exists
And the JSON node "title" should not exist
And the JSON node "hydra:title" should be equal to "An error occurred"
And the JSON node "detail" should exist
And the JSON node "description" should not exist
Expand Down
32 changes: 31 additions & 1 deletion src/Doctrine/Common/State/Options.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,14 @@
class Options implements OptionsInterface
{
/**
* @param mixed $handleLinks experimental callable, typed mixed as we may want a service name in the future
* @param mixed $handleLinks experimental callable, typed mixed as we may want a service name in the future
* @param mixed $toResourceTransformer experimental callable, typed mixed as we may want a service name in the future
* @param mixed $fromResourceTransformer experimental callable, typed mixed as we may want a service name in the future
*/
public function __construct(
protected mixed $handleLinks = null,
protected mixed $toResourceTransformer = null,
protected mixed $fromResourceTransformer = null,
) {
}

Expand All @@ -37,4 +41,30 @@ public function withHandleLinks(mixed $handleLinks): self

return $self;
}

public function getToResourceTransformer(): mixed
{
return $this->toResourceTransformer;
}

public function withToResourceTransformer(mixed $toResourceTransformer): self
{
$self = clone $this;
$self->toResourceTransformer = $toResourceTransformer;

return $self;
}

public function getFromResourceTransformer(): mixed
{
return $this->fromResourceTransformer;
}

public function withFromResourceTransformer(mixed $fromResourceTransformer): self
{
$self = clone $this;
$self->fromResourceTransformer = $fromResourceTransformer;

return $self;
}
}
17 changes: 15 additions & 2 deletions src/Doctrine/Common/State/PersistProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,18 @@
use ApiPlatform\State\ProcessorInterface;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Persistence\ObjectManager as DoctrineObjectManager;
use Psr\Container\ContainerInterface;

final class PersistProcessor implements ProcessorInterface
{
use ClassInfoTrait;
use LinksHandlerTrait;
use ResourceTransformerLocatorTrait;

public function __construct(private readonly ManagerRegistry $managerRegistry)
public function __construct(private readonly ManagerRegistry $managerRegistry,
?ContainerInterface $resourceTransformerLocator = null)
{
$this->resourceTransformerLocator = $resourceTransformerLocator;
}

/**
Expand All @@ -38,6 +42,12 @@ public function __construct(private readonly ManagerRegistry $managerRegistry)
*/
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
{
// if a transformer is defined, start with that
$data = match ($transformer = $this->getFromResourceTransformer($operation)) {
null => $data,
default => $transformer($data, $this->getManager($operation, $this->managerRegistry)),
};

if (
!\is_object($data)
|| !$manager = $this->managerRegistry->getManagerForClass($class = $this->getObjectClass($data))
Expand Down Expand Up @@ -104,7 +114,10 @@ public function process(mixed $data, Operation $operation, array $uriVariables =
$manager->flush();
$manager->refresh($data);

return $data;
return match ($transformer = $this->getToResourceTransformer($operation)) {
null => $data,
default => $transformer($data, $operation, $uriVariables, $context),
};
}

/**
Expand Down
34 changes: 34 additions & 0 deletions src/Doctrine/Common/State/ResourceTransformerInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* 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\Doctrine\Common\State;

use Doctrine\Persistence\ObjectManager;

interface ResourceTransformerInterface
{
/**
* @param object $entityOrDocument the doctrine entity or document to make a resource from
*
* @return object the resulting ApiResource
*/
public function toResource(object $entityOrDocument): object;

/**
* @param object $resource the resource you want to persist
* @param ObjectManager $objectManager the object manager to handle this kind of resources
*
* @return object the existing or new entity or document
*/
public function fromResource(object $resource, ObjectManager $objectManager): object;
}
79 changes: 79 additions & 0 deletions src/Doctrine/Common/State/ResourceTransformerLocatorTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* 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\Doctrine\Common\State;

use ApiPlatform\Metadata\Operation;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Persistence\ObjectManager;
use Psr\Container\ContainerInterface;

/**
* Maybe merge this and LinksHandlerLocatorTrait into a OptionsHooksLocatorTrait or something similar?
*/
trait ResourceTransformerLocatorTrait
{
private ?ContainerInterface $resourceTransformerLocator;

protected function getToResourceTransformer(Operation $operation): ?callable
{
if (!($options = $operation->getStateOptions()) || !$options instanceof Options) {
return null;
}

$transformer = $options->getToResourceTransformer();
if (\is_callable($transformer)) {
return $transformer;
}

if ($this->resourceTransformerLocator && \is_string($transformer) && $this->resourceTransformerLocator->has($transformer)) {
return [$this->resourceTransformerLocator->get($transformer), 'toResource'];
}

return null;
}

protected function getFromResourceTransformer(Operation $operation): ?callable
{
if (!($options = $operation->getStateOptions()) || !$options instanceof Options) {
return null;
}

$transformer = $options->getFromResourceTransformer();
if (\is_callable($transformer)) {
return $transformer;
}

if ($this->resourceTransformerLocator && \is_string($transformer) && $this->resourceTransformerLocator->has($transformer)) {
return [$this->resourceTransformerLocator->get($transformer), 'fromResource'];
}

return null;
}

protected function getManager(Operation $operation, ManagerRegistry $managerRegistry): ObjectManager
{
$options = $operation->getStateOptions();
$entityClass = match (true) {
$options instanceof \ApiPlatform\Doctrine\Orm\State\Options => $options->getEntityClass(),
$options instanceof \ApiPlatform\Doctrine\Odm\State\Options => $options->getDocumentClass(),
default => null,
};

if ($entityClass) {
return $managerRegistry->getManagerForClass($entityClass);
}

throw new \RuntimeException('This should not be called on an operation without StateOptions');
}
}
20 changes: 16 additions & 4 deletions src/Doctrine/Odm/State/CollectionProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace ApiPlatform\Doctrine\Odm\State;

use ApiPlatform\Doctrine\Common\State\LinksHandlerLocatorTrait;
use ApiPlatform\Doctrine\Common\State\ResourceTransformerLocatorTrait;
use ApiPlatform\Doctrine\Odm\Extension\AggregationCollectionExtensionInterface;
use ApiPlatform\Doctrine\Odm\Extension\AggregationResultCollectionExtensionInterface;
use ApiPlatform\Metadata\Exception\RuntimeException;
Expand All @@ -33,15 +34,20 @@ final class CollectionProvider implements ProviderInterface
{
use LinksHandlerLocatorTrait;
use LinksHandlerTrait;
use ResourceTransformerLocatorTrait;
use StateOptionsTrait;

/**
* @param AggregationCollectionExtensionInterface[] $collectionExtensions
*/
public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, ManagerRegistry $managerRegistry, private readonly iterable $collectionExtensions = [], ?ContainerInterface $handleLinksLocator = null)
{
public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, ManagerRegistry $managerRegistry,
private readonly iterable $collectionExtensions = [],
?ContainerInterface $handleLinksLocator = null,
?ContainerInterface $resourceTransformerLocator = null,
) {
$this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
$this->handleLinksLocator = $handleLinksLocator;
$this->resourceTransformerLocator = $resourceTransformerLocator;
$this->managerRegistry = $managerRegistry;
}

Expand Down Expand Up @@ -69,13 +75,19 @@ public function provide(Operation $operation, array $uriVariables = [], array $c
$extension->applyToCollection($aggregationBuilder, $documentClass, $operation, $context);

if ($extension instanceof AggregationResultCollectionExtensionInterface && $extension->supportsResult($documentClass, $operation, $context)) {
return $extension->getResult($aggregationBuilder, $documentClass, $operation, $context);
$result = $extension->getResult($aggregationBuilder, $documentClass, $operation, $context);
break;
}
}

$attribute = $operation->getExtraProperties()['doctrine_mongodb'] ?? [];
$executeOptions = $attribute['execute_options'] ?? [];

return $aggregationBuilder->hydrate($documentClass)->getAggregation($executeOptions)->getIterator();
$result = $result ?? $aggregationBuilder->hydrate($documentClass)->getAggregation($executeOptions)->getIterator();

return match ($transformer = $this->getToResourceTransformer($operation)) {
null => $result,
default => array_map($transformer, iterator_to_array($result)),
};
}
}
18 changes: 15 additions & 3 deletions src/Doctrine/Odm/State/ItemProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace ApiPlatform\Doctrine\Odm\State;

use ApiPlatform\Doctrine\Common\State\LinksHandlerLocatorTrait;
use ApiPlatform\Doctrine\Common\State\ResourceTransformerLocatorTrait;
use ApiPlatform\Doctrine\Odm\Extension\AggregationItemExtensionInterface;
use ApiPlatform\Doctrine\Odm\Extension\AggregationResultItemExtensionInterface;
use ApiPlatform\Metadata\Exception\RuntimeException;
Expand All @@ -36,15 +37,20 @@ final class ItemProvider implements ProviderInterface
{
use LinksHandlerLocatorTrait;
use LinksHandlerTrait;
use ResourceTransformerLocatorTrait;
use StateOptionsTrait;

/**
* @param AggregationItemExtensionInterface[] $itemExtensions
*/
public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, ManagerRegistry $managerRegistry, private readonly iterable $itemExtensions = [], ?ContainerInterface $handleLinksLocator = null)
public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, ManagerRegistry $managerRegistry,
private readonly iterable $itemExtensions = [],
?ContainerInterface $handleLinksLocator = null,
?ContainerInterface $resourceTransformerLocator = null)
{
$this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
$this->handleLinksLocator = $handleLinksLocator;
$this->resourceTransformerLocator = $resourceTransformerLocator;
$this->managerRegistry = $managerRegistry;
}

Expand Down Expand Up @@ -77,12 +83,18 @@ public function provide(Operation $operation, array $uriVariables = [], array $c
$extension->applyToItem($aggregationBuilder, $documentClass, $uriVariables, $operation, $context);

if ($extension instanceof AggregationResultItemExtensionInterface && $extension->supportsResult($documentClass, $operation, $context)) {
return $extension->getResult($aggregationBuilder, $documentClass, $operation, $context);
$result = $extension->getResult($aggregationBuilder, $documentClass, $operation, $context);
break;
}
}

$executeOptions = $operation->getExtraProperties()['doctrine_mongodb']['execute_options'] ?? [];

return $aggregationBuilder->hydrate($documentClass)->getAggregation($executeOptions)->getIterator()->current() ?: null;
$result = $result ?? ($aggregationBuilder->hydrate($documentClass)->getAggregation($executeOptions)->getIterator()->current() ?: null);

return match ($transformer = $this->getToResourceTransformer($operation)) {
null => $result,
default => (null !== $result) ? $transformer($result) : null,
};
}
}
Loading
Loading