TranslationWriter.php 2.1 KB

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