XliffFileLoader.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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', $xliffVersion, 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. $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:1.2');
  72. foreach ($xml->xpath('//xliff:trans-unit') as $translation) {
  73. $attributes = $translation->attributes();
  74. if (!(isset($attributes['resname']) || isset($translation->source))) {
  75. continue;
  76. }
  77. $source = isset($attributes['resname']) && $attributes['resname'] ? $attributes['resname'] : $translation->source;
  78. // If the xlf file has another encoding specified, try to convert it because
  79. // simple_xml will always return utf-8 encoded values
  80. $target = $this->utf8ToCharset((string) (isset($translation->target) ? $translation->target : $translation->source), $encoding);
  81. $catalogue->set((string) $source, $target, $domain);
  82. $metadata = [];
  83. if ($notes = $this->parseNotesMetadata($translation->note, $encoding)) {
  84. $metadata['notes'] = $notes;
  85. }
  86. if (isset($translation->target) && $translation->target->attributes()) {
  87. $metadata['target-attributes'] = [];
  88. foreach ($translation->target->attributes() as $key => $value) {
  89. $metadata['target-attributes'][$key] = (string) $value;
  90. }
  91. }
  92. if (isset($attributes['id'])) {
  93. $metadata['id'] = (string) $attributes['id'];
  94. }
  95. $catalogue->setMetadata((string) $source, $metadata, $domain);
  96. }
  97. }
  98. private function extractXliff2(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain)
  99. {
  100. $xml = simplexml_import_dom($dom);
  101. $encoding = strtoupper($dom->encoding);
  102. $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:2.0');
  103. foreach ($xml->xpath('//xliff:unit') as $unit) {
  104. foreach ($unit->segment as $segment) {
  105. $source = $segment->source;
  106. // If the xlf file has another encoding specified, try to convert it because
  107. // simple_xml will always return utf-8 encoded values
  108. $target = $this->utf8ToCharset((string) (isset($segment->target) ? $segment->target : $source), $encoding);
  109. $catalogue->set((string) $source, $target, $domain);
  110. $metadata = [];
  111. if (isset($segment->target) && $segment->target->attributes()) {
  112. $metadata['target-attributes'] = [];
  113. foreach ($segment->target->attributes() as $key => $value) {
  114. $metadata['target-attributes'][$key] = (string) $value;
  115. }
  116. }
  117. if (isset($unit->notes)) {
  118. $metadata['notes'] = [];
  119. foreach ($unit->notes->note as $noteNode) {
  120. $note = [];
  121. foreach ($noteNode->attributes() as $key => $value) {
  122. $note[$key] = (string) $value;
  123. }
  124. $note['content'] = (string) $noteNode;
  125. $metadata['notes'][] = $note;
  126. }
  127. }
  128. $catalogue->setMetadata((string) $source, $metadata, $domain);
  129. }
  130. }
  131. }
  132. /**
  133. * Convert a UTF8 string to the specified encoding.
  134. */
  135. private function utf8ToCharset(string $content, string $encoding = null): string
  136. {
  137. if ('UTF-8' !== $encoding && !empty($encoding)) {
  138. return mb_convert_encoding($content, $encoding, 'UTF-8');
  139. }
  140. return $content;
  141. }
  142. private function parseNotesMetadata(\SimpleXMLElement $noteElement = null, string $encoding = null): array
  143. {
  144. $notes = [];
  145. if (null === $noteElement) {
  146. return $notes;
  147. }
  148. /** @var \SimpleXMLElement $xmlNote */
  149. foreach ($noteElement as $xmlNote) {
  150. $noteAttributes = $xmlNote->attributes();
  151. $note = ['content' => $this->utf8ToCharset((string) $xmlNote, $encoding)];
  152. if (isset($noteAttributes['priority'])) {
  153. $note['priority'] = (int) $noteAttributes['priority'];
  154. }
  155. if (isset($noteAttributes['from'])) {
  156. $note['from'] = (string) $noteAttributes['from'];
  157. }
  158. $notes[] = $note;
  159. }
  160. return $notes;
  161. }
  162. }