blob: 0a349b824689f620f99932bda0e57803b253f75d [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\Translation\Writer;
13
14use Symfony\Component\Translation\Dumper\DumperInterface;
15use Symfony\Component\Translation\Exception\InvalidArgumentException;
16use Symfony\Component\Translation\Exception\RuntimeException;
17use Symfony\Component\Translation\MessageCatalogue;
18
19/**
20 * TranslationWriter writes translation messages.
21 *
22 * @author Michel Salib <michelsalib@hotmail.com>
23 */
24class TranslationWriter implements TranslationWriterInterface
25{
26 private $dumpers = [];
27
28 /**
29 * Adds a dumper to the writer.
30 */
31 public function addDumper(string $format, DumperInterface $dumper)
32 {
33 $this->dumpers[$format] = $dumper;
34 }
35
36 /**
37 * Obtains the list of supported formats.
38 *
39 * @return array
40 */
41 public function getFormats()
42 {
43 return array_keys($this->dumpers);
44 }
45
46 /**
47 * Writes translation from the catalogue according to the selected format.
48 *
49 * @param string $format The format to use to dump the messages
50 * @param array $options Options that are passed to the dumper
51 *
52 * @throws InvalidArgumentException
53 */
54 public function write(MessageCatalogue $catalogue, string $format, array $options = [])
55 {
56 if (!isset($this->dumpers[$format])) {
57 throw new InvalidArgumentException(sprintf('There is no dumper associated with format "%s".', $format));
58 }
59
60 // get the right dumper
61 $dumper = $this->dumpers[$format];
62
63 if (isset($options['path']) && !is_dir($options['path']) && !@mkdir($options['path'], 0777, true) && !is_dir($options['path'])) {
64 throw new RuntimeException(sprintf('Translation Writer was not able to create directory "%s".', $options['path']));
65 }
66
67 // save
68 $dumper->dump($catalogue, $options);
69 }
70}