blob: 35de9ef547e69925c942e3b3df8bc6fdaf09392c [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\Loader;
13
14use Symfony\Component\Translation\MessageCatalogue;
15
16/**
17 * ArrayLoader loads translations from a PHP array.
18 *
19 * @author Fabien Potencier <fabien@symfony.com>
20 */
21class ArrayLoader implements LoaderInterface
22{
23 /**
24 * {@inheritdoc}
25 */
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010026 public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +020027 {
28 $resource = $this->flatten($resource);
29 $catalogue = new MessageCatalogue($locale);
30 $catalogue->add($resource, $domain);
31
32 return $catalogue;
33 }
34
35 /**
36 * Flattens an nested array of translations.
37 *
38 * The scheme used is:
39 * 'key' => ['key2' => ['key3' => 'value']]
40 * Becomes:
41 * 'key.key2.key3' => 'value'
42 */
43 private function flatten(array $messages): array
44 {
45 $result = [];
46 foreach ($messages as $key => $value) {
47 if (\is_array($value)) {
48 foreach ($this->flatten($value) as $k => $v) {
49 $result[$key.'.'.$k] = $v;
50 }
51 } else {
52 $result[$key] = $value;
53 }
54 }
55
56 return $result;
57 }
58}