TranslationWriter.php 2.6 KB

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