You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

232 lines
8.4 KiB

3 years ago
  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($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. $source = isset($attributes['resname']) && $attributes['resname'] ? $attributes['resname'] : $translation->source;
  93. // If the xlf file has another encoding specified, try to convert it because
  94. // simple_xml will always return utf-8 encoded values
  95. $target = $this->utf8ToCharset((string) ($translation->target ?? $translation->source), $encoding);
  96. $catalogue->set((string) $source, $target, $domain);
  97. $metadata = [
  98. 'source' => (string) $translation->source,
  99. 'file' => [
  100. 'original' => (string) $fileAttributes['original'],
  101. ],
  102. ];
  103. if ($notes = $this->parseNotesMetadata($translation->note, $encoding)) {
  104. $metadata['notes'] = $notes;
  105. }
  106. if (isset($translation->target) && $translation->target->attributes()) {
  107. $metadata['target-attributes'] = [];
  108. foreach ($translation->target->attributes() as $key => $value) {
  109. $metadata['target-attributes'][$key] = (string) $value;
  110. }
  111. }
  112. if (isset($attributes['id'])) {
  113. $metadata['id'] = (string) $attributes['id'];
  114. }
  115. $catalogue->setMetadata((string) $source, $metadata, $domain);
  116. }
  117. }
  118. }
  119. private function extractXliff2(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain)
  120. {
  121. $xml = simplexml_import_dom($dom);
  122. $encoding = $dom->encoding ? strtoupper($dom->encoding) : null;
  123. $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:2.0');
  124. foreach ($xml->xpath('//xliff:unit') as $unit) {
  125. foreach ($unit->segment as $segment) {
  126. $attributes = $unit->attributes();
  127. $source = $attributes['name'] ?? $segment->source;
  128. // If the xlf file has another encoding specified, try to convert it because
  129. // simple_xml will always return utf-8 encoded values
  130. $target = $this->utf8ToCharset((string) ($segment->target ?? $segment->source), $encoding);
  131. $catalogue->set((string) $source, $target, $domain);
  132. $metadata = [];
  133. if (isset($segment->target) && $segment->target->attributes()) {
  134. $metadata['target-attributes'] = [];
  135. foreach ($segment->target->attributes() as $key => $value) {
  136. $metadata['target-attributes'][$key] = (string) $value;
  137. }
  138. }
  139. if (isset($unit->notes)) {
  140. $metadata['notes'] = [];
  141. foreach ($unit->notes->note as $noteNode) {
  142. $note = [];
  143. foreach ($noteNode->attributes() as $key => $value) {
  144. $note[$key] = (string) $value;
  145. }
  146. $note['content'] = (string) $noteNode;
  147. $metadata['notes'][] = $note;
  148. }
  149. }
  150. $catalogue->setMetadata((string) $source, $metadata, $domain);
  151. }
  152. }
  153. }
  154. /**
  155. * Convert a UTF8 string to the specified encoding.
  156. */
  157. private function utf8ToCharset(string $content, string $encoding = null): string
  158. {
  159. if ('UTF-8' !== $encoding && !empty($encoding)) {
  160. return mb_convert_encoding($content, $encoding, 'UTF-8');
  161. }
  162. return $content;
  163. }
  164. private function parseNotesMetadata(\SimpleXMLElement $noteElement = null, string $encoding = null): array
  165. {
  166. $notes = [];
  167. if (null === $noteElement) {
  168. return $notes;
  169. }
  170. /** @var \SimpleXMLElement $xmlNote */
  171. foreach ($noteElement as $xmlNote) {
  172. $noteAttributes = $xmlNote->attributes();
  173. $note = ['content' => $this->utf8ToCharset((string) $xmlNote, $encoding)];
  174. if (isset($noteAttributes['priority'])) {
  175. $note['priority'] = (int) $noteAttributes['priority'];
  176. }
  177. if (isset($noteAttributes['from'])) {
  178. $note['from'] = (string) $noteAttributes['from'];
  179. }
  180. $notes[] = $note;
  181. }
  182. return $notes;
  183. }
  184. private function isXmlString(string $resource): bool
  185. {
  186. return 0 === strpos($resource, '<?xml');
  187. }
  188. }