1<?php 2/** 3 * This file is part of the CodeAnalysis add-on for PHP_CodeSniffer. 4 * 5 * PHP version 5 6 * 7 * @category PHP 8 * @package PHP_CodeSniffer 9 * @author Greg Sherwood <gsherwood@squiz.net> 10 * @author Manuel Pichler <mapi@manuel-pichler.de> 11 * @copyright 2007-2014 Manuel Pichler. All rights reserved. 12 * @license http://www.opensource.org/licenses/bsd-license.php BSD License 13 * @link http://pear.php.net/package/PHP_CodeSniffer 14 */ 15 16/** 17 * Detects unconditional if- and elseif-statements. 18 * 19 * This rule is based on the PMD rule catalog. The Unconditional If Statement 20 * sniff detects statement conditions that are only set to one of the constant 21 * values <b>true</b> or <b>false</b> 22 * 23 * <code> 24 * class Foo 25 * { 26 * public function close() 27 * { 28 * if (true) 29 * { 30 * // ... 31 * } 32 * } 33 * } 34 * </code> 35 * 36 * @category PHP 37 * @package PHP_CodeSniffer 38 * @author Manuel Pichler <mapi@manuel-pichler.de> 39 * @copyright 2007-2014 Manuel Pichler. All rights reserved. 40 * @license http://www.opensource.org/licenses/bsd-license.php BSD License 41 * @version Release: @package_version@ 42 * @link http://pear.php.net/package/PHP_CodeSniffer 43 */ 44class Generic_Sniffs_CodeAnalysis_UnconditionalIfStatementSniff implements PHP_CodeSniffer_Sniff 45{ 46 47 48 /** 49 * Registers the tokens that this sniff wants to listen for. 50 * 51 * @return int[] 52 */ 53 public function register() 54 { 55 return array( 56 T_IF, 57 T_ELSEIF, 58 ); 59 60 }//end register() 61 62 63 /** 64 * Processes this test, when one of its tokens is encountered. 65 * 66 * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. 67 * @param int $stackPtr The position of the current token 68 * in the stack passed in $tokens. 69 * 70 * @return void 71 */ 72 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) 73 { 74 $tokens = $phpcsFile->getTokens(); 75 $token = $tokens[$stackPtr]; 76 77 // Skip for-loop without body. 78 if (isset($token['parenthesis_opener']) === false) { 79 return; 80 } 81 82 $next = ++$token['parenthesis_opener']; 83 $end = --$token['parenthesis_closer']; 84 85 $goodCondition = false; 86 for (; $next <= $end; ++$next) { 87 $code = $tokens[$next]['code']; 88 89 if (isset(PHP_CodeSniffer_Tokens::$emptyTokens[$code]) === true) { 90 continue; 91 } else if ($code !== T_TRUE && $code !== T_FALSE) { 92 $goodCondition = true; 93 } 94 } 95 96 if ($goodCondition === false) { 97 $error = 'Avoid IF statements that are always true or false'; 98 $phpcsFile->addWarning($error, $stackPtr, 'Found'); 99 } 100 101 }//end process() 102 103 104}//end class 105