Spaces:
Runtime error
Runtime error
File size: 1,904 Bytes
7a66774 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Serializer\Normalizer;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
use Symfony\Contracts\Translation\TranslatableInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
final class TranslatableNormalizer implements NormalizerInterface
{
public const NORMALIZATION_LOCALE_KEY = 'translatable_normalization_locale';
private array $defaultContext = [
self::NORMALIZATION_LOCALE_KEY => null,
];
public function __construct(
private readonly TranslatorInterface $translator,
array $defaultContext = [],
) {
$this->defaultContext = array_merge($this->defaultContext, $defaultContext);
}
/**
* @throws InvalidArgumentException
*/
public function normalize(mixed $object, ?string $format = null, array $context = []): string
{
if (!$object instanceof TranslatableInterface) {
throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The object must implement the "%s".', TranslatableInterface::class), $object, [TranslatableInterface::class]);
}
return $object->trans($this->translator, $context[self::NORMALIZATION_LOCALE_KEY] ?? $this->defaultContext[self::NORMALIZATION_LOCALE_KEY]);
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof TranslatableInterface;
}
public function getSupportedTypes(?string $format): array
{
return [TranslatableInterface::class => true];
}
}
|