Skip to content

Commit

Permalink
Add DictionaryEnumInterface and normalizer
Browse files Browse the repository at this point in the history
Co-authored-by: Vladyslav Yarysh <vladyslav.yarysh@stfalcon.com>
gabplch and Vladyslav Yarysh authored Nov 22, 2023
1 parent 1e89fdd commit cd7a6cb
Showing 2 changed files with 107 additions and 0 deletions.
29 changes: 29 additions & 0 deletions Enum/DictionaryEnumInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php
/*
* This file is part of the StfalconApiBundle.
*
* (c) Stfalcon LLC <stfalcon.com>
*
* 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;
}
78 changes: 78 additions & 0 deletions Serializer/Normalizer/DictionaryEnumNormalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php
/*
* This file is part of the StfalconApiBundle.
*
* (c) Stfalcon LLC <stfalcon.com>
*
* 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(),
);
}
}

0 comments on commit cd7a6cb

Please sign in to comment.