/
I18nSniff.php
746 lines (662 loc) · 26.8 KB
/
I18nSniff.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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
<?php
/**
* WordPress Coding Standard.
*
* @package WPCS\WordPressCodingStandards
* @link https://github.com/WordPress/WordPress-Coding-Standards
* @license https://opensource.org/licenses/MIT MIT
*/
namespace WordPressCS\WordPress\Sniffs\WP;
use WordPressCS\WordPress\AbstractFunctionRestrictionsSniff;
use WordPressCS\WordPress\PHPCSHelper;
use PHP_CodeSniffer\Util\Tokens;
/**
* Makes sure WP internationalization functions are used properly.
*
* @link https://make.wordpress.org/core/handbook/best-practices/internationalization/
* @link https://developer.wordpress.org/plugins/internationalization/
*
* @package WPCS\WordPressCodingStandards
*
* @since 0.10.0
* @since 0.11.0 - Now also checks for translators comments.
* - Now has the ability to handle text domain set via the command-line
* as a comma-delimited list.
* `phpcs --runtime-set text_domain my-slug,default`
* @since 0.13.0 Class name changed: this class is now namespaced.
* @since 1.0.0 This class now extends the WordPressCS native
* `AbstractFunctionRestrictionSniff` class.
* The parent `exclude` property is, however, disabled as it
* would disable the whole sniff.
*/
class I18nSniff extends AbstractFunctionRestrictionsSniff {
/**
* These Regexes copied from http://php.net/manual/en/function.sprintf.php#93552
* and adjusted for better precision and updated specs.
*/
const SPRINTF_PLACEHOLDER_REGEX = '/(?:
(?<!%) # Don\'t match a literal % (%%).
(
% # Start of placeholder.
(?:[0-9]+\$)? # Optional ordering of the placeholders.
[+-]? # Optional sign specifier.
(?:
(?:0|\'.)? # Optional padding specifier - excluding the space.
-? # Optional alignment specifier.
[0-9]* # Optional width specifier.
(?:\.(?:[ 0]|\'.)?[0-9]+)? # Optional precision specifier with optional padding character.
| # Only recognize the space as padding in combination with a width specifier.
(?:[ ])? # Optional space padding specifier.
-? # Optional alignment specifier.
[0-9]+ # Width specifier.
(?:\.(?:[ 0]|\'.)?[0-9]+)? # Optional precision specifier with optional padding character.
)
[bcdeEfFgGosuxX] # Type specifier.
)
)/x';
/**
* "Unordered" means there's no position specifier: '%s', not '%2$s'.
*/
const UNORDERED_SPRINTF_PLACEHOLDER_REGEX = '/(?:
(?<!%) # Don\'t match a literal % (%%).
% # Start of placeholder.
[+-]? # Optional sign specifier.
(?:
(?:0|\'.)? # Optional padding specifier - excluding the space.
-? # Optional alignment specifier.
[0-9]* # Optional width specifier.
(?:\.(?:[ 0]|\'.)?[0-9]+)? # Optional precision specifier with optional padding character.
| # Only recognize the space as padding in combination with a width specifier.
(?:[ ])? # Optional space padding specifier.
-? # Optional alignment specifier.
[0-9]+ # Width specifier.
(?:\.(?:[ 0]|\'.)?[0-9]+)? # Optional precision specifier with optional padding character.
)
[bcdeEfFgGosuxX] # Type specifier.
)/x';
/**
* Text domain.
*
* @todo Eventually this should be able to be auto-supplied via looking at $this->phpcsFile->getFilename()
* @link https://youtrack.jetbrains.com/issue/WI-17740
*
* @var string[]|string
*/
public $text_domain;
/**
* The I18N functions in use in WP.
*
* @since 0.10.0
* @since 0.11.0 Changed visibility from public to protected.
*
* @var array <string function name> => <string function type>
*/
protected $i18n_functions = array(
'translate' => 'simple',
'__' => 'simple',
'esc_attr__' => 'simple',
'esc_html__' => 'simple',
'_e' => 'simple',
'esc_attr_e' => 'simple',
'esc_html_e' => 'simple',
'translate_with_gettext_context' => 'context',
'_x' => 'context',
'_ex' => 'context',
'esc_attr_x' => 'context',
'esc_html_x' => 'context',
'_n' => 'number',
'_nx' => 'number_context',
'_n_noop' => 'noopnumber',
'_nx_noop' => 'noopnumber_context',
);
/**
* Toggle whether or not to check for translators comments for text string containing placeholders.
*
* Intended to make this part of the sniff unit testable, but can be used by end-users too,
* though they can just as easily disable this via the sniff code.
*
* @since 0.11.0
*
* @var bool
*/
public $check_translator_comments = true;
/**
* Whether or not the `default` text domain is one of the allowed text domains.
*
* @since 0.14.0
*
* @var bool
*/
private $text_domain_contains_default = false;
/**
* Whether or not the `default` text domain is the only allowed text domain.
*
* @since 0.14.0
*
* @var bool
*/
private $text_domain_is_default = false;
/**
* Groups of functions to restrict.
*
* Example: groups => array(
* 'lambda' => array(
* 'type' => 'error' | 'warning',
* 'message' => 'Use anonymous functions instead please!',
* 'functions' => array( 'file_get_contents', 'create_function' ),
* )
* )
*
* @return array
*/
public function getGroups() {
return array(
'i18n' => array(
'functions' => array_keys( $this->i18n_functions ),
),
'typos' => array(
'functions' => array(
'_',
),
),
);
}
/**
* Processes this test, when one of its tokens is encountered.
*
* @since 1.0.0 Defers to the abstractFunctionRestriction sniff for determining
* whether something is a function call. The logic after that has
* been split off to the `process_matched_token()` method.
*
* @param int $stack_ptr The position of the current token in the stack.
*
* @return void
*/
public function process_token( $stack_ptr ) {
// Reset defaults.
$this->text_domain_contains_default = false;
$this->text_domain_is_default = false;
// Allow overruling the text_domain set in a ruleset via the command line.
$cl_text_domain = trim( PHPCSHelper::get_config_data( 'text_domain' ) );
if ( ! empty( $cl_text_domain ) ) {
$this->text_domain = array_filter( array_map( 'trim', explode( ',', $cl_text_domain ) ) );
}
$this->text_domain = $this->merge_custom_array( $this->text_domain, array(), false );
if ( ! empty( $this->text_domain ) ) {
if ( \in_array( 'default', $this->text_domain, true ) ) {
$this->text_domain_contains_default = true;
if ( \count( $this->text_domain ) === 1 ) {
$this->text_domain_is_default = true;
}
}
}
// Prevent exclusion of the i18n group.
$this->exclude = array();
parent::process_token( $stack_ptr );
}
/**
* Process a matched token.
*
* @since 1.0.0 Logic split off from the `process_token()` method.
*
* @param int $stack_ptr The position of the current token in the stack.
* @param string $group_name The name of the group which was matched.
* @param string $matched_content The token content (function name) which was matched.
*
* @return int|void Integer stack pointer to skip forward or void to continue
* normal file processing.
*/
public function process_matched_token( $stack_ptr, $group_name, $matched_content ) {
$func_open_paren_token = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stack_ptr + 1 ), null, true );
if ( false === $func_open_paren_token
|| \T_OPEN_PARENTHESIS !== $this->tokens[ $func_open_paren_token ]['code']
|| ! isset( $this->tokens[ $func_open_paren_token ]['parenthesis_closer'] )
) {
// Live coding, parse error or not a function call.
return;
}
if ( 'typos' === $group_name && '_' === $matched_content ) {
$this->phpcsFile->addError( 'Found single-underscore "_()" function when double-underscore expected.', $stack_ptr, 'SingleUnderscoreGetTextFunction' );
return;
}
if ( \in_array( $matched_content, array( 'translate', 'translate_with_gettext_context' ), true ) ) {
$this->phpcsFile->addWarning( 'Use of the "%s()" function is reserved for low-level API usage.', $stack_ptr, 'LowLevelTranslationFunction', array( $matched_content ) );
}
$arguments_tokens = array();
$argument_tokens = array();
$tokens = $this->tokens;
// Look at arguments.
for ( $i = ( $func_open_paren_token + 1 ); $i < $this->tokens[ $func_open_paren_token ]['parenthesis_closer']; $i++ ) {
$this_token = $this->tokens[ $i ];
$this_token['token_index'] = $i;
if ( isset( Tokens::$emptyTokens[ $this_token['code'] ] ) ) {
continue;
}
if ( \T_COMMA === $this_token['code'] ) {
$arguments_tokens[] = $argument_tokens;
$argument_tokens = array();
continue;
}
// Merge consecutive single or double quoted strings (when they span multiple lines).
if ( isset( Tokens::$textStringTokens[ $this_token['code'] ] ) ) {
for ( $j = ( $i + 1 ); $j < $this->tokens[ $func_open_paren_token ]['parenthesis_closer']; $j++ ) {
if ( $this_token['code'] === $this->tokens[ $j ]['code'] ) {
$this_token['content'] .= $this->tokens[ $j ]['content'];
$i = $j;
} else {
break;
}
}
}
$argument_tokens[] = $this_token;
// Include everything up to and including the parenthesis_closer if this token has one.
if ( ! empty( $this_token['parenthesis_closer'] ) ) {
for ( $j = ( $i + 1 ); $j <= $this_token['parenthesis_closer']; $j++ ) {
$tokens[ $j ]['token_index'] = $j;
$argument_tokens[] = $tokens[ $j ];
}
$i = $this_token['parenthesis_closer'];
}
}
if ( ! empty( $argument_tokens ) ) {
$arguments_tokens[] = $argument_tokens;
}
unset( $argument_tokens );
$argument_assertions = array();
if ( 'simple' === $this->i18n_functions[ $matched_content ] ) {
$argument_assertions[] = array(
'arg_name' => 'text',
'tokens' => array_shift( $arguments_tokens ),
);
$argument_assertions[] = array(
'arg_name' => 'domain',
'tokens' => array_shift( $arguments_tokens ),
);
} elseif ( 'context' === $this->i18n_functions[ $matched_content ] ) {
$argument_assertions[] = array(
'arg_name' => 'text',
'tokens' => array_shift( $arguments_tokens ),
);
$argument_assertions[] = array(
'arg_name' => 'context',
'tokens' => array_shift( $arguments_tokens ),
);
$argument_assertions[] = array(
'arg_name' => 'domain',
'tokens' => array_shift( $arguments_tokens ),
);
} elseif ( 'number' === $this->i18n_functions[ $matched_content ] ) {
$argument_assertions[] = array(
'arg_name' => 'single',
'tokens' => array_shift( $arguments_tokens ),
);
$argument_assertions[] = array(
'arg_name' => 'plural',
'tokens' => array_shift( $arguments_tokens ),
);
array_shift( $arguments_tokens );
$argument_assertions[] = array(
'arg_name' => 'domain',
'tokens' => array_shift( $arguments_tokens ),
);
} elseif ( 'number_context' === $this->i18n_functions[ $matched_content ] ) {
$argument_assertions[] = array(
'arg_name' => 'single',
'tokens' => array_shift( $arguments_tokens ),
);
$argument_assertions[] = array(
'arg_name' => 'plural',
'tokens' => array_shift( $arguments_tokens ),
);
array_shift( $arguments_tokens );
$argument_assertions[] = array(
'arg_name' => 'context',
'tokens' => array_shift( $arguments_tokens ),
);
$argument_assertions[] = array(
'arg_name' => 'domain',
'tokens' => array_shift( $arguments_tokens ),
);
} elseif ( 'noopnumber' === $this->i18n_functions[ $matched_content ] ) {
$argument_assertions[] = array(
'arg_name' => 'single',
'tokens' => array_shift( $arguments_tokens ),
);
$argument_assertions[] = array(
'arg_name' => 'plural',
'tokens' => array_shift( $arguments_tokens ),
);
$argument_assertions[] = array(
'arg_name' => 'domain',
'tokens' => array_shift( $arguments_tokens ),
);
} elseif ( 'noopnumber_context' === $this->i18n_functions[ $matched_content ] ) {
$argument_assertions[] = array(
'arg_name' => 'single',
'tokens' => array_shift( $arguments_tokens ),
);
$argument_assertions[] = array(
'arg_name' => 'plural',
'tokens' => array_shift( $arguments_tokens ),
);
$argument_assertions[] = array(
'arg_name' => 'context',
'tokens' => array_shift( $arguments_tokens ),
);
$argument_assertions[] = array(
'arg_name' => 'domain',
'tokens' => array_shift( $arguments_tokens ),
);
}
if ( ! empty( $arguments_tokens ) ) {
$this->phpcsFile->addError( 'Too many arguments for function "%s".', $func_open_paren_token, 'TooManyFunctionArgs', array( $matched_content ) );
}
foreach ( $argument_assertions as $argument_assertion_context ) {
if ( empty( $argument_assertion_context['tokens'][0] ) ) {
$argument_assertion_context['stack_ptr'] = $func_open_paren_token;
} else {
$argument_assertion_context['stack_ptr'] = $argument_assertion_context['tokens'][0]['token_index'];
}
$this->check_argument_tokens( $argument_assertion_context );
}
// For _n*() calls, compare the singular and plural strings.
if ( false !== strpos( $this->i18n_functions[ $matched_content ], 'number' ) ) {
$single_context = $argument_assertions[0];
$plural_context = $argument_assertions[1];
$this->compare_single_and_plural_arguments( $stack_ptr, $single_context, $plural_context );
}
if ( true === $this->check_translator_comments ) {
$this->check_for_translator_comment( $stack_ptr, $argument_assertions );
}
}
/**
* Check if supplied tokens represent a translation text string literal.
*
* @param array $context Context (@todo needs better description).
* @return bool
*/
protected function check_argument_tokens( $context ) {
$stack_ptr = $context['stack_ptr'];
$tokens = $context['tokens'];
$arg_name = $context['arg_name'];
$is_error = empty( $context['warning'] );
$content = isset( $tokens[0] ) ? $tokens[0]['content'] : '';
if ( empty( $tokens ) || 0 === \count( $tokens ) ) {
$code = $this->string_to_errorcode( 'MissingArg' . ucfirst( $arg_name ) );
if ( 'domain' !== $arg_name ) {
$this->addMessage( 'Missing $%s arg.', $stack_ptr, $is_error, $code, array( $arg_name ) );
return false;
}
// Ok, we're examining a text domain, now deal correctly with the 'default' text domain.
if ( true === $this->text_domain_is_default ) {
return true;
}
if ( true === $this->text_domain_contains_default ) {
$this->phpcsFile->addWarning(
'Missing $%s arg. If this text string is supposed to use a WP Core translation, use the "default" text domain.',
$stack_ptr,
$code . 'Default',
array( $arg_name )
);
} elseif ( ! empty( $this->text_domain ) ) {
$this->addMessage( 'Missing $%s arg.', $stack_ptr, $is_error, $code, array( $arg_name ) );
}
return false;
}
if ( \count( $tokens ) > 1 ) {
$contents = '';
foreach ( $tokens as $token ) {
$contents .= $token['content'];
}
$code = $this->string_to_errorcode( 'NonSingularStringLiteral' . ucfirst( $arg_name ) );
$this->addMessage( 'The $%s arg must be a single string literal, not "%s".', $stack_ptr, $is_error, $code, array( $arg_name, $contents ) );
return false;
}
if ( \in_array( $arg_name, array( 'text', 'single', 'plural' ), true ) ) {
$this->check_text( $context );
}
if ( \T_DOUBLE_QUOTED_STRING === $tokens[0]['code'] || \T_HEREDOC === $tokens[0]['code'] ) {
$interpolated_variables = $this->get_interpolated_variables( $content );
foreach ( $interpolated_variables as $interpolated_variable ) {
$code = $this->string_to_errorcode( 'InterpolatedVariable' . ucfirst( $arg_name ) );
$this->addMessage( 'The $%s arg must not contain interpolated variables. Found "$%s".', $stack_ptr, $is_error, $code, array( $arg_name, $interpolated_variable ) );
}
if ( ! empty( $interpolated_variables ) ) {
return false;
}
}
if ( isset( Tokens::$textStringTokens[ $tokens[0]['code'] ] ) ) {
if ( 'domain' === $arg_name && ! empty( $this->text_domain ) ) {
$stripped_content = $this->strip_quotes( $content );
if ( ! \in_array( $stripped_content, $this->text_domain, true ) ) {
$this->addMessage(
'Mismatched text domain. Expected \'%s\' but got %s.',
$stack_ptr,
$is_error,
'TextDomainMismatch',
array( implode( "' or '", $this->text_domain ), $content )
);
return false;
}
if ( true === $this->text_domain_is_default && 'default' === $stripped_content ) {
$fixable = false;
$error = 'No need to supply the text domain when the only accepted text domain is "default".';
$error_code = 'SuperfluousDefaultTextDomain';
if ( $tokens[0]['token_index'] === $stack_ptr ) {
$prev = $this->phpcsFile->findPrevious( \T_WHITESPACE, ( $stack_ptr - 1 ), null, true );
if ( false !== $prev && \T_COMMA === $this->tokens[ $prev ]['code'] ) {
$fixable = true;
}
}
if ( false === $fixable ) {
$this->phpcsFile->addWarning( $error, $stack_ptr, $error_code );
return false;
}
$fix = $this->phpcsFile->addFixableWarning( $error, $stack_ptr, $error_code );
if ( true === $fix ) {
// Remove preceeding comma, whitespace and the text domain token.
$this->phpcsFile->fixer->beginChangeset();
for ( $i = $prev; $i <= $stack_ptr; $i++ ) {
$this->phpcsFile->fixer->replaceToken( $i, '' );
}
$this->phpcsFile->fixer->endChangeset();
}
return false;
}
}
return true;
}
$code = $this->string_to_errorcode( 'NonSingularStringLiteral' . ucfirst( $arg_name ) );
$this->addMessage( 'The $%s arg must be a single string literal, not "%s".', $stack_ptr, $is_error, $code, array( $arg_name, $content ) );
return false;
}
/**
* Check for inconsistencies between single and plural arguments.
*
* @param int $stack_ptr The position of the current token in the stack.
* @param array $single_context Single context (@todo needs better description).
* @param array $plural_context Plural context (@todo needs better description).
* @return void
*/
protected function compare_single_and_plural_arguments( $stack_ptr, $single_context, $plural_context ) {
$single_content = $single_context['tokens'][0]['content'];
$plural_content = $plural_context['tokens'][0]['content'];
preg_match_all( self::SPRINTF_PLACEHOLDER_REGEX, $single_content, $single_placeholders );
$single_placeholders = $single_placeholders[0];
preg_match_all( self::SPRINTF_PLACEHOLDER_REGEX, $plural_content, $plural_placeholders );
$plural_placeholders = $plural_placeholders[0];
// English conflates "singular" with "only one", described in the codex:
// https://codex.wordpress.org/I18n_for_WordPress_Developers#Plurals .
if ( \count( $single_placeholders ) < \count( $plural_placeholders ) ) {
$error_string = 'Missing singular placeholder, needed for some languages. See https://codex.wordpress.org/I18n_for_WordPress_Developers#Plurals';
$single_index = $single_context['tokens'][0]['token_index'];
$this->phpcsFile->addError( $error_string, $single_index, 'MissingSingularPlaceholder' );
}
// Reordering is fine, but mismatched placeholders is probably wrong.
sort( $single_placeholders );
sort( $plural_placeholders );
if ( $single_placeholders !== $plural_placeholders ) {
$this->phpcsFile->addWarning( 'Mismatched placeholders is probably an error', $stack_ptr, 'MismatchedPlaceholders' );
}
}
/**
* Check the string itself for problems.
*
* @param array $context Context (@todo needs better description).
* @return void
*/
protected function check_text( $context ) {
$stack_ptr = $context['stack_ptr'];
$arg_name = $context['arg_name'];
$content = $context['tokens'][0]['content'];
$is_error = empty( $context['warning'] );
// UnorderedPlaceholders: Check for multiple unordered placeholders.
$unordered_matches_count = preg_match_all( self::UNORDERED_SPRINTF_PLACEHOLDER_REGEX, $content, $unordered_matches );
$unordered_matches = $unordered_matches[0];
$all_matches_count = preg_match_all( self::SPRINTF_PLACEHOLDER_REGEX, $content, $all_matches );
if ( $unordered_matches_count > 0 && $unordered_matches_count !== $all_matches_count && $all_matches_count > 1 ) {
$code = $this->string_to_errorcode( 'MixedOrderedPlaceholders' . ucfirst( $arg_name ) );
$this->phpcsFile->addError(
'Multiple placeholders should be ordered. Mix of ordered and non-ordered placeholders found. Found: %s.',
$stack_ptr,
$code,
array( implode( ', ', $all_matches[0] ) )
);
} elseif ( $unordered_matches_count >= 2 ) {
$code = $this->string_to_errorcode( 'UnorderedPlaceholders' . ucfirst( $arg_name ) );
$suggestions = array();
$replace_regexes = array();
$replacements = array();
for ( $i = 0; $i < $unordered_matches_count; $i++ ) {
$to_insert = ( $i + 1 );
$to_insert .= ( '"' !== $content[0] ) ? '$' : '\$';
$suggestions[ $i ] = substr_replace( $unordered_matches[ $i ], $to_insert, 1, 0 );
// Prepare the strings for use a regex.
$replace_regexes[ $i ] = '`\Q' . $unordered_matches[ $i ] . '\E`';
// Note: the initial \\ is a literal \, the four \ in the replacement translate to also to a literal \.
$replacements[ $i ] = str_replace( '\\', '\\\\', $suggestions[ $i ] );
// Note: the $ needs escaping to prevent numeric sequences after the $ being interpreted as match replacements.
$replacements[ $i ] = str_replace( '$', '\\$', $replacements[ $i ] );
}
$fix = $this->addFixableMessage(
'Multiple placeholders should be ordered. Expected \'%s\', but got %s.',
$stack_ptr,
$is_error,
$code,
array( implode( ', ', $suggestions ), implode( ', ', $unordered_matches ) )
);
if ( true === $fix ) {
$fixed_str = preg_replace( $replace_regexes, $replacements, $content, 1 );
$this->phpcsFile->fixer->replaceToken( $stack_ptr, $fixed_str );
}
}
/*
* NoEmptyStrings.
*
* Strip placeholders and surrounding quotes.
*/
$non_placeholder_content = trim( $this->strip_quotes( $content ) );
$non_placeholder_content = preg_replace( self::SPRINTF_PLACEHOLDER_REGEX, '', $non_placeholder_content );
if ( '' === $non_placeholder_content ) {
$this->phpcsFile->addError( 'Strings should have translatable content', $stack_ptr, 'NoEmptyStrings' );
}
}
/**
* Check for the presence of a translators comment if one of the text strings contains a placeholder.
*
* @param int $stack_ptr The position of the gettext call token in the stack.
* @param array $args The function arguments.
* @return void
*/
protected function check_for_translator_comment( $stack_ptr, $args ) {
foreach ( $args as $arg ) {
if ( false === \in_array( $arg['arg_name'], array( 'text', 'single', 'plural' ), true ) ) {
continue;
}
if ( empty( $arg['tokens'] ) ) {
continue;
}
foreach ( $arg['tokens'] as $token ) {
if ( empty( $token['content'] ) ) {
continue;
}
if ( preg_match( self::SPRINTF_PLACEHOLDER_REGEX, $token['content'], $placeholders ) < 1 ) {
// No placeholders found.
continue;
}
$previous_comment = $this->phpcsFile->findPrevious( Tokens::$commentTokens, ( $stack_ptr - 1 ) );
if ( false !== $previous_comment ) {
/*
* Check that the comment is either on the line before the gettext call or
* if it's not, that there is only whitespace between.
*/
$correctly_placed = false;
if ( ( $this->tokens[ $previous_comment ]['line'] + 1 ) === $this->tokens[ $stack_ptr ]['line'] ) {
$correctly_placed = true;
} else {
$next_non_whitespace = $this->phpcsFile->findNext( \T_WHITESPACE, ( $previous_comment + 1 ), $stack_ptr, true );
if ( false === $next_non_whitespace || $this->tokens[ $next_non_whitespace ]['line'] === $this->tokens[ $stack_ptr ]['line'] ) {
// No non-whitespace found or next non-whitespace is on same line as gettext call.
$correctly_placed = true;
}
unset( $next_non_whitespace );
}
/*
* Check that the comment starts with 'translators:'.
*/
if ( true === $correctly_placed ) {
if ( \T_COMMENT === $this->tokens[ $previous_comment ]['code'] ) {
$comment_text = trim( $this->tokens[ $previous_comment ]['content'] );
// If it's multi-line /* */ comment, collect all the parts.
if ( '*/' === substr( $comment_text, -2 ) && '/*' !== substr( $comment_text, 0, 2 ) ) {
for ( $i = ( $previous_comment - 1 ); 0 <= $i; $i-- ) {
if ( \T_COMMENT !== $this->tokens[ $i ]['code'] ) {
break;
}
$comment_text = trim( $this->tokens[ $i ]['content'] ) . $comment_text;
}
}
if ( true === $this->is_translators_comment( $comment_text ) ) {
// Comment is ok.
return;
}
} elseif ( \T_DOC_COMMENT_CLOSE_TAG === $this->tokens[ $previous_comment ]['code'] ) {
// If it's docblock comment (wrong style) make sure that it's a translators comment.
$db_start = $this->phpcsFile->findPrevious( \T_DOC_COMMENT_OPEN_TAG, ( $previous_comment - 1 ) );
$db_first_text = $this->phpcsFile->findNext( \T_DOC_COMMENT_STRING, ( $db_start + 1 ), $previous_comment );
if ( true === $this->is_translators_comment( $this->tokens[ $db_first_text ]['content'] ) ) {
$this->phpcsFile->addWarning(
'A "translators:" comment must be a "/* */" style comment. Docblock comments will not be picked up by the tools to generate a ".pot" file.',
$stack_ptr,
'TranslatorsCommentWrongStyle'
);
return;
}
}
}
}
// Found placeholders but no translators comment.
$this->phpcsFile->addWarning(
'A gettext call containing placeholders was found, but was not accompanied by a "translators:" comment on the line above to clarify the meaning of the placeholders.',
$stack_ptr,
'MissingTranslatorsComment'
);
return;
}
}
}
/**
* Check if a (collated) comment string starts with 'translators:'.
*
* @since 0.11.0
*
* @param string $content Comment string content.
* @return bool
*/
private function is_translators_comment( $content ) {
if ( preg_match( '`^(?:(?://|/\*{1,2}) )?translators:`i', $content, $matches ) === 1 ) {
return true;
}
return false;
}
}