Passed
Pull Request — master (#19934)
by Alexander
08:51
created

MessageController::deleteUnusedPhpMessageFiles()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 2
dl 0
loc 11
ccs 9
cts 9
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\console\controllers;
9
10
use Yii;
11
use yii\console\Exception;
12
use yii\console\ExitCode;
13
use yii\db\Connection;
14
use yii\db\Query;
15
use yii\di\Instance;
16
use yii\helpers\Console;
17
use yii\helpers\FileHelper;
18
use yii\helpers\VarDumper;
19
use yii\i18n\GettextPoFile;
20
21
/**
22
 * Extracts messages to be translated from source files.
23
 *
24
 * The extracted messages can be saved the following depending on `format`
25
 * setting in config file:
26
 *
27
 * - PHP message source files.
28
 * - ".po" files.
29
 * - Database.
30
 *
31
 * Usage:
32
 * 1. Create a configuration file using the 'message/config' command:
33
 *    yii message/config /path/to/myapp/messages/config.php
34
 * 2. Edit the created config file, adjusting it for your web application needs.
35
 * 3. Run the 'message/extract' command, using created config:
36
 *    yii message /path/to/myapp/messages/config.php
37
 *
38
 * @author Qiang Xue <[email protected]>
39
 * @since 2.0
40
 */
41
class MessageController extends \yii\console\Controller
42
{
43
    /**
44
     * @var string controller default action ID.
45
     */
46
    public $defaultAction = 'extract';
47
    /**
48
     * @var string required, root directory of all source files.
49
     */
50
    public $sourcePath = '@yii';
51
    /**
52
     * @var string required, root directory containing message translations.
53
     */
54
    public $messagePath = '@yii/messages';
55
    /**
56
     * @var array required, list of language codes that the extracted messages
57
     * should be translated to. For example, ['zh-CN', 'de'].
58
     */
59
    public $languages = [];
60
    /**
61
     * @var string|string[] the name of the function for translating messages.
62
     * This is used as a mark to find the messages to be translated.
63
     * You may use a string for single function name or an array for multiple function names.
64
     */
65
    public $translator = ['Yii::t', '\Yii::t'];
66
    /**
67
     * @var bool whether to sort messages by keys when merging new messages
68
     * with the existing ones. Defaults to false, which means the new (untranslated)
69
     * messages will be separated from the old (translated) ones.
70
     */
71
    public $sort = false;
72
    /**
73
     * @var bool whether the message file should be overwritten with the merged messages
74
     */
75
    public $overwrite = true;
76
    /**
77
     * @var bool whether to remove messages that no longer appear in the source code.
78
     * Defaults to false, which means these messages will NOT be removed.
79
     */
80
    public $removeUnused = false;
81
    /**
82
     * @var bool whether to mark messages that no longer appear in the source code.
83
     * Defaults to true, which means each of these messages will be enclosed with a pair of '@@' marks.
84
     */
85
    public $markUnused = true;
86
    /**
87
     * @var array|null list of patterns that specify which files/directories should NOT be processed.
88
     * If empty or not set, all files/directories will be processed.
89
     * See helpers/FileHelper::findFiles() description for pattern matching rules.
90
     * If a file/directory matches both a pattern in "only" and "except", it will NOT be processed.
91
     */
92
    public $except = [
93
        '.*',
94
        '/.*',
95
        '/messages',
96
        '/tests',
97
        '/runtime',
98
        '/vendor',
99
        '/BaseYii.php', // contains examples about Yii::t()
100
    ];
101
    /**
102
     * @var array|null list of patterns that specify which files (not directories) should be processed.
103
     * If empty or not set, all files will be processed.
104
     * See helpers/FileHelper::findFiles() description for pattern matching rules.
105
     * If a file/directory matches both a pattern in "only" and "except", it will NOT be processed.
106
     */
107
    public $only = ['*.php'];
108
    /**
109
     * @var string generated file format. Can be "php", "db", "po" or "pot".
110
     */
111
    public $format = 'php';
112
    /**
113
     * @var string connection component ID for "db" format.
114
     */
115
    public $db = 'db';
116
    /**
117
     * @var string custom name for source message table for "db" format.
118
     */
119
    public $sourceMessageTable = '{{%source_message}}';
120
    /**
121
     * @var string custom name for translation message table for "db" format.
122
     */
123
    public $messageTable = '{{%message}}';
124
    /**
125
     * @var string name of the file that will be used for translations for "po" format.
126
     */
127
    public $catalog = 'messages';
128
    /**
129
     * @var array message categories to ignore. For example, 'yii', 'app*', 'widgets/menu', etc.
130
     * @see isCategoryIgnored
131
     */
132
    public $ignoreCategories = [];
133
    /**
134
     * @var string File header in generated PHP file with messages. This property is used only if [[$format]] is "php".
135
     * @since 2.0.13
136
     */
137
    public $phpFileHeader = '';
138
    /**
139
     * @var string|null DocBlock used for messages array in generated PHP file. If `null`, default DocBlock will be used.
140
     * This property is used only if [[$format]] is "php".
141
     * @since 2.0.13
142
     */
143
    public $phpDocBlock;
144
145
    /**
146
     * @var array Config for messages extraction.
147
     * @see actionExtract()
148
     * @see initConfig()
149
     * @since 2.0.13
150
     */
151
    protected $config;
152
153
154
    /**
155
     * {@inheritdoc}
156
     */
157 68
    public function options($actionID)
158
    {
159 68
        return array_merge(parent::options($actionID), [
160 68
            'sourcePath',
161
            'messagePath',
162
            'languages',
163
            'translator',
164
            'sort',
165
            'overwrite',
166
            'removeUnused',
167
            'markUnused',
168
            'except',
169
            'only',
170
            'format',
171
            'db',
172
            'sourceMessageTable',
173
            'messageTable',
174
            'catalog',
175
            'ignoreCategories',
176
            'phpFileHeader',
177
            'phpDocBlock',
178
        ]);
179
    }
180
181
    /**
182
     * {@inheritdoc}
183
     * @since 2.0.8
184
     */
185
    public function optionAliases()
186
    {
187
        return array_merge(parent::optionAliases(), [
188
            'c' => 'catalog',
189
            'e' => 'except',
190
            'f' => 'format',
191
            'i' => 'ignoreCategories',
192
            'l' => 'languages',
193
            'u' => 'markUnused',
194
            'p' => 'messagePath',
195
            'o' => 'only',
196
            'w' => 'overwrite',
197
            'S' => 'sort',
198
            't' => 'translator',
199
            'm' => 'sourceMessageTable',
200
            's' => 'sourcePath',
201
            'r' => 'removeUnused',
202
        ]);
203
    }
204
205
    /**
206
     * Creates a configuration file for the "extract" command using command line options specified.
207
     *
208
     * The generated configuration file contains parameters required
209
     * for source code messages extraction.
210
     * You may use this configuration file with the "extract" command.
211
     *
212
     * @param string $filePath output file name or alias.
213
     * @return int CLI exit code
214
     * @throws Exception on failure.
215
     */
216 6
    public function actionConfig($filePath)
217
    {
218 6
        $filePath = Yii::getAlias($filePath);
219 6
        $dir = dirname($filePath);
0 ignored issues
show
Bug introduced by
It seems like $filePath can also be of type false; however, parameter $path of dirname() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

219
        $dir = dirname(/** @scrutinizer ignore-type */ $filePath);
Loading history...
220
221 6
        if (file_exists($filePath)) {
0 ignored issues
show
Bug introduced by
It seems like $filePath can also be of type false; however, parameter $filename of file_exists() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

221
        if (file_exists(/** @scrutinizer ignore-type */ $filePath)) {
Loading history...
222
            if (!$this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?")) {
223
                return ExitCode::OK;
224
            }
225
        }
226
227 6
        $array = VarDumper::export($this->getOptionValues($this->action->id));
228
        $content = <<<EOD
229 6
<?php
230
/**
231 6
 * Configuration file for 'yii {$this->id}/{$this->defaultAction}' command.
232
 *
233 6
 * This file is automatically generated by 'yii {$this->id}/{$this->action->id}' command.
234
 * It contains parameters for source code messages extraction.
235
 * You may modify this file to suit your needs.
236
 *
237 6
 * You can use 'yii {$this->id}/{$this->action->id}-template' command to create
238
 * template configuration file with detailed description for each parameter.
239
 */
240 6
return $array;
241
242
EOD;
243
244 6
        if (FileHelper::createDirectory($dir) === false || file_put_contents($filePath, $content, LOCK_EX) === false) {
0 ignored issues
show
Bug introduced by
It seems like $filePath can also be of type false; however, parameter $filename of file_put_contents() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

244
        if (FileHelper::createDirectory($dir) === false || file_put_contents(/** @scrutinizer ignore-type */ $filePath, $content, LOCK_EX) === false) {
Loading history...
245
            $this->stdout("Configuration file was NOT created: '{$filePath}'.\n\n", Console::FG_RED);
246
            return ExitCode::UNSPECIFIED_ERROR;
247
        }
248
249 6
        $this->stdout("Configuration file created: '{$filePath}'.\n\n", Console::FG_GREEN);
250 6
        return ExitCode::OK;
251
    }
252
253
    /**
254
     * Creates a configuration file template for the "extract" command.
255
     *
256
     * The created configuration file contains detailed instructions on
257
     * how to customize it to fit for your needs. After customization,
258
     * you may use this configuration file with the "extract" command.
259
     *
260
     * @param string $filePath output file name or alias.
261
     * @return int CLI exit code
262
     * @throws Exception on failure.
263
     */
264
    public function actionConfigTemplate($filePath)
265
    {
266
        $filePath = Yii::getAlias($filePath);
267
268
        if (file_exists($filePath)) {
0 ignored issues
show
Bug introduced by
It seems like $filePath can also be of type false; however, parameter $filename of file_exists() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

268
        if (file_exists(/** @scrutinizer ignore-type */ $filePath)) {
Loading history...
269
            if (!$this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?")) {
270
                return ExitCode::OK;
271
            }
272
        }
273
274
        if (!copy(Yii::getAlias('@yii/views/messageConfig.php'), $filePath)) {
0 ignored issues
show
Bug introduced by
It seems like $filePath can also be of type false; however, parameter $to of copy() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

274
        if (!copy(Yii::getAlias('@yii/views/messageConfig.php'), /** @scrutinizer ignore-type */ $filePath)) {
Loading history...
Bug introduced by
It seems like Yii::getAlias('@yii/views/messageConfig.php') can also be of type false; however, parameter $from of copy() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

274
        if (!copy(/** @scrutinizer ignore-type */ Yii::getAlias('@yii/views/messageConfig.php'), $filePath)) {
Loading history...
275
            $this->stdout("Configuration file template was NOT created at '{$filePath}'.\n\n", Console::FG_RED);
276
            return ExitCode::UNSPECIFIED_ERROR;
277
        }
278
279
        $this->stdout("Configuration file template created at '{$filePath}'.\n\n", Console::FG_GREEN);
280
        return ExitCode::OK;
281
    }
282
283
    /**
284
     * Extracts messages to be translated from source code.
285
     *
286
     * This command will search through source code files and extract
287
     * messages that need to be translated in different languages.
288
     *
289
     * @param string|null $configFile the path or alias of the configuration file.
290
     * You may use the "yii message/config" command to generate
291
     * this file and then customize it for your needs.
292
     * @throws Exception on failure.
293
     */
294 62
    public function actionExtract($configFile = null)
295
    {
296 62
        $this->initConfig($configFile);
297
298 59
        $files = FileHelper::findFiles(realpath($this->config['sourcePath']), $this->config);
299
300 59
        $messages = [];
301 59
        foreach ($files as $file) {
302 53
            $messages = array_merge_recursive($messages, $this->extractMessages($file, $this->config['translator'], $this->config['ignoreCategories']));
303
        }
304
305 59
        $catalog = isset($this->config['catalog']) ? $this->config['catalog'] : 'messages';
306
307 59
        if (in_array($this->config['format'], ['php', 'po'])) {
308 45
            foreach ($this->config['languages'] as $language) {
309 45
                $dir = $this->config['messagePath'] . DIRECTORY_SEPARATOR . $language;
310 45
                if (!is_dir($dir) && !@mkdir($dir)) {
311
                    throw new Exception("Directory '{$dir}' can not be created.");
312
                }
313 45
                if ($this->config['format'] === 'po') {
314 16
                    $this->saveMessagesToPO($messages, $dir, $this->config['overwrite'], $this->config['removeUnused'], $this->config['sort'], $catalog, $this->config['markUnused']);
315
                } else {
316 29
                    $this->saveMessagesToPHP($messages, $dir, $this->config['overwrite'], $this->config['removeUnused'], $this->config['sort'], $this->config['markUnused']);
317
                }
318
            }
319 14
        } elseif ($this->config['format'] === 'db') {
320
            /** @var Connection $db */
321 14
            $db = Instance::ensure($this->config['db'], Connection::className());
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

321
            $db = Instance::ensure($this->config['db'], /** @scrutinizer ignore-deprecated */ Connection::className());

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
322 14
            $sourceMessageTable = isset($this->config['sourceMessageTable']) ? $this->config['sourceMessageTable'] : '{{%source_message}}';
323 14
            $messageTable = isset($this->config['messageTable']) ? $this->config['messageTable'] : '{{%message}}';
324 14
            $this->saveMessagesToDb(
325 14
                $messages,
326
                $db,
327
                $sourceMessageTable,
328
                $messageTable,
329 14
                $this->config['removeUnused'],
330 14
                $this->config['languages'],
331 14
                $this->config['markUnused']
332
            );
333
        } elseif ($this->config['format'] === 'pot') {
334
            $this->saveMessagesToPOT($messages, $this->config['messagePath'], $catalog);
335
        }
336 59
    }
337
338
    /**
339
     * Saves messages to database.
340
     *
341
     * @param array $messages
342
     * @param Connection $db
343
     * @param string $sourceMessageTable
344
     * @param string $messageTable
345
     * @param bool $removeUnused
346
     * @param array $languages
347
     * @param bool $markUnused
348
     */
349 14
    protected function saveMessagesToDb($messages, $db, $sourceMessageTable, $messageTable, $removeUnused, $languages, $markUnused)
350
    {
351 14
        $this->stdout("UPDATING DB\n\n");
352
        
353 14
        $this->stdout("SOURCE MESSAGE TABLE\n\n");
354
        
355 14
        $currentMessages = [];
356 14
        $rows = (new Query())->select(['id', 'category', 'message'])->from($sourceMessageTable)->all($db);
357 14
        foreach ($rows as $row) {
358 13
            $currentMessages[$row['category']][$row['id']] = $row['message'];
359
        }
360
        
361 14
        $new = [];
362 14
        $obsolete = [];
363
364 14
        foreach ($messages as $category => $msgs) {
365 14
            $msgs = array_unique($msgs);
366
367 14
            if (isset($currentMessages[$category])) {
368 9
                $new[$category] = array_diff($msgs, $currentMessages[$category]);
369
                // obsolete msgs per category
370 9
                $obsolete += array_diff($currentMessages[$category], $msgs);
371
            } else {
372 8
                $new[$category] = $msgs;
373
            }
374
        }
375
        
376
        // obsolete categories
377 14
        foreach (array_diff(array_keys($currentMessages), array_keys($messages)) as $category) {
378 9
            $obsolete += $currentMessages[$category];
379
        }
380
381 14
        if (!$removeUnused) {
382 13
            foreach ($obsolete as $pk => $msg) {
383
                // skip already marked unused
384 10
                if (strncmp($msg, '@@', 2) === 0 && substr($msg, -2) === '@@') {
385 6
                    unset($obsolete[$pk]);
386
                }
387
            }
388
        }        
389
        
390 14
        $this->stdout('Inserting new messages...');
391 14
        $insertCount = 0;
392
393 14
        foreach ($new as $category => $msgs) {
394 14
            foreach ($msgs as $msg) {
395 12
                $insertCount++;
396 12
                $db->schema->insert($sourceMessageTable, ['category' => $category, 'message' => $msg]);
397
            }
398
        }
399
        
400 14
        $this->stdout($insertCount ? "{$insertCount} saved.\n" : "Nothing to save.\n");
401
        
402 14
        $this->stdout($removeUnused ? 'Deleting obsoleted messages...' : 'Updating obsoleted messages...');
403
404 14
        if (empty($obsolete)) {
405 6
            $this->stdout("Nothing obsoleted...skipped.\n");
406
        }
407
408 14
        if ($obsolete) {
409 11
            if ($removeUnused) {
410 1
                $affected = $db->createCommand()
411 1
                   ->delete($sourceMessageTable, ['in', 'id', array_keys($obsolete)])
412 1
                   ->execute();
413 1
                $this->stdout("{$affected} deleted.\n");
414 10
            } elseif ($markUnused) {
415 8
                $marked=0;
416 8
                $rows = (new Query())
417 8
                    ->select(['id', 'message'])
418 8
                    ->from($sourceMessageTable)
419 8
                    ->where(['in', 'id', array_keys($obsolete)])
420 8
                    ->all($db);
421
    
422 8
                foreach ($rows as $row) {
423 8
                    $marked++;
424 8
                    $db->createCommand()->update(
425 8
                        $sourceMessageTable,
426 8
                        ['message' => '@@' . $row['message'] . '@@'],
427 8
                        ['id' => $row['id']]
428 8
                    )->execute();
429
                }
430 8
                $this->stdout("{$marked} updated.\n");
431
            } else {
432 2
                $this->stdout("kept untouched.\n");
433
            }
434
        }
435
         
436 14
        $this->stdout("\n\nMESSAGE TABLE\n\n");
437
        
438
        // get fresh message id list
439 14
        $freshMessagesIds = [];
440 14
        $rows = (new Query())->select(['id'])->from($sourceMessageTable)->all($db);
441 14
        foreach ($rows as $row) {
442 14
            $freshMessagesIds[] = $row['id'];
443
        }
444
            
445 14
        $this->stdout("Generating missing rows...");
446 14
        $generatedMissingRows = [];
447
        
448 14
        foreach ($languages as $language) {
449 14
          $count = 0;
450
          
451
          // get list of ids of translations for this language
452 14
          $msgRowsIds = [];
453 14
          $msgRows = (new Query())->select(['id'])->from($messageTable)->where([
454 14
              'language'=>$language,
455 14
          ])->all($db);
456 14
          foreach ($msgRows as $row) {
457 13
              $msgRowsIds[] = $row['id'];
458
          }
459
          
460
          // insert missing
461 14
          foreach ($freshMessagesIds as $id) {
462 14
            if (!in_array($id, $msgRowsIds)) {
463 12
              $db->createCommand()
464 12
                 ->insert($messageTable, ['id' => $id, 'language' => $language])
465 12
                 ->execute();
466 12
              $count++;
467
            }
468
          }
469 14
          if ($count) {
470 12
            $generatedMissingRows[] = "{$count} for {$language}";
471
          }
472
        }
473
        
474 14
        $this->stdout($generatedMissingRows ? implode(", ", $generatedMissingRows).".\n" : "Nothing to do.\n");
475
        
476 14
        $this->stdout("Dropping unused languages...");
477 14
        $droppedLanguages=[];
478
        
479 14
        $currentLanguages = [];
480 14
        $rows = (new Query())->select(['language'])->from($messageTable)->groupBy('language')->all($db);
481 14
        foreach ($rows as $row) {
482 14
            $currentLanguages[] = $row['language'];
483
        }
484
        
485 14
        foreach ($currentLanguages as $currentLanguage) {
486 14
          if (!in_array($currentLanguage, $languages)) {
487 1
            $deleted=$db->createCommand()->delete($messageTable, "language=:language", [
488 1
                'language'=>$currentLanguage,
489 1
            ])->execute();
490 1
            $droppedLanguages[] = "removed {$deleted} rows for $currentLanguage";
491
          }
492
        }
493
        
494 14
        $this->stdout($droppedLanguages ? implode(", ", $droppedLanguages).".\n" : "Nothing to do.\n");
495 14
    }
496
497
    /**
498
     * Extracts messages from a file.
499
     *
500
     * @param string $fileName name of the file to extract messages from
501
     * @param string $translator name of the function used to translate messages
502
     * @param array $ignoreCategories message categories to ignore.
503
     * This parameter is available since version 2.0.4.
504
     * @return array
505
     */
506 53
    protected function extractMessages($fileName, $translator, $ignoreCategories = [])
507
    {
508 53
        $this->stdout('Extracting messages from ');
509 53
        $this->stdout($fileName, Console::FG_CYAN);
510 53
        $this->stdout("...\n");
511
512 53
        $subject = file_get_contents($fileName);
513 53
        $messages = [];
514 53
        $tokens = token_get_all($subject);
515 53
        foreach ((array) $translator as $currentTranslator) {
516 53
            $translatorTokens = token_get_all('<?php ' . $currentTranslator);
517 53
            array_shift($translatorTokens);
518 53
            $messages = array_merge_recursive($messages, $this->extractMessagesFromTokens($tokens, $translatorTokens, $ignoreCategories));
519
        }
520
521 53
        $this->stdout("\n");
522
523 53
        return $messages;
524
    }
525
526
    /**
527
     * Extracts messages from a parsed PHP tokens list.
528
     * @param array $tokens tokens to be processed.
529
     * @param array $translatorTokens translator tokens.
530
     * @param array $ignoreCategories message categories to ignore.
531
     * @return array messages.
532
     */
533 53
    protected function extractMessagesFromTokens(array $tokens, array $translatorTokens, array $ignoreCategories)
534
    {
535 53
        $messages = [];
536 53
        $translatorTokensCount = count($translatorTokens);
537 53
        $matchedTokensCount = 0;
538 53
        $buffer = [];
539 53
        $pendingParenthesisCount = 0;
540
541 53
        foreach ($tokens as $tokenIndex => $token) {
542
            // finding out translator call
543 53
            if ($matchedTokensCount < $translatorTokensCount) {
544 53
                if ($this->tokensEqual($token, $translatorTokens[$matchedTokensCount])) {
545 53
                    $matchedTokensCount++;
546
                } else {
547 53
                    $matchedTokensCount = 0;
548
                }
549 53
            } elseif ($matchedTokensCount === $translatorTokensCount) {
550
                // translator found
551
552
                // end of function call
553 53
                if ($this->tokensEqual(')', $token)) {
554 53
                    $pendingParenthesisCount--;
555
556 53
                    if ($pendingParenthesisCount === 0) {
557
                        // end of translator call or end of something that we can't extract
558 53
                        if (isset($buffer[0][0], $buffer[1], $buffer[2][0]) && $buffer[0][0] === T_CONSTANT_ENCAPSED_STRING && $buffer[1] === ',' && $buffer[2][0] === T_CONSTANT_ENCAPSED_STRING) {
559
                            // is valid call we can extract
560 53
                            $category = stripcslashes($buffer[0][1]);
561 53
                            $category = mb_substr($category, 1, -1);
562
563 53
                            if (!$this->isCategoryIgnored($category, $ignoreCategories)) {
564 53
                                $fullMessage = mb_substr($buffer[2][1], 1, -1);
565 53
                                $i = 3;
566 53
                                while ($i < count($buffer) - 1 && !is_array($buffer[$i]) && $buffer[$i] === '.') {
567 3
                                    $fullMessage .= mb_substr($buffer[$i + 1][1], 1, -1);
568 3
                                    $i += 2;
569
                                }
570
571 53
                                $message = stripcslashes($fullMessage);
572 53
                                $messages[$category][] = $message;
573
                            }
574
575 53
                            $nestedTokens = array_slice($buffer, 3);
576 53
                            if (count($nestedTokens) > $translatorTokensCount) {
577
                                // search for possible nested translator calls
578 53
                                $messages = array_merge_recursive($messages, $this->extractMessagesFromTokens($nestedTokens, $translatorTokens, $ignoreCategories));
579
                            }
580
                        } else {
581
                            // invalid call or dynamic call we can't extract
582
                            $line = Console::ansiFormat($this->getLine($buffer), [Console::FG_CYAN]);
583
                            $skipping = Console::ansiFormat('Skipping line', [Console::FG_YELLOW]);
584
                            $this->stdout("$skipping $line. Make sure both category and message are static strings.\n");
585
                        }
586
587
                        // prepare for the next match
588 53
                        $matchedTokensCount = 0;
589 53
                        $pendingParenthesisCount = 0;
590 53
                        $buffer = [];
591
                    } else {
592 53
                        $buffer[] = $token;
593
                    }
594 53
                } elseif ($this->tokensEqual('(', $token)) {
595
                    // count beginning of function call, skipping translator beginning
596
597
                    // If we are not yet inside the translator, make sure that it's beginning of the real translator.
598
                    // See https://github.com/yiisoft/yii2/issues/16828
599 53
                    if ($pendingParenthesisCount === 0) {
600 53
                        $previousTokenIndex = $tokenIndex - $matchedTokensCount - 1;
601 53
                        if (is_array($tokens[$previousTokenIndex])) {
602 53
                            $previousToken = $tokens[$previousTokenIndex][0];
603 53
                            if (in_array($previousToken, [T_OBJECT_OPERATOR, T_PAAMAYIM_NEKUDOTAYIM], true)) {
604 3
                                $matchedTokensCount = 0;
605 3
                                continue;
606
                            }
607
                        }
608
                    }
609
610 53
                    if ($pendingParenthesisCount > 0) {
611 6
                        $buffer[] = $token;
612
                    }
613 53
                    $pendingParenthesisCount++;
614 53
                } elseif (isset($token[0]) && !in_array($token[0], [T_WHITESPACE, T_COMMENT])) {
615
                    // ignore comments and whitespaces
616 53
                    $buffer[] = $token;
617
                }
618
            }
619
        }
620
621 53
        return $messages;
622
    }
623
624
    /**
625
     * The method checks, whether the $category is ignored according to $ignoreCategories array.
626
     *
627
     * Examples:
628
     *
629
     * - `myapp` - will be ignored only `myapp` category;
630
     * - `myapp*` - will be ignored by all categories beginning with `myapp` (`myapp`, `myapplication`, `myapprove`, `myapp/widgets`, `myapp.widgets`, etc).
631
     *
632
     * @param string $category category that is checked
633
     * @param array $ignoreCategories message categories to ignore.
634
     * @return bool
635
     * @since 2.0.7
636
     */
637 53
    protected function isCategoryIgnored($category, array $ignoreCategories)
638
    {
639 53
        if (!empty($ignoreCategories)) {
640 3
            if (in_array($category, $ignoreCategories, true)) {
641 3
                return true;
642
            }
643 3
            foreach ($ignoreCategories as $pattern) {
644 3
                if (strpos($pattern, '*') > 0 && strpos($category, rtrim($pattern, '*')) === 0) {
645 3
                    return true;
646
                }
647
            }
648
        }
649
650 53
        return false;
651
    }
652
653
    /**
654
     * Finds out if two PHP tokens are equal.
655
     *
656
     * @param array|string $a
657
     * @param array|string $b
658
     * @return bool
659
     * @since 2.0.1
660
     */
661 53
    protected function tokensEqual($a, $b)
662
    {
663 53
        if (is_string($a) && is_string($b)) {
664 53
            return $a === $b;
665
        }
666 53
        if (isset($a[0], $a[1], $b[0], $b[1])) {
667 53
            return $a[0] === $b[0] && $a[1] == $b[1];
668
        }
669
670 53
        return false;
671
    }
672
673
    /**
674
     * Finds out a line of the first non-char PHP token found.
675
     *
676
     * @param array $tokens
677
     * @return int|string
678
     * @since 2.0.1
679
     */
680
    protected function getLine($tokens)
681
    {
682
        foreach ($tokens as $token) {
683
            if (isset($token[2])) {
684
                return $token[2];
685
            }
686
        }
687
688
        return 'unknown';
689
    }
690
691
    /**
692
     * Writes messages into PHP files.
693
     *
694
     * @param array $messages
695
     * @param string $dirName name of the directory to write to
696
     * @param bool $overwrite if existing file should be overwritten without backup
697
     * @param bool $removeUnused if obsolete translations should be removed
698
     * @param bool $sort if translations should be sorted
699
     * @param bool $markUnused if obsolete translations should be marked
700
     */
701 29
    protected function saveMessagesToPHP($messages, $dirName, $overwrite, $removeUnused, $sort, $markUnused)
702
    {
703 29
        foreach ($messages as $category => $msgs) {
704 23
            $file = str_replace('\\', '/', "$dirName/$category.php");
705 23
            $path = dirname($file);
706 23
            FileHelper::createDirectory($path);
707 23
            $msgs = array_values(array_unique($msgs));
708 23
            $coloredFileName = Console::ansiFormat($file, [Console::FG_CYAN]);
709 23
            $this->stdout("Saving messages to $coloredFileName...\n");
710 23
            $this->saveMessagesCategoryToPHP($msgs, $file, $overwrite, $removeUnused, $sort, $category, $markUnused);
711
        }
712
713 29
        if ($removeUnused) {
714 7
            $this->deleteUnusedPhpMessageFiles(array_keys($messages), $dirName);
715
        }
716 29
    }
717
718
    /**
719
     * Writes category messages into PHP file.
720
     *
721
     * @param array $messages
722
     * @param string $fileName name of the file to write to
723
     * @param bool $overwrite if existing file should be overwritten without backup
724
     * @param bool $removeUnused if obsolete translations should be removed
725
     * @param bool $sort if translations should be sorted
726
     * @param string $category message category
727
     * @param bool $markUnused if obsolete translations should be marked
728
     * @return int exit code
729
     */
730 23
    protected function saveMessagesCategoryToPHP($messages, $fileName, $overwrite, $removeUnused, $sort, $category, $markUnused)
731
    {
732 23
        if (is_file($fileName)) {
733 16
            $rawExistingMessages = require $fileName;
734 16
            $existingMessages = $rawExistingMessages;
735 16
            sort($messages);
736 16
            ksort($existingMessages);
737 16
            if (array_keys($existingMessages) === $messages && (!$sort || array_keys($rawExistingMessages) === $messages)) {
738 10
                $this->stdout("Nothing new in \"$category\" category... Nothing to save.\n\n", Console::FG_GREEN);
739 10
                return ExitCode::OK;
740
            }
741 7
            unset($rawExistingMessages);
742 7
            $merged = [];
743 7
            $untranslated = [];
744 7
            foreach ($messages as $message) {
745 7
                if (array_key_exists($message, $existingMessages) && $existingMessages[$message] !== '') {
746 4
                    $merged[$message] = $existingMessages[$message];
747
                } else {
748 6
                    $untranslated[] = $message;
749
                }
750
            }
751 7
            ksort($merged);
752 7
            sort($untranslated);
753 7
            $todo = [];
754 7
            foreach ($untranslated as $message) {
755 6
                $todo[$message] = '';
756
            }
757 7
            ksort($existingMessages);
758 7
            foreach ($existingMessages as $message => $translation) {
759 7
                if (!$removeUnused && !isset($merged[$message]) && !isset($todo[$message])) {
760 3
                    if (!$markUnused || (!empty($translation) && (strncmp($translation, '@@', 2) === 0 && substr_compare($translation, '@@', -2, 2) === 0))) {
761 2
                        $todo[$message] = $translation;
762
                    } else {
763 1
                        $todo[$message] = '@@' . $translation . '@@';
764
                    }
765
                }
766
            }
767 7
            $merged = array_merge($merged, $todo);
768 7
            if ($sort) {
769 1
                ksort($merged);
770
            }
771 7
            if (false === $overwrite) {
772
                $fileName .= '.merged';
773
            }
774 7
            $this->stdout("Translation merged.\n");
775
        } else {
776 11
            $merged = [];
777 11
            foreach ($messages as $message) {
778 11
                $merged[$message] = '';
779
            }
780 11
            ksort($merged);
781
        }
782
783 17
        $array = VarDumper::export($merged);
784
        $content = <<<EOD
785 17
<?php
786 17
{$this->config['phpFileHeader']}{$this->config['phpDocBlock']}
787 17
return $array;
788
789
EOD;
790
791 17
        if (file_put_contents($fileName, $content, LOCK_EX) === false) {
792
            $this->stdout("Translation was NOT saved.\n\n", Console::FG_RED);
793
            return ExitCode::UNSPECIFIED_ERROR;
794
        }
795
796 17
        $this->stdout("Translation saved.\n\n", Console::FG_GREEN);
797 17
        return ExitCode::OK;
798
    }
799
800
    /**
801
     * Writes messages into PO file.
802
     *
803
     * @param array $messages
804
     * @param string $dirName name of the directory to write to
805
     * @param bool $overwrite if existing file should be overwritten without backup
806
     * @param bool $removeUnused if obsolete translations should be removed
807
     * @param bool $sort if translations should be sorted
808
     * @param string $catalog message catalog
809
     * @param bool $markUnused if obsolete translations should be marked
810
     */
811 16
    protected function saveMessagesToPO($messages, $dirName, $overwrite, $removeUnused, $sort, $catalog, $markUnused)
812
    {
813 16
        $file = str_replace('\\', '/', "$dirName/$catalog.po");
814 16
        FileHelper::createDirectory(dirname($file));
815 16
        $this->stdout("Saving messages to $file...\n");
816
817 16
        $poFile = new GettextPoFile();
818
819 16
        $merged = [];
820 16
        $todos = [];
821
822 16
        $hasSomethingToWrite = false;
823 16
        foreach ($messages as $category => $msgs) {
824 16
            $notTranslatedYet = [];
825 16
            $msgs = array_values(array_unique($msgs));
826
827 16
            if (is_file($file)) {
828 10
                $existingMessages = $poFile->load($file, $category);
829
830 10
                sort($msgs);
831 10
                ksort($existingMessages);
832 10
                if (array_keys($existingMessages) == $msgs) {
833 4
                    $this->stdout("Nothing new in \"$category\" category...\n");
834
835 4
                    sort($msgs);
836 4
                    foreach ($msgs as $message) {
837 4
                        $merged[$category . chr(4) . $message] = $existingMessages[$message];
838
                    }
839 4
                    ksort($merged);
840 4
                    continue;
841
                }
842
843
                // merge existing message translations with new message translations
844 7
                foreach ($msgs as $message) {
845 7
                    if (array_key_exists($message, $existingMessages) && $existingMessages[$message] !== '') {
846 4
                        $merged[$category . chr(4) . $message] = $existingMessages[$message];
847
                    } else {
848 6
                        $notTranslatedYet[] = $message;
849
                    }
850
                }
851 7
                ksort($merged);
852 7
                sort($notTranslatedYet);
853
854
                // collect not yet translated messages
855 7
                foreach ($notTranslatedYet as $message) {
856 6
                    $todos[$category . chr(4) . $message] = '';
857
                }
858
859
                // add obsolete unused messages
860 7
                foreach ($existingMessages as $message => $translation) {
861 7
                    if (!$removeUnused && !isset($merged[$category . chr(4) . $message]) && !isset($todos[$category . chr(4) . $message])) {
862 3
                        if (!$markUnused || (!empty($translation) && (substr($translation, 0, 2) === '@@' && substr($translation, -2) === '@@'))) {
863 2
                            $todos[$category . chr(4) . $message] = $translation;
864
                        } else {
865 1
                            $todos[$category . chr(4) . $message] = '@@' . $translation . '@@';
866
                        }
867
                    }
868
                }
869
870 7
                $merged = array_merge($merged, $todos);
871 7
                if ($sort) {
872 1
                    ksort($merged);
873
                }
874
875 7
                if ($overwrite === false) {
876 7
                    $file .= '.merged';
877
                }
878
            } else {
879 10
                sort($msgs);
880 10
                foreach ($msgs as $message) {
881 10
                    $merged[$category . chr(4) . $message] = '';
882
                }
883 10
                ksort($merged);
884
            }
885 16
            $this->stdout("Category \"$category\" merged.\n");
886 16
            $hasSomethingToWrite = true;
887
        }
888 16
        if ($hasSomethingToWrite) {
889 16
            $poFile->save($file, $merged);
890 16
            $this->stdout("Translation saved.\n", Console::FG_GREEN);
891
        } else {
892 3
            $this->stdout("Nothing to save.\n", Console::FG_GREEN);
893
        }
894 16
    }
895
896
    /**
897
     * Writes messages into POT file.
898
     *
899
     * @param array $messages
900
     * @param string $dirName name of the directory to write to
901
     * @param string $catalog message catalog
902
     * @since 2.0.6
903
     */
904
    protected function saveMessagesToPOT($messages, $dirName, $catalog)
905
    {
906
        $file = str_replace('\\', '/', "$dirName/$catalog.pot");
907
        FileHelper::createDirectory(dirname($file));
908
        $this->stdout("Saving messages to $file...\n");
909
910
        $poFile = new GettextPoFile();
911
912
        $merged = [];
913
914
        $hasSomethingToWrite = false;
915
        foreach ($messages as $category => $msgs) {
916
            $msgs = array_values(array_unique($msgs));
917
918
            sort($msgs);
919
            foreach ($msgs as $message) {
920
                $merged[$category . chr(4) . $message] = '';
921
            }
922
            $this->stdout("Category \"$category\" merged.\n");
923
            $hasSomethingToWrite = true;
924
        }
925
        if ($hasSomethingToWrite) {
926
            ksort($merged);
927
            $poFile->save($file, $merged);
928
            $this->stdout("Translation saved.\n", Console::FG_GREEN);
929
        } else {
930
            $this->stdout("Nothing to save.\n", Console::FG_GREEN);
931
        }
932
    }
933
934 7
    private function deleteUnusedPhpMessageFiles($existingCategories, $dirName)
935
    {
936 7
        $messageFiles = FileHelper::findFiles($dirName);
937 7
        foreach ($messageFiles as $messageFile) {
938 7
            $categoryFileName = str_replace($dirName, '', $messageFile);
939 7
            $categoryFileName = ltrim($categoryFileName, DIRECTORY_SEPARATOR);
940 7
            $category = preg_replace('#\.php$#', '', $categoryFileName);
941 7
            $category = str_replace(DIRECTORY_SEPARATOR, '/', $category);
942
943 7
            if (!in_array($category, $existingCategories, true)) {
944 3
                unlink($messageFile);
945
            }
946
        }
947 7
    }
948
949
    /**
950
     * @param string $configFile
951
     * @throws Exception If configuration file does not exists.
952
     * @since 2.0.13
953
     */
954 62
    protected function initConfig($configFile)
955
    {
956 62
        $configFileContent = [];
957 62
        if ($configFile !== null) {
0 ignored issues
show
introduced by
The condition $configFile !== null is always true.
Loading history...
958 62
            $configFile = Yii::getAlias($configFile);
959 62
            if (!is_file($configFile)) {
0 ignored issues
show
Bug introduced by
It seems like $configFile can also be of type false; however, parameter $filename of is_file() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

959
            if (!is_file(/** @scrutinizer ignore-type */ $configFile)) {
Loading history...
960 3
                throw new Exception("The configuration file does not exist: $configFile");
961
            }
962 59
            $configFileContent = require $configFile;
963
        }
964
965 59
        $this->config = array_merge(
966 59
            $this->getOptionValues($this->action->id),
967
            $configFileContent,
968 59
            $this->getPassedOptionValues()
969
        );
970 59
        $this->config['sourcePath'] = Yii::getAlias($this->config['sourcePath']);
971 59
        $this->config['messagePath'] = Yii::getAlias($this->config['messagePath']);
972
973 59
        if (!isset($this->config['sourcePath'], $this->config['languages'])) {
974
            throw new Exception('The configuration file must specify "sourcePath" and "languages".');
975
        }
976 59
        if (!is_dir($this->config['sourcePath'])) {
0 ignored issues
show
Bug introduced by
It seems like $this->config['sourcePath'] can also be of type false; however, parameter $filename of is_dir() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

976
        if (!is_dir(/** @scrutinizer ignore-type */ $this->config['sourcePath'])) {
Loading history...
977
            throw new Exception("The source path {$this->config['sourcePath']} is not a valid directory.");
978
        }
979 59
        if (empty($this->config['format']) || !in_array($this->config['format'], ['php', 'po', 'pot', 'db'])) {
980
            throw new Exception('Format should be either "php", "po", "pot" or "db".');
981
        }
982 59
        if (in_array($this->config['format'], ['php', 'po', 'pot'])) {
983 45
            if (!isset($this->config['messagePath'])) {
984
                throw new Exception('The configuration file must specify "messagePath".');
985
            }
986 45
            if (!is_dir($this->config['messagePath'])) {
987
                throw new Exception("The message path {$this->config['messagePath']} is not a valid directory.");
988
            }
989
        }
990 59
        if (empty($this->config['languages'])) {
991
            throw new Exception('Languages cannot be empty.');
992
        }
993
994 59
        if ($this->config['format'] === 'php' && $this->config['phpDocBlock'] === null) {
995
            $this->config['phpDocBlock'] = <<<DOCBLOCK
996
/**
997
 * Message translations.
998
 *
999
 * This file is automatically generated by 'yii {$this->id}/{$this->action->id}' command.
1000
 * It contains the localizable messages extracted from source code.
1001
 * You may modify this file by translating the extracted messages.
1002
 *
1003
 * Each array element represents the translation (value) of a message (key).
1004
 * If the value is empty, the message is considered as not translated.
1005
 * Messages that no longer need translation will have their translations
1006
 * enclosed between a pair of '@@' marks.
1007
 *
1008
 * Message string can be used with plural forms format. Check i18n section
1009
 * of the guide for details.
1010
 *
1011
 * NOTE: this file must be saved in UTF-8 encoding.
1012
 */
1013
DOCBLOCK;
1014
        }
1015 59
    }
1016
}
1017