Documentation

PHP_CodeSniffer
in package

PHP_CodeSniffer tokenizes PHP code and detects violations of a defined set of coding standards.

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.

Tags
category

PHP

author

Greg Sherwood gsherwood@squiz.net

author

Marc McIntyre mmcintyre@squiz.net

copyright

2006-2014 Squiz Pty Ltd (ABN 77 084 670 600)

license

https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence

version

Release: @package_version@

link
http://pear.php.net/package/PHP_CodeSniffer

Table of Contents

STABILITY  = 'stable'
Package stability; either stable, beta or alpha.
VERSION  = '2.9.2'
The current version.
$allowedFileExtensions  : array<string|int, mixed>
An array of extensions for files we will check.
$allowedTypes  : array<string|int, mixed>|(string)
An array of variable types for param/var we will check.
$cli  : PHP_CodeSniffer_CLI
The CLI object controlling the run.
$defaultFileExtensions  : array<string|int, mixed>
An array of default extensions and associated tokenizers.
$reporting  : PHP_CodeSniffer_Reporting
The Reporting object controlling report generation.
$sniffCodes  : array<string, string>
A mapping of sniff codes to fully qualified class names.
$file  : string
The file or directory that is currently being processed.
$ignorePatterns  : array<string|int, mixed>
An array of patterns to use for skipping files.
$listeners  : array<string|int, mixed>|(\PHP_CodeSniffer_Sniff)
An array of sniff objects that are being used to check files.
$ruleset  : array<string|int, mixed>
An array of rules from the ruleset.xml file.
$rulesetDirs  : string
The directories that the processed rulesets are in.
$sniffs  : array<string|int, mixed>|(string)
An array of sniffs that are being used to check files.
$_tokenListeners  : array<string|int, mixed>
The listeners array, indexed by token type.
__construct()  : mixed
Constructs a PHP_CodeSniffer object.
autoload()  : void
Autoload static method for loading classes and interfaces.
chdir()  : void
CodeSniffer alternative for chdir().
generateDocs()  : void
Generates documentation for a coding standard.
getAllConfigData()  : array<string, string>
Get all config data in an array.
getConfigData()  : string|null
Get a single config value.
getFilesToProcess()  : array<string|int, mixed>
Get a list of files that will be processed.
getIgnorePatterns()  : array<string|int, mixed>
Gets the array of ignore patterns.
getInstalledStandardPath()  : string|null
Return the path of an installed coding standard.
getInstalledStandardPaths()  : array<string|int, mixed>
Get a list paths where standards are installed.
getInstalledStandards()  : array<string|int, mixed>
Get a list of all coding standards installed.
getSniffs()  : array<string|int, PHP_CodeSniffer_Sniff>
Gets the array of PHP_CodeSniffer_Sniff's.
getTokenSniffs()  : array<string|int, mixed>
Gets the array of PHP_CodeSniffer_Sniff's indexed by token type.
initStandard()  : void
Initialise the standard that the run will use.
isCamelCaps()  : bool
Returns true if the specified string is in the camel caps format.
isInstalledStandard()  : bool
Determine if a standard is installed.
isPharFile()  : mixed
Return TRUE, if the path is a phar file.
isUnderscoreName()  : bool
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
Prepares token content for output to screen.
process()  : void
Start a PHP_CodeSniffer run.
processFile()  : PHP_CodeSniffer_File
Run the code sniffs over a single given file.
processFiles()  : void
Processes the files/directories that PHP_CodeSniffer was constructed with.
processRuleset()  : array<string|int, mixed>
Processes a single ruleset and returns a list of the sniffs it represents.
realpath()  : mixed
CodeSniffer alternative for realpath.
registerSniffs()  : void
Loads and stores sniffs objects used for sniffing files.
setAllowedFileExtensions()  : void
Sets an array of file extensions that we will allow checking of.
setCli()  : void
Sets the internal CLI object.
setConfigData()  : bool
Set a single config value.
setEncoding()  : void
Sets the encoding.
setIgnorePatterns()  : void
Sets an array of ignore patterns that we use to skip files and folders.
setInteractive()  : void
Sets the interactive flag.
setSniffProperty()  : void
Set a single property for a sniff.
setTabWidth()  : void
Sets the tab width.
setVerbosity()  : void
Sets the verbosity level.
shouldIgnoreFile()  : bool
Checks filtering rules to see if a file should be ignored.
shouldProcessFile()  : bool
Checks filtering rules to see if a file should be checked.
suggestType()  : string
Returns a valid variable type for param/var tag.
_expandRulesetReference()  : array<string|int, mixed>
Expands a ruleset reference into a list of sniff files.
_expandSniffDirectory()  : array<string|int, mixed>
Expands a directory into a list of sniff files within.
_processFile()  : PHP_CodeSniffer_File
Process the sniffs for a single file.
_processRule()  : void
Processes a rule from a ruleset XML file, overriding built-in defaults.
_shouldProcessElement()  : bool
Determine if an element should be processed or ignored.

Constants

STABILITY

Package stability; either stable, beta or alpha.

public string STABILITY = 'stable'

VERSION

The current version.

public string VERSION = '2.9.2'

Properties

$allowedFileExtensions

An array of extensions for files we will check.

public array<string|int, mixed> $allowedFileExtensions = array()

$allowedTypes

An array of variable types for param/var we will check.

public static array<string|int, mixed>|(string) $allowedTypes = array('array', 'boolean', 'float', 'integer', 'mixed', 'object', 'string', 'resource', 'callable')

$defaultFileExtensions

An array of default extensions and associated tokenizers.

public array<string|int, mixed> $defaultFileExtensions = array('php' => 'PHP', 'inc' => 'PHP', 'js' => 'JS', 'css' => 'CSS')

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.

$sniffCodes

A mapping of sniff codes to fully qualified class names.

public array<string, string> $sniffCodes = array()

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

$file

The file or directory that is currently being processed.

protected string $file = ''

$ignorePatterns

An array of patterns to use for skipping files.

protected array<string|int, mixed> $ignorePatterns = array()

$listeners

An array of sniff objects that are being used to check files.

protected array<string|int, mixed>|(\PHP_CodeSniffer_Sniff) $listeners = array()

$ruleset

An array of rules from the ruleset.xml file.

protected array<string|int, mixed> $ruleset = array()

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

$rulesetDirs

The directories that the processed rulesets are in.

protected static string $rulesetDirs = array()

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

An array of sniffs that are being used to check files.

protected array<string|int, mixed>|(string) $sniffs = array()

$_tokenListeners

The listeners array, indexed by token type.

private array<string|int, mixed> $_tokenListeners = array()

Methods

__construct()

Constructs a PHP_CodeSniffer object.

public __construct(int $verbosity, int $tabWidth[, string $encoding = 'iso-8859-1' ][, bool $interactive = false ]) : mixed
Parameters
$verbosity : int

The verbosity level. 1: Print progress information. 2: Print tokenizer debug information. 3: Print sniff debug information.

$tabWidth : int

The number of spaces each tab represents. If greater than zero, tabs will be replaced by spaces before testing each file.

$encoding : string = 'iso-8859-1'

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 : bool = false

If TRUE, will stop after each file with errors and wait for user input.

Tags
see
process()
Return values
mixed

autoload()

Autoload static method for loading classes and interfaces.

public static autoload(string $className) : void
Parameters
$className : string

The name of the class or interface.

Return values
void

chdir()

CodeSniffer alternative for chdir().

public static chdir(string $path) : void

Allows for phar support.

Parameters
$path : string

The path to use.

Return values
void

generateDocs()

Generates documentation for a coding standard.

public generateDocs(string $standard[, array<string|int, mixed> $sniffs = array() ][, string $generator = 'Text' ]) : void
Parameters
$standard : string

The standard to generate docs for

$sniffs : array<string|int, mixed> = array()

A list of sniffs to limit the docs to.

$generator : string = 'Text'

The name of the generator class to use.

Return values
void

getAllConfigData()

Get all config data in an array.

public static getAllConfigData() : array<string, string>
Tags
see
getConfigData()
Return values
array<string, string>

getConfigData()

Get a single config value.

public static getConfigData(string $key) : string|null

Config data is stored in the data dir, in a file called CodeSniffer.conf. It is a simple PHP array.

Parameters
$key : string

The name of the config value.

Tags
see
setConfigData()
see
getAllConfigData()
Return values
string|null

getFilesToProcess()

Get a list of files that will be processed.

public getFilesToProcess(string $paths[, bool $local = false ]) : array<string|int, mixed>

If passed directories, this method will find all files within them. The method will also perform file extension and ignore pattern filtering.

Parameters
$paths : string

A list of file or directory paths to process.

$local : bool = false

If true, only process 1 level of files in directories

Tags
throws
Exception

If there was an error opening a directory.

see
shouldProcessFile()
Return values
array<string|int, mixed>

getIgnorePatterns()

Gets the array of ignore patterns.

public getIgnorePatterns([string $listener = null ]) : array<string|int, mixed>

Optionally takes a listener to get ignore patterns specified for that sniff only.

Parameters
$listener : string = null

The listener to get patterns for. If NULL, all patterns are returned.

Return values
array<string|int, mixed>

getInstalledStandardPath()

Return the path of an installed coding standard.

public static getInstalledStandardPath(string $standard) : string|null

Coding standards are directories located in the CodeSniffer/Standards directory. Valid coding standards include a ruleset.xml file.

Parameters
$standard : string

The name of the coding standard.

Return values
string|null

getInstalledStandardPaths()

Get a list paths where standards are installed.

public static getInstalledStandardPaths() : array<string|int, mixed>
Return values
array<string|int, mixed>

getInstalledStandards()

Get a list of all coding standards installed.

public static getInstalledStandards([bool $includeGeneric = false ][, string $standardsDir = '' ]) : array<string|int, mixed>

Coding standards are directories located in the CodeSniffer/Standards directory. Valid coding standards include a Sniffs subdirectory.

Parameters
$includeGeneric : bool = false

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.

Tags
see
isInstalledStandard()
Return values
array<string|int, mixed>

getTokenSniffs()

Gets the array of PHP_CodeSniffer_Sniff's indexed by token type.

public getTokenSniffs() : array<string|int, mixed>
Return values
array<string|int, mixed>

initStandard()

Initialise the standard that the run will use.

public initStandard(string|array<string|int, mixed> $standards[, array<string|int, mixed> $restrictions = array() ][, array<string|int, mixed> $exclusions = array() ]) : void
Parameters
$standards : string|array<string|int, mixed>

The set of code sniffs we are testing against.

$restrictions : array<string|int, mixed> = array()

The sniff codes to restrict the testing to.

$exclusions : array<string|int, mixed> = array()

The sniff codes to exclude from testing.

Return values
void

isCamelCaps()

Returns true if the specified string is in the camel caps format.

public static isCamelCaps(string $string[, bool $classFormat = false ][, bool $public = true ][, bool $strict = true ]) : bool
Parameters
$string : string

The string the verify.

$classFormat : bool = false

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 : bool = true

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 : bool = true

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 values
bool

isInstalledStandard()

Determine if a standard is installed.

public static isInstalledStandard(string $standard) : bool

Coding standards are directories located in the CodeSniffer/Standards directory. Valid coding standards include a ruleset.xml file.

Parameters
$standard : string

The name of the coding standard.

Tags
see
getInstalledStandards()
Return values
bool

isPharFile()

Return TRUE, if the path is a phar file.

public static isPharFile(string $path) : mixed
Parameters
$path : string

The path to use.

Return values
mixed

isUnderscoreName()

Returns true if the specified string is in the underscore caps format.

public static isUnderscoreName(string $string) : bool
Parameters
$string : string

The string to verify.

Return values
bool

populateTokenListeners()

Populates the array of PHP_CodeSniffer_Sniff's for this file.

public populateTokenListeners() : void
Tags
throws
PHP_CodeSniffer_Exception

If sniff registration fails.

Return values
void

prepareForOutput()

Prepares token content for output to screen.

public static prepareForOutput(string $content) : string

Replaces invisible characters so they are visible. On non-Windows OSes it will also colour the invisible characters.

Parameters
$content : string

The content to prepare.

Return values
string

process()

Start a PHP_CodeSniffer run.

public process(string|array<string|int, mixed> $files, string|array<string|int, mixed> $standards[, array<string|int, mixed> $restrictions = array() ][, bool $local = false ]) : void
Parameters
$files : string|array<string|int, mixed>

The files and directories to process. For directories, each sub directory will also be traversed for source files.

$standards : string|array<string|int, mixed>

The set of code sniffs we are testing against.

$restrictions : array<string|int, mixed> = array()

The sniff codes to restrict the violations to.

$local : bool = false

If true, don't recurse into directories.

Return values
void

processFile()

Run the code sniffs over a single given file.

public processFile(string $file[, string $contents = null ]) : PHP_CodeSniffer_File

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.

Parameters
$file : string

The file to process.

$contents : string = null

The contents to parse. If NULL, the content is taken from the file system.

Tags
throws
PHP_CodeSniffer_Exception

If the file could not be processed.

see
_processFile()
Return values
PHP_CodeSniffer_File

processFiles()

Processes the files/directories that PHP_CodeSniffer was constructed with.

public processFiles(string|array<string|int, mixed> $files[, bool $local = false ]) : void
Parameters
$files : string|array<string|int, mixed>

The files and directories to process. For directories, each sub directory will also be traversed for source files.

$local : bool = false

If true, don't recurse into directories.

Tags
throws
PHP_CodeSniffer_Exception

If files are invalid.

Return values
void

processRuleset()

Processes a single ruleset and returns a list of the sniffs it represents.

public processRuleset(string $rulesetPath, int $depth) : array<string|int, mixed>

Rules founds within the ruleset are processed immediately, but sniff classes are not registered by this method.

Parameters
$rulesetPath : string

The path to a ruleset XML file.

$depth : int

How many nested processing steps we are in. This is only used for debug output.

Tags
throws
PHP_CodeSniffer_Exception

If the ruleset path is invalid.

Return values
array<string|int, mixed>

realpath()

CodeSniffer alternative for realpath.

public static realpath(string $path) : mixed

Allows for phar support.

Parameters
$path : string

The path to use.

Return values
mixed

registerSniffs()

Loads and stores sniffs objects used for sniffing files.

public registerSniffs(array<string|int, mixed> $files, array<string|int, mixed> $restrictions, array<string|int, mixed> $exclusions) : void
Parameters
$files : array<string|int, mixed>

Paths to the sniff files to register.

$restrictions : array<string|int, mixed>

The sniff class names to restrict the allowed listeners to.

$exclusions : array<string|int, mixed>

The sniff class names to exclude from the listeners list.

Tags
throws
PHP_CodeSniffer_Exception

If a sniff file path is invalid.

Return values
void

setAllowedFileExtensions()

Sets an array of file extensions that we will allow checking of.

public setAllowedFileExtensions(array<string|int, mixed> $extensions) : void

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.

Parameters
$extensions : array<string|int, mixed>

An array of file extensions.

Return values
void

setCli()

Sets the internal CLI object.

public setCli(object $cli) : void
Parameters
$cli : object

The CLI object controlling the run.

Return values
void

setConfigData()

Set a single config value.

public static setConfigData(string $key, string|null $value[, bool $temp = false ]) : bool

Config data is stored in the data dir, in a file called CodeSniffer.conf. It is a simple PHP array.

Parameters
$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 : bool = false

Set this config data temporarily for this script run. This will not write the config data to the config file.

Tags
see
getConfigData()
throws
PHP_CodeSniffer_Exception

If the config file can not be written.

Return values
bool

setEncoding()

Sets the encoding.

public setEncoding(string $encoding) : void
Parameters
$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 values
void

setIgnorePatterns()

Sets an array of ignore patterns that we use to skip files and folders.

public setIgnorePatterns(array<string|int, mixed> $patterns) : void

Patterns are not case sensitive.

Parameters
$patterns : array<string|int, mixed>

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 values
void

setInteractive()

Sets the interactive flag.

public setInteractive(bool $interactive) : void
Parameters
$interactive : bool

If TRUE, will stop after each file with errors and wait for user input.

Return values
void

setSniffProperty()

Set a single property for a sniff.

public setSniffProperty(string $listenerClass, string $name, string $value) : void
Parameters
$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 values
void

setTabWidth()

Sets the tab width.

public setTabWidth(int $tabWidth) : void
Parameters
$tabWidth : int

The number of spaces each tab represents. If greater than zero, tabs will be replaced by spaces before testing each file.

Return values
void

setVerbosity()

Sets the verbosity level.

public setVerbosity(int $verbosity) : void
Parameters
$verbosity : int

The verbosity level. 1: Print progress information. 2: Print tokenizer debug information. 3: Print sniff debug information.

Return values
void

shouldIgnoreFile()

Checks filtering rules to see if a file should be ignored.

public shouldIgnoreFile(string $path, string $basedir) : bool
Parameters
$path : string

The path to the file being checked.

$basedir : string

The directory to use for relative path checks.

Return values
bool

shouldProcessFile()

Checks filtering rules to see if a file should be checked.

public shouldProcessFile(string $path, string $basedir) : bool

Checks both file extension filters and path ignore filters.

Parameters
$path : string

The path to the file being checked.

$basedir : string

The directory to use for relative path checks.

Return values
bool

suggestType()

Returns a valid variable type for param/var tag.

public static suggestType(string $varType) : string

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.

Parameters
$varType : string

The variable type to process.

Return values
string

_expandRulesetReference()

Expands a ruleset reference into a list of sniff files.

private _expandRulesetReference(string $ref, string $rulesetDir, int $depth) : array<string|int, mixed>
Parameters
$ref : string

The reference from the ruleset XML file.

$rulesetDir : string

The directory of the ruleset XML file, used to evaluate relative paths.

$depth : int

How many nested processing steps we are in. This is only used for debug output.

Tags
throws
PHP_CodeSniffer_Exception

If the reference is invalid.

Return values
array<string|int, mixed>

_expandSniffDirectory()

Expands a directory into a list of sniff files within.

private _expandSniffDirectory(string $directory, int $depth) : array<string|int, mixed>
Parameters
$directory : string

The path to a directory.

$depth : int

How many nested processing steps we are in. This is only used for debug output.

Return values
array<string|int, mixed>

_processFile()

Process the sniffs for a single file.

private _processFile(string $file, string $contents) : PHP_CodeSniffer_File

Does raw processing only. No interactive support or error checking.

Parameters
$file : string

The file to process.

$contents : string

The contents to parse. If NULL, the content is taken from the file system.

Tags
see
processFile()
Return values
PHP_CodeSniffer_File

_processRule()

Processes a rule from a ruleset XML file, overriding built-in defaults.

private _processRule(SimpleXMLElement $rule, int $depth) : void
Parameters
$rule : SimpleXMLElement

The rule object from a ruleset XML file.

$depth : int

How many nested processing steps we are in. This is only used for debug output.

Return values
void

_shouldProcessElement()

Determine if an element should be processed or ignored.

private _shouldProcessElement(SimpleXMLElement $element, int $depth) : bool
Parameters
$element : SimpleXMLElement

An object from a ruleset XML file.

$depth : int

How many nested processing steps we are in. This is only used for debug output.

Return values
bool

Search results