具有 JSon 类型字段的 Symfony 实体会导致 DoctrineExtension Translatable 方法 Translate 出错

问题描述 投票:0回答:1

使用 Symfony 5.4 和 stof/doctrine-extensions-bundle 1.7

我有一个项目,其中包含两种语言的现有数据。当被要求添加更多语言时,我尝试实现学说扩展的可翻译并摆脱旧的翻译“风格”。

所以我正在编写一个命令,将具有两个字段的旧数据转换为一个可翻译字段。

在我的实体中,我有很多字段,例如以下字段:

    #[ORM\Column(type: 'json', nullable: true)]
    private ?array $answers = null;

    #[ORM\Column(name: 'answers_en', type: 'json', nullable: true)]
    private ?array $answersEn = null;

    #[ORM\Column(type: 'json', nullable: true)]
    #[Gedmo\Translatable]
    private ?array $answersI18n = null;

    public function getAnswers(): ?array
    {
        if ($this->answers !== null) {
            $this->answers = array_map(function ($value) {
                return $value === null ? '' : $value;
            }, $this->answers);
        }
        return $this->answers;
    }

    public function setAnswersI18n(?array $answersI18n): static
    {
        $this->answersI18n = $answersI18n;

        return $this;
    }

在我的命令中,我有一个包含以下代码的循环:

    if (!empty($question->getAnswers())) {
        $translationRepository->translate($question, 'answersI18n', 'de', $question->getAnswers());
    }
    if (!empty($question->getAnswersEn())) {
        $translationRepository->translate($question, 'answersI18n', 'en', $question->getAnswersEn());
    }

文本或字符串类型的普通字段工作得很好。 但是 JSon 字段会导致以下错误:

In RuntimeReflectionProperty.php line 60:
Cannot assign string to property App\Entity\Question::$answersI18n of type ?array

示例值可以是:

["no","yes","n/a"]

我想到的最好的解决方案是包装方法,数据转换器...类似这样的...将数据转换为所需的格式,但这感觉不对...很可能这是开箱即用的,我有某个地方出错了...

php translation symfony5.4 stofdoctrineextensions
1个回答
0
投票

问题已解决,至少当实体的语言环境是默认语言环境时。 未在其他情况下进行测试。也没有测试问题是否可以在学说扩展本身或 stof/doctrine-extensions-bundle 中普遍解决。

发生了什么,或者错误从何而来: 对于序列化的类型(如 array、simple_array、json),默认区域设置的字段在翻译的侦听器开始操作之前被序列化。因此,数组或 json 被序列化为字符串,当 Translate 的侦听器尝试使用带有序列化字符串的 setter 时,会抛出错误。

解决方案: 解决方案非常简单:不要使用语言环境的翻译方法,而是使用“正常”设置器。

在命令中,代码现在如下所示

// only tested if the locale is the default_locale
// if it differs try the following code and if an error is thrown try to use the setAnwersI18n-method
// with the content of the locale, and use the translate-method on the other locales
if (!empty($question->getAnswers())) {
    //$translationRepository->translate will lead to an error on types like array, simple_array or json.
    // At least if the locale is the default locale
    $question->setAnswersI18n($question->getAnswersI18n());
}
if (!empty($question->getAnswersEn())) {
    $translationRepository->translate($question, 'answersI18n', 'en', json_encode($question->getAnswersEn()));
}

至少对我来说这就像一个魅力

© www.soinside.com 2019 - 2024. All rights reserved.