-
Notifications
You must be signed in to change notification settings - Fork 168
/
Copy pathManager.php
391 lines (329 loc) · 11 KB
/
Manager.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
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
<?php
namespace Themsaid\Langman;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
class Manager
{
/**
* The Filesystem instance.
*
* @var Filesystem
*/
private $disk;
/**
* The path to the language files.
*
* @var string
*/
private $path;
/**
* The paths to directories where we look for localised strings to sync.
*
* @var array
*/
private $syncPaths;
/**
* Manager constructor.
*
* @param Filesystem $disk
* @param string $path
*/
public function __construct(Filesystem $disk, $path, array $syncPaths)
{
$this->disk = $disk;
$this->path = $path;
$this->syncPaths = $syncPaths;
}
/**
* Array of language files grouped by file name.
*
* ex: ['user' => ['en' => 'user.php', 'nl' => 'user.php']]
*
* @return array
*/
public function files()
{
$files = Collection::make($this->disk->allFiles($this->path))->filter(function ($file) {
return $this->disk->extension($file) == 'php';
});
$filesByFile = $files->groupBy(function ($file) {
$fileName = $file->getBasename('.'.$file->getExtension());
if (Str::contains($file->getPath(), 'vendor')) {
$fileName = str_replace('.php', '', $file->getFileName());
$packageName = basename(dirname($file->getPath()));
return "{$packageName}::{$fileName}";
} else {
return $fileName;
}
})->map(function ($files) {
return $files->keyBy(function ($file) {
return basename($file->getPath());
})->map(function ($file) {
return $file->getRealPath();
});
});
// If the path does not contain "vendor" then we're looking at the
// main language files of the application, in this case we will
// neglect all vendor files.
if (! Str::contains($this->path, 'vendor')) {
$filesByFile = $this->neglectVendorFiles($filesByFile);
}
return $filesByFile;
}
/**
* Nelgect all vendor files.
*
* @param $filesByFile Collection
* @return array
*/
private function neglectVendorFiles($filesByFile)
{
$return = [];
foreach ($filesByFile->toArray() as $key => $value) {
if (! Str::contains($key, ':')) {
$return[$key] = $value;
}
}
return $return;
}
/**
* Array of supported languages.
*
* ex: ['en', 'sp']
*
* @return array
*/
public function languages()
{
$languages = array_map(function ($directory) {
return basename($directory);
}, $this->disk->directories($this->path));
$languages = array_filter($languages, function ($directory) {
return $directory != 'vendor' && $directory != 'json';
});
sort($languages);
return Arr::except($languages, ['vendor', 'json']);
}
/**
* Create a file for all languages if does not exist already.
*
* @param $fileName
* @return void
*/
public function createFile($fileName)
{
foreach ($this->languages() as $languageKey) {
$file = $this->path."/{$languageKey}/{$fileName}.php";
if (! $this->disk->exists($file)) {
file_put_contents($file, "<?php \n\n return[];");
}
}
}
/**
* Fills translation lines for given keys in different languages.
*
* ex. for $keys = ['name' => ['en' => 'name', 'nl' => 'naam']
*
* @param string $fileName
* @param array $keys
* @return void
*/
public function fillKeys($fileName, array $keys)
{
$appends = [];
foreach ($keys as $key => $values) {
foreach ($values as $languageKey => $value) {
$filePath = $this->path."/{$languageKey}/{$fileName}.php";
Arr::set($appends[$filePath], $key, $value);
}
}
foreach ($appends as $filePath => $values) {
$fileContent = $this->getFileContent($filePath, true);
$newContent = array_replace_recursive($fileContent, $values);
$this->writeFile($filePath, $newContent);
}
}
/**
* Remove a key from all language files.
*
* @param string $fileName
* @param string $key
* @return void
*/
public function removeKey($fileName, $key)
{
foreach ($this->languages() as $language) {
$filePath = $this->path."/{$language}/{$fileName}.php";
$fileContent = $this->getFileContent($filePath);
Arr::forget($fileContent, $key);
$this->writeFile($filePath, $fileContent);
}
}
/**
* Write a language file from array.
*
* @param string $filePath
* @param array $translations
* @return void
*/
public function writeFile($filePath, array $translations)
{
$content = "<?php\n\nreturn [";
$content .= $this->stringLineMaker($translations);
$content .= "\n];\n";
file_put_contents($filePath, $content);
}
/**
* Write the lines of the inner array of the language file.
*
* @param $array
* @return string
*/
private function stringLineMaker($array, $prepend = '')
{
$output = '';
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = $this->stringLineMaker($value, $prepend.' ');
$output .= "\n{$prepend} '{$key}' => [{$value}\n{$prepend} ],";
} else {
$value = str_replace('\"', '"', addslashes($value));
$output .= "\n{$prepend} '{$key}' => '{$value}',";
}
}
return $output;
}
/**
* Get the content in the given file path.
*
* @param string $filePath
* @param bool $createIfNotExists
* @return array
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
public function getFileContent($filePath, $createIfNotExists = false)
{
if ($createIfNotExists && ! $this->disk->exists($filePath)) {
if (! $this->disk->exists($directory = dirname($filePath))) {
mkdir($directory, 0777, true);
}
file_put_contents($filePath, "<?php\n\nreturn [];");
return [];
}
try {
return (array) include $filePath;
} catch (\ErrorException $e) {
throw new FileNotFoundException('File not found: '.$filePath);
}
}
/**
* Collect all translation keys from views files.
*
* e.g. ['users' => ['city', 'name', 'phone']]
*
* @return array
*/
public function collectFromFiles()
{
$translationKeys = [];
foreach ($this->getAllViewFilesWithTranslations() as $file => $matches) {
foreach ($matches as $key) {
try {
list($fileName, $keyName) = explode('.', $key, 2);
} catch (\ErrorException $e) {
continue;
}
if (isset($translationKeys[$fileName]) && in_array($keyName, $translationKeys[$fileName])) {
continue;
}
$translationKeys[$fileName][] = $keyName;
}
}
return $translationKeys;
}
/**
* Get found translation lines found per file.
*
* e.g. ['users.blade.php' => ['users.name'], 'users/index.blade.php' => ['users.phone', 'users.city']]
*
* @return array
*/
public function getAllViewFilesWithTranslations()
{
/*
* This pattern is derived from Barryvdh\TranslationManager by Barry vd. Heuvel <[email protected]>
*
* https://github.com/barryvdh/laravel-translation-manager/blob/master/src/Manager.php
*/
$functions = ['__', 'trans', 'trans_choice', 'Lang::get', 'Lang::choice', 'Lang::trans', 'Lang::transChoice', '@lang', '@choice'];
$pattern =
// See https://regex101.com/r/jS5fX0/4
'[^\w]'. // Must not start with any alphanum or _
'(?<!->)'. // Must not start with ->
'('.implode('|', $functions).')'.// Must start with one of the functions
"\(".// Match opening parentheses
"[\'\"]".// Match " or '
'('.// Start a new group to match:
'[a-zA-Z0-9_-]+'.// Must start with group
"([.][^\1)$]+)+".// Be followed by one or more items/keys
')'.// Close group
"[\'\"]".// Closing quote
"[\),]" // Close parentheses or new parameter
;
$allMatches = [];
/** @var \Symfony\Component\Finder\SplFileInfo $file */
foreach ($this->disk->allFiles($this->syncPaths) as $file) {
if (preg_match_all("/$pattern/siU", $file->getContents(), $matches)) {
$allMatches[$file->getRelativePathname()] = $matches[2];
}
}
return $allMatches;
}
/**
* Sets the path to a vendor package translation files.
*
* @param string $packageName
* @return void
*/
public function setPathToVendorPackage($packageName)
{
$this->path = $this->path.'/vendor/'.$packageName;
}
/**
* Extract keys that exists in a language but not the other.
*
* Given a dot array of all keys in the format 'file.language.key', this
* method searches for keys that exist in one language but not the
* other and outputs an array consists of those keys.
*
* @param $values
* @return array
*/
public function getKeysExistingInALanguageButNotTheOther($values)
{
$missing = [];
// Array of keys indexed by fileName.key, those are the keys we looked
// at before so we save them in order for us to not look at them
// again in a different language iteration.
$searched = [];
// Now we add keys that exist in a language but missing in any of the
// other languages. Those keys combined with ones with values = ''
// will be sent to the console user to fill and save in disk.
foreach ($values as $key => $value) {
list($fileName, $languageKey, $key) = explode('.', $key, 3);
if (in_array("{$fileName}.{$key}", $searched)) {
continue;
}
foreach ($this->languages() as $languageName) {
if (! Arr::has($values, "{$fileName}.{$languageName}.{$key}") && ! array_key_exists("{$fileName}.{$languageName}.{$key}", $values)) {
$missing[] = "{$fileName}.{$key}:{$languageName}";
}
}
$searched[] = "{$fileName}.{$key}";
}
return $missing;
}
}