Geen omschrijving

XliffFileLoader.php 7.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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(FileResource::class)) {
  38. $catalogue->addResource(new FileResource($resource));
  39. }
  40. return $catalogue;
  41. }
  42. private function extract($resource, MessageCatalogue $catalogue, string $domain)
  43. {
  44. try {
  45. $dom = XmlUtils::loadFile($resource);
  46. } catch (\InvalidArgumentException $e) {
  47. throw new InvalidResourceException(sprintf('Unable to load "%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: ', $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. private function extractXliff1(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain)
  64. {
  65. $xml = simplexml_import_dom($dom);
  66. $encoding = $dom->encoding ? strtoupper($dom->encoding) : null;
  67. $namespace = 'urn:oasis:names:tc:xliff:document:1.2';
  68. $xml->registerXPathNamespace('xliff', $namespace);
  69. foreach ($xml->xpath('//xliff:file') as $file) {
  70. $fileAttributes = $file->attributes();
  71. $file->registerXPathNamespace('xliff', $namespace);
  72. foreach ($file->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) ($translation->target ?? $translation->source), $encoding);
  81. $catalogue->set((string) $source, $target, $domain);
  82. $metadata = [
  83. 'source' => (string) $translation->source,
  84. 'file' => [
  85. 'original' => (string) $fileAttributes['original'],
  86. ],
  87. ];
  88. if ($notes = $this->parseNotesMetadata($translation->note, $encoding)) {
  89. $metadata['notes'] = $notes;
  90. }
  91. if (isset($translation->target) && $translation->target->attributes()) {
  92. $metadata['target-attributes'] = [];
  93. foreach ($translation->target->attributes() as $key => $value) {
  94. $metadata['target-attributes'][$key] = (string) $value;
  95. }
  96. }
  97. if (isset($attributes['id'])) {
  98. $metadata['id'] = (string) $attributes['id'];
  99. }
  100. $catalogue->setMetadata((string) $source, $metadata, $domain);
  101. }
  102. }
  103. }
  104. private function extractXliff2(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain)
  105. {
  106. $xml = simplexml_import_dom($dom);
  107. $encoding = $dom->encoding ? strtoupper($dom->encoding) : null;
  108. $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:2.0');
  109. foreach ($xml->xpath('//xliff:unit') as $unit) {
  110. foreach ($unit->segment as $segment) {
  111. $source = $segment->source;
  112. // If the xlf file has another encoding specified, try to convert it because
  113. // simple_xml will always return utf-8 encoded values
  114. $target = $this->utf8ToCharset((string) ($segment->target ?? $source), $encoding);
  115. $catalogue->set((string) $source, $target, $domain);
  116. $metadata = [];
  117. if (isset($segment->target) && $segment->target->attributes()) {
  118. $metadata['target-attributes'] = [];
  119. foreach ($segment->target->attributes() as $key => $value) {
  120. $metadata['target-attributes'][$key] = (string) $value;
  121. }
  122. }
  123. if (isset($unit->notes)) {
  124. $metadata['notes'] = [];
  125. foreach ($unit->notes->note as $noteNode) {
  126. $note = [];
  127. foreach ($noteNode->attributes() as $key => $value) {
  128. $note[$key] = (string) $value;
  129. }
  130. $note['content'] = (string) $noteNode;
  131. $metadata['notes'][] = $note;
  132. }
  133. }
  134. $catalogue->setMetadata((string) $source, $metadata, $domain);
  135. }
  136. }
  137. }
  138. /**
  139. * Convert a UTF8 string to the specified encoding.
  140. */
  141. private function utf8ToCharset(string $content, string $encoding = null): string
  142. {
  143. if ('UTF-8' !== $encoding && !empty($encoding)) {
  144. return mb_convert_encoding($content, $encoding, 'UTF-8');
  145. }
  146. return $content;
  147. }
  148. private function parseNotesMetadata(\SimpleXMLElement $noteElement = null, string $encoding = null): array
  149. {
  150. $notes = [];
  151. if (null === $noteElement) {
  152. return $notes;
  153. }
  154. /** @var \SimpleXMLElement $xmlNote */
  155. foreach ($noteElement as $xmlNote) {
  156. $noteAttributes = $xmlNote->attributes();
  157. $note = ['content' => $this->utf8ToCharset((string) $xmlNote, $encoding)];
  158. if (isset($noteAttributes['priority'])) {
  159. $note['priority'] = (int) $noteAttributes['priority'];
  160. }
  161. if (isset($noteAttributes['from'])) {
  162. $note['from'] = (string) $noteAttributes['from'];
  163. }
  164. $notes[] = $note;
  165. }
  166. return $notes;
  167. }
  168. }