TranslationWriter.php 2.3 KB

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