Skip to content

Commit 067cb22

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

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

core/metadata-mutators.md

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

outline.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ chapters:
7171
- bootstrap
7272
- configuration
7373
- client-integration
74+
- metadata-mutators
7475
- title: Schema Generator
7576
path: schema-generator
7677
items:

0 commit comments

Comments
 (0)