Skip to content

Commit e61eec1

Browse files
committed
1 parent 4775684 commit e61eec1

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

core/identifiers.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,71 @@ services:
172172

173173
Your `PersonProvider` will now work as expected!
174174

175+
## Decorating the IdentifiersExtractor
176+
177+
The `IdentifiersExtractor` is responsible for extracting identifiers from a resource. By default, when `\DateTime` objects are used as identifiers, their serialization to `IRI` format is handled by the `DateTimeUriVariableTransformer`, which internally uses Symfony's `DateTimeNormalizer`. If you need a custom format, you can decorate the `IdentifiersExtractor`.
178+
179+
Let's say you want to format all `\DateTime` identifiers to `Y-m-d`.
180+
181+
First, create a custom `IdentifiersExtractor` that decorates the original:
182+
183+
```php
184+
<?php
185+
// api/src/Identifier/DateTimeIdentifiersExtractor.php
186+
namespace App\Identifier;
187+
188+
use ApiPlatform\Api\IdentifiersExtractorInterface;
189+
use DateTimeInterface;
190+
191+
final class DateTimeIdentifiersExtractor implements IdentifiersExtractorInterface
192+
{
193+
public function __construct(private IdentifiersExtractorInterface $decorated)
194+
{
195+
}
196+
197+
/**
198+
* {@inheritdoc}
199+
*/
200+
public function getIdentifiersFromItem(object $item, array $options = []): array
201+
{
202+
$identifiers = $this->decorated->getIdentifiersFromItem($item, $options);
203+
204+
foreach ($identifiers as $key => $value) {
205+
if ($value instanceof DateTimeInterface) {
206+
$identifiers[$key] = $value->format('Y-m-d');
207+
}
208+
}
209+
210+
return $identifiers;
211+
}
212+
}
213+
```
214+
215+
Then, configure the service decoration in your `services.yaml`:
216+
217+
<code-selector>
218+
219+
```yaml
220+
# api/config/services.yaml
221+
services:
222+
App\Identifier\DateTimeIdentifiersExtractor:
223+
decorates: 'api_platform.identifiers.identifiers_extractor'
224+
arguments: ['@.inner']
225+
public: false
226+
```
227+
228+
```xml
229+
<!-- The XML syntax is only supported for Symfony -->
230+
<service id="App\Identifier\DateTimeIdentifiersExtractor" class="App\Identifier\DateTimeIdentifiersExtractor" public="false">
231+
<decorate id="api_platform.identifiers.identifiers_extractor" />
232+
<argument type="service" id="App\Identifier\DateTimeIdentifiersExtractor.inner" />
233+
</service>
234+
```
235+
236+
</code-selector>
237+
238+
Now, all `\DateTime` identifiers will be formatted as `Y-m-d` in your resource IRIs.
239+
175240
## Changing Identifier in a Doctrine Entity
176241

177242
If your resource is also a Doctrine entity and you want to use another identifier other than the

0 commit comments

Comments
 (0)