Skip to content

Instantly share code, notes, and snippets.

@codeinthehole
Created January 19, 2011 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeinthehole/787117 to your computer and use it in GitHub Desktop.
Save codeinthehole/787117 to your computer and use it in GitHub Desktop.
PHP_CodeSniffer sniff file for checking for idiotic ternary assignments
<?php
class TangentLabs_Sniffs_BestPractice_SensibleTernarysSniff implements PHP_CodeSniffer_Sniff
{
/**
* @return array
*/
public function register()
{
return array(T_INLINE_THEN);
}
/**
* @param PHP_CodeSniffer_File $phpcsFile
* @param int $stackPtr
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// Collect non-whitespace tokens within the true condition
$trueConditionTokens = array();
$foundColon = false;
$pointer = $stackPtr;
while (!$foundColon) {
$pointer += 1;
if ($tokens[$pointer]['code'] == T_COLON) {
$foundColon = true;
} elseif ($tokens[$pointer]['code'] != T_WHITESPACE) {
$trueConditionTokens[] = $tokens[$pointer];
}
}
// Collect non-whitespace tokens within the false condition
$falseConditionTokens = array();
$foundSemiColon = false;
while (!$foundSemiColon) {
$pointer += 1;
if ($tokens[$pointer]['code'] == T_SEMICOLON) {
$foundSemiColon = true;
} elseif ($tokens[$pointer]['code'] != T_WHITESPACE) {
$falseConditionTokens[] = $tokens[$pointer];
}
}
// Error if both the conditions are simple booleans
if ($this->isTokenSetABoolean($trueConditionTokens) &&
$this->isTokenSetABoolean($falseConditionTokens)) {
$error = 'Don\'t use true and false in ternary assignments - it\'s redundant' ;
$phpcsFile->addError($error, $stackPtr);
}
}
/**
* @param array $tokens
* @return boolean
*/
private function isTokenSetABoolean(array $tokens)
{
return count($tokens) == 1 && in_array($tokens[0]['code'], array(T_TRUE, T_FALSE));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment