TranslationWriter.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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\Writer;
  11. use Symfony\Component\Translation\MessageCatalogue;
  12. use Symfony\Component\Translation\Dumper\DumperInterface;
  13. use Symfony\Component\Translation\Exception\InvalidArgumentException;
  14. use Symfony\Component\Translation\Exception\RuntimeException;
  15. /**
  16. * TranslationWriter writes translation messages.
  17. *
  18. * @author Michel Salib <michelsalib@hotmail.com>
  19. */
  20. class TranslationWriter
  21. {
  22. /**
  23. * Dumpers used for export.
  24. *
  25. * @var array
  26. */
  27. private $dumpers = array();
  28. /**
  29. * Adds a dumper to the writer.
  30. *
  31. * @param string $format The format of the dumper
  32. * @param DumperInterface $dumper The dumper
  33. */
  34. public function addDumper($format, DumperInterface $dumper)
  35. {
  36. $this->dumpers[$format] = $dumper;
  37. }
  38. /**
  39. * Disables dumper backup.
  40. */
  41. public function disableBackup()
  42. {
  43. foreach ($this->dumpers as $dumper) {
  44. if (method_exists($dumper, 'setBackup')) {
  45. $dumper->setBackup(false);
  46. }
  47. }
  48. }
  49. /**
  50. * Obtains the list of supported formats.
  51. *
  52. * @return array
  53. */
  54. public function getFormats()
  55. {
  56. return array_keys($this->dumpers);
  57. }
  58. /**
  59. * Writes translation from the catalogue according to the selected format.
  60. *
  61. * @param MessageCatalogue $catalogue The message catalogue to dump
  62. * @param string $format The format to use to dump the messages
  63. * @param array $options Options that are passed to the dumper
  64. *
  65. * @throws InvalidArgumentException
  66. */
  67. public function writeTranslations(MessageCatalogue $catalogue, $format, $options = array())
  68. {
  69. if (!isset($this->dumpers[$format])) {
  70. throw new InvalidArgumentException(sprintf('There is no dumper associated with format "%s".', $format));
  71. }
  72. // get the right dumper
  73. $dumper = $this->dumpers[$format];
  74. if (isset($options['path']) && !is_dir($options['path']) && !@mkdir($options['path'], 0777, true) && !is_dir($options['path'])) {
  75. throw new RuntimeException(sprintf('Translation Writer was not able to create directory "%s"', $options['path']));
  76. }
  77. // save
  78. $dumper->dump($catalogue, $options);
  79. }
  80. }