QtFileLoader.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. /**
  17. * QtFileLoader loads translations from QT Translations XML files.
  18. *
  19. * @author Benjamin Eberlei <kontakt@beberlei.de>
  20. */
  21. class QtFileLoader implements LoaderInterface
  22. {
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function load($resource, $locale, $domain = 'messages')
  27. {
  28. if (!stream_is_local($resource)) {
  29. throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
  30. }
  31. if (!file_exists($resource)) {
  32. throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
  33. }
  34. try {
  35. $dom = XmlUtils::loadFile($resource);
  36. } catch (\InvalidArgumentException $e) {
  37. throw new InvalidResourceException(sprintf('Unable to load "%s".', $resource), $e->getCode(), $e);
  38. }
  39. $internalErrors = libxml_use_internal_errors(true);
  40. libxml_clear_errors();
  41. $xpath = new \DOMXPath($dom);
  42. $nodes = $xpath->evaluate('//TS/context/name[text()="'.$domain.'"]');
  43. $catalogue = new MessageCatalogue($locale);
  44. if (1 == $nodes->length) {
  45. $translations = $nodes->item(0)->nextSibling->parentNode->parentNode->getElementsByTagName('message');
  46. foreach ($translations as $translation) {
  47. $translationValue = (string) $translation->getElementsByTagName('translation')->item(0)->nodeValue;
  48. if (!empty($translationValue)) {
  49. $catalogue->set(
  50. (string) $translation->getElementsByTagName('source')->item(0)->nodeValue,
  51. $translationValue,
  52. $domain
  53. );
  54. }
  55. $translation = $translation->nextSibling;
  56. }
  57. if (class_exists('Symfony\Component\Config\Resource\FileResource')) {
  58. $catalogue->addResource(new FileResource($resource));
  59. }
  60. }
  61. libxml_use_internal_errors($internalErrors);
  62. return $catalogue;
  63. }
  64. }