diff --git a/Enum/DictionaryEnumInterface.php b/Enum/DictionaryEnumInterface.php new file mode 100644 index 0000000..b2240b3 --- /dev/null +++ b/Enum/DictionaryEnumInterface.php @@ -0,0 +1,29 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace StfalconStudio\ApiBundle\Enum; + +/** + * DictionaryEnumInterface. + */ +interface DictionaryEnumInterface extends \BackedEnum +{ + /** + * @return string|null + */ + public function getPrefix(): ?string; + + /** + * @return string + */ + public static function getTranslatorDomain(): string; +} diff --git a/Serializer/Normalizer/DictionaryEnumNormalizer.php b/Serializer/Normalizer/DictionaryEnumNormalizer.php new file mode 100644 index 0000000..a85f648 --- /dev/null +++ b/Serializer/Normalizer/DictionaryEnumNormalizer.php @@ -0,0 +1,78 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace StfalconStudio\ApiBundle\Serializer\Normalizer; + +use StfalconStudio\ApiBundle\Enum\DictionaryEnumInterface; +use StfalconStudio\ApiBundle\Traits\TranslatorTrait; +use Symfony\Component\Serializer\Normalizer\NormalizerInterface; + +/** + * DictionaryEnumNormalizer. + */ +class DictionaryEnumNormalizer implements NormalizerInterface +{ + use TranslatorTrait; + + /** + * @param mixed $data + * @param string|null $format + * + * @return bool + */ + public function supportsNormalization(mixed $data, string $format = null): bool + { + return $data instanceof DictionaryEnumInterface; + } + + /** + * @param DictionaryEnumInterface $object + * @param string|null $format + * @param array $context + * + * @return array + */ + public function normalize(mixed $object, string $format = null, array $context = []): array + { + $data = []; + + $this->normalizeId($object, $data); + $this->normalizeValue($object, $data); + + return $data; + } + + /** + * @param DictionaryEnumInterface $object + * @param array $data + * + * @return void + */ + protected function normalizeId(DictionaryEnumInterface $object, array &$data): void + { + $data['id'] = $object->value; + } + + /** + * @param DictionaryEnumInterface $object + * @param array $data + * + * @return void + */ + protected function normalizeValue(DictionaryEnumInterface $object, array &$data): void + { + $data['value'] = $this->translator->trans( + id: null === $object->getPrefix() ? (string) $object->value : sprintf('%s.%s', $object->getPrefix(), $object->value), + domain: $object::getTranslatorDomain(), + ); + } +}