TranslationWriter.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. /**
  23. * @var array<string, DumperInterface>
  24. */
  25. private $dumpers = [];
  26. /**
  27. * Adds a dumper to the writer.
  28. */
  29. public function addDumper(string $format, DumperInterface $dumper)
  30. {
  31. $this->dumpers[$format] = $dumper;
  32. }
  33. /**
  34. * Obtains the list of supported formats.
  35. *
  36. * @return array
  37. */
  38. public function getFormats()
  39. {
  40. return array_keys($this->dumpers);
  41. }
  42. /**
  43. * Writes translation from the catalogue according to the selected format.
  44. *
  45. * @param string $format The format to use to dump the messages
  46. * @param array $options Options that are passed to the dumper
  47. *
  48. * @throws InvalidArgumentException
  49. */
  50. public function write(MessageCatalogue $catalogue, string $format, array $options = [])
  51. {
  52. if (!isset($this->dumpers[$format])) {
  53. throw new InvalidArgumentException(sprintf('There is no dumper associated with format "%s".', $format));
  54. }
  55. // get the right dumper
  56. $dumper = $this->dumpers[$format];
  57. if (isset($options['path']) && !is_dir($options['path']) && !@mkdir($options['path'], 0777, true) && !is_dir($options['path'])) {
  58. throw new RuntimeException(sprintf('Translation Writer was not able to create directory "%s".', $options['path']));
  59. }
  60. // save
  61. $dumper->dump($catalogue, $options);
  62. }
  63. }