forked from php-translation/symfony-bundle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CatalogueFetcher.php
83 lines (70 loc) · 2.44 KB
/
CatalogueFetcher.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
/*
* This file is part of the PHP Translation package.
*
* (c) PHP Translation team <tobias.nyholm@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Translation\Bundle\Catalogue;
use Nyholm\NSA;
use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\Reader\TranslationReaderInterface;
use Translation\Bundle\Model\Configuration;
/**
* Fetches catalogues from source files. This will only work with local file storage
* and the actions are read only.
*
* This should be considered as a "ReadFromCache" service.
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
final class CatalogueFetcher
{
private $reader;
public function __construct(TranslationReaderInterface $reader)
{
$this->reader = $reader;
}
/**
* load any existing messages from the translation files.
*/
public function getCatalogues(Configuration $config, array $locales = []): array
{
$dirs = $config->getPathsToTranslationFiles();
if (empty($locales)) {
$locales = $config->getLocales();
}
$catalogues = [];
foreach ($locales as $locale) {
$currentCatalogue = new MessageCatalogue($locale);
foreach ($dirs as $path) {
if (is_dir($path)) {
$this->reader->read($path, $currentCatalogue);
}
}
foreach ($currentCatalogue->getDomains() as $domain) {
if (!$this->isValidDomain($config, $domain)) {
$messages = NSA::getProperty($currentCatalogue, 'messages');
unset($messages[$domain], $messages[$domain . '+intl-icu' /* MessageCatalogueInterface::INTL_DOMAIN_SUFFIX */]);
NSA::setProperty($currentCatalogue, 'messages', $messages);
}
}
$catalogues[] = $currentCatalogue;
}
return $catalogues;
}
private function isValidDomain(Configuration $config, string $domain): bool
{
$blacklist = $config->getBlacklistDomains();
$whitelist = $config->getWhitelistDomains();
if (!empty($blacklist) && \in_array($domain, $blacklist, true)) {
return false;
}
if (!empty($whitelist) && !\in_array($domain, $whitelist, true)) {
return false;
}
return true;
}
}