TranslationWriter.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 array $dumpers = [];
  26. /**
  27. * Adds a dumper to the writer.
  28. *
  29. * @return void
  30. */
  31. public function addDumper(string $format, DumperInterface $dumper)
  32. {
  33. $this->dumpers[$format] = $dumper;
  34. }
  35. /**
  36. * Obtains the list of supported formats.
  37. */
  38. public function getFormats(): array
  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. * @return void
  49. *
  50. * @throws InvalidArgumentException
  51. */
  52. public function write(MessageCatalogue $catalogue, string $format, array $options = [])
  53. {
  54. if (!isset($this->dumpers[$format])) {
  55. throw new InvalidArgumentException(sprintf('There is no dumper associated with format "%s".', $format));
  56. }
  57. // get the right dumper
  58. $dumper = $this->dumpers[$format];
  59. if (isset($options['path']) && !is_dir($options['path']) && !@mkdir($options['path'], 0777, true) && !is_dir($options['path'])) {
  60. throw new RuntimeException(sprintf('Translation Writer was not able to create directory "%s".', $options['path']));
  61. }
  62. // save
  63. $dumper->dump($catalogue, $options);
  64. }
  65. }