XliffFileLoader.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. /**
  28. * {@inheritdoc}
  29. */
  30. public function load($resource, string $locale, string $domain = 'messages')
  31. {
  32. if (!class_exists(XmlUtils::class)) {
  33. throw new RuntimeException('Loading translations from the Xliff format requires the Symfony Config component.');
  34. }
  35. if (!$this->isXmlString($resource)) {
  36. if (!stream_is_local($resource)) {
  37. throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
  38. }
  39. if (!file_exists($resource)) {
  40. throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
  41. }
  42. if (!is_file($resource)) {
  43. throw new InvalidResourceException(sprintf('This is neither a file nor an XLIFF string "%s".', $resource));
  44. }
  45. }
  46. try {
  47. if ($this->isXmlString($resource)) {
  48. $dom = XmlUtils::parse($resource);
  49. } else {
  50. $dom = XmlUtils::loadFile($resource);
  51. }
  52. } catch (\InvalidArgumentException|XmlParsingException|InvalidXmlException $e) {
  53. throw new InvalidResourceException(sprintf('Unable to load "%s": ', $resource).$e->getMessage(), $e->getCode(), $e);
  54. }
  55. if ($errors = XliffUtils::validateSchema($dom)) {
  56. throw new InvalidResourceException(sprintf('Invalid resource provided: "%s"; Errors: ', $resource).XliffUtils::getErrorsAsString($errors));
  57. }
  58. $catalogue = new MessageCatalogue($locale);
  59. $this->extract($dom, $catalogue, $domain);
  60. if (is_file($resource) && class_exists(FileResource::class)) {
  61. $catalogue->addResource(new FileResource($resource));
  62. }
  63. return $catalogue;
  64. }
  65. private function extract(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain)
  66. {
  67. $xliffVersion = XliffUtils::getVersionNumber($dom);
  68. if ('1.2' === $xliffVersion) {
  69. $this->extractXliff1($dom, $catalogue, $domain);
  70. }
  71. if ('2.0' === $xliffVersion) {
  72. $this->extractXliff2($dom, $catalogue, $domain);
  73. }
  74. }
  75. /**
  76. * Extract messages and metadata from DOMDocument into a MessageCatalogue.
  77. */
  78. private function extractXliff1(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain)
  79. {
  80. $xml = simplexml_import_dom($dom);
  81. $encoding = $dom->encoding ? strtoupper($dom->encoding) : null;
  82. $namespace = 'urn:oasis:names:tc:xliff:document:1.2';
  83. $xml->registerXPathNamespace('xliff', $namespace);
  84. foreach ($xml->xpath('//xliff:file') as $file) {
  85. $fileAttributes = $file->attributes();
  86. $file->registerXPathNamespace('xliff', $namespace);
  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. if (isset($translation->target) && 'needs-translation' === (string) $translation->target->attributes()['state']) {
  93. continue;
  94. }
  95. $source = isset($attributes['resname']) && $attributes['resname'] ? $attributes['resname'] : $translation->source;
  96. // If the xlf file has another encoding specified, try to convert it because
  97. // simple_xml will always return utf-8 encoded values
  98. $target = $this->utf8ToCharset((string) ($translation->target ?? $translation->source), $encoding);
  99. $catalogue->set((string) $source, $target, $domain);
  100. $metadata = [
  101. 'source' => (string) $translation->source,
  102. 'file' => [
  103. 'original' => (string) $fileAttributes['original'],
  104. ],
  105. ];
  106. if ($notes = $this->parseNotesMetadata($translation->note, $encoding)) {
  107. $metadata['notes'] = $notes;
  108. }
  109. if (isset($translation->target) && $translation->target->attributes()) {
  110. $metadata['target-attributes'] = [];
  111. foreach ($translation->target->attributes() as $key => $value) {
  112. $metadata['target-attributes'][$key] = (string) $value;
  113. }
  114. }
  115. if (isset($attributes['id'])) {
  116. $metadata['id'] = (string) $attributes['id'];
  117. }
  118. $catalogue->setMetadata((string) $source, $metadata, $domain);
  119. }
  120. }
  121. }
  122. private function extractXliff2(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain)
  123. {
  124. $xml = simplexml_import_dom($dom);
  125. $encoding = $dom->encoding ? strtoupper($dom->encoding) : null;
  126. $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:2.0');
  127. foreach ($xml->xpath('//xliff:unit') as $unit) {
  128. foreach ($unit->segment as $segment) {
  129. $attributes = $unit->attributes();
  130. $source = $attributes['name'] ?? $segment->source;
  131. // If the xlf file has another encoding specified, try to convert it because
  132. // simple_xml will always return utf-8 encoded values
  133. $target = $this->utf8ToCharset((string) ($segment->target ?? $segment->source), $encoding);
  134. $catalogue->set((string) $source, $target, $domain);
  135. $metadata = [];
  136. if (isset($segment->target) && $segment->target->attributes()) {
  137. $metadata['target-attributes'] = [];
  138. foreach ($segment->target->attributes() as $key => $value) {
  139. $metadata['target-attributes'][$key] = (string) $value;
  140. }
  141. }
  142. if (isset($unit->notes)) {
  143. $metadata['notes'] = [];
  144. foreach ($unit->notes->note as $noteNode) {
  145. $note = [];
  146. foreach ($noteNode->attributes() as $key => $value) {
  147. $note[$key] = (string) $value;
  148. }
  149. $note['content'] = (string) $noteNode;
  150. $metadata['notes'][] = $note;
  151. }
  152. }
  153. $catalogue->setMetadata((string) $source, $metadata, $domain);
  154. }
  155. }
  156. }
  157. /**
  158. * Convert a UTF8 string to the specified encoding.
  159. */
  160. private function utf8ToCharset(string $content, ?string $encoding = null): string
  161. {
  162. if ('UTF-8' !== $encoding && !empty($encoding)) {
  163. return mb_convert_encoding($content, $encoding, 'UTF-8');
  164. }
  165. return $content;
  166. }
  167. private function parseNotesMetadata(?\SimpleXMLElement $noteElement = null, ?string $encoding = null): array
  168. {
  169. $notes = [];
  170. if (null === $noteElement) {
  171. return $notes;
  172. }
  173. /** @var \SimpleXMLElement $xmlNote */
  174. foreach ($noteElement as $xmlNote) {
  175. $noteAttributes = $xmlNote->attributes();
  176. $note = ['content' => $this->utf8ToCharset((string) $xmlNote, $encoding)];
  177. if (isset($noteAttributes['priority'])) {
  178. $note['priority'] = (int) $noteAttributes['priority'];
  179. }
  180. if (isset($noteAttributes['from'])) {
  181. $note['from'] = (string) $noteAttributes['from'];
  182. }
  183. $notes[] = $note;
  184. }
  185. return $notes;
  186. }
  187. private function isXmlString(string $resource): bool
  188. {
  189. return 0 === strpos($resource, '<?xml');
  190. }
  191. }