-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTranslationParserScript.php
564 lines (492 loc) · 15.6 KB
/
TranslationParserScript.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
<?php
namespace Charcoal\Translator\Script;
// From Pimple
use Pimple\Container;
// From PSR-7
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
// From `charcoal-admin`
use Charcoal\Admin\AdminScript;
// From `charcoal-translator`
use Charcoal\Translator\TranslatorAwareTrait;
/**
* Find all strings to be translated in templates
*/
class TranslationParserScript extends AdminScript
{
use TranslatorAwareTrait;
/**
* @var AppConfig
*/
private $appConfig;
/**
* @var string
*/
protected $fileType;
/**
* Output File.
*
* @var string
*/
protected $output;
/**
* Paths to search.
*
* @var array
*/
protected $paths;
/**
* Path to translations.
*
* @var string
*/
protected $path;
/**
* Path for the CSV file to store.
*
* Noe: Full path with base path.
*
* @var string
*/
protected $filePath;
/**
* @var array
*/
protected $locales;
/**
* @param Container $container Pimple DI container.
* @return void
*/
public function setDependencies(Container $container)
{
$this->appConfig = $container['config'];
$this->setTranslator($container['translator']);
parent::setDependencies($container);
}
/**
* Arguments that can be use in the script.
* If no path is provided, all views path are parsed.
* If you do precise a path, notice that you will loose
* all modified translations that comes from other paths.
*
* Valid arguments:
* - output : path-to-csv/
* - domain : filename prefix
* - recursive : level of recursiveness (how deep the glob checks for the strings)
* - path : Path to get translation from a precise location (i.e: templates/emails/)
* - type : file type (either mustache or php)
*
* @todo Support php file type.
* @return array
*/
public function defaultArguments()
{
$arguments = [
'output' => [
'prefix' => 'o',
'longPrefix' => 'output',
'description' => 'Output file path. Make sure the path exists in the translator paths definition. (Default: translation/)',
'defaultValue' => 'translations/'
],
'domain' => [
'prefix' => 'd',
'longPrefix' => 'domain',
'description' => 'Doman for the csv file. Based on symfony/translator CsvLoader.',
'defaultValue' => 'messages'
],
'recursive' => [
'prefix' => 'r',
'longPrefix' => 'recursive-level',
'description' => 'Max recursive level for the glob operation on folders.',
'defaultValue' => 4
],
'path' => [
'longPrefix' => 'path',
'prefix' => 'p',
'description' => 'Path relative to the project installation (ex: templates/*/*/)',
'defaultValue' => false
],
'type' => [
'longPrefix' => 'type',
'prefix' => 't',
'description' => 'File type (mustache || php)',
'defaultValue' => 'mustache'
],
'php_function' => [
'longPrefix' => 'php',
'description' => 'Php function to be parsed.',
'defaultValue' => 'translate'
],
'mustache_tag' => [
'longPrefix' => 'mustache',
'description' => 'Mustache function to be parsed.',
'defaultValue' => '_t'
]
];
$arguments = array_merge(parent::defaultArguments(), $arguments);
return $arguments;
}
/**
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
* @return ResponseInterface
*/
public function run(RequestInterface $request, ResponseInterface $response)
{
// Unused
unset($request);
// Parse arguments
$this->displayInformations();
// Get translations
$translations = $this->parseTranslations($this->getTranslations());
// Output to CSV file.
$this->toCSV($translations);
// Warn the user
$base = $this->appConfig->get('base_path');
$output = $this->output();
$filePath = str_replace('/', DIRECTORY_SEPARATOR, $base.$output);
$this->climate()->backgroundGreen()->out(
'Make sure to include <light_green>'.$filePath.'</light_green> in your <light_green>translator/paths</light_green> configurations.'
);
return $response;
}
/**
* @param array $trans The translations array.
* @return array
*/
protected function parseTranslations(array $trans)
{
// Must be the first occurrence of the the key.
foreach ($trans as $lang => &$value) {
array_walk($value, function (&$val, $key) {
// remove key template ident in translation value.
if (preg_match('|^\[([^\]]*)\]|', $key, $translationContext)) {
$val = str_replace($translationContext[0], '', $val);
}
// remove key input type from translation value.
if (preg_match('|:(?:\S*)$|', $key, $translationInputType)) {
$val = str_replace($translationInputType[0], '', $val);
}
});
}
return $trans;
}
/**
* Give feedback about what's going on.
* @return self Chainable.
*/
protected function displayInformations()
{
$this->climate()->underline()->out(
'Initializing translations parser script...'
);
$this->climate()->green()->out(
'CSV file output: <white>'.$this->filePath().'</white>'
);
$this->climate()->green()->out(
'CSV file names: <white>'.$this->domain().'.{locale}.csv</white>'
);
$this->climate()->green()->out(
'Looping through <white>'.$this->maxRecursiveLevel().'</white> level of folders'
);
$this->climate()->green()->out(
'File type parsed: <white>mustache</white>'
);
return $this;
}
/**
* Complete filepath to the CSV location.
* @return string Filepath to the csv.
*/
protected function filePath()
{
if ($this->filePath) {
return $this->filePath;
}
$base = $this->appConfig->get('base_path');
$output = $this->output();
$this->filePath = str_replace('/', DIRECTORY_SEPARATOR, $base.$output);
return $this->filePath;
}
/**
* Available locales (languages)
* @return array Locales.
*/
protected function locales()
{
return $this->translator()->availableLocales();
}
/**
* @return string Current locale.
*/
protected function locale()
{
return $this->translator()->getLocale();
}
/**
* @return string
*/
public function output()
{
if ($this->output) {
return $this->output;
}
$output = $this->argOrInput('output');
$this->output = $output;
return $this->output;
}
/**
* Domain which is the csv file name prefix
* @return string domain.
*/
public function domain()
{
return $this->argOrInput('domain');
}
/**
* Regex to match in files.
*
* @param string $type File type (mustache|php).
* @return string Regex string.
*/
public function regEx($type)
{
switch ($type) {
case 'php':
$f = $this->phpFunction();
$regex = '/->'.$f.'\(\s*\n*\r*(["\'])(?<text>(.|\n|\r|\n\r)*?)\s*\n*\r*\1\)/i';
break;
case 'mustache':
$tag = $this->mustacheTag();
$regex = '/({{|\[\[)\s*#\s*'.$tag.'\s*(}}|\]\])(?<text>(.|\n|\r|\n\r)*?)({{|\[\[)\s*\/\s*'.$tag.'\s*(}}|\]\])/i';
break;
default:
$regex = '/({{|\[\[)\s*#\s*_t\s*(}}|\]\])(?<text>(.|\n|\r|\n\r)*?)({{|\[\[)\s*\/\s*_t\s*(}}|\]\])/i';
break;
}
return $regex;
}
/**
* Loop through all paths to get translations.
* Also merge with already existing translations.
* Translations associated with the locale.
* [
* 'fr' => [
* 'string' => 'translation',
* 'string' => 'translation',
* 'string' => 'translation',
* 'string' => 'translation'
* ],
* 'en' => [
* 'string' => 'translation',
* 'string' => 'translation',
* 'string' => 'translation',
* 'string' => 'translation'
* ]
* ]
* @return array Translations.
*/
public function getTranslations()
{
$path = $this->path();
if ($path) {
$this->climate()->green()->out('Parsing files in <white>'.$path.'</white>');
$translations = $this->getTranslationsFromPath($path, 'mustache');
$translations = array_replace($translations, $this->getTranslationsFromPath($path, 'php'));
return $translations;
}
$paths = $this->paths();
$translations = [];
foreach ($paths as $p) {
$this->climate()->green()->out('Parsing files in <white>'.$p.'</white>');
$translations = array_replace_recursive($translations, $this->getTranslationsFromPath($p, 'mustache'));
$translations = array_replace_recursive($translations, $this->getTranslationsFromPath($p, 'php'));
}
return $translations;
}
/**
* Get all translations in given path for the given file extension (mustache | php).
* @param string $path The path.
* @param string $fileType The file extension|type.
* @return array Translations.
*/
public function getTranslationsFromPath($path, $fileType)
{
// remove vendor/locomotivemtl/charcoal-app
$base = $this->appConfig->get('base_path');
$glob = $this->globRecursive($base.$path.'*.'.$fileType);
$regex = $this->regEx($fileType);
$translations = [];
// Array index for the preg_match.
$index = 'text';
// if ($fileType == 'php') {
// $index = 'text';
// }
$k = 0;
$this->climate()->inline('.');
// Loop files to get original text.
foreach ($glob as $k => $file) {
$k++;
$this->climate()->inline('.');
$text = file_get_contents($file);
if (preg_match($regex, $text)) {
preg_match_all($regex, $text, $array);
$i = 0;
$t = count($array[$index]);
$locales = $this->locales();
for (; $i < $t; $i++) {
$this->climate()->inline('.');
$orig = $array[$index][$i];
foreach ($locales as $lang) {
$this->climate()->inline('.');
$this->translator()->setLocale($lang);
// By calling translate, we make sure all existings translations are taking into consideration.
$translations[$lang][$orig] = stripslashes($this->translator()->translate($orig));
}
}
}
}
$this->climate()->out('.');
$this->climate()->green()->out('Translations parsed from '.$path);
return $translations;
}
/**
* @todo Added support for max depth.
* @param string $pattern The pattern to search.
* @param integer $flags The glob flags.
* @return array
* @see http://in.php.net/manual/en/function.glob.php#106595
*/
public function globRecursive($pattern, $flags = 0)
{
// $max = $this->maxRecursiveLevel();
$i = 1;
$files = glob($pattern, $flags);
foreach (glob(dirname($pattern).'/*', (GLOB_ONLYDIR | GLOB_NOSORT)) as $dir) {
$files = array_merge($files, $this->globRecursive($dir.'/'.basename($pattern), $flags));
$i++;
// if ($i >= $max) {
// break;
// }
}
return $files;
}
/**
* Custom path
* @return string
*/
public function path()
{
if ($this->climate()->arguments->defined('path')) {
$this->path = $this->climate()->arguments->get('path');
}
return $this->path;
}
/**
* @return string
*/
public function paths()
{
if (!$this->paths) {
$this->paths = $this->appConfig->get('translator.parser.view.paths') ?:
$this->appConfig->get('view.paths');
/** @todo Hardcoded; Change this! */
$this->paths[] = 'src/';
}
return $this->paths;
}
/**
* @return string
*/
public function fileTypes()
{
if (!$this->fileTypes) {
$this->fileTypes = [
'php',
'mustache'
];
}
return $this->fileTypes;
}
/**
* @param array $translations The translations to save in CSV.
* @return TranslateScript Chainable
*/
public function toCSV(array $translations)
{
if (!count($translations)) {
$this->climate()->error('
There was no translations in the provided path ('.$this->path().')
with the given recursive level ('.$this->maxRecursiveLevel().')
');
return $this;
}
$base = $this->appConfig->get('base_path');
$output = $this->output();
$domain = $this->domain();
$separator = $this->separator();
$enclosure = $this->enclosure();
foreach ($translations as $lang => $trans) {
// Create / open the handle
$filePath = str_replace('/', DIRECTORY_SEPARATOR, $base.$output);
$dirname = dirname($filePath);
if (!file_exists($filePath)) {
mkdir($filePath, 0755, true);
}
$file = fopen($base.$output.$domain.'.'.$lang.'.csv', 'w');
if (!$file) {
continue;
}
foreach ($trans as $key => $translation) {
$data = [ $key, $translation ];
fputcsv($file, $data, $separator, $enclosure);
}
fclose($file);
}
return $this;
}
/**
* @return string
*/
public function enclosure()
{
return '"';
}
/**
* @return string
*/
public function separator()
{
return ';';
}
/**
* @return integer
*/
public function maxRecursiveLevel()
{
if ($this->climate()->arguments->defined('recursive')) {
return $this->climate()->arguments->get('recursive');
}
return 10;
}
/**
* @return string Php function
*/
private function phpFunction()
{
if ($this->climate()->arguments->defined('php_function')) {
return $this->climate()->arguments->get('php_function');
}
return 'translate';
}
/**
* @return string Mustache tag
*/
private function mustacheTag()
{
if ($this->climate()->arguments->defined('mustache_tag')) {
return $this->climate()->arguments->get('mustache_tag');
}
return '_t';
}
}