Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[FrameworkBundle][Serializer] Add TranslatableNormalizer #50212

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1879,6 +1879,10 @@ private function registerSerializerConfiguration(array $config, ContainerBuilder
$container->removeDefinition('serializer.normalizer.mime_message');
}

if (!class_exists(Translator::class)) {
$container->removeDefinition('serializer.normalizer.translatable');
}

// compat with Symfony < 6.3
if (!is_subclass_of(ProblemNormalizer::class, SerializerAwareInterface::class)) {
$container->getDefinition('serializer.normalizer.problem')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\ProblemNormalizer;
use Symfony\Component\Serializer\Normalizer\PropertyNormalizer;
use Symfony\Component\Serializer\Normalizer\TranslatableNormalizer;
use Symfony\Component\Serializer\Normalizer\UidNormalizer;
use Symfony\Component\Serializer\Normalizer\UnwrappingDenormalizer;
use Symfony\Component\Serializer\Serializer;
Expand Down Expand Up @@ -113,6 +114,10 @@
->set('serializer.normalizer.uid', UidNormalizer::class)
->tag('serializer.normalizer', ['priority' => -890])

->set('serializer.normalizer.translatable', TranslatableNormalizer::class)
->args(['$translator' => service('translator')])
->tag('serializer.normalizer', ['priority' => -890])

->set('serializer.normalizer.form_error', FormErrorNormalizer::class)
->tag('serializer.normalizer', ['priority' => -915])

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
use Symfony\Component\Serializer\Normalizer\FormErrorNormalizer;
use Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\TranslatableNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Translation\DependencyInjection\TranslatorPass;
use Symfony\Component\Translation\LocaleSwitcher;
Expand Down Expand Up @@ -1586,6 +1587,18 @@ public function testConstraintViolationListNormalizerRegistered()
$this->assertEquals(new Reference('serializer.name_converter.metadata_aware'), $definition->getArgument(1));
}

public function testTranslatableNormalizerRegistered()
{
$container = $this->createContainerFromFile('full');

$definition = $container->getDefinition('serializer.normalizer.translatable');
$tag = $definition->getTag('serializer.normalizer');

$this->assertSame(TranslatableNormalizer::class, $definition->getClass());
$this->assertSame(-890, $tag[0]['priority']);
$this->assertEquals(new Reference('translator'), $definition->getArgument('$translator'));
}

public function testSerializerCacheActivated()
{
$container = $this->createContainerFromFile('serializer_enabled');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ public static function provideNormalizersAndEncodersWithDefaultContextOption():
['serializer.normalizer.json_serializable.alias'],
['serializer.normalizer.problem.alias'],
['serializer.normalizer.uid.alias'],
['serializer.normalizer.translatable.alias'],
['serializer.normalizer.object.alias'],
['serializer.encoder.xml.alias'],
['serializer.encoder.yaml.alias'],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ services:
alias: serializer.normalizer.uid
public: true

serializer.normalizer.translatable.alias:
alias: serializer.normalizer.translatable
public: true

serializer.normalizer.property.alias:
alias: serializer.normalizer.property
public: true
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* 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\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 new InvalidArgumentException(sprintf('The object must implement the "%s".', 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];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Serializer\Tests\Normalizer;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Normalizer\TranslatableNormalizer;
use Symfony\Contracts\Translation\TranslatableInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

class TranslatableNormalizerTest extends TestCase
{
private readonly TranslatableNormalizer $normalizer;

protected function setUp(): void
{
$this->normalizer = new TranslatableNormalizer($this->createMock(TranslatorInterface::class));
}

public function testSupportsNormalization()
{
$this->assertTrue($this->normalizer->supportsNormalization(new TestMessage()));
$this->assertFalse($this->normalizer->supportsNormalization(new \stdClass()));
}

public function testNormalize()
{
$message = new TestMessage();

$this->assertSame('key_null', $this->normalizer->normalize($message));
$this->assertSame('key_fr', $this->normalizer->normalize($message, context: ['translatable_normalization_locale' => 'fr']));
$this->assertSame('key_en', $this->normalizer->normalize($message, context: ['translatable_normalization_locale' => 'en']));
}

public function testNormalizeWithNormalizationLocalePassedInConstructor()
{
$normalizer = new TranslatableNormalizer(
$this->createMock(TranslatorInterface::class),
['translatable_normalization_locale' => 'es'],
);
$message = new TestMessage();

$this->assertSame('key_es', $normalizer->normalize($message));
$this->assertSame('key_fr', $normalizer->normalize($message, context: ['translatable_normalization_locale' => 'fr']));
$this->assertSame('key_en', $normalizer->normalize($message, context: ['translatable_normalization_locale' => 'en']));
}
}

class TestMessage implements TranslatableInterface
{
public function trans(TranslatorInterface $translator, string $locale = null): string
{
return 'key_'.($locale ?? 'null');
}
}