Skip to content

Commit fa16555

Browse files
committed
docs: metadata mutators
1 parent 263c804 commit fa16555

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

core/metadata-mutators.md

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Metadata Mutators
2+
3+
Metadata mutators allow a dynamic control over ressources and operations, by programmatically altering metadata before
4+
they are exposed as endpoint. Providing a way to modify, add or remove operations, adjust serialization groups or pagination settings...
5+
6+
It also make it possible to customize built-in endpoints from a third party API, such as Sylius.
7+
8+
9+
## Resource Mutator
10+
11+
Use the resource mutator to modify the entire resource metadata by adding the attribute and target ressource class as argument:
12+
13+
```php
14+
<?php
15+
16+
namespace App\Mutator;
17+
18+
use ApiPlatform\Metadata\ResourceMutatorInterface;
19+
use App\Entity\Book;
20+
21+
#[AsResourceMutator(resourceClass: Book::class)]
22+
final class BookResourceMutator implements ResourceMutatorInterface
23+
{
24+
public function __invoke(ApiResource $resource): ApiResource
25+
{
26+
$operations = $resource->getOperations();
27+
// remove delete operation on Book
28+
$operations->remove('api_Book_delete');
29+
30+
return $resource->withOperations($operations);
31+
}
32+
}
33+
```
34+
35+
## Operation Mutator
36+
37+
The operation mutator will modify a specific operation's metadata, by using the attribute and passing operation name:
38+
```php
39+
<?php
40+
41+
namespace App\Mutator;
42+
43+
use ApiPlatform\Metadata\AsOperationMutator;
44+
use ApiPlatform\Metadata\Operation;
45+
use ApiPlatform\Metadata\OperationMutatorInterface;
46+
47+
#[AsOperationMutator(operationName: '_api_Book_get_collection')]
48+
final class BookOperationMutator implements OperationMutatorInterface
49+
{
50+
public function __invoke(Operation $operation): Operation
51+
{
52+
$context = $operation->getNormalizationContext() ?? [];
53+
// add another group to normalization group
54+
$context['groups'][] = 'review:list:read';
55+
56+
return $operation->withNormalizationContext($context);
57+
}
58+
}
59+
```
60+

0 commit comments

Comments
 (0)