]> git.immae.eu Git - github/wallabag/wallabag.git/blob - vendor/symfony/translation/Symfony/Component/Translation/Loader/IcuResFileLoader.php
twig implementation
[github/wallabag/wallabag.git] / vendor / symfony / translation / Symfony / Component / Translation / Loader / IcuResFileLoader.php
1 <?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
12 namespace Symfony\Component\Translation\Loader;
13
14 use Symfony\Component\Translation\MessageCatalogue;
15 use Symfony\Component\Translation\Exception\InvalidResourceException;
16 use Symfony\Component\Translation\Exception\NotFoundResourceException;
17 use Symfony\Component\Config\Resource\DirectoryResource;
18
19 /**
20 * IcuResFileLoader loads translations from a resource bundle.
21 *
22 * @author stealth35
23 */
24 class IcuResFileLoader implements LoaderInterface
25 {
26 /**
27 * {@inheritdoc}
28 */
29 public function load($resource, $locale, $domain = 'messages')
30 {
31 if (!stream_is_local($resource)) {
32 throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
33 }
34
35 if (!is_dir($resource)) {
36 throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
37 }
38
39 $rb = new \ResourceBundle($locale, $resource);
40
41 if (!$rb) {
42 throw new InvalidResourceException(sprintf('Cannot load resource "%s"', $resource));
43 } elseif (intl_is_failure($rb->getErrorCode())) {
44 throw new InvalidResourceException($rb->getErrorMessage(), $rb->getErrorCode());
45 }
46
47 $messages = $this->flatten($rb);
48 $catalogue = new MessageCatalogue($locale);
49 $catalogue->add($messages, $domain);
50 $catalogue->addResource(new DirectoryResource($resource));
51
52 return $catalogue;
53 }
54
55 /**
56 * Flattens an ResourceBundle
57 *
58 * The scheme used is:
59 * key { key2 { key3 { "value" } } }
60 * Becomes:
61 * 'key.key2.key3' => 'value'
62 *
63 * This function takes an array by reference and will modify it
64 *
65 * @param \ResourceBundle $rb the ResourceBundle that will be flattened
66 * @param array $messages used internally for recursive calls
67 * @param string $path current path being parsed, used internally for recursive calls
68 *
69 * @return array the flattened ResourceBundle
70 */
71 protected function flatten(\ResourceBundle $rb, array &$messages = array(), $path = null)
72 {
73 foreach ($rb as $key => $value) {
74 $nodePath = $path ? $path.'.'.$key : $key;
75 if ($value instanceof \ResourceBundle) {
76 $this->flatten($value, $messages, $nodePath);
77 } else {
78 $messages[$nodePath] = $value;
79 }
80 }
81
82 return $messages;
83 }
84 }