Debian Codegraph @

lib/3rdParty/composer/symfony/serializer/Normalizer/TranslatableNormalizer.php

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