PHP Class PHP_CodeSniffer, PHP_CodeSniffer

Standards are specified by classes that implement the PHP_CodeSniffer_Sniff interface. A sniff registers what token types it wishes to listen for, then PHP_CodeSniffer encounters that token, the sniff is invoked and passed information about where the token was found in the stack, and the token stack itself. Sniff files and their containing class must be prefixed with Sniff, and have an extension of .php. Multiple PHP_CodeSniffer operations can be performed by re-calling the process function with different parameters.
Author: Greg Sherwood ([email protected])
Author: Marc McIntyre ([email protected])
Mostrar archivo Open project: squizlabs/php_codesniffer Class Usage Examples

Public Properties

Property Type Description
$allowedFileExtensions array An array of extensions for files we will check.
$allowedTypes array(string) An array of variable types for param/var we will check.
$cli PHP_CodeSniffer_CLI The CLI object controlling the run.
$defaultFileExtensions array If no extensions are set, these will be used as the defaults. If extensions are set, these will be used when the correct tokenizer can not be determined, such as when checking a passed filename instead of files in a directory.
$reporting PHP_CodeSniffer_Reporting The Reporting object controlling report generation.
$sniffCodes The key is the sniff code and the value is the fully qualified name of the sniff class.

Protected Properties

Property Type Description
$file string The file or directory that is currently being processed.
$ignorePatterns array An array of patterns to use for skipping files.
$listeners array(PHP_CodeSniffer_Sniff) An array of sniff objects that are being used to check files.
$ruleset array It may be empty, indicating that the ruleset does not override any of the default sniff settings.
$rulesetDirs string This is declared static because it is also used in the autoloader to look for sniffs outside the PHPCS install. This way, standards designed to be installed inside PHPCS can also be used from outside the PHPCS Standards directory.
$sniffs array(string) An array of sniffs that are being used to check files.

Public Methods

Method Description
__construct ( integer $verbosity, integer $tabWidth, string $encoding = 'iso-8859-1', boolean $interactive = false ) Constructs a PHP_CodeSniffer object.
autoload ( string $className ) : void Autoload static method for loading classes and interfaces.
chdir ( string $path ) : void CodeSniffer alternative for chdir().
generateDocs ( string $standard, array $sniffs = [], string $generator = 'Text' ) : void Generates documentation for a coding standard.
getAllConfigData ( ) : array Get all config data in an array.
getConfigData ( string $key ) : string | null Get a single config value.
getFilesToProcess ( string $paths, boolean $local = false ) : array Get a list of files that will be processed.
getIgnorePatterns ( string $listener = null ) : array Gets the array of ignore patterns.
getInstalledStandardPath ( string $standard ) : string | null Return the path of an installed coding standard.
getInstalledStandardPaths ( ) : array Get a list paths where standards are installed.
getInstalledStandards ( boolean $includeGeneric = false, string $standardsDir = '' ) : array Get a list of all coding standards installed.
getSniffs ( ) : PHP_CodeSniffer_Sniff[] Gets the array of PHP_CodeSniffer_Sniff's.
getTokenSniffs ( ) : array Gets the array of PHP_CodeSniffer_Sniff's indexed by token type.
initStandard ( string | array $standards, array $restrictions = [], array $exclusions = [] ) : void Initialise the standard that the run will use.
isCamelCaps ( string $string, boolean $classFormat = false, boolean $public = true, boolean $strict = true ) : boolean Returns true if the specified string is in the camel caps format.
isInstalledStandard ( string $standard ) : boolean Determine if a standard is installed.
isPharFile ( string $path ) : mixed Return TRUE, if the path is a phar file.
isUnderscoreName ( string $string ) : boolean Returns true if the specified string is in the underscore caps format.
populateTokenListeners ( ) : void Populates the array of PHP_CodeSniffer_Sniff's for this file.
prepareForOutput ( string $content ) : string Prepares token content for output to screen.
process ( string | array $files, string | array $standards, array $restrictions = [], boolean $local = false ) : void Start a PHP_CodeSniffer run.
processFile ( string $file, string $contents = null ) : PHP_CodeSniffer_File Run the code sniffs over a single given file.
processFiles ( string | array $files, boolean $local = false ) : void Processes the files/directories that PHP_CodeSniffer was constructed with.
processRuleset ( string $rulesetPath, integer $depth ) : array Processes a single ruleset and returns a list of the sniffs it represents.
realpath ( string $path ) : mixed CodeSniffer alternative for realpath.
registerSniffs ( array $files, array $restrictions, array $exclusions ) : void Loads and stores sniffs objects used for sniffing files.
setAllowedFileExtensions ( array $extensions ) : void Sets an array of file extensions that we will allow checking of.
setCli ( object $cli ) : void Sets the internal CLI object.
setConfigData ( string $key, string | null $value, boolean $temp = false ) : boolean Set a single config value.
setEncoding ( string $encoding ) : void Sets the encoding.
setIgnorePatterns ( array $patterns ) : void Sets an array of ignore patterns that we use to skip files and folders.
setInteractive ( boolean $interactive ) : void Sets the interactive flag.
setSniffProperty ( string $listenerClass, string $name, string $value ) : void Set a single property for a sniff.
setTabWidth ( integer $tabWidth ) : void Sets the tab width.
setVerbosity ( integer $verbosity ) : void Sets the verbosity level.
shouldIgnoreFile ( string $path, string $basedir ) : boolean Checks filtering rules to see if a file should be ignored.
shouldProcessFile ( string $path, string $basedir ) : boolean Checks filtering rules to see if a file should be checked.
suggestType ( string $varType ) : string Returns a valid variable type for param/var tag.

Private Methods

Method Description
_expandRulesetReference ( string $ref, string $rulesetDir, integer $depth ) : array Expands a ruleset reference into a list of sniff files.
_expandSniffDirectory ( string $directory, integer $depth ) : array Expands a directory into a list of sniff files within.
_processFile ( string $file, string $contents ) : PHP_CodeSniffer_File Process the sniffs for a single file.
_processRule ( SimpleXMLElement $rule, integer $depth ) : void Processes a rule from a ruleset XML file, overriding built-in defaults.
_shouldProcessElement ( SimpleXMLElement $element, integer $depth ) : boolean Determine if an element should be processed or ignored.

Method Details

__construct() public method

Constructs a PHP_CodeSniffer object.
See also: process()
public __construct ( integer $verbosity, integer $tabWidth, string $encoding = 'iso-8859-1', boolean $interactive = false )
$verbosity integer The verbosity level. 1: Print progress information. 2: Print tokenizer debug information. 3: Print sniff debug information.
$tabWidth integer The number of spaces each tab represents. If greater than zero, tabs will be replaced by spaces before testing each file.
$encoding string The charset of the sniffed files. This is important for some reports that output with utf-8 encoding as you don't want it double encoding messages.
$interactive boolean If TRUE, will stop after each file with errors and wait for user input.

autoload() public static method

Autoload static method for loading classes and interfaces.
public static autoload ( string $className ) : void
$className string The name of the class or interface.
return void

chdir() public static method

Allows for phar support.
public static chdir ( string $path ) : void
$path string The path to use.
return void

generateDocs() public method

Generates documentation for a coding standard.
public generateDocs ( string $standard, array $sniffs = [], string $generator = 'Text' ) : void
$standard string The standard to generate docs for
$sniffs array A list of sniffs to limit the docs to.
$generator string The name of the generator class to use.
return void

getAllConfigData() public static method

Get all config data in an array.
See also: getConfigData()
public static getAllConfigData ( ) : array
return array

getConfigData() public static method

Config data is stored in the data dir, in a file called CodeSniffer.conf. It is a simple PHP array.
See also: setConfigData()
See also: getAllConfigData()
public static getConfigData ( string $key ) : string | null
$key string The name of the config value.
return string | null

getFilesToProcess() public method

If passed directories, this method will find all files within them. The method will also perform file extension and ignore pattern filtering.
See also: shouldProcessFile()
public getFilesToProcess ( string $paths, boolean $local = false ) : array
$paths string A list of file or directory paths to process.
$local boolean If true, only process 1 level of files in directories
return array

getIgnorePatterns() public method

Optionally takes a listener to get ignore patterns specified for that sniff only.
public getIgnorePatterns ( string $listener = null ) : array
$listener string The listener to get patterns for. If NULL, all patterns are returned.
return array

getInstalledStandardPath() public static method

Coding standards are directories located in the CodeSniffer/Standards directory. Valid coding standards include a ruleset.xml file.
public static getInstalledStandardPath ( string $standard ) : string | null
$standard string The name of the coding standard.
return string | null

getInstalledStandardPaths() public static method

Get a list paths where standards are installed.
public static getInstalledStandardPaths ( ) : array
return array

getInstalledStandards() public static method

Coding standards are directories located in the CodeSniffer/Standards directory. Valid coding standards include a Sniffs subdirectory.
See also: isInstalledStandard()
public static getInstalledStandards ( boolean $includeGeneric = false, string $standardsDir = '' ) : array
$includeGeneric boolean If true, the special "Generic" coding standard will be included if installed.
$standardsDir string A specific directory to look for standards in. If not specified, PHP_CodeSniffer will look in its default locations.
return array

getSniffs() public method

Gets the array of PHP_CodeSniffer_Sniff's.
public getSniffs ( ) : PHP_CodeSniffer_Sniff[]
return PHP_CodeSniffer_Sniff[]

getTokenSniffs() public method

Gets the array of PHP_CodeSniffer_Sniff's indexed by token type.
public getTokenSniffs ( ) : array
return array

initStandard() public method

Initialise the standard that the run will use.
public initStandard ( string | array $standards, array $restrictions = [], array $exclusions = [] ) : void
$standards string | array The set of code sniffs we are testing against.
$restrictions array The sniff codes to restrict the testing to.
$exclusions array The sniff codes to exclude from testing.
return void

isCamelCaps() public static method

Returns true if the specified string is in the camel caps format.
public static isCamelCaps ( string $string, boolean $classFormat = false, boolean $public = true, boolean $strict = true ) : boolean
$string string The string the verify.
$classFormat boolean If true, check to see if the string is in the class format. Class format strings must start with a capital letter and contain no underscores.
$public boolean If true, the first character in the string must be an a-z character. If false, the character must be an underscore. This argument is only applicable if $classFormat is false.
$strict boolean If true, the string must not have two capital letters next to each other. If false, a relaxed camel caps policy is used to allow for acronyms.
return boolean

isInstalledStandard() public static method

Coding standards are directories located in the CodeSniffer/Standards directory. Valid coding standards include a ruleset.xml file.
See also: getInstalledStandards()
public static isInstalledStandard ( string $standard ) : boolean
$standard string The name of the coding standard.
return boolean

isPharFile() public static method

Return TRUE, if the path is a phar file.
public static isPharFile ( string $path ) : mixed
$path string The path to use.
return mixed

isUnderscoreName() public static method

Returns true if the specified string is in the underscore caps format.
public static isUnderscoreName ( string $string ) : boolean
$string string The string to verify.
return boolean

populateTokenListeners() public method

Populates the array of PHP_CodeSniffer_Sniff's for this file.
public populateTokenListeners ( ) : void
return void

prepareForOutput() public static method

Replaces invisible characters so they are visible. On non-Windows OSes it will also colour the invisible characters.
public static prepareForOutput ( string $content ) : string
$content string The content to prepare.
return string

process() public method

Start a PHP_CodeSniffer run.
public process ( string | array $files, string | array $standards, array $restrictions = [], boolean $local = false ) : void
$files string | array The files and directories to process. For directories, each sub directory will also be traversed for source files.
$standards string | array The set of code sniffs we are testing against.
$restrictions array The sniff codes to restrict the violations to.
$local boolean If true, don't recurse into directories.
return void

processFile() public method

Processes the file and runs the PHP_CodeSniffer sniffs to verify that it conforms with the standard. Returns the processed file object, or NULL if no file was processed due to error.
See also: _processFile()
public processFile ( string $file, string $contents = null ) : PHP_CodeSniffer_File
$file string The file to process.
$contents string The contents to parse. If NULL, the content is taken from the file system.
return PHP_CodeSniffer_File

processFiles() public method

Processes the files/directories that PHP_CodeSniffer was constructed with.
public processFiles ( string | array $files, boolean $local = false ) : void
$files string | array The files and directories to process. For directories, each sub directory will also be traversed for source files.
$local boolean If true, don't recurse into directories.
return void

processRuleset() public method

Rules founds within the ruleset are processed immediately, but sniff classes are not registered by this method.
public processRuleset ( string $rulesetPath, integer $depth ) : array
$rulesetPath string The path to a ruleset XML file.
$depth integer How many nested processing steps we are in. This is only used for debug output.
return array

realpath() public static method

Allows for phar support.
public static realpath ( string $path ) : mixed
$path string The path to use.
return mixed

registerSniffs() public method

Loads and stores sniffs objects used for sniffing files.
public registerSniffs ( array $files, array $restrictions, array $exclusions ) : void
$files array Paths to the sniff files to register.
$restrictions array The sniff class names to restrict the allowed listeners to.
$exclusions array The sniff class names to exclude from the listeners list.
return void

setAllowedFileExtensions() public method

If the extension is one of the defaults, a specific tokenizer will be used. Otherwise, the PHP tokenizer will be used for all extensions passed.
public setAllowedFileExtensions ( array $extensions ) : void
$extensions array An array of file extensions.
return void

setCli() public method

Sets the internal CLI object.
public setCli ( object $cli ) : void
$cli object The CLI object controlling the run.
return void

setConfigData() public static method

Config data is stored in the data dir, in a file called CodeSniffer.conf. It is a simple PHP array.
See also: getConfigData()
public static setConfigData ( string $key, string | null $value, boolean $temp = false ) : boolean
$key string The name of the config value.
$value string | null The value to set. If null, the config entry is deleted, reverting it to the default value.
$temp boolean Set this config data temporarily for this script run. This will not write the config data to the config file.
return boolean

setEncoding() public method

Sets the encoding.
public setEncoding ( string $encoding ) : void
$encoding string The charset of the sniffed files. This is important for some reports that output with utf-8 encoding as you don't want it double encoding messages.
return void

setIgnorePatterns() public method

Patterns are not case sensitive.
public setIgnorePatterns ( array $patterns ) : void
$patterns array An array of ignore patterns. The pattern is the key and the value is either "absolute" or "relative", depending on how the pattern should be applied to a file path.
return void

setInteractive() public method

Sets the interactive flag.
public setInteractive ( boolean $interactive ) : void
$interactive boolean If TRUE, will stop after each file with errors and wait for user input.
return void

setSniffProperty() public method

Set a single property for a sniff.
public setSniffProperty ( string $listenerClass, string $name, string $value ) : void
$listenerClass string The class name of the sniff.
$name string The name of the property to change.
$value string The new value of the property.
return void

setTabWidth() public method

Sets the tab width.
public setTabWidth ( integer $tabWidth ) : void
$tabWidth integer The number of spaces each tab represents. If greater than zero, tabs will be replaced by spaces before testing each file.
return void

setVerbosity() public method

Sets the verbosity level.
public setVerbosity ( integer $verbosity ) : void
$verbosity integer The verbosity level. 1: Print progress information. 2: Print tokenizer debug information. 3: Print sniff debug information.
return void

shouldIgnoreFile() public method

Checks filtering rules to see if a file should be ignored.
public shouldIgnoreFile ( string $path, string $basedir ) : boolean
$path string The path to the file being checked.
$basedir string The directory to use for relative path checks.
return boolean

shouldProcessFile() public method

Checks both file extension filters and path ignore filters.
public shouldProcessFile ( string $path, string $basedir ) : boolean
$path string The path to the file being checked.
$basedir string The directory to use for relative path checks.
return boolean

suggestType() public static method

If type is not one of the standard type, it must be a custom type. Returns the correct type name suggestion if type name is invalid.
public static suggestType ( string $varType ) : string
$varType string The variable type to process.
return string

Property Details

$allowedFileExtensions public_oe property

An array of extensions for files we will check.
public array $allowedFileExtensions
return array

$allowedTypes public_oe static_oe property

An array of variable types for param/var we will check.
public static array(string) $allowedTypes
return array(string)

$cli public_oe property

The CLI object controlling the run.
public PHP_CodeSniffer_CLI $cli
return PHP_CodeSniffer_CLI

$defaultFileExtensions public_oe property

If no extensions are set, these will be used as the defaults. If extensions are set, these will be used when the correct tokenizer can not be determined, such as when checking a passed filename instead of files in a directory.
public array $defaultFileExtensions
return array

$file protected_oe property

The file or directory that is currently being processed.
protected string $file
return string

$ignorePatterns protected_oe property

An array of patterns to use for skipping files.
protected array $ignorePatterns
return array

$listeners protected_oe property

An array of sniff objects that are being used to check files.
protected array(PHP_CodeSniffer_Sniff) $listeners
return array(PHP_CodeSniffer_Sniff)

$reporting public_oe property

The Reporting object controlling report generation.
public PHP_CodeSniffer_Reporting $reporting
return PHP_CodeSniffer_Reporting

$ruleset protected_oe property

It may be empty, indicating that the ruleset does not override any of the default sniff settings.
protected array $ruleset
return array

$rulesetDirs protected_oe static_oe property

This is declared static because it is also used in the autoloader to look for sniffs outside the PHPCS install. This way, standards designed to be installed inside PHPCS can also be used from outside the PHPCS Standards directory.
protected static string $rulesetDirs
return string

$sniffCodes public_oe property

The key is the sniff code and the value is the fully qualified name of the sniff class.
public $sniffCodes

$sniffs protected_oe property

An array of sniffs that are being used to check files.
protected array(string) $sniffs
return array(string)