22
33namespace Gettext \Generators ;
44
5+ use Gettext \Translation ;
56use Gettext \Translations ;
67use DOMDocument ;
78
89class Xliff extends Generator implements GeneratorInterface
910{
11+ const UNIT_ID_REGEXP = '/^XLIFF_UNIT_ID: (.*)$/ ' ;
12+
1013 /**
1114 * {@inheritdoc}
1215 */
@@ -34,8 +37,11 @@ public static function toString(Translations $translations, array $options = [])
3437 }
3538
3639 foreach ($ translations as $ translation ) {
40+ //Find an XLIFF unit ID, if one is available; otherwise generate
41+ $ unitId = self ::getUnitID ($ translation )?:md5 ($ translation ->getContext ().$ translation ->getOriginal ());
42+
3743 $ unit = $ dom ->createElement ('unit ' );
38- $ unit ->setAttribute ('id ' , md5 ( $ translation -> getContext (). $ translation -> getOriginal ()) );
44+ $ unit ->setAttribute ('id ' , $ unitId );
3945
4046 //Save comments as notes
4147 $ notes = $ dom ->createElement ('notes ' );
@@ -44,6 +50,11 @@ public static function toString(Translations $translations, array $options = [])
4450 ->setAttribute ('category ' , 'context ' );
4551
4652 foreach ($ translation ->getComments () as $ comment ) {
53+ //Skip XLIFF unit ID comments.
54+ if (preg_match (self ::UNIT_ID_REGEXP , $ comment )) {
55+ continue ;
56+ }
57+
4758 $ notes ->appendChild (self ::createTextNode ($ dom , 'note ' , $ comment ))
4859 ->setAttribute ('category ' , 'comment ' );
4960 }
@@ -91,4 +102,21 @@ private static function createTextNode(DOMDocument $dom, $name, $string)
91102
92103 return $ node ;
93104 }
105+
106+ /**
107+ * Gets the translation's unit ID, if one is available.
108+ *
109+ * @param Translation $translation
110+ *
111+ * @return string|null
112+ */
113+ public static function getUnitID (Translation $ translation )
114+ {
115+ foreach ($ translation ->getComments () as $ comment ) {
116+ if (preg_match (self ::UNIT_ID_REGEXP , $ comment , $ matches )) {
117+ return $ matches [1 ];
118+ }
119+ }
120+ return null ;
121+ }
94122}
0 commit comments