diff --git a/core/extending.md b/core/extending.md index 9bf25614d43..0bb05f67d44 100644 --- a/core/extending.md +++ b/core/extending.md @@ -20,6 +20,7 @@ The following tables summarizes which extension point to use depending on what y | [Messenger Handlers](../symfony/messenger.md) | create 100% custom, RPC, async, service-oriented endpoints (should be used in place of custom controllers because the messenger integration is compatible with both REST and GraphQL, while custom controllers only work with REST) | | [DTOs](dto.md) | use a specific class to represent the input or output data structure related to an operation | | [Kernel Events](events.md) | customize the HTTP request or response (REST only, other extension points must be preferred when possible) | +| [Operations and Resources](operations.md) | use mutators to dynamically alter metadata (works for third party API endpoints) | ## Doctrine Specific Extension Points diff --git a/core/operations.md b/core/operations.md index f2d819edee2..0923ef23ad0 100644 --- a/core/operations.md +++ b/core/operations.md @@ -589,3 +589,79 @@ class Weather ``` That's it! + +## Customize Operation and Resource Metadata + +Metadata mutators allow a dynamic control over resources and operations, by programmatically altering metadata before they are exposed as endpoints. Providing a way to modify, add or remove operations, adjust serialization groups or pagination settings. + +It also makes it possible to customize built-in endpoints from a third-party API, such as Sylius. + +### Resource Mutator + +Use the resource mutator to modify the entire resource metadata by adding the attribute and target resource class as argument: + +```php +getOperations()) { + return $resource; + } + + foreach ($operations as $name => $operation) { + // add route prefix to each resource operation + $prefixedOperation = $operation->withRoutePrefix($this->apiDomain); + $operations->add($name, $prefixedOperation); + } + + return $resource->withOperations($operations); + } +} +``` + +### Operation Mutator + +The operation mutator will modify a specific operation's metadata, by using the attribute and passing the operation name: + +```php +getNormalizationContext() ?? []; + // add another group to normalization group + $context['groups'][] = 'review:list:read'; + + return $operation->withNormalizationContext($context); + } +} +```