-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathMessageLoader.php
More file actions
209 lines (181 loc) · 6.41 KB
/
MessageLoader.php
File metadata and controls
209 lines (181 loc) · 6.41 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
<?php
/**
* This file is part of skillshare/formatphp
*
* skillshare/formatphp is open source software: you can distribute
* it and/or modify it under the terms of the MIT License
* (the "License"). You may not use this file except in
* compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* @copyright Copyright (c) Skillshare, Inc. <https://www.skillshare.com>
* @license https://opensource.org/licenses/MIT MIT License
*/
declare(strict_types=1);
namespace FormatPHP;
use FormatPHP\Exception\ImproperContextException;
use FormatPHP\Exception\InvalidArgumentException;
use FormatPHP\Exception\InvalidMessageShapeException;
use FormatPHP\Exception\LocaleNotFoundException;
use FormatPHP\Exception\UnableToProcessFileException;
use FormatPHP\Format\Reader\FormatPHPReader;
use FormatPHP\Format\ReaderInterface;
use FormatPHP\Util\FileSystemHelper;
use FormatPHP\Util\FormatHelper;
use function array_filter;
use function array_unique;
use function array_values;
use function file_exists;
use function implode;
use function is_callable;
use function scandir;
use function sprintf;
use function str_replace;
use function strtolower;
use const DIRECTORY_SEPARATOR;
use const SCANDIR_SORT_NONE;
/**
* Loads messages for a given locale from the file system or cache
*
* @psalm-import-type ReaderType from ReaderInterface
*/
class MessageLoader
{
private const MESSAGE_FILE_EXTENSION = '.json';
private ConfigInterface $config;
private FileSystemHelper $fileSystemHelper;
private FormatHelper $formatHelper;
private string $messagesDirectory;
/**
* @var ReaderType
*/
private $formatReader;
/**
* @param ReaderType | string | null $formatReader
*
* @throws InvalidArgumentException
* @throws ImproperContextException
*/
public function __construct(
string $messagesDirectory,
ConfigInterface $config,
$formatReader = null,
?FileSystemHelper $fileSystemHelper = null,
?FormatHelper $formatHelper = null
) {
$this->config = $config;
$this->fileSystemHelper = $fileSystemHelper ?? new FileSystemHelper();
$this->formatHelper = $formatHelper ?? new FormatHelper($this->fileSystemHelper);
$this->messagesDirectory = $this->fileSystemHelper->getRealPath($messagesDirectory);
$this->formatReader = $this->loadFormatReader($formatReader);
if (!$this->fileSystemHelper->isDirectory($this->messagesDirectory)) {
throw new InvalidArgumentException(sprintf(
'Messages directory "%s" is not a valid directory',
$messagesDirectory,
));
}
}
/**
* Returns a MessageCollection according to the configuration provided to
* this MessageLoader
*
* @throws InvalidMessageShapeException
* @throws LocaleNotFoundException
*/
public function loadMessages(): MessageCollection
{
return ($this->formatReader)($this->getLocaleMessages());
}
/**
* @return array<array-key, mixed>
*
* @throws LocaleNotFoundException
*/
private function getLocaleMessages(): array
{
$messagesContents = false;
foreach ($this->getFallbackLocales() as $locale) {
try {
$messagesContents = $this->fileSystemHelper->getJsonContents(
$this->getFilePathForLocale($locale),
);
break;
} catch (UnableToProcessFileException $exception) {
continue;
}
}
if ($messagesContents === false) {
throw new LocaleNotFoundException(sprintf(
'Unable to find a suitable locale for "%s" in %s; please set a default locale',
$this->config->getLocale()->toString(),
$this->messagesDirectory,
));
}
return $messagesContents;
}
/**
* @return string[]
*/
private function getFallbackLocales(): array
{
$locale = $this->config->getLocale();
$defaultLocale = $this->config->getDefaultLocale();
$fallbacks = [
$locale->toString(),
$locale->baseName(),
implode('-', array_filter([$locale->language(), $locale->region()])),
$locale->language(),
$defaultLocale ? $defaultLocale->toString() : null,
];
/** @var string[] */
return array_values(array_unique(array_filter($fallbacks)));
}
/**
* @param ReaderType | string | null $formatReader
*
* @return ReaderType
*
* @throws ImproperContextException
* @throws InvalidArgumentException
*/
private function loadFormatReader($formatReader): callable
{
if ($formatReader === null) {
return new FormatPHPReader();
}
if ($formatReader instanceof ReaderInterface) {
return $formatReader;
}
if (is_callable($formatReader)) {
return $this->formatHelper->validateReaderCallable($formatReader);
}
return $this->formatHelper->getReader($formatReader);
}
private function getFilePathForLocale(string $locale): string
{
$filePath = $this->messagesDirectory . DIRECTORY_SEPARATOR . $locale . self::MESSAGE_FILE_EXTENSION;
if (file_exists($filePath)) {
return $filePath;
}
// If the file doesn't exist, check for alternate casings and notations.
// e.g., en-XB, en_XB, en-xb, en_xb, EN-XB, EN_XB, eN-xB, etc.
$normalize = fn (string $filename): string => str_replace('_', '-', strtolower($filename));
$searchFile = $normalize($locale . self::MESSAGE_FILE_EXTENSION);
$localeFiles = scandir($this->messagesDirectory, SCANDIR_SORT_NONE) ?: [];
foreach ($localeFiles as $localeFile) {
if ($normalize($localeFile) === $searchFile) {
return $this->messagesDirectory . DIRECTORY_SEPARATOR . $localeFile;
}
}
throw new UnableToProcessFileException(sprintf(
'Could not find file for locale "%s" in %s',
$locale,
$this->messagesDirectory,
));
}
}