Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions WordPressVIPMinimum/Sniffs/Constants/ConstantStringSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,26 @@ public function process_token( $stackPtr ) {
return;
}

$nextToken = $this->phpcsFile->findNext( Tokens::$emptyTokens, $nextToken + 1, null, true, null, true );
$param = $this->get_function_call_parameter( $stackPtr, 1 );
if ( $param === false ) {
// Target parameter not found.
return;
}

$search = Tokens::$emptyTokens;
$search[ T_STRING ] = T_STRING;

if ( $this->tokens[ $nextToken ]['code'] !== T_CONSTANT_ENCAPSED_STRING ) {
$message = 'Constant name, as a string, should be used along with `%s()`.';
$data = [ $this->tokens[ $stackPtr ]['content'] ];
$this->phpcsFile->addError( $message, $nextToken, 'NotCheckingConstantName', $data );
$has_only_tstring = $this->phpcsFile->findNext( $search, $param['start'], $param['end'] + 1, true );
if ( $has_only_tstring !== false ) {
// Came across something other than a T_STRING token. Ignore.
return;
}

$tstring_token = $this->phpcsFile->findNext( T_STRING, $param['start'], $param['end'] + 1 );

$message = 'Constant name, as a string, should be used along with `%s()`.';
$data = [ $this->tokens[ $stackPtr ]['content'] ];
$this->phpcsFile->addError( $message, $tstring_token, 'NotCheckingConstantName', $data );
}

}
30 changes: 27 additions & 3 deletions WordPressVIPMinimum/Tests/Constants/ConstantStringUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,30 @@ if ( ! defined( 'WPCOM_VIP' ) ) { // Okay.
define( 'WPCOM_VIP', true ); // Okay.
}

if ( ! defined( WPCOM_VIP ) ) { // NOK.
define( WPCOM_VIP ); // NOK.
}
if ( ! defined( WPCOM_VIP ) ) { // Error.
define( WPCOM_VIP, true ); // Error.
}

namespace Foo\Bar;
const REST_ALLOWED_META_PREFIXES = [ 'foo-', 'bar-', 'baz-' ];
if ( defined( __NAMESPACE__ . '\REST_ALLOWED_META_PREFIXES' ) && in_array( 'foo-', REST_ALLOWED_META_PREFIXES, true ) ) { // Ok.
define( __NAMESPACE__ . '\\' . REST_ALLOWED_META_PREFIXES[1], $value ); // OK.
}

define( __NAMESPACE__ . '\PLUGIN_URL', \plugins_url( '/', __FILE__ ) ); // OK.
if ( defined( __NAMESPACE__ . '\\LOADED' ) ) {} // OK.

if ( defined( $obj->constant_name_property ) === false ) { // OK.
define( $variable_containing_constant_name, $constant_value ); // OK.
}

if ( defined( MY_PREFIX . '_CONSTANT_NAME' ) === false ) { // OK.
define( 'PREFIX_' . $variable_part, $constant_value ); // OK.
}

if ( ! defined($generator->get()) { // OK.
define( $generator->getLast(), 'value'); // OK.
}

$defined = defined(); // OK, ignore.
$defined = defined( /*comment*/ ); // OK, ignore.