Skip to content

[Contracts] add TranslatableInterface #38330

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
Sep 29, 2020
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
2 changes: 1 addition & 1 deletion src/Symfony/Bridge/Twig/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ CHANGELOG

* added the `impersonation_exit_url()` and `impersonation_exit_path()` functions. They return a URL that allows to switch back to the original user.
* added the `workflow_transition()` function to easily retrieve a specific transition object
* added support for translating `Translatable` objects
* added support for translating `TranslatableInterface` objects
* added the `t()` function to easily create `Translatable` objects
* Added support for extracting messages from the `t()` function

Expand Down
28 changes: 20 additions & 8 deletions src/Symfony/Bridge/Twig/Extension/TranslationExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Symfony\Bridge\Twig\TokenParser\TransDefaultDomainTokenParser;
use Symfony\Bridge\Twig\TokenParser\TransTokenParser;
use Symfony\Component\Translation\Translatable;
use Symfony\Contracts\Translation\TranslatableInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Contracts\Translation\TranslatorTrait;
use Twig\Extension\AbstractExtension;
Expand Down Expand Up @@ -104,17 +105,24 @@ public function getTranslationNodeVisitor(): TranslationNodeVisitor
}

/**
* @param ?string|Translatable $message The message id (may also be an object that can be cast to string)
* @param string|\Stringable|TranslatableInterface|null $message
* @param array|string $arguments Can be the locale as a string when $message is a TranslatableInterface
*/
public function trans($message, array $arguments = [], string $domain = null, string $locale = null, int $count = null): string
public function trans($message, $arguments = [], string $domain = null, string $locale = null, int $count = null): string
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new semantics of the $arguments parameter is not covered by a test, is it? I also wonder if this change is really necessary. I find the error message rather confusing that a developer gets when passing an array of arguments to the trans filter (which can be an honest C&P mistake).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test case added as {{ t("Hello")|trans("fr") }}

Not doing this polymorphism means that ppl would be forced to always write
{{ translateble|trans(locale=fr) }} instead of {{ translateble|trans(fr) }} which the current changes allows.

If the issue is the error message, we could improve it. Suggestions welcome :)

{
if ($message instanceof Translatable) {
$arguments += $message->getParameters();
$domain = $message->getDomain();
$message = $message->getMessage();
if ($message instanceof TranslatableInterface) {
if ([] !== $arguments && !\is_string($arguments)) {
throw new \TypeError(sprintf('Argument 2 passed to "%s()" must be a locale passed as a string when the message is a "%s", "%s" given.', __METHOD__, TranslatableInterface::class, get_debug_type($arguments)));
}

return $message->trans($this->getTranslator(), $locale ?? (\is_string($arguments) ? $arguments : null));
}

if (!\is_array($arguments)) {
throw new \TypeError(sprintf('Unless the message is a "%s", argument 2 passed to "%s()" must be an array of parameters, "%s" given.', TranslatableInterface::class, __METHOD__, get_debug_type($arguments)));
}

if (null === $message || '' === $message) {
if ('' === $message = (string) $message) {
return '';
}

Expand All @@ -125,8 +133,12 @@ public function trans($message, array $arguments = [], string $domain = null, st
return $this->getTranslator()->trans($message, $arguments, $domain, $locale);
}

public function createTranslatable(string $message, array $parameters = [], string $domain = 'messages'): Translatable
public function createTranslatable(string $message, array $parameters = [], string $domain = null): Translatable
{
if (!class_exists(Translatable::class)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it could be an anonymous data object, for general compatibility

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it could but I doubt this would provide many benefits. The dependency on the component is quite a loose one for someone using the extension.

throw new \LogicException(sprintf('You cannot use the "%s" as the Translation Component is not installed. Try running "composer require symfony/translation".', __CLASS__));
}

return new Translatable($message, $parameters, $domain);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -126,19 +126,14 @@ public function getTransTests()
// trans object
['{{ t("Hello")|trans }}', 'Hello'],
['{{ t(name)|trans }}', 'Symfony', ['name' => 'Symfony']],
['{{ t(hello)|trans({ \'%name%\': \'Symfony\' }) }}', 'Hello Symfony', ['hello' => 'Hello %name%']],
['{{ t(hello, { \'%name%\': \'Symfony\' })|trans }}', 'Hello Symfony', ['hello' => 'Hello %name%']],
['{{ t(hello, { \'%name%\': \'Another Name\' })|trans({ \'%name%\': \'Symfony\' }) }}', 'Hello Symfony', ['hello' => 'Hello %name%']],
['{% set vars = { \'%name%\': \'Symfony\' } %}{{ t(hello)|trans(vars) }}', 'Hello Symfony', ['hello' => 'Hello %name%']],
['{% set vars = { \'%name%\': \'Symfony\' } %}{{ t(hello, vars)|trans }}', 'Hello Symfony', ['hello' => 'Hello %name%']],
['{{ t("Hello")|trans("fr") }}', 'Hello'],
['{{ t("Hello")|trans(locale="fr") }}', 'Hello'],
['{{ t("Hello", {}, "messages")|trans(locale="fr") }}', 'Hello'],

// trans object with count
['{{ t("{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples")|trans(count=count) }}', 'There is 5 apples', ['count' => 5]],
['{{ t(text)|trans(count=5, arguments={\'%name%\': \'Symfony\'}) }}', 'There is 5 apples (Symfony)', ['text' => '{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples (%name%)']],
['{{ t(text, {\'%name%\': \'Symfony\'})|trans(count=5) }}', 'There is 5 apples (Symfony)', ['text' => '{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples (%name%)']],
['{{ t("{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples", {}, "messages")|trans(locale="fr", count=count) }}', 'There is 5 apples', ['count' => 5]],
['{{ t("{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples", {\'%count%\': count})|trans }}', 'There is 5 apples', ['count' => 5]],
];
}

Expand Down
20 changes: 20 additions & 0 deletions src/Symfony/Component/Translation/Resources/functions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?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\Translation;

/**
* @author Nate Wiebe <nate@northern.co>
*/
function t(string $message, array $parameters = [], string $domain = null): Translatable
{
return new Translatable($message, $parameters, $domain);
}

This file was deleted.

4 changes: 2 additions & 2 deletions src/Symfony/Component/Translation/Tests/TranslatableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public function testTrans($expected, $translatable, $translation, $locale)
$translator->addLoader('array', new ArrayLoader());
$translator->addResource('array', [$translatable->getMessage() => $translation], $locale, $translatable->getDomain());

$this->assertSame($expected, Translatable::trans($translator, $translatable, $locale));
$this->assertSame($expected, $translatable->trans($translator, $locale));
}

/**
Expand All @@ -39,7 +39,7 @@ public function testFlattenedTrans($expected, $messages, $translatable)
$translator->addLoader('array', new ArrayLoader());
$translator->addResource('array', $messages, 'fr', '');

$this->assertSame($expected, Translatable::trans($translator, $translatable, 'fr'));
$this->assertSame($expected, $translatable->trans($translator, 'fr'));
}

public function testToString()
Expand Down
13 changes: 7 additions & 6 deletions src/Symfony/Component/Translation/Translatable.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,19 @@

namespace Symfony\Component\Translation;

use Symfony\Contracts\Translation\TranslatableInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
* @author Nate Wiebe <nate@northern.co>
*/
final class Translatable
class Translatable implements TranslatableInterface
{
private $message;
private $parameters;
private $domain;

public function __construct(string $message, array $parameters = [], string $domain = 'messages')
public function __construct(string $message, array $parameters = [], string $domain = null)
{
$this->message = $message;
$this->parameters = $parameters;
Expand All @@ -31,7 +32,7 @@ public function __construct(string $message, array $parameters = [], string $dom

public function __toString(): string
{
return $this->message;
return $this->getMessage();
}

public function getMessage(): string
Expand All @@ -44,13 +45,13 @@ public function getParameters(): array
return $this->parameters;
}

public function getDomain(): string
public function getDomain(): ?string
{
return $this->domain;
}

public static function trans(TranslatorInterface $translator, self $translatable, ?string $locale = null): string
public function trans(TranslatorInterface $translator, string $locale = null): string
{
return $translator->trans($translatable->getMessage(), $translatable->getParameters(), $translatable->getDomain(), $locale);
return $translator->trans($this->getMessage(), $this->getParameters(), $this->getDomain(), $locale);
}
}
4 changes: 2 additions & 2 deletions src/Symfony/Component/Translation/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"php": ">=7.2.5",
"symfony/polyfill-mbstring": "~1.0",
"symfony/polyfill-php80": "^1.15",
"symfony/translation-contracts": "^2"
"symfony/translation-contracts": "^2.3"
},
"require-dev": {
"symfony/config": "^4.4|^5.0",
Expand Down Expand Up @@ -48,7 +48,7 @@
"psr/log-implementation": "To use logging capability in translator"
},
"autoload": {
"files": [ "Resources/functions/translatable.php" ],
"files": [ "Resources/functions.php" ],
"psr-4": { "Symfony\\Component\\Translation\\": "" },
"exclude-from-classmap": [
"/Tests/"
Expand Down
11 changes: 11 additions & 0 deletions src/Symfony/Contracts/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
CHANGELOG
=========

2.3.0
-----

* added `Translation\TranslatableInterface` to enable value-objects to be translated
* made `Translation\TranslatorTrait::getLocale()` fallback to intl's `Locale::getDefault()` when available

2.2.0
-----

* added `Service\Attribute\Required` attribute for PHP 8

2.1.3
-----

Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Contracts/Cache/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
"dev-master": "2.2-dev"
"dev-master": "2.3-dev"
},
"thanks": {
"name": "symfony/contracts",
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Contracts/Deprecation/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
"dev-master": "2.2-dev"
"dev-master": "2.3-dev"
},
"thanks": {
"name": "symfony/contracts",
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Contracts/EventDispatcher/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
"dev-master": "2.2-dev"
"dev-master": "2.3-dev"
},
"thanks": {
"name": "symfony/contracts",
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Contracts/HttpClient/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
"dev-master": "2.2-dev"
"dev-master": "2.3-dev"
},
"thanks": {
"name": "symfony/contracts",
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Contracts/Service/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
"dev-master": "2.2-dev"
"dev-master": "2.3-dev"
},
"thanks": {
"name": "symfony/contracts",
Expand Down
20 changes: 20 additions & 0 deletions src/Symfony/Contracts/Translation/TranslatableInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?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\Contracts\Translation;

/**
* @author Nicolas Grekas <p@tchwork.com>
*/
interface TranslatableInterface
{
public function trans(TranslatorInterface $translator, string $locale = null): string;
}
2 changes: 1 addition & 1 deletion src/Symfony/Contracts/Translation/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
"dev-master": "2.2-dev"
"dev-master": "2.3-dev"
},
"thanks": {
"name": "symfony/contracts",
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Contracts/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
"dev-master": "2.2-dev"
"dev-master": "2.3-dev"
}
}
}