PHP Class PHP_CodeSniffer_File, PHP_CodeSniffer

It provides a means for traversing the token stack, along with other token related operations. If a PHP_CodeSniffer_Sniff finds and error or warning within a PHP_CodeSniffer_File, you can raise an error using the addError() or addWarning() methods. Token Information Each token within the stack contains information about itself: array( 'code' => 301, // the token type code (see token_get_all()) 'content' => 'if', // the token content 'type' => 'T_IF', // the token name 'line' => 56, // the line number when the token is located 'column' => 12, // the column in the line where this token starts (starts from 1) 'level' => 2 // the depth a token is within the scopes open 'conditions' => array( // a list of scope condition token positions => codes that 2 => 50, // opened the scopes that this token exists 9 => 353, // in (see conditional tokens section below) ), ); Conditional Tokens In addition to the standard token fields, conditions contain information to determine where their scope begins and ends: array( 'scope_condition' => 38, // the token position of the condition 'scope_opener' => 41, // the token position that started the scope 'scope_closer' => 70, // the token position that ended the scope ); The condition, the scope opener and the scope closer each contain this information. Parenthesis Tokens Each parenthesis token (T_OPEN_PARENTHESIS and T_CLOSE_PARENTHESIS) has a reference to their opening and closing parenthesis, one being itself, the other being its opposite. array( 'parenthesis_opener' => 34, 'parenthesis_closer' => 40, ); Some tokens can "own" a set of parenthesis. For example a T_FUNCTION token has parenthesis around its argument list. These tokens also have the parenthesis_opener and and parenthesis_closer indices. Not all parenthesis have owners, for example parenthesis used for arithmetic operations and function calls. The parenthesis tokens that have an owner have the following auxiliary array indices. array( 'parenthesis_opener' => 34, 'parenthesis_closer' => 40, 'parenthesis_owner' => 33, ); Each token within a set of parenthesis also has an array index 'nested_parenthesis' which is an array of the left parenthesis => right parenthesis token positions. 'nested_parenthesis' => array( 12 => 15 11 => 14 ); Extended Tokens PHP_CodeSniffer extends and augments some of the tokens created by token_get_all(). A full list of these tokens can be seen in the Tokens.php file.
Author: Greg Sherwood ([email protected])
Author: Marc McIntyre ([email protected])
Show file Open project: squizlabs/php_codesniffer Class Usage Examples

Public Properties

Property Type Description
$eolChar string The EOL character this file uses.
$fixer PHP_CodeSniffer_Fixer The Fixer object to control fixing errors.
$numTokens integer Stored here to save calling count() everywhere.
$phpcs PHP_CodeSniffer The PHP_CodeSniffer object controlling this run.
$tokenizer object The tokenizer being used for this file.
$tokenizerType string The tokenizer being used for this file.

Protected Properties

Property Type Description
$ruleset array This value gets set by PHP_CodeSniffer when the object is created. It may be empty, indicating that the ruleset does not override any of the default sniff settings.

Public Methods

Method Description
__construct ( string $file, array $listeners, array $ruleset, PHP_CodeSniffer $phpcs ) Constructs a PHP_CodeSniffer_File.
addError ( string $error, integer $stackPtr, string $code = '', array $data = [], integer $severity, boolean $fixable = false ) : boolean Records an error against a specific token in the file.
addErrorOnLine ( string $error, integer $line, string $code = '', array $data = [], integer $severity ) : boolean Records an error against a specific line in the file.
addFixableError ( string $error, integer $stackPtr, string $code = '', array $data = [], integer $severity ) : boolean Records a fixable error against a specific token in the file.
addFixableWarning ( string $warning, integer $stackPtr, string $code = '', array $data = [], integer $severity ) : boolean Records a fixable warning against a specific token in the file.
addTokenListener ( PHP_CodeSniffer_Sniff $listener, array $tokens ) : void Adds a listener to the token stack that listens to the specific tokens.
addWarning ( string $warning, integer $stackPtr, string $code = '', array $data = [], integer $severity, boolean $fixable = false ) : boolean Records a warning against a specific token in the file.
addWarningOnLine ( string $warning, integer $line, string $code = '', array $data = [], integer $severity ) : boolean Records a warning against a specific token in the file.
cleanUp ( ) : void Remove vars stored in this file that are no longer required.
detectLineEndings ( string $file, string $contents = null ) : string Opens a file and detects the EOL character being used.
findEndOfStatement ( integer $start, integer | array $ignore = null ) : integer Returns the position of the last non-whitespace token in a statement.
findExtendedClassName ( integer $stackPtr ) : string Returns the name of the class that the specified class extends.
findFirstOnLine ( integer | array $types, integer $start, boolean $exclude = false, string $value = null ) : integer | boolean Returns the position of the first token on a line, matching given type.
findImplementedInterfaceNames ( integer $stackPtr ) : array | false Returns the name(s) of the interface(s) that the specified class implements.
findNext ( integer | array $types, integer $start, integer $end = null, boolean $exclude = false, string $value = null, boolean $local = false ) : integer | boolean Returns the position of the next specified token(s).
findPrevious ( integer | array $types, integer $start, integer $end = null, boolean $exclude = false, string $value = null, boolean $local = false ) : integer | boolean Returns the position of the previous specified token(s).
findStartOfStatement ( integer $start, integer | array $ignore = null ) : integer Returns the position of the first non-whitespace token in a statement.
getClassProperties ( integer $stackPtr ) : array Returns the visibility and implementation properties of a class.
getCondition ( integer $stackPtr, integer $type ) : integer Return the position of the condition for the passed token.
getDeclarationName ( integer $stackPtr ) : string | null Returns the declaration names for T_CLASS, T_INTERFACE and T_FUNCTION tokens.
getErrorCount ( ) : integer Returns the number of errors raised.
getErrors ( ) : array Returns the errors raised from processing this file.
getFilename ( ) : string Returns the absolute filename of this file.
getFixableCount ( ) : integer Returns the number of fixable errors/warnings raised.
getIgnoredLines ( ) : array Returns the list of ignored lines.
getMemberProperties ( integer $stackPtr ) : array Returns the visibility and implementation properties of the class member variable found at the specified position in the stack.
getMethodParameters ( integer $stackPtr ) : array Returns the method parameters for the specified T_FUNCTION token.
getMethodProperties ( integer $stackPtr ) : array Returns the visibility and implementation properties of a method.
getMetrics ( ) : array Returns the metrics found while processing this file.
getSuccessCount ( ) : integer Returns the number of successes recorded.
getTokens ( ) : array Returns the token stack for this file.
getTokensAsString ( integer $start, integer $length ) : string Returns the content of the tokens from the specified start position in the token stack for the specified length.
getWarningCount ( ) : integer Returns the number of warnings raised.
getWarnings ( ) : array Returns the warnings raised from processing this file.
hasCondition ( integer $stackPtr, integer | array $types ) : boolean Determine if the passed token has a condition of one of the passed types.
isAnonymousFunction ( integer $stackPtr ) : boolean Check if the token at the specified position is a anonymous function.
isReference ( integer $stackPtr ) : boolean Determine if the passed token is a reference operator.
recordMetric ( integer $stackPtr, string $metric, string $value ) : boolean Adds an warning to the warning stack.
refreshTokenListeners ( ) : void Rebuilds the list of listeners to ensure their state is cleared.
removeTokenListener ( PHP_CodeSniffer_Sniff $listener, array $tokens ) : void Removes a listener from listening from the specified tokens.
setActiveListener ( string $activeListener ) : void Sets the name of the currently active sniff.
start ( string $contents = null ) : void Starts the stack traversal and tells listeners when tokens are found.
tokenizeString ( string $string, object $tokenizer, string $eolChar = '\n', integer $tabWidth = null, string $encoding = null ) : array Creates an array of tokens when given some PHP code.

Private Methods

Method Description
_addError ( string $error, integer $line, integer $column, string $code, array $data, integer $severity, boolean $fixable ) : boolean Adds an error to the error stack.
_addWarning ( string $warning, integer $line, integer $column, string $code, array $data, integer $severity, boolean $fixable ) : boolean Adds an warning to the warning stack.
_createLevelMap ( array &$tokens, object $tokenizer, string $eolChar ) : void Constructs the level map.
_createParenthesisNestingMap ( array &$tokens, object $tokenizer, string $eolChar ) : void Creates a map for the parenthesis tokens that surround other tokens.
_createPositionMap ( array &$tokens, object $tokenizer, string $eolChar, string $encoding, integer $tabWidth ) : void Sets token position information.
_createScopeMap ( array &$tokens, object $tokenizer, string $eolChar ) : void Creates a scope map of tokens that open scopes.
_createTokenMap ( array &$tokens, object $tokenizer, string $eolChar ) : void Creates a map of brackets positions.
_parse ( string $contents = null ) : void Tokenizes the file and prepares it for the test run.
_recurseScopeMap ( array &$tokens, integer $numTokens, object $tokenizer, string $eolChar, integer $stackPtr, integer $depth = 1, integer &$ignore ) : integer Recurses though the scope openers to build a scope map.

Method Details

__construct() public method

Constructs a PHP_CodeSniffer_File.
public __construct ( string $file, array $listeners, array $ruleset, PHP_CodeSniffer $phpcs )
$file string The absolute path to the file to process.
$listeners array
$ruleset array An array of rules from the ruleset.xml file. ruleset.xml file.
$phpcs PHP_CodeSniffer The PHP_CodeSniffer object controlling this run. this run.

addError() public method

Records an error against a specific token in the file.
public addError ( string $error, integer $stackPtr, string $code = '', array $data = [], integer $severity, boolean $fixable = false ) : boolean
$error string The error message.
$stackPtr integer The stack position where the error occurred.
$code string A violation code unique to the sniff message.
$data array Replacements for the error message.
$severity integer The severity level for this error. A value of 0 will be converted into the default severity level.
$fixable boolean Can the error be fixed by the sniff?
return boolean

addErrorOnLine() public method

Records an error against a specific line in the file.
public addErrorOnLine ( string $error, integer $line, string $code = '', array $data = [], integer $severity ) : boolean
$error string The error message.
$line integer The line on which the error occurred.
$code string A violation code unique to the sniff message.
$data array Replacements for the error message.
$severity integer The severity level for this error. A value of 0 will be converted into the default severity level.
return boolean

addFixableError() public method

Returns true if the error was recorded and should be fixed.
public addFixableError ( string $error, integer $stackPtr, string $code = '', array $data = [], integer $severity ) : boolean
$error string The error message.
$stackPtr integer The stack position where the error occurred.
$code string A violation code unique to the sniff message.
$data array Replacements for the error message.
$severity integer The severity level for this error. A value of 0 will be converted into the default severity level.
return boolean

addFixableWarning() public method

Returns true if the warning was recorded and should be fixed.
public addFixableWarning ( string $warning, integer $stackPtr, string $code = '', array $data = [], integer $severity ) : boolean
$warning string The error message.
$stackPtr integer The stack position where the error occurred.
$code string A violation code unique to the sniff message.
$data array Replacements for the warning message.
$severity integer The severity level for this warning. A value of 0 will be converted into the default severity level.
return boolean

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

addWarning() public method

Records a warning against a specific token in the file.
public addWarning ( string $warning, integer $stackPtr, string $code = '', array $data = [], integer $severity, boolean $fixable = false ) : boolean
$warning string The error message.
$stackPtr integer The stack position where the error occurred.
$code string A violation code unique to the sniff message.
$data array Replacements for the warning message.
$severity integer The severity level for this warning. A value of 0 will be converted into the default severity level.
$fixable boolean Can the warning be fixed by the sniff?
return boolean

addWarningOnLine() public method

Records a warning against a specific token in the file.
public addWarningOnLine ( string $warning, integer $line, string $code = '', array $data = [], integer $severity ) : boolean
$warning string The error message.
$line integer The line on which the warning occurred.
$code string A violation code unique to the sniff message.
$data array Replacements for the warning message.
$severity integer The severity level for this warning. A value of 0 will be converted into the default severity level.
return boolean

cleanUp() public method

Remove vars stored in this file that are no longer required.
public cleanUp ( ) : void
return void

detectLineEndings() public static method

Opens a file and detects the EOL character being used.
public static detectLineEndings ( string $file, string $contents = null ) : string
$file string The full path to the file.
$contents string The contents to parse. If NULL, the content is taken from the file system.
return string

findEndOfStatement() public method

Returns the position of the last non-whitespace token in a statement.
public findEndOfStatement ( integer $start, integer | array $ignore = null ) : integer
$start integer The position to start searching from in the token stack.
$ignore integer | array Token types that should not be considered stop points.
return integer

findExtendedClassName() public method

Returns FALSE on error or if there is no extended class name.
public findExtendedClassName ( integer $stackPtr ) : string
$stackPtr integer The stack position of the class.
return string

findFirstOnLine() public method

Returns false if no token can be found.
public findFirstOnLine ( integer | array $types, integer $start, boolean $exclude = false, string $value = null ) : integer | boolean
$types integer | array The type(s) of tokens to search for.
$start integer The position to start searching from in the token stack. The first token matching on this line before this token will be returned.
$exclude boolean If true, find the token that is NOT of the types specified in $types.
$value string The value that the token must be equal to. If value is omitted, tokens with any value will be returned.
return integer | boolean | bool

findImplementedInterfaceNames() public method

Returns FALSE on error or if there are no implemented interface names.
public findImplementedInterfaceNames ( integer $stackPtr ) : array | false
$stackPtr integer The stack position of the class.
return array | false

findNext() public method

If a value is specified, the next token of the specified type(s) containing the specified value will be returned. Returns false if no token can be found.
See also: findPrevious()
public findNext ( integer | array $types, integer $start, integer $end = null, boolean $exclude = false, string $value = null, boolean $local = false ) : integer | boolean
$types integer | array The type(s) of tokens to search for.
$start integer The position to start searching from in the token stack.
$end integer The end position to fail if no token is found. if not specified or null, end will default to the end of the token stack.
$exclude boolean If true, find the next token that is NOT of a type specified in $types.
$value string The value that the token(s) must be equal to. If value is omitted, tokens with any value will be returned.
$local boolean If true, tokens outside the current statement will not be checked. i.e., checking will stop at the next semi-colon found.
return integer | boolean

findPrevious() public method

If a value is specified, the previous token of the specified type(s) containing the specified value will be returned. Returns false if no token can be found.
See also: findNext()
public findPrevious ( integer | array $types, integer $start, integer $end = null, boolean $exclude = false, string $value = null, boolean $local = false ) : integer | boolean
$types integer | array The type(s) of tokens to search for.
$start integer The position to start searching from in the token stack.
$end integer The end position to fail if no token is found. if not specified or null, end will default to the start of the token stack.
$exclude boolean If true, find the previous token that are NOT of the types specified in $types.
$value string The value that the token(s) must be equal to. If value is omitted, tokens with any value will be returned.
$local boolean If true, tokens outside the current statement will not be checked. IE. checking will stop at the previous semi-colon found.
return integer | boolean

findStartOfStatement() public method

Returns the position of the first non-whitespace token in a statement.
public findStartOfStatement ( integer $start, integer | array $ignore = null ) : integer
$start integer The position to start searching from in the token stack.
$ignore integer | array Token types that should not be considered stop points.
return integer

getClassProperties() public method

The format of the array is: array( 'is_abstract' => false, // true if the abstract keyword was found. 'is_final' => false, // true if the final keyword was found. );
public getClassProperties ( integer $stackPtr ) : array
$stackPtr integer The position in the stack of the T_CLASS token to acquire the properties for.
return array

getCondition() public method

Returns FALSE if the token does not have the condition.
public getCondition ( integer $stackPtr, integer $type ) : integer
$stackPtr integer The position of the token we are checking.
$type integer The type of token to search for.
return integer

getDeclarationName() public method

Returns the declaration names for T_CLASS, T_INTERFACE and T_FUNCTION tokens.
public getDeclarationName ( integer $stackPtr ) : string | null
$stackPtr integer The position of the declaration token which declared the class, interface or function.
return string | null The name of the class, interface or function. or NULL if the function is a closure.

getErrorCount() public method

Returns the number of errors raised.
public getErrorCount ( ) : integer
return integer

getErrors() public method

Returns the errors raised from processing this file.
public getErrors ( ) : array
return array

getFilename() public method

Returns the absolute filename of this file.
public getFilename ( ) : string
return string

getFixableCount() public method

Returns the number of fixable errors/warnings raised.
public getFixableCount ( ) : integer
return integer

getIgnoredLines() public method

Returns the list of ignored lines.
public getIgnoredLines ( ) : array
return array

getMemberProperties() public method

The format of the array is: array( 'scope' => 'public', // public private or protected 'is_static' => false, // true if the static keyword was found. );
public getMemberProperties ( integer $stackPtr ) : array
$stackPtr integer The position in the stack of the T_VARIABLE token to acquire the properties for.
return array

getMethodParameters() public method

Each parameter is in the following format: 0 => array( 'name' => '$var', // The variable name. 'pass_by_reference' => false, // Passed by reference. 'type_hint' => string, // Type hint for array or custom type ) Parameters with default values have an additional array index of 'default' with the value of the default as a string.
public getMethodParameters ( integer $stackPtr ) : array
$stackPtr integer The position in the stack of the T_FUNCTION token to acquire the parameters for.
return array

getMethodProperties() public method

The format of the array is: array( 'scope' => 'public', // public private or protected 'scope_specified' => true, // true is scope keyword was found. 'is_abstract' => false, // true if the abstract keyword was found. 'is_final' => false, // true if the final keyword was found. 'is_static' => false, // true if the static keyword was found. 'is_closure' => false, // true if no name is found. );
public getMethodProperties ( integer $stackPtr ) : array
$stackPtr integer The position in the stack of the T_FUNCTION token to acquire the properties for.
return array

getMetrics() public method

Returns the metrics found while processing this file.
public getMetrics ( ) : array
return array

getSuccessCount() public method

Returns the number of successes recorded.
public getSuccessCount ( ) : integer
return integer

getTokens() public method

Returns the token stack for this file.
public getTokens ( ) : array
return array

getTokensAsString() public method

Returns the content of the tokens from the specified start position in the token stack for the specified length.
public getTokensAsString ( integer $start, integer $length ) : string
$start integer The position to start from in the token stack.
$length integer The length of tokens to traverse from the start pos.
return string The token contents.

getWarningCount() public method

Returns the number of warnings raised.
public getWarningCount ( ) : integer
return integer

getWarnings() public method

Returns the warnings raised from processing this file.
public getWarnings ( ) : array
return array

hasCondition() public method

Determine if the passed token has a condition of one of the passed types.
public hasCondition ( integer $stackPtr, integer | array $types ) : boolean
$stackPtr integer The position of the token we are checking.
$types integer | array The type(s) of tokens to search for.
return boolean

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

isReference() public method

Returns true if the specified token position represents a reference. Returns false if the token represents a bitwise operator.
public isReference ( integer $stackPtr ) : boolean
$stackPtr integer The position of the T_BITWISE_AND token.
return boolean

recordMetric() public method

Adds an warning to the warning stack.
public recordMetric ( integer $stackPtr, string $metric, string $value ) : boolean
$stackPtr integer The stack position where the metric was recorded.
$metric string The name of the metric being recorded.
$value string The value of the metric being recorded.
return boolean

refreshTokenListeners() public method

Rebuilds the list of listeners to ensure their state is cleared.
public refreshTokenListeners ( ) : void
return void

removeTokenListener() public method

Removes a listener from listening from the specified tokens.
public removeTokenListener ( PHP_CodeSniffer_Sniff $listener, array $tokens ) : void
$listener PHP_CodeSniffer_Sniff The listener to remove from the listener stack.
$tokens array
return void

setActiveListener() public method

Sets the name of the currently active sniff.
public setActiveListener ( string $activeListener ) : void
$activeListener string The class name of the current sniff.
return void

start() public method

Starts the stack traversal and tells listeners when tokens are found.
public start ( string $contents = null ) : void
$contents string The contents to parse. If NULL, the content is taken from the file system.
return void

tokenizeString() public static method

Starts by using token_get_all() but does a lot of extra processing to insert information about the context of the token.
public static tokenizeString ( string $string, object $tokenizer, string $eolChar = '\n', integer $tabWidth = null, string $encoding = null ) : array
$string string The string to tokenize.
$tokenizer object A tokenizer class to use to tokenize the string.
$eolChar string The EOL character to use for splitting strings.
$tabWidth integer The number of spaces each tab respresents.
$encoding string The charset of the sniffed file.
return array

Property Details

$eolChar public property

The EOL character this file uses.
public string $eolChar
return string

$fixer public property

The Fixer object to control fixing errors.
public PHP_CodeSniffer_Fixer $fixer
return PHP_CodeSniffer_Fixer

$numTokens public property

Stored here to save calling count() everywhere.
public int $numTokens
return integer

$phpcs public property

The PHP_CodeSniffer object controlling this run.
public PHP_CodeSniffer $phpcs
return PHP_CodeSniffer

$ruleset protected property

This value gets set by PHP_CodeSniffer when the object is created. It may be empty, indicating that the ruleset does not override any of the default sniff settings.
protected array $ruleset
return array

$tokenizer public property

The tokenizer being used for this file.
public object $tokenizer
return object

$tokenizerType public property

The tokenizer being used for this file.
public string $tokenizerType
return string