XliffFileLoader.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Translation\Loader;
  11. use Symfony\Component\Config\Resource\FileResource;
  12. use Symfony\Component\Config\Util\Exception\InvalidXmlException;
  13. use Symfony\Component\Config\Util\Exception\XmlParsingException;
  14. use Symfony\Component\Config\Util\XmlUtils;
  15. use Symfony\Component\Translation\Exception\InvalidResourceException;
  16. use Symfony\Component\Translation\Exception\NotFoundResourceException;
  17. use Symfony\Component\Translation\Exception\RuntimeException;
  18. use Symfony\Component\Translation\MessageCatalogue;
  19. use Symfony\Component\Translation\Util\XliffUtils;
  20. /**
  21. * XliffFileLoader loads translations from XLIFF files.
  22. *
  23. * @author Fabien Potencier <fabien@symfony.com>
  24. */
  25. class XliffFileLoader implements LoaderInterface
  26. {
  27. public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue
  28. {
  29. if (!class_exists(XmlUtils::class)) {
  30. throw new RuntimeException('Loading translations from the Xliff format requires the Symfony Config component.');
  31. }
  32. if (!$this->isXmlString($resource)) {
  33. if (!stream_is_local($resource)) {
  34. throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
  35. }
  36. if (!file_exists($resource)) {
  37. throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
  38. }
  39. if (!is_file($resource)) {
  40. throw new InvalidResourceException(sprintf('This is neither a file nor an XLIFF string "%s".', $resource));
  41. }
  42. }
  43. try {
  44. if ($this->isXmlString($resource)) {
  45. $dom = XmlUtils::parse($resource);
  46. } else {
  47. $dom = XmlUtils::loadFile($resource);
  48. }
  49. } catch (\InvalidArgumentException|XmlParsingException|InvalidXmlException $e) {
  50. throw new InvalidResourceException(sprintf('Unable to load "%s": ', $resource).$e->getMessage(), $e->getCode(), $e);
  51. }
  52. if ($errors = XliffUtils::validateSchema($dom)) {
  53. throw new InvalidResourceException(sprintf('Invalid resource provided: "%s"; Errors: ', $resource).XliffUtils::getErrorsAsString($errors));
  54. }
  55. $catalogue = new MessageCatalogue($locale);
  56. $this->extract($dom, $catalogue, $domain);
  57. if (is_file($resource) && class_exists(FileResource::class)) {
  58. $catalogue->addResource(new FileResource($resource));
  59. }
  60. return $catalogue;
  61. }
  62. private function extract(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain): void
  63. {
  64. $xliffVersion = XliffUtils::getVersionNumber($dom);
  65. if ('1.2' === $xliffVersion) {
  66. $this->extractXliff1($dom, $catalogue, $domain);
  67. }
  68. if ('2.0' === $xliffVersion) {
  69. $this->extractXliff2($dom, $catalogue, $domain);
  70. }
  71. }
  72. /**
  73. * Extract messages and metadata from DOMDocument into a MessageCatalogue.
  74. */
  75. private function extractXliff1(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain): void
  76. {
  77. $xml = simplexml_import_dom($dom);
  78. $encoding = $dom->encoding ? strtoupper($dom->encoding) : null;
  79. $namespace = 'urn:oasis:names:tc:xliff:document:1.2';
  80. $xml->registerXPathNamespace('xliff', $namespace);
  81. foreach ($xml->xpath('//xliff:file') as $file) {
  82. $fileAttributes = $file->attributes();
  83. $file->registerXPathNamespace('xliff', $namespace);
  84. foreach ($file->xpath('.//xliff:prop') as $prop) {
  85. $catalogue->setCatalogueMetadata($prop->attributes()['prop-type'], (string) $prop, $domain);
  86. }
  87. foreach ($file->xpath('.//xliff:trans-unit') as $translation) {
  88. $attributes = $translation->attributes();
  89. if (!(isset($attributes['resname']) || isset($translation->source))) {
  90. continue;
  91. }
  92. $source = (string) (isset($attributes['resname']) && $attributes['resname'] ? $attributes['resname'] : $translation->source);
  93. if (isset($translation->target)
  94. && 'needs-translation' === (string) $translation->target->attributes()['state']
  95. && \in_array((string) $translation->target, [$source, (string) $translation->source], true)
  96. ) {
  97. continue;
  98. }
  99. // If the xlf file has another encoding specified, try to convert it because
  100. // simple_xml will always return utf-8 encoded values
  101. $target = $this->utf8ToCharset((string) ($translation->target ?? $translation->source), $encoding);
  102. $catalogue->set($source, $target, $domain);
  103. $metadata = [
  104. 'source' => (string) $translation->source,
  105. 'file' => [
  106. 'original' => (string) $fileAttributes['original'],
  107. ],
  108. ];
  109. if ($notes = $this->parseNotesMetadata($translation->note, $encoding)) {
  110. $metadata['notes'] = $notes;
  111. }
  112. if (isset($translation->target) && $translation->target->attributes()) {
  113. $metadata['target-attributes'] = [];
  114. foreach ($translation->target->attributes() as $key => $value) {
  115. $metadata['target-attributes'][$key] = (string) $value;
  116. }
  117. }
  118. if (isset($attributes['id'])) {
  119. $metadata['id'] = (string) $attributes['id'];
  120. }
  121. $catalogue->setMetadata($source, $metadata, $domain);
  122. }
  123. }
  124. }
  125. private function extractXliff2(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain): void
  126. {
  127. $xml = simplexml_import_dom($dom);
  128. $encoding = $dom->encoding ? strtoupper($dom->encoding) : null;
  129. $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:2.0');
  130. foreach ($xml->xpath('//xliff:unit') as $unit) {
  131. foreach ($unit->segment as $segment) {
  132. $attributes = $unit->attributes();
  133. $source = $attributes['name'] ?? $segment->source;
  134. // If the xlf file has another encoding specified, try to convert it because
  135. // simple_xml will always return utf-8 encoded values
  136. $target = $this->utf8ToCharset((string) ($segment->target ?? $segment->source), $encoding);
  137. $catalogue->set((string) $source, $target, $domain);
  138. $metadata = [];
  139. if (isset($segment->target) && $segment->target->attributes()) {
  140. $metadata['target-attributes'] = [];
  141. foreach ($segment->target->attributes() as $key => $value) {
  142. $metadata['target-attributes'][$key] = (string) $value;
  143. }
  144. }
  145. if (isset($unit->notes)) {
  146. $metadata['notes'] = [];
  147. foreach ($unit->notes->note as $noteNode) {
  148. $note = [];
  149. foreach ($noteNode->attributes() as $key => $value) {
  150. $note[$key] = (string) $value;
  151. }
  152. $note['content'] = (string) $noteNode;
  153. $metadata['notes'][] = $note;
  154. }
  155. }
  156. $catalogue->setMetadata((string) $source, $metadata, $domain);
  157. }
  158. }
  159. }
  160. /**
  161. * Convert a UTF8 string to the specified encoding.
  162. */
  163. private function utf8ToCharset(string $content, ?string $encoding = null): string
  164. {
  165. if ('UTF-8' !== $encoding && !empty($encoding)) {
  166. return mb_convert_encoding($content, $encoding, 'UTF-8');
  167. }
  168. return $content;
  169. }
  170. private function parseNotesMetadata(?\SimpleXMLElement $noteElement = null, ?string $encoding = null): array
  171. {
  172. $notes = [];
  173. if (null === $noteElement) {
  174. return $notes;
  175. }
  176. /** @var \SimpleXMLElement $xmlNote */
  177. foreach ($noteElement as $xmlNote) {
  178. $noteAttributes = $xmlNote->attributes();
  179. $note = ['content' => $this->utf8ToCharset((string) $xmlNote, $encoding)];
  180. if (isset($noteAttributes['priority'])) {
  181. $note['priority'] = (int) $noteAttributes['priority'];
  182. }
  183. if (isset($noteAttributes['from'])) {
  184. $note['from'] = (string) $noteAttributes['from'];
  185. }
  186. $notes[] = $note;
  187. }
  188. return $notes;
  189. }
  190. private function isXmlString(string $resource): bool
  191. {
  192. return str_starts_with($resource, '<?xml');
  193. }
  194. }