| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace Symfony\Component\Translation\Loader; |
| 13 |
|
| 14 |
use Symfony\Component\Config\Resource\DirectoryResource; |
| 15 |
use Symfony\Component\Translation\Exception\InvalidResourceException; |
| 16 |
use Symfony\Component\Translation\Exception\NotFoundResourceException; |
| 17 |
use Symfony\Component\Translation\MessageCatalogue; |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
class IcuResFileLoader implements LoaderInterface |
| 25 |
{ |
| 26 |
public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue |
| 27 |
{ |
| 28 |
if (!stream_is_local($resource)) { |
| 29 |
throw new InvalidResourceException(\sprintf('This is not a local file "%s".', $resource)); |
| 30 |
} |
| 31 |
|
| 32 |
if (!is_dir($resource)) { |
| 33 |
throw new NotFoundResourceException(\sprintf('File "%s" not found.', $resource)); |
| 34 |
} |
| 35 |
|
| 36 |
try { |
| 37 |
$rb = new \ResourceBundle($locale, $resource); |
| 38 |
} catch (\Exception) { |
| 39 |
$rb = null; |
| 40 |
} |
| 41 |
|
| 42 |
if (!$rb) { |
| 43 |
throw new InvalidResourceException(\sprintf('Cannot load resource "%s".', $resource)); |
| 44 |
} elseif (intl_is_failure($rb->getErrorCode())) { |
| 45 |
throw new InvalidResourceException($rb->getErrorMessage(), $rb->getErrorCode()); |
| 46 |
} |
| 47 |
|
| 48 |
$messages = $this->flatten($rb); |
| 49 |
$catalogue = new MessageCatalogue($locale); |
| 50 |
$catalogue->add($messages, $domain); |
| 51 |
|
| 52 |
if (class_exists(DirectoryResource::class)) { |
| 53 |
$catalogue->addResource(new DirectoryResource($resource)); |
| 54 |
} |
| 55 |
|
| 56 |
return $catalogue; |
| 57 |
} |
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
protected function flatten(\ResourceBundle $rb, array &$messages = [], ?string $path = null): array |
| 74 |
{ |
| 75 |
foreach ($rb as $key => $value) { |
| 76 |
$nodePath = $path ? $path.'.'.$key : $key; |
| 77 |
if ($value instanceof \ResourceBundle) { |
| 78 |
$this->flatten($value, $messages, $nodePath); |
| 79 |
} else { |
| 80 |
$messages[$nodePath] = $value; |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
return $messages; |
| 85 |
} |
| 86 |
} |