XliffFileLoader.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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\XmlUtils;
  13. use Symfony\Component\Translation\Exception\InvalidResourceException;
  14. use Symfony\Component\Translation\Exception\NotFoundResourceException;
  15. use Symfony\Component\Translation\MessageCatalogue;
  16. use Symfony\Component\Translation\Util\XliffUtils;
  17. /**
  18. * XliffFileLoader loads translations from XLIFF files.
  19. *
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. */
  22. class XliffFileLoader implements LoaderInterface
  23. {
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function load($resource, $locale, $domain = 'messages')
  28. {
  29. if (!stream_is_local($resource)) {
  30. throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
  31. }
  32. if (!file_exists($resource)) {
  33. throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
  34. }
  35. $catalogue = new MessageCatalogue($locale);
  36. $this->extract($resource, $catalogue, $domain);
  37. if (class_exists('Symfony\Component\Config\Resource\FileResource')) {
  38. $catalogue->addResource(new FileResource($resource));
  39. }
  40. return $catalogue;
  41. }
  42. private function extract($resource, MessageCatalogue $catalogue, $domain)
  43. {
  44. try {
  45. $dom = XmlUtils::loadFile($resource);
  46. } catch (\InvalidArgumentException $e) {
  47. throw new InvalidResourceException(sprintf('Unable to load "%s": %s', $resource, $e->getMessage()), $e->getCode(), $e);
  48. }
  49. $xliffVersion = XliffUtils::getVersionNumber($dom);
  50. if ($errors = XliffUtils::validateSchema($dom)) {
  51. throw new InvalidResourceException(sprintf('Invalid resource provided: "%s"; Errors: %s', $resource, XliffUtils::getErrorsAsString($errors)));
  52. }
  53. if ('1.2' === $xliffVersion) {
  54. $this->extractXliff1($dom, $catalogue, $domain);
  55. }
  56. if ('2.0' === $xliffVersion) {
  57. $this->extractXliff2($dom, $catalogue, $domain);
  58. }
  59. }
  60. /**
  61. * Extract messages and metadata from DOMDocument into a MessageCatalogue.
  62. *
  63. * @param \DOMDocument $dom Source to extract messages and metadata
  64. * @param MessageCatalogue $catalogue Catalogue where we'll collect messages and metadata
  65. * @param string $domain The domain
  66. */
  67. private function extractXliff1(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain)
  68. {
  69. $xml = simplexml_import_dom($dom);
  70. $encoding = strtoupper($dom->encoding);
  71. $namespace = 'urn:oasis:names:tc:xliff:document:1.2';
  72. $xml->registerXPathNamespace('xliff', $namespace);
  73. foreach ($xml->xpath('//xliff:file') as $file) {
  74. $fileAttributes = $file->attributes();
  75. $file->registerXPathNamespace('xliff', $namespace);
  76. foreach ($file->xpath('.//xliff:trans-unit') as $translation) {
  77. $attributes = $translation->attributes();
  78. if (!(isset($attributes['resname']) || isset($translation->source))) {
  79. continue;
  80. }
  81. $source = isset($attributes['resname']) && $attributes['resname'] ? $attributes['resname'] : $translation->source;
  82. // If the xlf file has another encoding specified, try to convert it because
  83. // simple_xml will always return utf-8 encoded values
  84. $target = $this->utf8ToCharset((string) ($translation->target ?? $translation->source), $encoding);
  85. $catalogue->set((string) $source, $target, $domain);
  86. $metadata = [
  87. 'source' => (string) $translation->source,
  88. 'file' => [
  89. 'original' => (string) $fileAttributes['original'],
  90. ],
  91. ];
  92. if ($notes = $this->parseNotesMetadata($translation->note, $encoding)) {
  93. $metadata['notes'] = $notes;
  94. }
  95. if (isset($translation->target) && $translation->target->attributes()) {
  96. $metadata['target-attributes'] = [];
  97. foreach ($translation->target->attributes() as $key => $value) {
  98. $metadata['target-attributes'][$key] = (string) $value;
  99. }
  100. }
  101. if (isset($attributes['id'])) {
  102. $metadata['id'] = (string) $attributes['id'];
  103. }
  104. $catalogue->setMetadata((string) $source, $metadata, $domain);
  105. }
  106. }
  107. }
  108. private function extractXliff2(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain)
  109. {
  110. $xml = simplexml_import_dom($dom);
  111. $encoding = strtoupper($dom->encoding);
  112. $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:2.0');
  113. foreach ($xml->xpath('//xliff:unit') as $unit) {
  114. foreach ($unit->segment as $segment) {
  115. $source = $segment->source;
  116. // If the xlf file has another encoding specified, try to convert it because
  117. // simple_xml will always return utf-8 encoded values
  118. $target = $this->utf8ToCharset((string) (isset($segment->target) ? $segment->target : $source), $encoding);
  119. $catalogue->set((string) $source, $target, $domain);
  120. $metadata = [];
  121. if (isset($segment->target) && $segment->target->attributes()) {
  122. $metadata['target-attributes'] = [];
  123. foreach ($segment->target->attributes() as $key => $value) {
  124. $metadata['target-attributes'][$key] = (string) $value;
  125. }
  126. }
  127. if (isset($unit->notes)) {
  128. $metadata['notes'] = [];
  129. foreach ($unit->notes->note as $noteNode) {
  130. $note = [];
  131. foreach ($noteNode->attributes() as $key => $value) {
  132. $note[$key] = (string) $value;
  133. }
  134. $note['content'] = (string) $noteNode;
  135. $metadata['notes'][] = $note;
  136. }
  137. }
  138. $catalogue->setMetadata((string) $source, $metadata, $domain);
  139. }
  140. }
  141. }
  142. /**
  143. * Convert a UTF8 string to the specified encoding.
  144. */
  145. private function utf8ToCharset(string $content, string $encoding = null): string
  146. {
  147. if ('UTF-8' !== $encoding && !empty($encoding)) {
  148. return mb_convert_encoding($content, $encoding, 'UTF-8');
  149. }
  150. return $content;
  151. }
  152. private function parseNotesMetadata(\SimpleXMLElement $noteElement = null, string $encoding = null): array
  153. {
  154. $notes = [];
  155. if (null === $noteElement) {
  156. return $notes;
  157. }
  158. /** @var \SimpleXMLElement $xmlNote */
  159. foreach ($noteElement as $xmlNote) {
  160. $noteAttributes = $xmlNote->attributes();
  161. $note = ['content' => $this->utf8ToCharset((string) $xmlNote, $encoding)];
  162. if (isset($noteAttributes['priority'])) {
  163. $note['priority'] = (int) $noteAttributes['priority'];
  164. }
  165. if (isset($noteAttributes['from'])) {
  166. $note['from'] = (string) $noteAttributes['from'];
  167. }
  168. $notes[] = $note;
  169. }
  170. return $notes;
  171. }
  172. }