Symfony 可翻译枚举

Hri*_*cer 5 php enums symfony symfony-translator

我的供应商实体具有枚举属性notifyType。知道如何以这种方式翻译枚举吗?

{{ supplier.notifyType|trans }}
Run Code Online (Sandbox Code Playgroud)

不幸的是,在 Enum 中使用 __toString 方法是不可能的。

{{ supplier.notifyType|trans }}
Run Code Online (Sandbox Code Playgroud)

然后我就尝试了这个:

// error - Enum may not include __toString
public function __toString(): string
{
    return 'supplier.notify.'.$this->name;
}
Run Code Online (Sandbox Code Playgroud)

但不可能将可翻译对象传递给 trans 方法。仅接受字符串。

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

enum NotifyType: int implements TranslatableInterface
{
    case EMAIL = 1;
    case WEBHOOK = 2;
    case PUNCH_OUT = 4;

    public function trans(TranslatorInterface $translator, string $locale = null): string
    {
        return $translator->trans('supplier.notify.'.$this->name, locale: $locale);
    }
}

Run Code Online (Sandbox Code Playgroud)

CAV*_*ian 7

长话短说:NotifyType::EMAIL->trans($this->translator)


您的枚举是正确的,并且由于实现而应该像这样工作TranslatableInterface

我能发现的唯一问题是translation:extractsymfony 命令的“自动发现”将无法正确工作,因为您的翻译是动态的

您应该避免使用连接trans id并改用match表达式(假设您由于枚举问题而
进入):PHP >= 8.1

enum NotifyType: int implements TranslatableInterface
{
    case EMAIL = 1;
    case WEBHOOK = 2;
    case PUNCH_OUT = 4;

    public function trans(TranslatorInterface $translator, string $locale = null): string
    {
        return match ($this) {
            self::EMAIL     => $translator->trans('supplier.notify.email', locale: $locale),
            self::WEBHOOK   => $translator->trans('supplier.notify.webhook', locale: $locale),
            self::PUNCH_OUT => $translator->trans('supplier.notify.punch_out', locale: $locale),
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

PHP使用

NotifyType::EMAIL->trans($this->translator)

树枝的使用

{{ supplier.notifyType | trans }}

但绝对不是那样的:

  • {{ supplier.notifyType.value | trans }}=> 错误
  • {{ supplier.notifyType.name | trans }}=> 错误

编辑:添加$locale到 trans() 函数调用,thx @jared-farrish