blob: 9cf2fe976037186eee858e2e2d3e6745314143c4 [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\Translation\Loader;
13
14use Symfony\Component\Config\Resource\FileResource;
15use Symfony\Component\Config\Util\XmlUtils;
16use Symfony\Component\Translation\Exception\InvalidResourceException;
17use Symfony\Component\Translation\Exception\NotFoundResourceException;
18use Symfony\Component\Translation\Exception\RuntimeException;
19use Symfony\Component\Translation\MessageCatalogue;
20
21/**
22 * QtFileLoader loads translations from QT Translations XML files.
23 *
24 * @author Benjamin Eberlei <kontakt@beberlei.de>
25 */
26class QtFileLoader implements LoaderInterface
27{
28 /**
29 * {@inheritdoc}
30 */
31 public function load($resource, string $locale, string $domain = 'messages')
32 {
33 if (!class_exists(XmlUtils::class)) {
34 throw new RuntimeException('Loading translations from the QT format requires the Symfony Config component.');
35 }
36
37 if (!stream_is_local($resource)) {
38 throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
39 }
40
41 if (!file_exists($resource)) {
42 throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
43 }
44
45 try {
46 $dom = XmlUtils::loadFile($resource);
47 } catch (\InvalidArgumentException $e) {
48 throw new InvalidResourceException(sprintf('Unable to load "%s".', $resource), $e->getCode(), $e);
49 }
50
51 $internalErrors = libxml_use_internal_errors(true);
52 libxml_clear_errors();
53
54 $xpath = new \DOMXPath($dom);
55 $nodes = $xpath->evaluate('//TS/context/name[text()="'.$domain.'"]');
56
57 $catalogue = new MessageCatalogue($locale);
58 if (1 == $nodes->length) {
59 $translations = $nodes->item(0)->nextSibling->parentNode->parentNode->getElementsByTagName('message');
60 foreach ($translations as $translation) {
61 $translationValue = (string) $translation->getElementsByTagName('translation')->item(0)->nodeValue;
62
63 if (!empty($translationValue)) {
64 $catalogue->set(
65 (string) $translation->getElementsByTagName('source')->item(0)->nodeValue,
66 $translationValue,
67 $domain
68 );
69 }
70 $translation = $translation->nextSibling;
71 }
72
73 if (class_exists(FileResource::class)) {
74 $catalogue->addResource(new FileResource($resource));
75 }
76 }
77
78 libxml_use_internal_errors($internalErrors);
79
80 return $catalogue;
81 }
82}