bug #40283 [Translation] Make `name` attribute optional in xliff2 (MarieMinasyan)

This PR was submitted for the 5.2 branch but it was merged into the 4.4 branch instead.

Discussion
----------

[Translation] Make `name` attribute optional in xliff2

Do not set a fake `name` attribute on `unit` element from xliff2 to allow using `source` attribute and avoid missing translation error

| Q             | A
| ------------- | ---
| Branch?       | 5.2
| Bug fix?      | yes/no
| New feature?  | no
| Deprecations? | no
| Tickets       | Fix #37055
| License       | MIT
| Doc PR        | symfony/symfony-docs#... <!-- required for new features -->

When `xlf` translations are loaded, if a name exists on `unit` element, the segment's source is ignored:
```foreach ($xml->xpath('//xliff:unit') as $unit) {
            foreach ($unit->segment as $segment) {
                $attributes = $unit->attributes();
                $source = $attributes['name'] ?? $segment->source;
```

At the same time, when dumping translations, the segment's source is copied into the unit's name attribute, unless it's longer than 80 characters. In that case, `substr(md5($source), -7)` is set into the name attribute.
This results in a missing translation error, because the source is ignored and the name is a random string.

Suggested solution: only set the name attribute if the string is less than 80 characters.

Commits
-------

97058559cc [Translation] Make `name` attribute optional in xliff2
This commit is contained in:
Nicolas Grekas 2021-02-24 17:01:10 +01:00
commit 91121acf4b
3 changed files with 11 additions and 4 deletions

View File

@ -150,11 +150,11 @@ class XliffFileDumper extends FileDumper
foreach ($messages->all($domain) as $source => $target) {
$translation = $dom->createElement('unit');
$translation->setAttribute('id', strtr(substr(base64_encode(hash('sha256', $source, true)), 0, 7), '/+', '._'));
$name = $source;
if (\strlen($source) > 80) {
$name = substr(md5($source), -7);
if (\strlen($source) <= 80) {
$translation->setAttribute('name', $source);
}
$translation->setAttribute('name', $name);
$metadata = $messages->getMetadata($source, $domain);
// Add notes section

View File

@ -43,6 +43,7 @@ class XliffFileDumperTest extends TestCase
'foo' => 'bar',
'key' => '',
'key.with.cdata' => '<source> & <target>',
'translation.key.that.is.longer.than.eighty.characters.should.not.have.name.attribute' => 'value',
]);
$catalogue->setMetadata('key', ['target-attributes' => ['order' => 1]]);

View File

@ -19,5 +19,11 @@
<target><![CDATA[<source> & <target>]]></target>
</segment>
</unit>
<unit id="aF1tx51">
<segment>
<source>translation.key.that.is.longer.than.eighty.characters.should.not.have.name.attribute</source>
<target>value</target>
</segment>
</unit>
</file>
</xliff>