1<?php 2/** 3 * PEAR_Sniffs_Functions_ValidDefaultValueSniff. 4 * 5 * PHP version 5 6 * 7 * @category PHP 8 * @package PHP_CodeSniffer 9 * @author Greg Sherwood <gsherwood@squiz.net> 10 * @author Marc McIntyre <mmcintyre@squiz.net> 11 * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) 12 * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence 13 * @link http://pear.php.net/package/PHP_CodeSniffer 14 */ 15 16/** 17 * PEAR_Sniffs_Functions_ValidDefaultValueSniff. 18 * 19 * A Sniff to ensure that parameters defined for a function that have a default 20 * value come at the end of the function signature. 21 * 22 * @category PHP 23 * @package PHP_CodeSniffer 24 * @author Greg Sherwood <gsherwood@squiz.net> 25 * @author Marc McIntyre <mmcintyre@squiz.net> 26 * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) 27 * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence 28 * @version Release: @package_version@ 29 * @link http://pear.php.net/package/PHP_CodeSniffer 30 */ 31class PEAR_Sniffs_Functions_ValidDefaultValueSniff implements PHP_CodeSniffer_Sniff 32{ 33 34 35 /** 36 * Returns an array of tokens this test wants to listen for. 37 * 38 * @return array 39 */ 40 public function register() 41 { 42 return array( 43 T_FUNCTION, 44 T_CLOSURE, 45 ); 46 47 }//end register() 48 49 50 /** 51 * Processes this test, when one of its tokens is encountered. 52 * 53 * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. 54 * @param int $stackPtr The position of the current token in the 55 * stack passed in $tokens. 56 * 57 * @return void 58 */ 59 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) 60 { 61 $tokens = $phpcsFile->getTokens(); 62 63 $argStart = $tokens[$stackPtr]['parenthesis_opener']; 64 $argEnd = $tokens[$stackPtr]['parenthesis_closer']; 65 66 // Flag for when we have found a default in our arg list. 67 // If there is a value without a default after this, it is an error. 68 $defaultFound = false; 69 70 $params = $phpcsFile->getMethodParameters($stackPtr); 71 foreach ($params as $param) { 72 if ($param['variable_length'] === true) { 73 continue; 74 } 75 76 if (array_key_exists('default', $param) === true) { 77 $defaultFound = true; 78 // Check if the arg is type hinted and using NULL for the default. 79 // This does not make the argument optional - it just allows NULL 80 // to be passed in. 81 if ($param['type_hint'] !== '' && strtolower($param['default']) === 'null') { 82 $defaultFound = false; 83 } 84 85 continue; 86 } 87 88 if ($defaultFound === true) { 89 $error = 'Arguments with default values must be at the end of the argument list'; 90 $phpcsFile->addError($error, $param['token'], 'NotAtEnd'); 91 return; 92 } 93 }//end foreach 94 95 }//end process() 96 97 98}//end class 99