You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.1 KiB

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