Skip to content

Commit

Permalink
Feature/upd dictionary normalizer (#64)
Browse files Browse the repository at this point in the history
* add `default_normalization` option

* add usage section with dictionary enums

---------

Co-authored-by: Vladyslav Yarysh <[email protected]>
  • Loading branch information
gabplch and Vladyslav Yarysh authored Jun 4, 2024
1 parent 8133e18 commit 8d4efcb
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,33 @@ stfalcon_api:
redis_client_jwt_black_list: "@snc_redis.jwt_black_list"
```

# Usage
## Dictionary enums
For simple dictionary enums, you can use the `DictionaryEnumInteface` interface on Enums.
It will register for serialization like a dictionary, so the result will be like:
```json
{
"id": 1,
"value": "Enum name"
}
```

So, now the dictionary action will look like:
```php
#[Route(path: '/foo/bar', name: 'foo_bar', methods: [Request::METHOD_GET])]
public function __invoke(): JsonResponse
{
// ...
return new JsonResponse(data: $this->serializer->serialize(FooBar::cases()), json: true);
}
```

In some cases, you may need to serialise dictionary value not as dictionary, for this just add in context parameter `default_normalization` with any value.
```php
$this->serializer->serialize($fooBar, 'json', ['default_normalization' => true]);
```

## Contributing

Read the [CONTRIBUTING](https://github.com/stfalcon-studio/ApiBundle/blob/main/.github/CONTRIBUTING.md) file.
2 changes: 1 addition & 1 deletion Serializer/Normalizer/DictionaryEnumNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class DictionaryEnumNormalizer implements NormalizerInterface
*/
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof DictionaryEnumInterface;
return $data instanceof DictionaryEnumInterface && !isset($context['default_normalization']);
}

/**
Expand Down

0 comments on commit 8d4efcb

Please sign in to comment.