blob: 5dd3a5c401d0eefc4ecedd840c09c7799814b263 [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{
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010026 /**
27 * @var array<string, DumperInterface>
28 */
29 private array $dumpers = [];
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +020030
31 /**
32 * Adds a dumper to the writer.
33 */
34 public function addDumper(string $format, DumperInterface $dumper)
35 {
36 $this->dumpers[$format] = $dumper;
37 }
38
39 /**
40 * Obtains the list of supported formats.
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +020041 */
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010042 public function getFormats(): array
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +020043 {
44 return array_keys($this->dumpers);
45 }
46
47 /**
48 * Writes translation from the catalogue according to the selected format.
49 *
50 * @param string $format The format to use to dump the messages
51 * @param array $options Options that are passed to the dumper
52 *
53 * @throws InvalidArgumentException
54 */
55 public function write(MessageCatalogue $catalogue, string $format, array $options = [])
56 {
57 if (!isset($this->dumpers[$format])) {
58 throw new InvalidArgumentException(sprintf('There is no dumper associated with format "%s".', $format));
59 }
60
61 // get the right dumper
62 $dumper = $this->dumpers[$format];
63
64 if (isset($options['path']) && !is_dir($options['path']) && !@mkdir($options['path'], 0777, true) && !is_dir($options['path'])) {
65 throw new RuntimeException(sprintf('Translation Writer was not able to create directory "%s".', $options['path']));
66 }
67
68 // save
69 $dumper->dump($catalogue, $options);
70 }
71}