PHP_CodeSniffer_File::isAnonymousFunction PHP Method

isAnonymousFunction() public method

Check if the token at the specified position is a anonymous function.
public isAnonymousFunction ( integer $stackPtr ) : boolean
$stackPtr integer The position of the declaration token which declared the class, interface or function.
return boolean
    public function isAnonymousFunction($stackPtr)
    {
        $tokenCode = $this->_tokens[$stackPtr]['code'];
        if ($tokenCode !== T_FUNCTION) {
            throw new PHP_CodeSniffer_Exception('Token type is not T_FUNCTION');
        }
        if (isset($this->_tokens[$stackPtr]['parenthesis_opener']) === false) {
            // Something is not right with this function.
            return false;
        }
        $name = false;
        for ($i = $stackPtr + 1; $i < $this->numTokens; $i++) {
            if ($this->_tokens[$i]['code'] === T_STRING) {
                $name = $i;
                break;
            }
        }
        if ($name === false) {
            // No name found.
            return true;
        }
        $open = $this->_tokens[$stackPtr]['parenthesis_opener'];
        if ($name > $open) {
            return true;
        }
        return false;
    }

Usage Example

 public function process(CodeSnifferFile $file, $stackPtr)
 {
     $tokens = $file->getTokens();
     if ($tokens[$stackPtr]['code'] === T_FUNCTION && $file->isAnonymousFunction($stackPtr)) {
         return;
     }
     $bracketPos = $file->findNext(T_OPEN_CURLY_BRACKET, $stackPtr, null, false, null, true);
     if (!$bracketPos) {
         return;
     }
     $symbolName = $file->getDeclarationName($stackPtr);
     $symbolType = $tokens[$stackPtr]['content'];
     if ($tokens[$bracketPos]['column'] !== 4 * $tokens[$stackPtr]['level'] + 1) {
         $file->addError('Opening bracket of "%s %s" must be in the next line', $stackPtr, sprintf('MissingNewline%sBrace', ucfirst($symbolType)), [$symbolType, $symbolName]);
     }
     $previousStringTokenPos = $file->findPrevious([T_STRING, T_CLOSE_PARENTHESIS], $bracketPos);
     if (1 + $tokens[$previousStringTokenPos]['line'] < $tokens[$bracketPos]['line']) {
         $file->addError('Exactly a single newline must follow after the declaration of "%s %s"', $stackPtr, sprintf('TooManyNewlines%sBrace', ucfirst($symbolType)), [$symbolType, $symbolName]);
     }
 }