PHP_CodeSniffer_File::addTokenListener PHP Method

addTokenListener() public method

When PHP_CodeSniffer encounters on the the tokens specified in $tokens, it invokes the process method of the sniff.
public addTokenListener ( PHP_CodeSniffer_Sniff $listener, array $tokens ) : void
$listener PHP_CodeSniffer_Sniff The listener to add to the listener stack.
$tokens array
return void
    public function addTokenListener(PHP_CodeSniffer_Sniff $listener, array $tokens)
    {
        $class = get_class($listener);
        foreach ($tokens as $token) {
            if (isset($this->_listeners[$token]) === false) {
                $this->_listeners[$token] = array();
            }
            if (isset($this->_listeners[$token][$class]) === false) {
                $this->_listeners[$token][$class] = $listener;
            }
        }
    }

Usage Example

 /**
  * Processes the tokens that this test is listening for.
  *
  * @param PHP_CodeSniffer_File $phpcsFile The file where this token was found.
  * @param int                  $stackPtr  The position in the stack where this
  *                                        token was found.
  *
  * @return void
  * @see processTokenWithinScope()
  */
 public final function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     $file = $phpcsFile->getFilename();
     if ($this->currFile !== $file) {
         // We have changed files, so clean up.
         $this->currScope = null;
         $this->currFile = $file;
     }
     $tokens = $phpcsFile->getTokens();
     if (in_array($tokens[$stackPtr]['code'], $this->_scopeTokens) === true) {
         $this->currScope = $stackPtr;
         $phpcsFile->addTokenListener($this, $this->_tokens);
     } else {
         if ($this->currScope !== null && isset($tokens[$this->currScope]['scope_closer']) === true && $stackPtr > $tokens[$this->currScope]['scope_closer']) {
             $this->currScope = null;
             if ($this->_listenOutside === true) {
                 // This is a token outside the current scope, so notify the
                 // extender as they wish to know about this.
                 $this->processTokenOutsideScope($phpcsFile, $stackPtr);
             } else {
                 // Don't remove the listener if the extender wants to know about
                 // tokens that live outside the current scope.
                 $phpcsFile->removeTokenListener($this, $this->_tokens);
             }
         } else {
             if ($this->currScope !== null) {
                 $this->processTokenWithinScope($phpcsFile, $stackPtr, $this->currScope);
             } else {
                 $this->processTokenOutsideScope($phpcsFile, $stackPtr);
             }
         }
     }
 }