Initial Commit

This commit is contained in:
Riley Schneider
2025-12-03 16:38:10 +01:00
parent c5e26bf594
commit b732d8d4b5
17680 changed files with 5977495 additions and 2 deletions

View File

@@ -0,0 +1,752 @@
<?php
/**
* A class to process command line phpcs scripts.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (is_file(dirname(__FILE__).'/../CodeSniffer.php') === true) {
include_once dirname(__FILE__).'/../CodeSniffer.php';
} else {
include_once 'PHP/CodeSniffer.php';
}
/**
* A class to process command line phpcs scripts.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_CLI
{
/**
* An array of all values specified on the command line.
*
* @var array
*/
protected $values = array();
/**
* The minimum severity level errors must have to be displayed.
*
* @var bool
*/
public $errorSeverity = 0;
/**
* The minimum severity level warnings must have to be displayed.
*
* @var bool
*/
public $warningSeverity = 0;
/**
* Exits if the minimum requirements of PHP_CodSniffer are not met.
*
* @return array
*/
public function checkRequirements()
{
// Check the PHP version.
if (version_compare(PHP_VERSION, '5.1.2') === -1) {
echo 'ERROR: PHP_CodeSniffer requires PHP version 5.1.2 or greater.'.PHP_EOL;
exit(2);
}
if (extension_loaded('tokenizer') === false) {
echo 'ERROR: PHP_CodeSniffer requires the tokenizer extension to be enabled.'.PHP_EOL;
exit(2);
}
}//end checkRequirements()
/**
* Get a list of default values for all possible command line arguments.
*
* @return array
*/
public function getDefaults()
{
// The default values for config settings.
$defaults['files'] = array();
$defaults['standard'] = null;
$defaults['verbosity'] = 0;
$defaults['interactive'] = false;
$defaults['local'] = false;
$defaults['showSources'] = false;
$defaults['extensions'] = array();
$defaults['sniffs'] = array();
$defaults['ignored'] = array();
$defaults['reportFile'] = null;
$defaults['generator'] = '';
$defaults['reports'] = array();
$reportFormat = PHP_CodeSniffer::getConfigData('report_format');
if ($reportFormat !== null) {
$defaults['reports'][$reportFormat] = null;
}
$defaults['warningSeverity'] = null;
$showWarnings = PHP_CodeSniffer::getConfigData('show_warnings');
if ($showWarnings !== null) {
$showWarnings = (bool) $showWarnings;
if ($showWarnings === false) {
$defaults['warningSeverity'] = 0;
}
}
$tabWidth = PHP_CodeSniffer::getConfigData('tab_width');
if ($tabWidth === null) {
$defaults['tabWidth'] = 0;
} else {
$defaults['tabWidth'] = (int) $tabWidth;
}
$encoding = PHP_CodeSniffer::getConfigData('encoding');
if ($encoding === null) {
$defaults['encoding'] = 'iso-8859-1';
} else {
$defaults['encoding'] = strtolower($encoding);
}
$severity = PHP_CodeSniffer::getConfigData('severity');
if ($severity === null) {
$defaults['errorSeverity'] = null;
$defaults['warningSeverity'] = null;
} else {
$defaults['errorSeverity'] = (int) $severity;
$defaults['warningSeverity'] = (int) $severity;
}
$severity = PHP_CodeSniffer::getConfigData('error_severity');
if ($severity === null) {
$defaults['errorSeverity'] = null;
} else {
$defaults['errorSeverity'] = (int) $severity;
}
$severity = PHP_CodeSniffer::getConfigData('warning_severity');
if ($severity === null) {
$defaults['warningSeverity'] = null;
} else {
$defaults['warningSeverity'] = (int) $severity;
}
$reportWidth = PHP_CodeSniffer::getConfigData('report_width');
if ($reportWidth === null) {
$defaults['reportWidth'] = 80;
} else {
$defaults['reportWidth'] = (int) $reportWidth;
}
$showProgress = PHP_CodeSniffer::getConfigData('show_progress');
if ($showProgress === null) {
$defaults['showProgress'] = false;
} else {
$defaults['showProgress'] = (bool) $showProgress;
}
return $defaults;
}//end getDefaults()
/**
* Process the command line arguments and returns the values.
*
* @return array
*/
public function getCommandLineValues()
{
if (empty($this->values) === false) {
return $this->values;
}
$values = $this->getDefaults();
for ($i = 1; $i < $_SERVER['argc']; $i++) {
$arg = $_SERVER['argv'][$i];
if ($arg === '') {
continue;
}
if ($arg{0} === '-') {
if ($arg === '-' || $arg === '--') {
// Empty argument, ignore it.
continue;
}
if ($arg{1} === '-') {
$values
= $this->processLongArgument(substr($arg, 2), $i, $values);
} else {
$switches = str_split($arg);
foreach ($switches as $switch) {
if ($switch === '-') {
continue;
}
$values = $this->processShortArgument($switch, $i, $values);
}
}
} else {
$values = $this->processUnknownArgument($arg, $i, $values);
}//end if
}//end for
$this->values = $values;
return $values;
}//end getCommandLineValues()
/**
* Processes a short (-e) command line argument.
*
* @param string $arg The command line argument.
* @param int $pos The position of the argument on the command line.
* @param array $values An array of values determined from CLI args.
*
* @return array The updated CLI values.
* @see getCommandLineValues()
*/
public function processShortArgument($arg, $pos, $values)
{
switch ($arg) {
case 'h':
case '?':
$this->printUsage();
exit(0);
break;
case 'i' :
$this->printInstalledStandards();
exit(0);
break;
case 'v' :
$values['verbosity']++;
break;
case 'l' :
$values['local'] = true;
break;
case 's' :
$values['showSources'] = true;
break;
case 'a' :
$values['interactive'] = true;
break;
case 'p' :
$values['showProgress'] = true;
break;
case 'd' :
$ini = explode('=', $_SERVER['argv'][($pos + 1)]);
$_SERVER['argv'][($pos + 1)] = '';
if (isset($ini[1]) === true) {
ini_set($ini[0], $ini[1]);
} else {
ini_set($ini[0], true);
}
break;
case 'n' :
$values['warningSeverity'] = 0;
break;
case 'w' :
$values['warningSeverity'] = null;
break;
default:
$values = $this->processUnknownArgument('-'.$arg, $pos, $values);
}//end switch
return $values;
}//end processShortArgument()
/**
* Processes a long (--example) command line argument.
*
* @param string $arg The command line argument.
* @param int $pos The position of the argument on the command line.
* @param array $values An array of values determined from CLI args.
*
* @return array The updated CLI values.
* @see getCommandLineValues()
*/
public function processLongArgument($arg, $pos, $values)
{
switch ($arg) {
case 'help':
$this->printUsage();
exit(0);
break;
case 'version':
echo 'PHP_CodeSniffer version 1.3.3 (stable) ';
echo 'by Squiz Pty Ltd. (http://www.squiz.net)'.PHP_EOL;
exit(0);
break;
case 'config-set':
$key = $_SERVER['argv'][($pos + 1)];
$value = $_SERVER['argv'][($pos + 2)];
PHP_CodeSniffer::setConfigData($key, $value);
exit(0);
break;
case 'config-delete':
$key = $_SERVER['argv'][($pos + 1)];
PHP_CodeSniffer::setConfigData($key, null);
exit(0);
break;
case 'config-show':
$data = PHP_CodeSniffer::getAllConfigData();
print_r($data);
exit(0);
break;
default:
if (substr($arg, 0, 7) === 'sniffs=') {
$values['sniffs'] = array();
$sniffs = substr($arg, 7);
$sniffs = explode(',', $sniffs);
// Convert the sniffs to class names.
foreach ($sniffs as $sniff) {
$parts = explode('.', $sniff);
$values['sniffs'][] = $parts[0].'_Sniffs_'.$parts[1].'_'.$parts[2].'Sniff';
}
} else if (substr($arg, 0, 12) === 'report-file=') {
$values['reportFile'] = realpath(substr($arg, 12));
// It may not exist and return false instead.
if ($values['reportFile'] === false) {
$values['reportFile'] = substr($arg, 12);
}
if (is_dir($values['reportFile']) === true) {
echo 'ERROR: The specified report file path "'.$values['reportFile'].'" is a directory.'.PHP_EOL.PHP_EOL;
$this->printUsage();
exit(2);
}
$dir = dirname($values['reportFile']);
if (is_dir($dir) === false) {
echo 'ERROR: The specified report file path "'.$values['reportFile'].'" points to a non-existent directory.'.PHP_EOL.PHP_EOL;
$this->printUsage();
exit(2);
}
} else if (substr($arg, 0, 13) === 'report-width=') {
$values['reportWidth'] = (int) substr($arg, 13);
} else if (substr($arg, 0, 7) === 'report='
|| substr($arg, 0, 7) === 'report-'
) {
if ($arg[6] === '-') {
// This is a report with file output.
$split = strpos($arg, '=');
if ($split === false) {
$report = substr($arg, 7);
$output = null;
} else {
$report = substr($arg, 7, ($split - 7));
$output = substr($arg, ($split + 1));
if ($output === false) {
$output = null;
}
}
} else {
// This is a single report.
$report = substr($arg, 7);
$output = null;
}
$validReports = array(
'full',
'xml',
'checkstyle',
'csv',
'emacs',
'source',
'summary',
'svnblame',
'gitblame',
'hgblame',
);
if (in_array($report, $validReports) === false) {
echo 'ERROR: Report type "'.$report.'" not known.'.PHP_EOL;
exit(2);
}
$values['reports'][$report] = $output;
} else if (substr($arg, 0, 9) === 'standard=') {
$values['standard'] = substr($arg, 9);
} else if (substr($arg, 0, 11) === 'extensions=') {
$values['extensions'] = explode(',', substr($arg, 11));
} else if (substr($arg, 0, 9) === 'severity=') {
$values['errorSeverity'] = (int) substr($arg, 9);
$values['warningSeverity'] = $values['errorSeverity'];
} else if (substr($arg, 0, 15) === 'error-severity=') {
$values['errorSeverity'] = (int) substr($arg, 15);
} else if (substr($arg, 0, 17) === 'warning-severity=') {
$values['warningSeverity'] = (int) substr($arg, 17);
} else if (substr($arg, 0, 7) === 'ignore=') {
// Split the ignore string on commas, unless the comma is escaped
// using 1 or 3 slashes (\, or \\\,).
$values['ignored'] = preg_split(
'/(?<=(?<!\\\\)\\\\\\\\),|(?<!\\\\),/',
substr($arg, 7)
);
} else if (substr($arg, 0, 10) === 'generator=') {
$values['generator'] = substr($arg, 10);
} else if (substr($arg, 0, 9) === 'encoding=') {
$values['encoding'] = strtolower(substr($arg, 9));
} else if (substr($arg, 0, 10) === 'tab-width=') {
$values['tabWidth'] = (int) substr($arg, 10);
} else {
$values = $this->processUnknownArgument('--'.$arg, $pos, $values);
}//end if
break;
}//end switch
return $values;
}//end processLongArgument()
/**
* Processes an unknown command line argument.
*
* Assumes all unknown arguments are files and folders to check.
*
* @param string $arg The command line argument.
* @param int $pos The position of the argument on the command line.
* @param array $values An array of values determined from CLI args.
*
* @return array The updated CLI values.
* @see getCommandLineValues()
*/
public function processUnknownArgument($arg, $pos, $values)
{
// We don't know about any additional switches; just files.
if ($arg{0} === '-') {
echo 'ERROR: option "'.$arg.'" not known.'.PHP_EOL.PHP_EOL;
$this->printUsage();
exit(2);
}
$file = realpath($arg);
if (file_exists($file) === false) {
echo 'ERROR: The file "'.$arg.'" does not exist.'.PHP_EOL.PHP_EOL;
$this->printUsage();
exit(2);
} else {
$values['files'][] = $file;
}
return $values;
}//end processUnknownArgument()
/**
* Runs PHP_CodeSniffer over files and directories.
*
* @param array $values An array of values determined from CLI args.
*
* @return int The number of error and warning messages shown.
* @see getCommandLineValues()
*/
public function process($values=array())
{
if (empty($values) === true) {
$values = $this->getCommandLineValues();
}
if ($values['generator'] !== '') {
$phpcs = new PHP_CodeSniffer($values['verbosity']);
$phpcs->generateDocs(
$values['standard'],
$values['files'],
$values['generator']
);
exit(0);
}
$fileContents = '';
if (empty($values['files']) === true) {
// Check if they passing in the file contents.
$handle = fopen('php://stdin', 'r');
$fileContents = stream_get_contents($handle);
fclose($handle);
if ($fileContents === '') {
// No files and no content passed in.
echo 'ERROR: You must supply at least one file or directory to process.'.PHP_EOL.PHP_EOL;
$this->printUsage();
exit(2);
}
}
$values['standard'] = $this->validateStandard($values['standard']);
if (PHP_CodeSniffer::isInstalledStandard($values['standard']) === false) {
// They didn't select a valid coding standard, so help them
// out by letting them know which standards are installed.
echo 'ERROR: the "'.$values['standard'].'" coding standard is not installed. ';
$this->printInstalledStandards();
exit(2);
}
$phpcs = new PHP_CodeSniffer(
$values['verbosity'],
$values['tabWidth'],
$values['encoding'],
$values['interactive']
);
// Set file extensions if they were specified. Otherwise,
// let PHP_CodeSniffer decide on the defaults.
if (empty($values['extensions']) === false) {
$phpcs->setAllowedFileExtensions($values['extensions']);
}
// Set ignore patterns if they were specified.
if (empty($values['ignored']) === false) {
$phpcs->setIgnorePatterns($values['ignored']);
}
// Set some convenience member vars.
if ($values['errorSeverity'] === null) {
$this->errorSeverity = PHPCS_DEFAULT_ERROR_SEV;
} else {
$this->errorSeverity = $values['errorSeverity'];
}
if ($values['warningSeverity'] === null) {
$this->warningSeverity = PHPCS_DEFAULT_WARN_SEV;
} else {
$this->warningSeverity = $values['warningSeverity'];
}
$phpcs->setCli($this);
$phpcs->process(
$values['files'],
$values['standard'],
$values['sniffs'],
$values['local']
);
if ($fileContents !== '') {
$phpcs->processFile('STDIN', $fileContents);
}
return $this->printErrorReport(
$phpcs,
$values['reports'],
$values['showSources'],
$values['reportFile'],
$values['reportWidth']
);
}//end process()
/**
* Prints the error report for the run.
*
* Note that this function may actually print multiple reports
* as the user may have specified a number of output formats.
*
* @param PHP_CodeSniffer $phpcs The PHP_CodeSniffer object containing
* the errors.
* @param array $reports A list of reports to print.
* @param bool $showSources TRUE if report should show error sources
* (not used by all reports).
* @param string $reportFile A default file to log report output to.
* @param int $reportWidth How wide the screen reports should be.
*
* @return int The number of error and warning messages shown.
*/
public function printErrorReport(
PHP_CodeSniffer $phpcs,
$reports,
$showSources,
$reportFile,
$reportWidth
) {
$reporting = new PHP_CodeSniffer_Reporting();
$filesViolations = $phpcs->getFilesErrors();
if (empty($reports) === true) {
$reports['full'] = $reportFile;
}
$errors = 0;
$toScreen = false;
foreach ($reports as $report => $output) {
if ($output === null) {
$output = $reportFile;
}
if ($reportFile === null) {
$toScreen = true;
}
// We don't add errors here because the number of
// errors reported by each report type will always be the
// same, so we really just need 1 number.
$errors = $reporting->printReport(
$report,
$filesViolations,
$showSources,
$output,
$reportWidth
);
}
// Only print PHP_Timer output if no reports were
// printed to the screen so we don't put additional output
// in something like an XML report. If we are printing to screen,
// the report types would have already worked out who should
// print the timer info.
if ($toScreen === false
&& PHP_CODESNIFFER_INTERACTIVE === false
&& class_exists('PHP_Timer', false) === true
) {
echo PHP_Timer::resourceUsage().PHP_EOL.PHP_EOL;
}
// They should all return the same value, so it
// doesn't matter which return value we end up using.
return $errors;
}//end printErrorReport()
/**
* Convert the passed standard into a valid standard.
*
* Checks things like default values and case.
*
* @param string $standard The standard to validate.
*
* @return string
*/
public function validateStandard($standard)
{
if ($standard === null) {
// They did not supply a standard to use.
// Try to get the default from the config system.
$standard = PHP_CodeSniffer::getConfigData('default_standard');
if ($standard === null) {
$standard = 'PEAR';
}
}
// Check if the standard name is valid. If not, check that the case
// was not entered incorrectly.
if (PHP_CodeSniffer::isInstalledStandard($standard) === false) {
$installedStandards = PHP_CodeSniffer::getInstalledStandards();
foreach ($installedStandards as $validStandard) {
if (strtolower($standard) === strtolower($validStandard)) {
$standard = $validStandard;
break;
}
}
}
return $standard;
}//end validateStandard()
/**
* Prints out the usage information for this script.
*
* @return void
*/
public function printUsage()
{
echo 'Usage: phpcs [-nwlsapvi] [-d key[=value]]'.PHP_EOL;
echo ' [--report=<report>] [--report-file=<reportfile>] [--report-<report>=<reportfile>] ...'.PHP_EOL;
echo ' [--report-width=<reportWidth>] [--generator=<generator>] [--tab-width=<tabWidth>]'.PHP_EOL;
echo ' [--severity=<severity>] [--error-severity=<severity>] [--warning-severity=<severity>]'.PHP_EOL;
echo ' [--config-set key value] [--config-delete key] [--config-show]'.PHP_EOL;
echo ' [--standard=<standard>] [--sniffs=<sniffs>] [--encoding=<encoding>]'.PHP_EOL;
echo ' [--extensions=<extensions>] [--ignore=<patterns>] <file> ...'.PHP_EOL;
echo ' -n Do not print warnings (shortcut for --warning-severity=0)'.PHP_EOL;
echo ' -w Print both warnings and errors (on by default)'.PHP_EOL;
echo ' -l Local directory only, no recursion'.PHP_EOL;
echo ' -s Show sniff codes in all reports'.PHP_EOL;
echo ' -a Run interactively'.PHP_EOL;
echo ' -p Show progress of the run'.PHP_EOL;
echo ' -v[v][v] Print verbose output'.PHP_EOL;
echo ' -i Show a list of installed coding standards'.PHP_EOL;
echo ' -d Set the [key] php.ini value to [value] or [true] if value is omitted'.PHP_EOL;
echo ' --help Print this help message'.PHP_EOL;
echo ' --version Print version information'.PHP_EOL;
echo ' <file> One or more files and/or directories to check'.PHP_EOL;
echo ' <extensions> A comma separated list of file extensions to check'.PHP_EOL;
echo ' (only valid if checking a directory)'.PHP_EOL;
echo ' <patterns> A comma separated list of patterns to ignore files and directories'.PHP_EOL;
echo ' <encoding> The encoding of the files being checked (default is iso-8859-1)'.PHP_EOL;
echo ' <sniffs> A comma separated list of sniff codes to limit the check to'.PHP_EOL;
echo ' (all sniffs must be part of the specified standard)'.PHP_EOL;
echo ' <severity> The minimum severity required to display an error or warning'.PHP_EOL;
echo ' <standard> The name or path of the coding standard to use'.PHP_EOL;
echo ' <tabWidth> The number of spaces each tab represents'.PHP_EOL;
echo ' <generator> The name of a doc generator to use'.PHP_EOL;
echo ' (forces doc generation instead of checking)'.PHP_EOL;
echo ' <report> Print either the "full", "xml", "checkstyle", "csv", "emacs"'.PHP_EOL;
echo ' "source", "summary", "svnblame", "gitblame" or "hgblame" report'.PHP_EOL;
echo ' (the "full" report is printed by default)'.PHP_EOL;
echo ' <reportfile> Write the report to the specified file path'.PHP_EOL;
echo ' <reportWidth> How many columns wide screen reports should be printed'.PHP_EOL;
}//end printUsage()
/**
* Prints out a list of installed coding standards.
*
* @return void
*/
public function printInstalledStandards()
{
$installedStandards = PHP_CodeSniffer::getInstalledStandards();
$numStandards = count($installedStandards);
if ($numStandards === 0) {
echo 'No coding standards are installed.'.PHP_EOL;
} else {
$lastStandard = array_pop($installedStandards);
if ($numStandards === 1) {
echo "The only coding standard installed is $lastStandard".PHP_EOL;
} else {
$standardList = implode(', ', $installedStandards);
$standardList .= ' and '.$lastStandard;
echo 'The installed coding standards are '.$standardList.PHP_EOL;
}
}
}//end printInstalledStandards()
}//end class
?>

View File

@@ -0,0 +1,353 @@
<?php
/**
* A class to handle most of the parsing operations of a doc comment element.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (interface_exists('PHP_CodeSniffer_CommentParser_DocElement', true) === false) {
$error = 'Interface PHP_CodeSniffer_CommentParser_DocElement not found';
throw new PHP_CodeSniffer_Exception($error);
}
/**
* A class to handle most of the parsing operations of a doc comment element.
*
* Extending classes should implement the getSubElements method to return
* a list of elements that the doc comment element contains, in the order that
* they appear in the element. For example a function parameter element has a
* type, a variable name and a comment. It should therefore implement the method
* as follows:
*
* <code>
* protected function getSubElements()
* {
* return array(
* 'type',
* 'variable',
* 'comment',
* );
* }
* </code>
*
* The processSubElement will be called for each of the sub elements to allow
* the extending class to process them. So for the parameter element we would
* have:
*
* <code>
* protected function processSubElement($name, $content, $whitespaceBefore)
* {
* if ($name === 'type') {
* echo 'The name of the variable was '.$content;
* }
* // Process other tags.
* }
* </code>
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
abstract class PHP_CodeSniffer_CommentParser_AbstractDocElement implements PHP_CodeSniffer_CommentParser_DocElement
{
/**
* The element previous to this element.
*
* @var PHP_CodeSniffer_CommentParser_DocElement
*/
protected $previousElement = null;
/**
* The element proceeding this element.
*
* @var PHP_CodeSniffer_CommentParser_DocElement
*/
protected $nextElement = null;
/**
* The whitespace the occurs after this element and its sub elements.
*
* @var string
*/
protected $afterWhitespace = '';
/**
* The tokens that comprise this element.
*
* @var array(string)
*/
protected $tokens = array();
/**
* The file this element is in.
*
* @var array(string)
*/
protected $phpcsFile = null;
/**
* The tag that this element represents (omiting the @ symbol).
*
* @var string
*/
protected $tag = '';
/**
* Constructs a Doc Element.
*
* @param PHP_CodeSniffer_CommentParser_DocElement $previousElement The element
* that ocurred
* before this.
* @param array $tokens The tokens of
* this element.
* @param string $tag The doc
* element tag
* this element
* represents.
* @param PHP_CodeSniffer_File $phpcsFile The file that
* this element
* is in.
*
* @throws Exception If $previousElement in not a DocElement or if
* getSubElements() does not return an array.
*/
public function __construct(
$previousElement,
array $tokens,
$tag,
PHP_CodeSniffer_File $phpcsFile
) {
if ($previousElement !== null
&& ($previousElement instanceof PHP_CodeSniffer_CommentParser_DocElement) === false
) {
$error = '$previousElement must be an instance of DocElement';
throw new Exception($error);
}
$this->phpcsFile = $phpcsFile;
$this->previousElement = $previousElement;
if ($previousElement !== null) {
$this->previousElement->nextElement = $this;
}
$this->tag = $tag;
$this->tokens = $tokens;
$subElements = $this->getSubElements();
if (is_array($subElements) === false) {
throw new Exception('getSubElements() must return an array');
}
$whitespace = '';
$currElem = 0;
$lastElement = '';
$lastElementWhitespace = null;
$numSubElements = count($subElements);
foreach ($this->tokens as $token) {
if (trim($token) === '') {
$whitespace .= $token;
} else {
if ($currElem < ($numSubElements - 1)) {
$element = $subElements[$currElem];
$this->processSubElement($element, $token, $whitespace);
$whitespace = '';
$currElem++;
} else {
if ($lastElementWhitespace === null) {
$lastElementWhitespace = $whitespace;
}
$lastElement .= $whitespace.$token;
$whitespace = '';
}
}
}//end foreach
$lastElement = ltrim($lastElement);
$lastElementName = $subElements[($numSubElements - 1)];
// Process the last element in this tag.
$this->processSubElement(
$lastElementName,
$lastElement,
$lastElementWhitespace
);
$this->afterWhitespace = $whitespace;
}//end __construct()
/**
* Returns the element that exists before this.
*
* @return PHP_CodeSniffer_CommentParser_DocElement
*/
public function getPreviousElement()
{
return $this->previousElement;
}//end getPreviousElement()
/**
* Returns the element that exists after this.
*
* @return PHP_CodeSniffer_CommentParser_DocElement
*/
public function getNextElement()
{
return $this->nextElement;
}//end getNextElement()
/**
* Returns the whitespace that exists before this element.
*
* @return string
*/
public function getWhitespaceBefore()
{
if ($this->previousElement !== null) {
return $this->previousElement->getWhitespaceAfter();
}
return '';
}//end getWhitespaceBefore()
/**
* Returns the whitespace that exists after this element.
*
* @return string
*/
public function getWhitespaceAfter()
{
return $this->afterWhitespace;
}//end getWhitespaceAfter()
/**
* Returns the order that this element appears in the comment.
*
* @return int
*/
public function getOrder()
{
if ($this->previousElement === null) {
return 1;
} else {
return ($this->previousElement->getOrder() + 1);
}
}//end getOrder()
/**
* Returns the tag that this element represents, ommiting the @ symbol.
*
* @return string
*/
public function getTag()
{
return $this->tag;
}//end getTag()
/**
* Returns the raw content of this element, ommiting the tag.
*
* @return string
*/
public function getRawContent()
{
return implode('', $this->tokens);
}//end getRawContent()
/**
* Returns the comment tokens.
*
* @return array
*/
public function getTokens()
{
return $this->tokens;
}//end getTokens()
/**
* Returns the line in which this element first occured.
*
* @return int
*/
public function getLine()
{
if ($this->previousElement === null) {
// First element is on line one.
return 1;
} else {
$previousContent = $this->previousElement->getRawContent();
$previousLine = $this->previousElement->getLine();
return ($previousLine + substr_count($previousContent, $this->phpcsFile->eolChar));
}
}//end getLine()
/**
* Returns the sub element names that make up this element in the order they
* appear in the element.
*
* @return array(string)
* @see processSubElement()
*/
abstract protected function getSubElements();
/**
* Called to process each sub element as sepcified in the return value
* of getSubElements().
*
* @param string $name The name of the element to process.
* @param string $content The content of the the element.
* @param string $whitespaceBefore The whitespace found before this element.
*
* @return void
* @see getSubElements()
*/
abstract protected function processSubElement(
$name,
$content,
$whitespaceBefore
);
}//end class
?>

View File

@@ -0,0 +1,684 @@
<?php
/**
* Parses doc comments.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (class_exists('PHP_CodeSniffer_CommentParser_SingleElement', true) === false) {
$error = 'Class PHP_CodeSniffer_CommentParser_SingleElement not found';
throw new PHP_CodeSniffer_Exception($error);
}
if (class_exists('PHP_CodeSniffer_CommentParser_CommentElement', true) === false) {
$error = 'Class PHP_CodeSniffer_CommentParser_CommentElement not found';
throw new PHP_CodeSniffer_Exception($error);
}
if (class_exists('PHP_CodeSniffer_CommentParser_ParserException', true) === false) {
$error = 'Class PHP_CodeSniffer_CommentParser_ParserException not found';
throw new PHP_CodeSniffer_Exception($error);
}
/**
* Parses doc comments.
*
* This abstract parser handles the following tags:
*
* <ul>
* <li>The short description and the long description</li>
* <li>@see</li>
* <li>@link</li>
* <li>@deprecated</li>
* <li>@since</li>
* </ul>
*
* Extending classes should implement the getAllowedTags() method to return the
* tags that they wish to process, ommiting the tags that this base class
* processes. When one of these tags in encountered, the process&lt;tag_name&gt;
* method is called on that class. For example, if a parser's getAllowedTags()
* method returns \@param as one of its tags, the processParam method will be
* called so that the parser can process such a tag.
*
* The method is passed the tokens that comprise this tag. The tokens array
* includes the whitespace that exists between the tokens, as seperate tokens.
* It's up to the method to create a element that implements the DocElement
* interface, which should be returned. The AbstractDocElement class is a helper
* class that can be used to handle most of the parsing of the tokens into their
* individual sub elements. It requires that you construct it with the element
* previous to the element currently being processed, which can be acquired
* with the protected $previousElement class member of this class.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
abstract class PHP_CodeSniffer_CommentParser_AbstractParser
{
/**
* The comment element that appears in the doc comment.
*
* @var PHP_CodeSniffer_CommentParser_CommentElement
*/
protected $comment = null;
/**
* The string content of the comment.
*
* @var string
*/
protected $commentString = '';
/**
* The file that the comment exists in.
*
* @var PHP_CodeSniffer_File
*/
protected $phpcsFile = null;
/**
* The word tokens that appear in the comment.
*
* Whitespace tokens also appear in this stack, but are separate tokens
* from words.
*
* @var array(string)
*/
protected $words = array();
/**
* An array of all tags found in the comment.
*
* @var array(string)
*/
protected $foundTags = array();
/**
* The previous doc element that was processed.
*
* null if the current element being processed is the first element in the
* doc comment.
*
* @var PHP_CodeSniffer_CommentParser_DocElement
*/
protected $previousElement = null;
/**
* A list of see elements that appear in this doc comment.
*
* @var array(PHP_CodeSniffer_CommentParser_SingleElement)
*/
protected $sees = array();
/**
* A list of see elements that appear in this doc comment.
*
* @var array(PHP_CodeSniffer_CommentParser_SingleElement)
*/
protected $deprecated = null;
/**
* A list of see elements that appear in this doc comment.
*
* @var array(PHP_CodeSniffer_CommentParser_SingleElement)
*/
protected $links = array();
/**
* A element to represent \@since tags.
*
* @var PHP_CodeSniffer_CommentParser_SingleElement
*/
protected $since = null;
/**
* True if the comment has been parsed.
*
* @var boolean
*/
private $_hasParsed = false;
/**
* The tags that this class can process.
*
* @var array(string)
*/
private static $_tags = array(
'see' => false,
'link' => false,
'deprecated' => true,
'since' => true,
);
/**
* An array of unknown tags.
*
* @var array(string)
*/
public $unknown = array();
/**
* The order of tags.
*
* @var array(string)
*/
public $orders = array();
/**
* Constructs a Doc Comment Parser.
*
* @param string $comment The comment to parse.
* @param PHP_CodeSniffer_File $phpcsFile The file that this comment is in.
*/
public function __construct($comment, PHP_CodeSniffer_File $phpcsFile)
{
$this->commentString = $comment;
$this->phpcsFile = $phpcsFile;
}//end __construct()
/**
* Initiates the parsing of the doc comment.
*
* @return void
* @throws PHP_CodeSniffer_CommentParser_ParserException If the parser finds a
* problem with the
* comment.
*/
public function parse()
{
if ($this->_hasParsed === false) {
$this->_parse($this->commentString);
}
}//end parse()
/**
* Parse the comment.
*
* @param string $comment The doc comment to parse.
*
* @return void
* @see _parseWords()
*/
private function _parse($comment)
{
// Firstly, remove the comment tags and any stars from the left side.
$lines = explode($this->phpcsFile->eolChar, $comment);
foreach ($lines as &$line) {
$line = trim($line);
if ($line !== '') {
if (substr($line, 0, 3) === '/**') {
$line = substr($line, 3);
} else if (substr($line, -2, 2) === '*/') {
$line = substr($line, 0, -2);
} else if ($line{0} === '*') {
$line = substr($line, 1);
}
// Add the words to the stack, preserving newlines. Other parsers
// might be interested in the spaces between words, so tokenize
// spaces as well as separate tokens.
$flags = (PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$words = preg_split(
'|(\s+)|',
$line.$this->phpcsFile->eolChar,
-1,
$flags
);
$this->words = array_merge($this->words, $words);
}//end if
}//end foreach
$this->_parseWords();
}//end _parse()
/**
* Parses each word within the doc comment.
*
* @return void
* @see _parse()
* @throws PHP_CodeSniffer_CommentParser_ParserException If more than the allowed
* number of occurances of
* a tag is found.
*/
private function _parseWords()
{
$allowedTags = (self::$_tags + $this->getAllowedTags());
$allowedTagNames = array_keys($allowedTags);
$prevTagPos = false;
$wordWasEmpty = true;
foreach ($this->words as $wordPos => $word) {
if (trim($word) !== '') {
$wordWasEmpty = false;
}
if ($word{0} === '@') {
$tag = substr($word, 1);
// Filter out @ tags in the comment description.
// A real comment tag should have whitespace and a newline before it.
if (isset($this->words[($wordPos - 1)]) === false
|| trim($this->words[($wordPos - 1)]) !== ''
) {
continue;
}
if (isset($this->words[($wordPos - 2)]) === false
|| $this->words[($wordPos - 2)] !== $this->phpcsFile->eolChar
) {
continue;
}
$this->foundTags[] = array(
'tag' => $tag,
'line' => $this->getLine($wordPos),
'pos' => $wordPos,
);
if ($prevTagPos !== false) {
// There was a tag before this so let's process it.
$prevTag = substr($this->words[$prevTagPos], 1);
$this->parseTag($prevTag, $prevTagPos, ($wordPos - 1));
} else {
// There must have been a comment before this tag, so
// let's process that.
$this->parseTag('comment', 0, ($wordPos - 1));
}
$prevTagPos = $wordPos;
if (in_array($tag, $allowedTagNames) === false) {
// This is not a tag that we process, but let's check to
// see if it is a tag we know about. If we don't know about it,
// we add it to a list of unknown tags.
$knownTags = array(
'abstract',
'access',
'example',
'filesource',
'global',
'ignore',
'internal',
'name',
'static',
'staticvar',
'todo',
'tutorial',
'uses',
'package_version@',
);
if (in_array($tag, $knownTags) === false) {
$this->unknown[] = array(
'tag' => $tag,
'line' => $this->getLine($wordPos),
'pos' => $wordPos,
);
}
}//end if
}//end if
}//end foreach
// Only process this tag if there was something to process.
if ($wordWasEmpty === false) {
if ($prevTagPos === false) {
// There must only be a comment in this doc comment.
$this->parseTag('comment', 0, count($this->words));
} else {
// Process the last tag element.
$prevTag = substr($this->words[$prevTagPos], 1);
$numWords = count($this->words);
$endPos = $numWords;
if ($prevTag === 'package' || $prevTag === 'subpackage') {
// These are single-word tags, so anything after a newline
// is really a comment.
for ($endPos = $prevTagPos; $endPos < $numWords; $endPos++) {
if (strpos($this->words[$endPos], $this->phpcsFile->eolChar) !== false) {
break;
}
}
}
$this->parseTag($prevTag, $prevTagPos, $endPos);
if ($endPos !== $numWords) {
// Process the final comment, if it is not empty.
$tokens = array_slice($this->words, ($endPos + 1), $numWords);
$content = implode('', $tokens);
if (trim($content) !== '') {
$this->parseTag('comment', ($endPos + 1), $numWords);
}
}
}//end if
}//end if
}//end _parseWords()
/**
* Returns the line that the token exists on in the doc comment.
*
* @param int $tokenPos The position in the words stack to find the line
* number for.
*
* @return int
*/
protected function getLine($tokenPos)
{
$newlines = 0;
for ($i = 0; $i < $tokenPos; $i++) {
$newlines += substr_count($this->phpcsFile->eolChar, $this->words[$i]);
}
return $newlines;
}//end getLine()
/**
* Parses see tag element within the doc comment.
*
* @param array(string) $tokens The word tokens that comprise this element.
*
* @return DocElement The element that represents this see comment.
*/
protected function parseSee($tokens)
{
$see = new PHP_CodeSniffer_CommentParser_SingleElement(
$this->previousElement,
$tokens,
'see',
$this->phpcsFile
);
$this->sees[] = $see;
return $see;
}//end parseSee()
/**
* Parses the comment element that appears at the top of the doc comment.
*
* @param array(string) $tokens The word tokens that comprise tihs element.
*
* @return DocElement The element that represents this comment element.
*/
protected function parseComment($tokens)
{
$this->comment = new PHP_CodeSniffer_CommentParser_CommentElement(
$this->previousElement,
$tokens,
$this->phpcsFile
);
return $this->comment;
}//end parseComment()
/**
* Parses \@deprecated tags.
*
* @param array(string) $tokens The word tokens that comprise tihs element.
*
* @return DocElement The element that represents this deprecated tag.
*/
protected function parseDeprecated($tokens)
{
$this->deprecated = new PHP_CodeSniffer_CommentParser_SingleElement(
$this->previousElement,
$tokens,
'deprecated',
$this->phpcsFile
);
return $this->deprecated;
}//end parseDeprecated()
/**
* Parses \@since tags.
*
* @param array(string) $tokens The word tokens that comprise this element.
*
* @return SingleElement The element that represents this since tag.
*/
protected function parseSince($tokens)
{
$this->since = new PHP_CodeSniffer_CommentParser_SingleElement(
$this->previousElement,
$tokens,
'since',
$this->phpcsFile
);
return $this->since;
}//end parseSince()
/**
* Parses \@link tags.
*
* @param array(string) $tokens The word tokens that comprise this element.
*
* @return SingleElement The element that represents this link tag.
*/
protected function parseLink($tokens)
{
$link = new PHP_CodeSniffer_CommentParser_SingleElement(
$this->previousElement,
$tokens,
'link',
$this->phpcsFile
);
$this->links[] = $link;
return $link;
}//end parseLink()
/**
* Returns the see elements that appear in this doc comment.
*
* @return array(SingleElement)
*/
public function getSees()
{
return $this->sees;
}//end getSees()
/**
* Returns the comment element that appears at the top of this doc comment.
*
* @return CommentElement
*/
public function getComment()
{
return $this->comment;
}//end getComment()
/**
* Returns the word list.
*
* @return array
*/
public function getWords()
{
return $this->words;
}//end getWords()
/**
* Returns the list of found tags.
*
* @return array
*/
public function getTags()
{
return $this->foundTags;
}//end getTags()
/**
* Returns the link elements found in this comment.
*
* Returns an empty array if no links are found in the comment.
*
* @return array(SingleElement)
*/
public function getLinks()
{
return $this->links;
}//end getLinks()
/**
* Returns the deprecated element found in this comment.
*
* Returns null if no element exists in the comment.
*
* @return SingleElement
*/
public function getDeprecated()
{
return $this->deprecated;
}//end getDeprecated()
/**
* Returns the since element found in this comment.
*
* Returns null if no element exists in the comment.
*
* @return SingleElement
*/
public function getSince()
{
return $this->since;
}//end getSince()
/**
* Parses the specified tag.
*
* @param string $tag The tag name to parse (omitting the @ sybmol from
* the tag)
* @param int $start The position in the word tokens where this element
* started.
* @param int $end The position in the word tokens where this element
* ended.
*
* @return void
* @throws Exception If the process method for the tag cannot be found.
*/
protected function parseTag($tag, $start, $end)
{
$tokens = array_slice($this->words, ($start + 1), ($end - $start));
$allowedTags = (self::$_tags + $this->getAllowedTags());
$allowedTagNames = array_keys($allowedTags);
if ($tag === 'comment' || in_array($tag, $allowedTagNames) === true) {
$method = 'parse'.$tag;
if (method_exists($this, $method) === false) {
$error = 'Method '.$method.' must be implemented to process '.$tag.' tags';
throw new Exception($error);
}
$this->previousElement = $this->$method($tokens);
} else {
$this->previousElement = new PHP_CodeSniffer_CommentParser_SingleElement(
$this->previousElement,
$tokens,
$tag,
$this->phpcsFile
);
}
$this->orders[] = $tag;
if ($this->previousElement === null
|| ($this->previousElement instanceof PHP_CodeSniffer_CommentParser_DocElement) === false
) {
throw new Exception('Parse method must return a DocElement');
}
}//end parseTag()
/**
* Returns a list of tags that this comment parser allows for it's comment.
*
* Each tag should indicate if only one entry of this tag can exist in the
* comment by specifying true as the array value, or false if more than one
* is allowed. Each tag should ommit the @ symbol. Only tags other than
* the standard tags should be returned.
*
* @return array(string => boolean)
*/
protected abstract function getAllowedTags();
/**
* Returns the tag orders (index => tagName).
*
* @return array
*/
public function getTagOrders()
{
return $this->orders;
}//end getTagOrders()
/**
* Returns the unknown tags.
*
* @return array
*/
public function getUnknown()
{
return $this->unknown;
}//end getUnknown()
}//end class
?>

View File

@@ -0,0 +1,341 @@
<?php
/**
* Parses Class doc comments.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (class_exists('PHP_CodeSniffer_CommentParser_AbstractParser', true) === false) {
$error = 'Class PHP_CodeSniffer_CommentParser_AbstractParser not found';
throw new PHP_CodeSniffer_Exception($error);
}
/**
* Parses Class doc comments.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_CommentParser_ClassCommentParser extends PHP_CodeSniffer_CommentParser_AbstractParser
{
/**
* The package element of this class.
*
* @var SingleElement
*/
private $_package = null;
/**
* The subpackage element of this class.
*
* @var SingleElement
*/
private $_subpackage = null;
/**
* The version element of this class.
*
* @var SingleElement
*/
private $_version = null;
/**
* The category element of this class.
*
* @var SingleElement
*/
private $_category = null;
/**
* The copyright elements of this class.
*
* @var array(SingleElement)
*/
private $_copyrights = array();
/**
* The licence element of this class.
*
* @var PairElement
*/
private $_license = null;
/**
* The author elements of this class.
*
* @var array(SingleElement)
*/
private $_authors = array();
/**
* Returns the allowed tags withing a class comment.
*
* @return array(string => int)
*/
protected function getAllowedTags()
{
return array(
'category' => false,
'package' => true,
'subpackage' => true,
'author' => false,
'copyright' => true,
'license' => false,
'version' => true,
);
}//end getAllowedTags()
/**
* Parses the license tag of this class comment.
*
* @param array $tokens The tokens that comprise this tag.
*
* @return PHP_CodeSniffer_CommentParser_PairElement
*/
protected function parseLicense($tokens)
{
$this->_license = new PHP_CodeSniffer_CommentParser_PairElement(
$this->previousElement,
$tokens,
'license',
$this->phpcsFile
);
return $this->_license;
}//end parseLicense()
/**
* Parses the copyright tags of this class comment.
*
* @param array $tokens The tokens that comprise this tag.
*
* @return PHP_CodeSniffer_CommentParser_SingleElement
*/
protected function parseCopyright($tokens)
{
$copyright = new PHP_CodeSniffer_CommentParser_SingleElement(
$this->previousElement,
$tokens,
'copyright',
$this->phpcsFile
);
$this->_copyrights[] = $copyright;
return $copyright;
}//end parseCopyright()
/**
* Parses the category tag of this class comment.
*
* @param array $tokens The tokens that comprise this tag.
*
* @return PHP_CodeSniffer_CommentParser_SingleElement
*/
protected function parseCategory($tokens)
{
$this->_category = new PHP_CodeSniffer_CommentParser_SingleElement(
$this->previousElement,
$tokens,
'category',
$this->phpcsFile
);
return $this->_category;
}//end parseCategory()
/**
* Parses the author tag of this class comment.
*
* @param array $tokens The tokens that comprise this tag.
*
* @return array(PHP_CodeSniffer_CommentParser_SingleElement)
*/
protected function parseAuthor($tokens)
{
$author = new PHP_CodeSniffer_CommentParser_SingleElement(
$this->previousElement,
$tokens,
'author',
$this->phpcsFile
);
$this->_authors[] = $author;
return $author;
}//end parseAuthor()
/**
* Parses the version tag of this class comment.
*
* @param array $tokens The tokens that comprise this tag.
*
* @return PHP_CodeSniffer_CommentParser_SingleElement
*/
protected function parseVersion($tokens)
{
$this->_version = new PHP_CodeSniffer_CommentParser_SingleElement(
$this->previousElement,
$tokens,
'version',
$this->phpcsFile
);
return $this->_version;
}//end parseVersion()
/**
* Parses the package tag found in this test.
*
* @param array $tokens The tokens that comprise this var.
*
* @return PHP_CodeSniffer_CommentParser_SingleElement
*/
protected function parsePackage($tokens)
{
$this->_package = new PHP_CodeSniffer_CommentParser_SingleElement(
$this->previousElement,
$tokens,
'package',
$this->phpcsFile
);
return $this->_package;
}//end parsePackage()
/**
* Parses the package tag found in this test.
*
* @param array $tokens The tokens that comprise this var.
*
* @return PHP_CodeSniffer_CommentParser_SingleElement
*/
protected function parseSubpackage($tokens)
{
$this->_subpackage = new PHP_CodeSniffer_CommentParser_SingleElement(
$this->previousElement,
$tokens,
'subpackage',
$this->phpcsFile
);
return $this->_subpackage;
}//end parseSubpackage()
/**
* Returns the authors of this class comment.
*
* @return array(PHP_CodeSniffer_CommentParser_SingleElement)
*/
public function getAuthors()
{
return $this->_authors;
}//end getAuthors()
/**
* Returns the version of this class comment.
*
* @return PHP_CodeSniffer_CommentParser_SingleElement
*/
public function getVersion()
{
return $this->_version;
}//end getVersion()
/**
* Returns the license of this class comment.
*
* @return PHP_CodeSniffer_CommentParser_PairElement
*/
public function getLicense()
{
return $this->_license;
}//end getLicense()
/**
* Returns the copyrights of this class comment.
*
* @return PHP_CodeSniffer_CommentParser_SingleElement
*/
public function getCopyrights()
{
return $this->_copyrights;
}//end getCopyrights()
/**
* Returns the category of this class comment.
*
* @return PHP_CodeSniffer_CommentParser_SingleElement
*/
public function getCategory()
{
return $this->_category;
}//end getCategory()
/**
* Returns the package that this class belongs to.
*
* @return PHP_CodeSniffer_CommentParser_SingleElement
*/
public function getPackage()
{
return $this->_package;
}//end getPackage()
/**
* Returns the subpackage that this class belongs to.
*
* @return PHP_CodeSniffer_CommentParser_SingleElement
*/
public function getSubpackage()
{
return $this->_subpackage;
}//end getSubpackage()
}//end class
?>

View File

@@ -0,0 +1,245 @@
<?php
/**
* A class to represent Comments of a doc comment.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (class_exists('PHP_CodeSniffer_CommentParser_SingleElement', true) === false) {
$error = 'Class PHP_CodeSniffer_CommentParser_SingleElement not found';
throw new PHP_CodeSniffer_Exception($error);
}
/**
* A class to represent Comments of a doc comment.
*
* Comments are in the following format.
* <code>
* /** <--this is the start of the comment.
* * This is a short comment description
* *
* * This is a long comment description
* * <-- this is the end of the comment
* * @return something
* {@/}
* </code>
*
* Note that the sentence before two newlines is assumed
* the short comment description.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_CommentParser_CommentElement extends PHP_CodeSniffer_CommentParser_SingleElement
{
/**
* Constructs a PHP_CodeSniffer_CommentParser_CommentElement.
*
* @param PHP_CodeSniffer_CommentParser_DocElemement $previousElement The element
* that
* appears
* before this
* element.
* @param array $tokens The tokens
* that make
* up this
* element.
* @param PHP_CodeSniffer_File $phpcsFile The file
* that this
* element is
* in.
*/
public function __construct(
$previousElement,
$tokens,
PHP_CodeSniffer_File $phpcsFile
) {
parent::__construct($previousElement, $tokens, 'comment', $phpcsFile);
}//end __construct()
/**
* Returns the short comment description.
*
* @return string
* @see getLongComment()
*/
public function getShortComment()
{
$pos = $this->_getShortCommentEndPos();
if ($pos === -1) {
return '';
}
return implode('', array_slice($this->tokens, 0, ($pos + 1)));
}//end getShortComment()
/**
* Returns the last token position of the short comment description.
*
* @return int The last token position of the short comment description
* @see _getLongCommentStartPos()
*/
private function _getShortCommentEndPos()
{
$found = false;
$whiteSpace = array(
' ',
"\t",
);
foreach ($this->tokens as $pos => $token) {
$token = str_replace($whiteSpace, '', $token);
if ($token === $this->phpcsFile->eolChar) {
if ($found === false) {
// Include newlines before short description.
continue;
} else {
if (isset($this->tokens[($pos + 1)]) === true) {
if ($this->tokens[($pos + 1)] === $this->phpcsFile->eolChar) {
return ($pos - 1);
}
} else {
return $pos;
}
}
} else {
$found = true;
}
}//end foreach
return (count($this->tokens) - 1);
}//end _getShortCommentEndPos()
/**
* Returns the long comment description.
*
* @return string
* @see getShortComment
*/
public function getLongComment()
{
$start = $this->_getLongCommentStartPos();
if ($start === -1) {
return '';
}
return implode('', array_slice($this->tokens, $start));
}//end getLongComment()
/**
* Returns the start position of the long comment description.
*
* Returns -1 if there is no long comment.
*
* @return int The start position of the long comment description.
* @see _getShortCommentEndPos()
*/
private function _getLongCommentStartPos()
{
$pos = ($this->_getShortCommentEndPos() + 1);
if ($pos === (count($this->tokens) - 1)) {
return -1;
}
$count = count($this->tokens);
for ($i = $pos; $i < $count; $i++) {
$content = trim($this->tokens[$i]);
if ($content !== '') {
if ($content{0} === '@') {
return -1;
}
return $i;
}
}
return -1;
}//end _getLongCommentStartPos()
/**
* Returns the whitespace that exists between
* the short and the long comment description.
*
* @return string
*/
public function getWhiteSpaceBetween()
{
$endShort = ($this->_getShortCommentEndPos() + 1);
$startLong = ($this->_getLongCommentStartPos() - 1);
if ($startLong === -1) {
return '';
}
return implode(
'',
array_slice($this->tokens, $endShort, ($startLong - $endShort))
);
}//end getWhiteSpaceBetween()
/**
* Returns the number of newlines that exist before the tags.
*
* @return int
*/
public function getNewlineAfter()
{
$long = $this->getLongComment();
if ($long !== '') {
$long = rtrim($long, ' ');
$long = strrev($long);
$newlines = strspn($long, $this->phpcsFile->eolChar);
} else {
$endShort = ($this->_getShortCommentEndPos() + 1);
$after = implode('', array_slice($this->tokens, $endShort));
$after = trim($after, ' ');
$newlines = strspn($after, $this->phpcsFile->eolChar);
}
return ($newlines / strlen($this->phpcsFile->eolChar));
}//end getNewlineAfter()
/**
* Returns true if there is no comment.
*
* @return boolean
*/
public function isEmpty()
{
return (trim($this->getContent()) === '');
}//end isEmpty()
}//end class
?>

View File

@@ -0,0 +1,104 @@
<?php
/**
* A DocElement represents a logical element within a Doc Comment.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* A DocElement represents a logical element within a Doc Comment.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
interface PHP_CodeSniffer_CommentParser_DocElement
{
/**
* Returns the name of the tag this element represents, omitting the @ symbol.
*
* @return string
*/
public function getTag();
/**
* Returns the whitespace that exists before this element.
*
* @return string
* @see getWhitespaceAfter()
*/
public function getWhitespaceBefore();
/**
* Returns the whitespace that exists after this element.
*
* @return string
* @see getWhitespaceBefore()
*/
public function getWhitespaceAfter();
/**
* Returns the order that this element appears in the doc comment.
*
* The first element in the comment should have an order of 1.
*
* @return int
*/
public function getOrder();
/**
* Returns the element that appears before this element.
*
* @return PHP_CodeSniffer_CommentParser_DocElement
* @see getNextElement()
*/
public function getPreviousElement();
/**
* Returns the element that appears after this element.
*
* @return PHP_CodeSniffer_CommentParser_DocElement
* @see getPreviousElement()
*/
public function getNextElement();
/**
* Returns the line that this element started on.
*
* @return int
*/
public function getLine();
/**
* Returns the raw content of this element, ommiting the tag.
*
* @return string
*/
public function getRawContent();
}//end interface
?>

View File

@@ -0,0 +1,212 @@
<?php
/**
* Parses function doc comments.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (class_exists('PHP_CodeSniffer_CommentParser_AbstractParser', true) === false) {
$error = 'Class PHP_CodeSniffer_CommentParser_AbstractParser not found';
throw new PHP_CodeSniffer_Exception($error);
}
if (class_exists('PHP_CodeSniffer_CommentParser_ParameterElement', true) === false) {
$error = 'Class PHP_CodeSniffer_CommentParser_ParameterElement not found';
throw new PHP_CodeSniffer_Exception($error);
}
if (class_exists('PHP_CodeSniffer_CommentParser_PairElement', true) === false) {
$error = 'Class PHP_CodeSniffer_CommentParser_PairElement not found';
throw new PHP_CodeSniffer_Exception($error);
}
if (class_exists('PHP_CodeSniffer_CommentParser_SingleElement', true) === false) {
$error = 'Class PHP_CodeSniffer_CommentParser_SingleElement not found';
throw new PHP_CodeSniffer_Exception($error);
}
/**
* Parses function doc comments.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_CommentParser_FunctionCommentParser extends PHP_CodeSniffer_CommentParser_AbstractParser
{
/**
* The parameter elements within this function comment.
*
* @var array(PHP_CodeSniffer_CommentParser_ParameterElement)
*/
private $_params = array();
/**
* The return element in this function comment.
*
* @var PHP_CodeSniffer_CommentParser_PairElement.
*/
private $_return = null;
/**
* The throws element list for this function comment.
*
* @var array(PHP_CodeSniffer_CommentParser_PairElement)
*/
private $_throws = array();
/**
* Constructs a PHP_CodeSniffer_CommentParser_FunctionCommentParser.
*
* @param string $comment The comment to parse.
* @param PHP_CodeSniffer_File $phpcsFile The file that this comment is in.
*/
public function __construct($comment, PHP_CodeSniffer_File $phpcsFile)
{
parent::__construct($comment, $phpcsFile);
}//end __construct()
/**
* Parses parameter elements.
*
* @param array(string) $tokens The tokens that conmpise this sub element.
*
* @return PHP_CodeSniffer_CommentParser_ParameterElement
*/
protected function parseParam($tokens)
{
$param = new PHP_CodeSniffer_CommentParser_ParameterElement(
$this->previousElement,
$tokens,
$this->phpcsFile
);
$this->_params[] = $param;
return $param;
}//end parseParam()
/**
* Parses return elements.
*
* @param array(string) $tokens The tokens that conmpise this sub element.
*
* @return PHP_CodeSniffer_CommentParser_PairElement
*/
protected function parseReturn($tokens)
{
$return = new PHP_CodeSniffer_CommentParser_PairElement(
$this->previousElement,
$tokens,
'return',
$this->phpcsFile
);
$this->_return = $return;
return $return;
}//end parseReturn()
/**
* Parses throws elements.
*
* @param array(string) $tokens The tokens that conmpise this sub element.
*
* @return PHP_CodeSniffer_CommentParser_PairElement
*/
protected function parseThrows($tokens)
{
$throws = new PHP_CodeSniffer_CommentParser_PairElement(
$this->previousElement,
$tokens,
'throws',
$this->phpcsFile
);
$this->_throws[] = $throws;
return $throws;
}//end parseThrows()
/**
* Returns the parameter elements that this function comment contains.
*
* Returns an empty array if no parameter elements are contained within
* this function comment.
*
* @return array(PHP_CodeSniffer_CommentParser_ParameterElement)
*/
public function getParams()
{
return $this->_params;
}//end getParams()
/**
* Returns the return element in this fucntion comment.
*
* Returns null if no return element exists in the comment.
*
* @return PHP_CodeSniffer_CommentParser_PairElement
*/
public function getReturn()
{
return $this->_return;
}//end getReturn()
/**
* Returns the throws elements in this fucntion comment.
*
* Returns empty array if no throws elements in the comment.
*
* @return array(PHP_CodeSniffer_CommentParser_PairElement)
*/
public function getThrows()
{
return $this->_throws;
}//end getThrows()
/**
* Returns the allowed tags that can exist in a function comment.
*
* @return array(string => boolean)
*/
protected function getAllowedTags()
{
return array(
'param' => false,
'return' => true,
'throws' => false,
);
}//end getAllowedTags()
}//end class
?>

View File

@@ -0,0 +1,91 @@
<?php
/**
* Parses class member comments.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (class_exists('PHP_CodeSniffer_CommentParser_ClassCommentParser', true) === false) {
$error = 'Class PHP_CodeSniffer_CommentParser_ClassCommentParser not found';
throw new PHP_CodeSniffer_Exception($error);
}
/**
* Parses class member comments.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_CommentParser_MemberCommentParser extends PHP_CodeSniffer_CommentParser_ClassCommentParser
{
/**
* Represents a \@var tag in a member comment.
*
* @var PHP_CodeSniffer_CommentParser_SingleElement
*/
private $_var = null;
/**
* Parses Var tags.
*
* @param array $tokens The tokens that represent this tag.
*
* @return PHP_CodeSniffer_CommentParser_SingleElement
*/
protected function parseVar($tokens)
{
$this->_var = new PHP_CodeSniffer_CommentParser_SingleElement(
$this->previousElement,
$tokens,
'var',
$this->phpcsFile
);
return $this->_var;
}//end parseVar()
/**
* Returns the var tag found in the member comment.
*
* @return PHP_CodeSniffer_CommentParser_PairElement
*/
public function getVar()
{
return $this->_var;
}//end getVar()
/**
* Returns the allowed tags for this parser.
*
* @return array
*/
protected function getAllowedTags()
{
return array('var' => true);
}//end getAllowedTags()
}//end class
?>

View File

@@ -0,0 +1,171 @@
<?php
/**
* A class to represent elements that have a value => comment format.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (class_exists('PHP_CodeSniffer_CommentParser_AbstractDocElement', true) === false) {
$error = 'Class PHP_CodeSniffer_CommentParser_AbstractDocElement not found';
throw new PHP_CodeSniffer_Exception($error);
}
/**
* A class to represent elements that have a value => comment format.
*
* An example of a pair element tag is the \@throws as it has an exception type
* and a comment on the circumstance of when the exception is thrown.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_CommentParser_PairElement extends PHP_CodeSniffer_CommentParser_AbstractDocElement
{
/**
* The value of the tag.
*
* @var string
*/
private $_value = '';
/**
* The comment of the tag.
*
* @var string
*/
private $_comment = '';
/**
* The whitespace that exists before the value elem.
*
* @var string
*/
private $_valueWhitespace = '';
/**
* The whitespace that exists before the comment elem.
*
* @var string
*/
private $_commentWhitespace = '';
/**
* Constructs a PHP_CodeSniffer_CommentParser_PairElement doc tag.
*
* @param PHP_CodeSniffer_CommentParser_DocElement $previousElement The element
* before this
* one.
* @param array $tokens The tokens
* that comprise
* this element.
* @param string $tag The tag that
* this element
* represents.
* @param PHP_CodeSniffer_File $phpcsFile The file that
* this element
* is in.
*/
public function __construct(
$previousElement,
$tokens,
$tag,
PHP_CodeSniffer_File $phpcsFile
) {
parent::__construct($previousElement, $tokens, $tag, $phpcsFile);
}//end __construct()
/**
* Returns the element names that this tag is comprised of, in the order
* that they appear in the tag.
*
* @return array(string)
* @see processSubElement()
*/
protected function getSubElements()
{
return array(
'value',
'comment',
);
}//end getSubElements()
/**
* Processes the sub element with the specified name.
*
* @param string $name The name of the sub element to process.
* @param string $content The content of this sub element.
* @param string $whitespaceBefore The whitespace that exists before the
* sub element.
*
* @return void
* @see getSubElements()
*/
protected function processSubElement($name, $content, $whitespaceBefore)
{
$element = '_'.$name;
$whitespace = $element.'Whitespace';
$this->$element = $content;
$this->$whitespace = $whitespaceBefore;
}//end processSubElement()
/**
* Returns the value of the tag.
*
* @return string
*/
public function getValue()
{
return $this->_value;
}//end getValue()
/**
* Returns the comment associated with the value of this tag.
*
* @return string
*/
public function getComment()
{
return $this->_comment;
}//end getComment()
/**
* Returns the witespace before the content of this tag.
*
* @return string
*/
public function getWhitespaceBeforeValue()
{
return $this->_valueWhitespace;
}//end getWhitespaceBeforeValue()
}//end class
?>

View File

@@ -0,0 +1,334 @@
<?php
/**
* A class to represent param tags within a function comment.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (class_exists('PHP_CodeSniffer_CommentParser_AbstractDocElement', true) === false) {
$error = 'Class PHP_CodeSniffer_CommentParser_AbstractDocElement not found';
throw new PHP_CodeSniffer_Exception($error);
}
/**
* A class to represent param tags within a function comment.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_CommentParser_ParameterElement extends PHP_CodeSniffer_CommentParser_AbstractDocElement
{
/**
* The variable name of this parameter name, including the $ sign.
*
* @var string
*/
private $_varName = '';
/**
* The comment of this parameter tag.
*
* @var string
*/
private $_comment = '';
/**
* The variable type of this parameter tag.
*
* @var string
*/
private $_type = '';
/**
* The whitespace that exists before the variable name.
*
* @var string
*/
private $_varNameWhitespace = '';
/**
* The whitespace that exists before the comment.
*
* @var string
*/
private $_commentWhitespace = null;
/**
* The whitespace that exists before the variable type.
*
* @var string
*/
private $_typeWhitespace = '';
/**
* Constructs a PHP_CodeSniffer_CommentParser_ParameterElement.
*
* @param PHP_CodeSniffer_CommentParser_DocElement $previousElement The element
* previous to
* this one.
* @param array $tokens The tokens
* that make up
* this element.
* @param PHP_CodeSniffer_File $phpcsFile The file that
* this element
* is in.
*/
public function __construct(
$previousElement,
$tokens,
PHP_CodeSniffer_File $phpcsFile
) {
parent::__construct($previousElement, $tokens, 'param', $phpcsFile);
// Handle special variable type: array(x => y).
$type = strtolower($this->_type);
if ($this->_varName === '=>' && strpos($type, 'array(') !== false) {
$rawContent = $this->getRawContent();
$matches = array();
$pattern = '/^(\s+)(array\(.*\))(\s+)(\$\S*)(\s+)(.*)/i';
if (preg_match($pattern, $rawContent, $matches) !== 0) {
// Process the sub elements correctly for this special case.
if (count($matches) === 7) {
$this->processSubElement('type', $matches[2], $matches[1]);
$this->processSubElement('varName', $matches[4], $matches[3]);
$this->processSubElement('comment', $matches[6], $matches[5]);
}
}
}
}//end __construct()
/**
* Returns the element names that this tag is comprised of, in the order
* that they appear in the tag.
*
* @return array(string)
* @see processSubElement()
*/
protected function getSubElements()
{
return array(
'type',
'varName',
'comment',
);
}//end getSubElements()
/**
* Processes the sub element with the specified name.
*
* @param string $name The name of the sub element to process.
* @param string $content The content of this sub element.
* @param string $beforeWhitespace The whitespace that exists before the
* sub element.
*
* @return void
* @see getSubElements()
*/
protected function processSubElement($name, $content, $beforeWhitespace)
{
$element = '_'.$name;
$whitespace = $element.'Whitespace';
$this->$element = $content;
$this->$whitespace = $beforeWhitespace;
}//end processSubElement()
/**
* Returns the variable name that this parameter tag represents.
*
* @return string
*/
public function getVarName()
{
return $this->_varName;
}//end getVarName()
/**
* Returns the variable type that this string represents.
*
* @return string
*/
public function getType()
{
return $this->_type;
}//end getType()
/**
* Returns the comment of this comment for this parameter.
*
* @return string
*/
public function getComment()
{
return $this->_comment;
}//end getComment()
/**
* Returns the whitespace before the variable type.
*
* @return stirng
* @see getWhiteSpaceBeforeVarName()
* @see getWhiteSpaceBeforeComment()
*/
public function getWhiteSpaceBeforeType()
{
return $this->_typeWhitespace;
}//end getWhiteSpaceBeforeType()
/**
* Returns the whitespace before the variable name.
*
* @return string
* @see getWhiteSpaceBeforeComment()
* @see getWhiteSpaceBeforeType()
*/
public function getWhiteSpaceBeforeVarName()
{
return $this->_varNameWhitespace;
}//end getWhiteSpaceBeforeVarName()
/**
* Returns the whitespace before the comment.
*
* @return string
* @see getWhiteSpaceBeforeVarName()
* @see getWhiteSpaceBeforeType()
*/
public function getWhiteSpaceBeforeComment()
{
return $this->_commentWhitespace;
}//end getWhiteSpaceBeforeComment()
/**
* Returns the postition of this parameter are it appears in the comment.
*
* This method differs from getOrder as it is only relative to method
* parameters.
*
* @return int
*/
public function getPosition()
{
if (($this->getPreviousElement() instanceof PHP_CodeSniffer_CommentParser_ParameterElement) === false) {
return 1;
} else {
return ($this->getPreviousElement()->getPosition() + 1);
}
}//end getPosition()
/**
* Returns true if this parameter's variable aligns with the other's.
*
* @param PHP_CodeSniffer_CommentParser_ParameterElement $other The other param
* to check
* alignment with.
*
* @return boolean
*/
public function alignsVariableWith(
PHP_CodeSniffer_CommentParser_ParameterElement $other
) {
// Format is:
// @param type $variable Comment.
// @param <-a-><---b---->
// Compares the index before param variable.
$otherVar = (strlen($other->_type) + strlen($other->_varNameWhitespace));
$thisVar = (strlen($this->_type) + strlen($this->_varNameWhitespace));
if ($otherVar !== $thisVar) {
return false;
}
return true;
}//end alignsVariableWith()
/**
* Returns true if this parameter's comment aligns with the other's.
*
* @param PHP_CodeSniffer_CommentParser_ParameterElement $other The other param
* to check
* alignment with.
*
* @return boolean
*/
public function alignsCommentWith(
PHP_CodeSniffer_CommentParser_ParameterElement $other
) {
// Compares the index before param comment.
$otherComment
= (strlen($other->_varName) + strlen($other->_commentWhitespace));
$thisComment
= (strlen($this->_varName) + strlen($this->_commentWhitespace));
if ($otherComment !== $thisComment) {
return false;
}
return true;
}//end alignsCommentWith()
/**
* Returns true if this parameter aligns with the other paramter.
*
* @param PHP_CodeSniffer_CommentParser_ParameterElement $other The other param
* to check
* alignment with.
*
* @return boolean
*/
public function alignsWith(PHP_CodeSniffer_CommentParser_ParameterElement $other)
{
if ($this->alignsVariableWith($other) === false) {
return false;
}
if ($this->alignsCommentWith($other) === false) {
return false;
}
return true;
}//end alignsWith()
}//end class
?>

View File

@@ -0,0 +1,71 @@
<?php
/**
* An exception to be thrown when a DocCommentParser finds an anomilty in a
* doc comment.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* An exception to be thrown when a DocCommentParser finds an anomilty in a
* doc comment.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_CommentParser_ParserException extends Exception
{
/**
* The line where the exception occured, in relation to the doc comment.
*
* @var int
*/
private $_line = 0;
/**
* Constructs a DocCommentParserException.
*
* @param string $message The message of the exception.
* @param int $line The position in comment where the error occured.
* A position of 0 indicates that the error occured
* at the opening line of the doc comment.
*/
public function __construct($message, $line)
{
parent::__construct($message);
$this->_line = $line;
}//end __construct()
/**
* Returns the line number within the comment where the exception occured.
*
* @return int
*/
public function getLineWithinComment()
{
return $this->_line;
}//end getLineWithinComment()
}//end class
?>

View File

@@ -0,0 +1,171 @@
<?php
/**
* A class to represent single element doc tags.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (class_exists('PHP_CodeSniffer_CommentParser_AbstractDocElement', true) === false) {
$error = 'Class PHP_CodeSniffer_CommentParser_AbstractDocElement not found';
throw new PHP_CodeSniffer_Exception($error);
}
/**
* A class to represent single element doc tags.
*
* A single element doc tag contains only one value after the tag itself. An
* example would be the \@package tag.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_CommentParser_SingleElement extends PHP_CodeSniffer_CommentParser_AbstractDocElement
{
/**
* The content that exists after the tag.
*
* @var string
* @see getContent()
*/
protected $content = '';
/**
* The whitespace that exists before the content.
*
* @var string
* @see getWhitespaceBeforeContent()
*/
protected $contentWhitespace = '';
/**
* Constructs a SingleElement doc tag.
*
* @param PHP_CodeSniffer_CommentParser_DocElement $previousElement The element
* before this
* one.
* @param array $tokens The tokens
* that comprise
* this element.
* @param string $tag The tag that
* this element
* represents.
* @param PHP_CodeSniffer_File $phpcsFile The file that
* this element
* is in.
*/
public function __construct(
$previousElement,
$tokens,
$tag,
PHP_CodeSniffer_File $phpcsFile
) {
parent::__construct($previousElement, $tokens, $tag, $phpcsFile);
}//end __construct()
/**
* Returns the element names that this tag is comprised of, in the order
* that they appear in the tag.
*
* @return array(string)
* @see processSubElement()
*/
protected function getSubElements()
{
return array('content');
}//end getSubElements()
/**
* Processes the sub element with the specified name.
*
* @param string $name The name of the sub element to process.
* @param string $content The content of this sub element.
* @param string $whitespaceBefore The whitespace that exists before the
* sub element.
*
* @return void
* @see getSubElements()
*/
protected function processSubElement($name, $content, $whitespaceBefore)
{
$this->content = $content;
$this->contentWhitespace = $whitespaceBefore;
}//end processSubElement()
/**
* Returns the content of this tag.
*
* @return string
*/
public function getContent()
{
return $this->content;
}//end getContent()
/**
* Returns the witespace before the content of this tag.
*
* @return string
*/
public function getWhitespaceBeforeContent()
{
return $this->contentWhitespace;
}//end getWhitespaceBeforeContent()
/**
* Processes a content check for single doc element.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $commentStart The line number where
* the error occurs.
* @param string $docBlock Whether this is a file or
* class comment doc.
*
* @return void
*/
public function process(
PHP_CodeSniffer_File $phpcsFile,
$commentStart,
$docBlock
) {
if ($this->content === '') {
$errorPos = ($commentStart + $this->getLine());
$error = 'Content missing for %s tag in %s comment';
$data = array(
$this->tag,
$docBlock,
);
$phpcsFile->addError($error, $errorPos, 'EmptyTagContent', $data);
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,197 @@
<?php
/**
* The base class for all PHP_CodeSniffer documentation generators.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* The base class for all PHP_CodeSniffer documentation generators.
*
* Documentation generators are used to print documentation about code sniffs
* in a standard.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_DocGenerators_Generator
{
/**
* The name of the coding standard we are generating docs for.
*
* @var string
*/
private $_standard = '';
/**
* An array of sniffs that we are limiting the generated docs to.
*
* If this array is empty, docs are generated for all sniffs in the
* supplied coding standard.
*
* @var string
*/
private $_sniffs = array();
/**
* Constructs a PHP_CodeSniffer_DocGenerators_Generator object.
*
* @param string $standard The name of the coding standard to generate
* docs for.
* @param array $sniffs An array of sniffs that we are limiting the
* generated docs to.
*
* @see generate()
*/
public function __construct($standard, array $sniffs=array())
{
$this->_standard = $standard;
$this->_sniffs = $sniffs;
}//end __construct()
/**
* Retrieves the title of the sniff from the DOMNode supplied.
*
* @param DOMNode $doc The DOMNode object for the sniff.
* It represents the "documentation" tag in the XML
* standard file.
*
* @return string
*/
protected function getTitle(DOMNode $doc)
{
return $doc->getAttribute('title');
}//end getTitle()
/**
* Retrieves the name of the standard we are generating docs for.
*
* @return string
*/
protected function getStandard()
{
return $this->_standard;
}//end getStandard()
/**
* Generates the documentation for a standard.
*
* It's probably wise for doc generators to override this method so they
* have control over how the docs are produced. Otherwise, the processSniff
* method should be overridden to output content for each sniff.
*
* @return void
* @see processSniff()
*/
public function generate()
{
$standardFiles = $this->getStandardFiles();
foreach ($standardFiles as $standard) {
$doc = new DOMDocument();
$doc->load($standard);
$documentation = $doc->getElementsByTagName('documentation')->item(0);
$this->processSniff($documentation);
}
}//end generate()
/**
* Returns a list of paths to XML standard files for all sniffs in a standard.
*
* Any sniffs that do not have an XML standard file are obviously not included
* in the returned array. If documentation is only being generated for some
* sniffs (ie. $this->_sniffs is not empty) then all others sniffs will
* be filtered from the results as well.
*
* @return array(string)
*/
protected function getStandardFiles()
{
if (is_dir($this->_standard) === true) {
// This is a custom standard.
$standardDir = $this->_standard;
$standard = basename($this->_standard);
} else {
$standardDir
= realpath(dirname(__FILE__).'/../Standards/'.$this->_standard);
$standard = $this->_standard;
}
$phpcs = new PHP_CodeSniffer();
$sniffs = $phpcs->getSniffFiles($standardDir, $standard);
$standardFiles = array();
foreach ($sniffs as $sniff) {
if (empty($this->_sniffs) === false) {
// We are limiting the docs to certain sniffs only, so filter
// out any unwanted sniffs.
$sniffName = substr($sniff, (strrpos($sniff, '/') + 1));
$sniffName = substr($sniffName, 0, -9);
if (in_array($sniffName, $this->_sniffs) === false) {
continue;
}
}
$standardFile = str_replace(
DIRECTORY_SEPARATOR.'Sniffs'.DIRECTORY_SEPARATOR,
DIRECTORY_SEPARATOR.'Docs'.DIRECTORY_SEPARATOR,
$sniff
);
$standardFile = str_replace('Sniff.php', 'Standard.xml', $standardFile);
if (is_file($standardFile) === true) {
$standardFiles[] = $standardFile;
}
}//end foreach
return $standardFiles;
}//end getStandardFiles()
/**
* Process the documentation for a single sniff.
*
* Doc generators should override this function to produce output.
*
* @param DOMNode $doc The DOMNode object for the sniff.
* It represents the "documentation" tag in the XML
* standard file.
*
* @return void
* @see generate()
*/
protected function processSniff(DOMNode $doc)
{
}//end processSniff()
}//end class
?>

View File

@@ -0,0 +1,292 @@
<?php
/**
* A doc generator that outputs documentation in one big HTML file.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (class_exists('PHP_CodeSniffer_DocGenerators_Generator', true) === false) {
throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_DocGenerators_Generator not found');
}
/**
* A doc generator that outputs documentation in one big HTML file.
*
* Output is in one large HTML file and is designed for you to style with
* your own stylesheet. It contains a table of contents at the top with anchors
* to each sniff.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_DocGenerators_HTML extends PHP_CodeSniffer_DocGenerators_Generator
{
/**
* Generates the documentation for a standard.
*
* @return void
* @see processSniff()
*/
public function generate()
{
ob_start();
$this->printHeader();
$standardFiles = $this->getStandardFiles();
$this->printToc($standardFiles);
foreach ($standardFiles as $standard) {
$doc = new DOMDocument();
$doc->load($standard);
$documentation = $doc->getElementsByTagName('documentation')->item(0);
$this->processSniff($documentation);
}
$this->printFooter();
$content = ob_get_contents();
ob_end_clean();
echo $content;
}//end generate()
/**
* Print the header of the HTML page.
*
* @return void
*/
protected function printHeader()
{
$standard = $this->getStandard();
echo '<html>'.PHP_EOL;
echo ' <head>'.PHP_EOL;
echo " <title>$standard Coding Standards</title>".PHP_EOL;
echo ' <style>
body {
background-color: #FFFFFF;
font-size: 14px;
font-family: Arial, Helvetica, sans-serif;
color: #000000;
}
h1 {
color: #666666;
font-size: 20px;
font-weight: bold;
margin-top: 0px;
background-color: #E6E7E8;
padding: 20px;
border: 1px solid #BBBBBB;
}
h2 {
color: #00A5E3;
font-size: 16px;
font-weight: normal;
margin-top: 50px;
}
.code-comparison {
width: 100%;
}
.code-comparison td {
border: 1px solid #CCCCCC;
}
.code-comparison-title, .code-comparison-code {
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
color: #000000;
vertical-align: top;
padding: 4px;
width: 50%;
background-color: #F1F1F1;
line-height: 15px;
}
.code-comparison-code {
font-family: Courier;
background-color: #F9F9F9;
}
.code-comparison-highlight {
background-color: #DDF1F7;
border: 1px solid #00A5E3;
line-height: 15px;
}
.tag-line {
text-align: center;
width: 100%;
margin-top: 30px;
font-size: 12px;
}
.tag-line a {
color: #000000;
}
</style>'.PHP_EOL;
echo ' </head>'.PHP_EOL;
echo ' <body>'.PHP_EOL;
echo " <h1>$standard Coding Standards</h1>".PHP_EOL;
}//end printHeader()
/**
* Print the table of contents for the standard.
*
* The TOC is just an unordered list of bookmarks to sniffs on the page.
*
* @param array $standardFiles An array of paths to the XML standard files.
*
* @return void
*/
protected function printToc($standardFiles)
{
echo ' <h2>Table of Contents</h2>'.PHP_EOL;
echo ' <ul class="toc">'.PHP_EOL;
foreach ($standardFiles as $standard) {
$doc = new DOMDocument();
$doc->load($standard);
$documentation = $doc->getElementsByTagName('documentation')->item(0);
$title = $this->getTitle($documentation);
echo ' <li><a href="#'.str_replace(' ', '-', $title)."\">$title</a></li>".PHP_EOL;
}
echo ' </ul>'.PHP_EOL;
}//end printToc()
/**
* Print the footer of the HTML page.
*
* @return void
*/
protected function printFooter()
{
// Turn off strict errors so we don't get timezone warnings if people
// don't have their timezone set.
error_reporting(E_ALL);
echo ' <div class="tag-line">';
echo 'Documentation generated on '.date('r');
echo ' by <a href="http://pear.php.net/package/PHP_CodeSniffer">PHP_CodeSniffer 1.3.3</a>';
echo '</div>'.PHP_EOL;
error_reporting(E_ALL | E_STRICT);
echo ' </body>'.PHP_EOL;
echo '</html>'.PHP_EOL;
}//end printFooter()
/**
* Process the documentation for a single sniff.
*
* @param DOMNode $doc The DOMNode object for the sniff.
* It represents the "documentation" tag in the XML
* standard file.
*
* @return void
*/
public function processSniff(DOMNode $doc)
{
$title = $this->getTitle($doc);
echo ' <a name="'.str_replace(' ', '-', $title).'" />'.PHP_EOL;
echo " <h2>$title</h2>".PHP_EOL;
foreach ($doc->childNodes as $node) {
if ($node->nodeName === 'standard') {
$this->printTextBlock($node);
} else if ($node->nodeName === 'code_comparison') {
$this->printCodeComparisonBlock($node);
}
}
}//end processSniff()
/**
* Print a text block found in a standard.
*
* @param DOMNode $node The DOMNode object for the text block.
*
* @return void
*/
protected function printTextBlock($node)
{
$content = trim($node->nodeValue);
$content = htmlspecialchars($content);
// Allow em tags only.
$content = str_replace('&lt;em&gt;', '<em>', $content);
$content = str_replace('&lt;/em&gt;', '</em>', $content);
echo " <p class=\"text\">$content</p>".PHP_EOL;
}//end printTextBlock()
/**
* Print a code comparison block found in a standard.
*
* @param DOMNode $node The DOMNode object for the code comparison block.
*
* @return void
*/
protected function printCodeComparisonBlock($node)
{
$codeBlocks = $node->getElementsByTagName('code');
$firstTitle = $codeBlocks->item(0)->getAttribute('title');
$first = trim($codeBlocks->item(0)->nodeValue);
$first = str_replace("\n", '</br>', $first);
$first = str_replace(' ', '&nbsp;', $first);
$first = str_replace('<em>', '<span class="code-comparison-highlight">', $first);
$first = str_replace('</em>', '</span>', $first);
$secondTitle = $codeBlocks->item(1)->getAttribute('title');
$second = trim($codeBlocks->item(1)->nodeValue);
$second = str_replace("\n", '</br>', $second);
$second = str_replace(' ', '&nbsp;', $second);
$second = str_replace('<em>', '<span class="code-comparison-highlight">', $second);
$second = str_replace('</em>', '</span>', $second);
echo ' <table class="code-comparison">'.PHP_EOL;
echo ' <tr>'.PHP_EOL;
echo " <td class=\"code-comparison-title\">$firstTitle</td>".PHP_EOL;
echo " <td class=\"code-comparison-title\">$secondTitle</td>".PHP_EOL;
echo ' </tr>'.PHP_EOL;
echo ' <tr>'.PHP_EOL;
echo " <td class=\"code-comparison-code\">$first</td>".PHP_EOL;
echo " <td class=\"code-comparison-code\">$second</td>".PHP_EOL;
echo ' </tr>'.PHP_EOL;
echo ' </table>'.PHP_EOL;
}//end printCodeComparisonBlock()
}//end class
?>

View File

@@ -0,0 +1,267 @@
<?php
/**
* A doc generator that outputs text-based documentation.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (class_exists('PHP_CodeSniffer_DocGenerators_Generator', true) === false) {
throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_DocGenerators_Generator not found');
}
/**
* A doc generator that outputs text-based documentation.
*
* Output is designed to be displayed in a terminal and is wrapped to 100 characters.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_DocGenerators_Text extends PHP_CodeSniffer_DocGenerators_Generator
{
/**
* Process the documentation for a single sniff.
*
* @param DOMNode $doc The DOMNode object for the sniff.
* It represents the "documentation" tag in the XML
* standard file.
*
* @return void
*/
public function processSniff(DOMNode $doc)
{
$this->printTitle($doc);
foreach ($doc->childNodes as $node) {
if ($node->nodeName === 'standard') {
$this->printTextBlock($node);
} else if ($node->nodeName === 'code_comparison') {
$this->printCodeComparisonBlock($node);
}
}
}//end processSniff()
/**
* Prints the title area for a single sniff.
*
* @param DOMNode $doc The DOMNode object for the sniff.
* It represents the "documentation" tag in the XML
* standard file.
*
* @return void
*/
protected function printTitle(DOMNode $doc)
{
$title = $this->getTitle($doc);
$standard = $this->getStandard();
echo PHP_EOL;
echo str_repeat('-', (strlen("$standard CODING STANDARD: $title") + 4));
echo strtoupper(PHP_EOL."| $standard CODING STANDARD: $title |".PHP_EOL);
echo str_repeat('-', (strlen("$standard CODING STANDARD: $title") + 4));
echo PHP_EOL.PHP_EOL;
}//end printTitle()
/**
* Print a text block found in a standard.
*
* @param DOMNode $node The DOMNode object for the text block.
*
* @return void
*/
protected function printTextBlock($node)
{
$text = trim($node->nodeValue);
$text = str_replace('<em>', '*', $text);
$text = str_replace('</em>', '*', $text);
$lines = array();
$tempLine = '';
$words = explode(' ', $text);
foreach ($words as $word) {
if (strlen($tempLine.$word) >= 99) {
if (strlen($tempLine.$word) === 99) {
// Adding the extra space will push us to the edge
// so we are done.
$lines[] = $tempLine.$word;
$tempLine = '';
} else if (strlen($tempLine.$word) === 100) {
// We are already at the edge, so we are done.
$lines[] = $tempLine.$word;
$tempLine = '';
} else {
$lines[] = rtrim($tempLine);
$tempLine = $word.' ';
}
} else {
$tempLine .= $word.' ';
}
}//end foreach
if ($tempLine !== '') {
$lines[] = rtrim($tempLine);
}
echo implode(PHP_EOL, $lines).PHP_EOL.PHP_EOL;
}//end printTextBlock()
/**
* Print a code comparison block found in a standard.
*
* @param DOMNode $node The DOMNode object for the code comparison block.
*
* @return void
*/
protected function printCodeComparisonBlock($node)
{
$codeBlocks = $node->getElementsByTagName('code');
$first = trim($codeBlocks->item(0)->nodeValue);
$firstTitle = $codeBlocks->item(0)->getAttribute('title');
$firstTitleLines = array();
$tempTitle = '';
$words = explode(' ', $firstTitle);
foreach ($words as $word) {
if (strlen($tempTitle.$word) >= 45) {
if (strlen($tempTitle.$word) === 45) {
// Adding the extra space will push us to the edge
// so we are done.
$firstTitleLines[] = $tempTitle.$word;
$tempTitle = '';
} else if (strlen($tempTitle.$word) === 46) {
// We are already at the edge, so we are done.
$firstTitleLines[] = $tempTitle.$word;
$tempTitle = '';
} else {
$firstTitleLines[] = $tempTitle;
$tempTitle = $word;
}
} else {
$tempTitle .= $word.' ';
}
}//end foreach
if ($tempTitle !== '') {
$firstTitleLines[] = $tempTitle;
}
$first = str_replace('<em>', '', $first);
$first = str_replace('</em>', '', $first);
$firstLines = explode("\n", $first);
$second = trim($codeBlocks->item(1)->nodeValue);
$secondTitle = $codeBlocks->item(1)->getAttribute('title');
$secondTitleLines = array();
$tempTitle = '';
$words = explode(' ', $secondTitle);
foreach ($words as $word) {
if (strlen($tempTitle.$word) >= 45) {
if (strlen($tempTitle.$word) === 45) {
// Adding the extra space will push us to the edge
// so we are done.
$secondTitleLines[] = $tempTitle.$word;
$tempTitle = '';
} else if (strlen($tempTitle.$word) === 46) {
// We are already at the edge, so we are done.
$secondTitleLines[] = $tempTitle.$word;
$tempTitle = '';
} else {
$secondTitleLines[] = $tempTitle;
$tempTitle = $word;
}
} else {
$tempTitle .= $word.' ';
}
}//end foreach
if ($tempTitle !== '') {
$secondTitleLines[] = $tempTitle;
}
$second = str_replace('<em>', '', $second);
$second = str_replace('</em>', '', $second);
$secondLines = explode("\n", $second);
$maxCodeLines = max(count($firstLines), count($secondLines));
$maxTitleLines = max(count($firstTitleLines), count($secondTitleLines));
echo str_repeat('-', 41);
echo ' CODE COMPARISON ';
echo str_repeat('-', 42).PHP_EOL;
for ($i = 0; $i < $maxTitleLines; $i++) {
if (isset($firstTitleLines[$i]) === true) {
$firstLineText = $firstTitleLines[$i];
} else {
$firstLineText = '';
}
if (isset($secondTitleLines[$i]) === true) {
$secondLineText = $secondTitleLines[$i];
} else {
$secondLineText = '';
}
echo '| ';
echo $firstLineText.str_repeat(' ', (46 - strlen($firstLineText)));
echo ' | ';
echo $secondLineText.str_repeat(' ', (47 - strlen($secondLineText)));
echo ' |'.PHP_EOL;
}//end for
echo str_repeat('-', 100).PHP_EOL;
for ($i = 0; $i < $maxCodeLines; $i++) {
if (isset($firstLines[$i]) === true) {
$firstLineText = $firstLines[$i];
} else {
$firstLineText = '';
}
if (isset($secondLines[$i]) === true) {
$secondLineText = $secondLines[$i];
} else {
$secondLineText = '';
}
echo '| ';
echo $firstLineText.str_repeat(' ', (47 - strlen($firstLineText)));
echo '| ';
echo $secondLineText.str_repeat(' ', (48 - strlen($secondLineText)));
echo '|'.PHP_EOL;
}//end for
echo str_repeat('-', 100).PHP_EOL.PHP_EOL;
}//end printCodeComparisonBlock()
}//end class
?>

View File

@@ -0,0 +1,33 @@
<?php
/**
* An exception thrown by PHP_CodeSniffer when it encounters an unrecoverable error.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* An exception thrown by PHP_CodeSniffer when it encounters an unrecoverable error.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_Exception extends Exception
{
}//end class
?>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,47 @@
<?php
/**
* Represents a PHP_CodeSniffer sniff for sniffing coding standards.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Represents a PHP_CodeSniffer multi-file sniff for sniffing coding standards.
*
* A multi-file sniff is called after all files have been checked using the
* regular sniffs. The process() method is passed an array of PHP_CodeSniffer_File
* objects, one for each file checked during the script run.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
interface PHP_CodeSniffer_MultiFileSniff
{
/**
* Called once per script run to allow for processing of this sniff.
*
* @param array(PHP_CodeSniffer_File) $files The PHP_CodeSniffer files processed
* during the script run.
*
* @return void
*/
public function process(array $files);
}//end interface
?>

View File

@@ -0,0 +1,54 @@
<?php
/**
* Represents a PHP_CodeSniffer report.
*
* PHP version 5.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Represents a PHP_CodeSniffer report.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
interface PHP_CodeSniffer_Report
{
/**
* Generate the actual report.
*
* @param array $report Prepared report.
* @param boolean $showSources Show sources?
* @param int $width Maximum allowed lne width.
* @param boolean $toScreen Is the report being printed to screen?
*
* @return string
*/
public function generate(
$report,
$showSources=false,
$width=80,
$toScreen=true
);
}//end interface
?>

View File

@@ -0,0 +1,231 @@
<?php
/**
* A class to manage reporting.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (is_file(dirname(__FILE__).'/../CodeSniffer.php') === true) {
include_once dirname(__FILE__).'/../CodeSniffer.php';
} else {
include_once 'PHP/CodeSniffer.php';
}
/**
* A class to manage reporting.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_Reporting
{
/**
* Produce the appropriate report object based on $type parameter.
*
* @param string $type Demanded report type.
*
* @return PHP_CodeSniffer_Report
* @throws PHP_CodeSniffer_Exception If report is not available.
*/
public function factory($type)
{
$type = ucfirst($type);
$filename = $type.'.php';
$reportClassName = 'PHP_CodeSniffer_Reports_'.$type;
if (class_exists($reportClassName, true) === false) {
throw new PHP_CodeSniffer_Exception('Report type "'.$type.'" not found.');
}
$reportClass = new $reportClassName();
if (false === ($reportClass instanceof PHP_CodeSniffer_Report)) {
throw new PHP_CodeSniffer_Exception('Class "'.$reportClassName.'" must implement the "PHP_CodeSniffer_Report" interface.');
}
return $reportClass;
}//end factory()
/**
* Actually generates the report.
*
* @param string $report Report type.
* @param array $filesViolations Collected violations.
* @param boolean $showSources Show sources?
* @param string $reportFile Report file to generate.
* @param integer $reportWidth Report max width.
*
* @return integer
*/
public function printReport(
$report,
$filesViolations,
$showSources,
$reportFile='',
$reportWidth=80
) {
if ($reportFile !== null) {
$reportDir = dirname($reportFile);
if ($reportDir === '.') {
// Passed report file is a filename in the current directory.
$reportFile = PHPCS_CWD.'/'.basename($reportFile);
} else {
$reportDir = realpath(PHPCS_CWD.'/'.$reportDir);
if ($reportDir !== false) {
// Report file path is relative.
$reportFile = $reportDir.'/'.basename($reportFile);
}
}
}
$reportClass = self::factory($report);
$reportData = $this->prepare($filesViolations);
$toScreen = true;
if ($reportFile !== null) {
$toScreen = false;
ob_start();
}
$numErrors = $reportClass->generate($reportData, $showSources, $reportWidth, $toScreen);
if ($reportFile !== null) {
$generatedReport = ob_get_contents();
if (PHP_CODESNIFFER_VERBOSITY > 0) {
ob_end_flush();
} else {
ob_end_clean();
}
$generatedReport = trim($generatedReport);
file_put_contents($reportFile, $generatedReport.PHP_EOL);
}
return $numErrors;
}//end printReport()
/**
* Pre-process and package violations for all files.
*
* Used by error reports to get a packaged list of all errors in each file.
*
* @param array $filesViolations List of found violations.
*
* @return array
*/
public function prepare(array $filesViolations)
{
$report = array(
'totals' => array(
'warnings' => 0,
'errors' => 0,
),
'files' => array(),
);
foreach ($filesViolations as $filename => $fileViolations) {
$warnings = $fileViolations['warnings'];
$errors = $fileViolations['errors'];
$numWarnings = $fileViolations['numWarnings'];
$numErrors = $fileViolations['numErrors'];
$report['files'][$filename] = array(
'errors' => 0,
'warnings' => 0,
'messages' => array(),
);
if ($numErrors === 0 && $numWarnings === 0) {
// Prefect score!
continue;
}
$report['files'][$filename]['errors'] = $numErrors;
$report['files'][$filename]['warnings'] = $numWarnings;
$report['totals']['errors'] += $numErrors;
$report['totals']['warnings'] += $numWarnings;
// Merge errors and warnings.
foreach ($errors as $line => $lineErrors) {
foreach ($lineErrors as $column => $colErrors) {
$newErrors = array();
foreach ($colErrors as $data) {
$newErrors[] = array(
'message' => $data['message'],
'source' => $data['source'],
'severity' => $data['severity'],
'type' => 'ERROR',
);
}//end foreach
$errors[$line][$column] = $newErrors;
}//end foreach
ksort($errors[$line]);
}//end foreach
foreach ($warnings as $line => $lineWarnings) {
foreach ($lineWarnings as $column => $colWarnings) {
$newWarnings = array();
foreach ($colWarnings as $data) {
$newWarnings[] = array(
'message' => $data['message'],
'source' => $data['source'],
'severity' => $data['severity'],
'type' => 'WARNING',
);
}//end foreach
if (isset($errors[$line]) === false) {
$errors[$line] = array();
}
if (isset($errors[$line][$column]) === true) {
$errors[$line][$column] = array_merge(
$newWarnings,
$errors[$line][$column]
);
} else {
$errors[$line][$column] = $newWarnings;
}
}//end foreach
ksort($errors[$line]);
}//end foreach
ksort($errors);
$report['files'][$filename]['messages'] = $errors;
}//end foreach
ksort($report['files']);
return $report;
}//end prepare()
}//end class
?>

View File

@@ -0,0 +1,104 @@
<?php
/**
* Checkstyle report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Checkstyle report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_Reports_Checkstyle implements PHP_CodeSniffer_Report
{
/**
* Prints all violations for processed files, in a Checkstyle format.
*
* Violations are grouped by file.
*
* @param array $report Prepared report.
* @param boolean $showSources Show sources?
* @param int $width Maximum allowed lne width.
* @param boolean $toScreen Is the report being printed to screen?
*
* @return string
*/
public function generate(
$report,
$showSources=false,
$width=80,
$toScreen=true
) {
$out = new XMLWriter;
$out->openMemory();
$out->setIndent(true);
$out->startDocument('1.0', 'UTF-8');
$out->startElement('checkstyle');
$out->writeAttribute('version', '1.3.3');
$errorsShown = 0;
foreach ($report['files'] as $filename => $file) {
if (count($file['messages']) === 0) {
continue;
}
$out->startElement('file');
$out->writeAttribute('name', $filename);
foreach ($file['messages'] as $line => $lineErrors) {
foreach ($lineErrors as $column => $colErrors) {
foreach ($colErrors as $error) {
$error['type'] = strtolower($error['type']);
if (PHP_CODESNIFFER_ENCODING !== 'utf-8') {
$error['message'] = iconv(PHP_CODESNIFFER_ENCODING, 'utf-8', $error['message']);
}
$out->startElement('error');
$out->writeAttribute('line', $line);
$out->writeAttribute('column', $column);
$out->writeAttribute('severity', $error['type']);
$out->writeAttribute('message', $error['message']);
$out->writeAttribute('source', $error['source']);
$out->endElement();
$errorsShown++;
}
}
}//end foreach
$out->endElement();
}//end foreach
$out->endElement();
echo $out->flush();
return $errorsShown;
}//end generate()
}//end class
?>

View File

@@ -0,0 +1,78 @@
<?php
/**
* Csv report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Csv report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_Reports_Csv implements PHP_CodeSniffer_Report
{
/**
* Generates a csv report.
*
* @param array $report Prepared report.
* @param boolean $showSources Show sources?
* @param int $width Maximum allowed lne width.
* @param boolean $toScreen Is the report being printed to screen?
*
* @return string
*/
public function generate(
$report,
$showSources=false,
$width=80,
$toScreen=true
) {
echo 'File,Line,Column,Type,Message,Source,Severity'.PHP_EOL;
$errorsShown = 0;
foreach ($report['files'] as $filename => $file) {
foreach ($file['messages'] as $line => $lineErrors) {
foreach ($lineErrors as $column => $colErrors) {
foreach ($colErrors as $error) {
$filename = str_replace('"', '\"', $filename);
$message = str_replace('"', '\"', $error['message']);
$type = strtolower($error['type']);
$source = $error['source'];
$severity = $error['severity'];
echo "\"$filename\",$line,$column,$type,\"$message\",$source,$severity".PHP_EOL;
$errorsShown++;
}
}
}//end foreach
}//end foreach
return $errorsShown;
}//end generate()
}//end class
?>

View File

@@ -0,0 +1,78 @@
<?php
/**
* Emacs report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Emacs report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_Reports_Emacs implements PHP_CodeSniffer_Report
{
/**
* Generates an emacs report.
*
* @param array $report Prepared report.
* @param boolean $showSources Show sources?
* @param int $width Maximum allowed lne width.
* @param boolean $toScreen Is the report being printed to screen?
*
* @return string
*/
public function generate(
$report,
$showSources=false,
$width=80,
$toScreen=true
) {
$errorsShown = 0;
foreach ($report['files'] as $filename => $file) {
foreach ($file['messages'] as $line => $lineErrors) {
foreach ($lineErrors as $column => $colErrors) {
foreach ($colErrors as $error) {
$message = $error['message'];
if ($showSources === true) {
$message .= ' ('.$error['source'].')';
}
$type = strtolower($error['type']);
echo $filename.':'.$line.':'.$column.': '.$type.' - '.$message.PHP_EOL;
$errorsShown++;
}
}
}//end foreach
}//end foreach
return $errorsShown;
}//end generate()
}//end class
?>

View File

@@ -0,0 +1,153 @@
<?php
/**
* Full report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Full report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_Reports_Full implements PHP_CodeSniffer_Report
{
/**
* Prints all errors and warnings for each file processed.
*
* Errors and warnings are displayed together, grouped by file.
*
* @param array $report Prepared report.
* @param boolean $showSources Show sources?
* @param int $width Maximum allowed lne width.
* @param boolean $toScreen Is the report being printed to screen?
*
* @return string
*/
public function generate(
$report,
$showSources=false,
$width=80,
$toScreen=true
) {
$errorsShown = 0;
$width = max($width, 70);
foreach ($report['files'] as $filename => $file) {
if (empty($file['messages']) === true) {
continue;
}
echo PHP_EOL.'FILE: ';
if (strlen($filename) <= ($width - 9)) {
echo $filename;
} else {
echo '...'.substr($filename, (strlen($filename) - ($width - 9)));
}
echo PHP_EOL;
echo str_repeat('-', $width).PHP_EOL;
echo 'FOUND '.$file['errors'].' ERROR(S) ';
if ($file['warnings'] > 0) {
echo 'AND '.$file['warnings'].' WARNING(S) ';
}
echo 'AFFECTING '.count($file['messages']).' LINE(S)'.PHP_EOL;
echo str_repeat('-', $width).PHP_EOL;
// Work out the max line number for formatting.
$maxLine = 0;
foreach ($file['messages'] as $line => $lineErrors) {
if ($line > $maxLine) {
$maxLine = $line;
}
}
$maxLineLength = strlen($maxLine);
// The length of the word ERROR or WARNING; used for padding.
if ($file['warnings'] > 0) {
$typeLength = 7;
} else {
$typeLength = 5;
}
// The padding that all lines will require that are
// printing an error message overflow.
$paddingLine2 = str_repeat(' ', ($maxLineLength + 1));
$paddingLine2 .= ' | ';
$paddingLine2 .= str_repeat(' ', $typeLength);
$paddingLine2 .= ' | ';
// The maxium amount of space an error message can use.
$maxErrorSpace = ($width - strlen($paddingLine2) - 1);
foreach ($file['messages'] as $line => $lineErrors) {
foreach ($lineErrors as $column => $colErrors) {
foreach ($colErrors as $error) {
$message = $error['message'];
if ($showSources === true) {
$message .= ' ('.$error['source'].')';
}
// The padding that goes on the front of the line.
$padding = ($maxLineLength - strlen($line));
$errorMsg = wordwrap(
$message,
$maxErrorSpace,
PHP_EOL.$paddingLine2
);
echo ' '.str_repeat(' ', $padding).$line.' | '.$error['type'];
if ($error['type'] === 'ERROR') {
if ($file['warnings'] > 0) {
echo ' ';
}
}
echo ' | '.$errorMsg.PHP_EOL;
$errorsShown++;
}//end foreach
}//end foreach
}//end foreach
echo str_repeat('-', $width).PHP_EOL.PHP_EOL;
}//end foreach
if ($toScreen === true
&& PHP_CODESNIFFER_INTERACTIVE === false
&& class_exists('PHP_Timer', false) === true
) {
echo PHP_Timer::resourceUsage().PHP_EOL.PHP_EOL;
}
return $errorsShown;
}//end generate()
}//end class
?>

View File

@@ -0,0 +1,133 @@
<?php
/**
* Gitblame report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Ben Selby <benmatselby@gmail.com>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Gitblame report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Ben Selby <benmatselby@gmail.com>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.2.2
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_Reports_Gitblame extends PHP_CodeSniffer_Reports_VersionControl
{
/**
* The name of the report we want in the output
*
* @var string
*/
protected $reportName = 'GIT';
/**
* Extract the author from a blame line.
*
* @param string $line Line to parse.
*
* @return mixed string or false if impossible to recover.
*/
protected function getAuthor($line)
{
$blameParts = array();
$line = preg_replace('|\s+|', ' ', $line);
preg_match(
'|\(.+[0-9]{4}-[0-9]{2}-[0-9]{2}\s+[0-9]+\)|',
$line,
$blameParts
);
if (isset($blameParts[0]) === false) {
return false;
}
$parts = explode(' ', $blameParts[0]);
if (count($parts) < 2) {
return false;
}
$parts = array_slice($parts, 0, (count($parts) - 2));
return preg_replace('|\(|', '', implode($parts, ' '));
}//end getAuthor()
/**
* Gets the blame output.
*
* @param string $filename File to blame.
*
* @return array
*/
protected function getBlameContent($filename)
{
$cwd = getcwd();
if (PHP_CODESNIFFER_VERBOSITY > 0) {
echo 'Getting GIT blame info for '.basename($filename).'... ';
}
$fileParts = explode('/', $filename);
$found = false;
$location = '';
while (empty($fileParts) === false) {
array_pop($fileParts);
$location = implode($fileParts, '/');
if (is_dir($location.'/.git') === true) {
$found = true;
break;
}
}
if ($found === true) {
chdir($location);
} else {
echo 'ERROR: Could not locate .git directory '.PHP_EOL.PHP_EOL;
exit(2);
}
$command = 'git blame --date=short '.$filename;
$handle = popen($command, 'r');
if ($handle === false) {
echo 'ERROR: Could not execute "'.$command.'"'.PHP_EOL.PHP_EOL;
exit(2);
}
$rawContent = stream_get_contents($handle);
fclose($handle);
if (PHP_CODESNIFFER_VERBOSITY > 0) {
echo 'DONE'.PHP_EOL;
}
$blames = explode("\n", $rawContent);
chdir($cwd);
return $blames;
}//end getBlameContent()
}//end class
?>

View File

@@ -0,0 +1,134 @@
<?php
/**
* Mercurial report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Ben Selby <benmatselby@gmail.com>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Mercurial report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Ben Selby <benmatselby@gmail.com>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_Reports_Hgblame extends PHP_CodeSniffer_Reports_VersionControl
{
/**
* The name of the report we want in the output
*
* @var string
*/
protected $reportName = 'MERCURIAL';
/**
* Extract the author from a blame line.
*
* @param string $line Line to parse.
*
* @return mixed string or false if impossible to recover.
*/
protected function getAuthor($line)
{
$blameParts = array();
$line = preg_replace('|\s+|', ' ', $line);
preg_match(
'|(.+[0-9]{2}:[0-9]{2}:[0-9]{2}\s[0-9]{4}\s.[0-9]{4}:)|',
$line,
$blameParts
);
if (isset($blameParts[0]) === false) {
return false;
}
$parts = explode(' ', $blameParts[0]);
if (count($parts) < 6) {
return false;
}
$parts = array_slice($parts, 0, (count($parts) - 6));
return trim(preg_replace('|<.+>|', '', implode($parts, ' ')));
}//end getAuthor()
/**
* Gets the blame output.
*
* @param string $filename File to blame.
*
* @return array
*/
protected function getBlameContent($filename)
{
$cwd = getcwd();
if (PHP_CODESNIFFER_VERBOSITY > 0) {
echo 'Getting MERCURIAL blame info for '.basename($filename).'... ';
}
$fileParts = explode('/', $filename);
$found = false;
$location = '';
while (empty($fileParts) === false) {
array_pop($fileParts);
$location = implode($fileParts, '/');
if (is_dir($location.'/.hg') === true) {
$found = true;
break;
}
}
if ($found === true) {
chdir($location);
} else {
echo 'ERROR: Could not locate .hg directory '.PHP_EOL.PHP_EOL;
exit(2);
}
$command = 'hg blame -u -d -v '.$filename;
$handle = popen($command, 'r');
if ($handle === false) {
echo 'ERROR: Could not execute "'.$command.'"'.PHP_EOL.PHP_EOL;
exit(2);
}
$rawContent = stream_get_contents($handle);
fclose($handle);
if (PHP_CODESNIFFER_VERBOSITY > 0) {
echo 'DONE'.PHP_EOL;
}
$blames = explode("\n", $rawContent);
chdir($cwd);
return $blames;
}//end getBlameContent()
}//end class
?>

View File

@@ -0,0 +1,202 @@
<?php
/**
* Source report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Source report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_Reports_Source implements PHP_CodeSniffer_Report
{
/**
* Prints the source of all errors and warnings.
*
* @param array $report Prepared report.
* @param boolean $showSources Show sources?
* @param int $width Maximum allowed lne width.
* @param boolean $toScreen Is the report being printed to screen?
*
* @return string
*/
public function generate(
$report,
$showSources=false,
$width=80,
$toScreen=true
) {
$sources = array();
$width = max($width, 70);
$errorsShown = 0;
foreach ($report['files'] as $filename => $file) {
foreach ($file['messages'] as $line => $lineErrors) {
foreach ($lineErrors as $column => $colErrors) {
foreach ($colErrors as $error) {
$errorsShown++;
$source = $error['source'];
if (isset($sources[$source]) === false) {
$sources[$source] = 1;
} else {
$sources[$source]++;
}
}
}
}
}
if ($errorsShown === 0) {
// Nothing to show.
return 0;
}
asort($sources);
$sources = array_reverse($sources);
echo PHP_EOL.'PHP CODE SNIFFER VIOLATION SOURCE SUMMARY'.PHP_EOL;
echo str_repeat('-', $width).PHP_EOL;
if ($showSources === true) {
echo 'SOURCE'.str_repeat(' ', ($width - 11)).'COUNT'.PHP_EOL;
echo str_repeat('-', $width).PHP_EOL;
} else {
echo 'STANDARD CATEGORY SNIFF'.str_repeat(' ', ($width - 40)).'COUNT'.PHP_EOL;
echo str_repeat('-', $width).PHP_EOL;
}
foreach ($sources as $source => $count) {
if ($showSources === true) {
echo $source.str_repeat(' ', ($width - 5 - strlen($source)));
} else {
$parts = explode('.', $source);
if (strlen($parts[0]) > 8) {
$parts[0] = substr($parts[0], 0, ((strlen($parts[0]) - 8) * -1));
}
echo $parts[0].str_repeat(' ', (10 - strlen($parts[0])));
$category = $this->makeFriendlyName($parts[1]);
if (strlen($category) > 18) {
$category = substr($category, 0, ((strlen($category) - 18) * -1));
}
echo $category.str_repeat(' ', (20 - strlen($category)));
$sniff = $this->makeFriendlyName($parts[2]);
if (isset($parts[3]) === true) {
$name = $this->makeFriendlyName($parts[3]);
$name[0] = strtolower($name[0]);
$sniff .= ' '.$name;
}
if (strlen($sniff) > ($width - 37)) {
$sniff = substr($sniff, 0, ($width - 37 - strlen($sniff)));
}
echo $sniff.str_repeat(' ', ($width - 35 - strlen($sniff)));
}//end if
echo $count.PHP_EOL;
}//end foreach
echo str_repeat('-', $width).PHP_EOL;
echo 'A TOTAL OF '.$errorsShown.' SNIFF VIOLATION(S) ';
echo 'WERE FOUND IN '.count($sources).' SOURCE(S)'.PHP_EOL;
echo str_repeat('-', $width).PHP_EOL.PHP_EOL;
if ($toScreen === true
&& PHP_CODESNIFFER_INTERACTIVE === false
&& class_exists('PHP_Timer', false) === true
) {
echo PHP_Timer::resourceUsage().PHP_EOL.PHP_EOL;
}
return $errorsShown;
}//end generate()
/**
* Converts a camel caps name into a readable string.
*
* @param string $name The camel caps name to convert.
*
* @return string
*/
public function makeFriendlyName($name)
{
$friendlyName = '';
$length = strlen($name);
$lastWasUpper = false;
$lastWasNumeric = false;
for ($i = 0; $i < $length; $i++) {
if (is_numeric($name[$i]) === true) {
if ($lastWasNumeric === false) {
$friendlyName .= ' ';
}
$lastWasUpper = false;
$lastWasNumeric = true;
} else {
$lastWasNumeric = false;
$char = strtolower($name[$i]);
if ($char === $name[$i]) {
// Lowercase.
$lastWasUpper = false;
} else {
// Uppercase.
if ($lastWasUpper === false) {
$friendlyName .= ' ';
$next = $name[($i + 1)];
if (strtolower($next) === $next) {
// Next char is lowercase so it is a word boundary.
$name[$i] = strtolower($name[$i]);
}
}
$lastWasUpper = true;
}
}//end if
$friendlyName .= $name[$i];
}//end for
$friendlyName = trim($friendlyName);
$friendlyName[0] = strtoupper($friendlyName[0]);
return $friendlyName;
}//end makeFriendlyName()
}//end class
?>

View File

@@ -0,0 +1,132 @@
<?php
/**
* Summary report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Summary report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_Reports_Summary implements PHP_CodeSniffer_Report
{
/**
* Generates a summary of errors and warnings for each file processed.
*
* If verbose output is enabled, results are shown for all files, even if
* they have no errors or warnings. If verbose output is disabled, we only
* show files that have at least one warning or error.
*
* @param array $report Prepared report.
* @param boolean $showSources Show sources?
* @param int $width Maximum allowed lne width.
* @param boolean $toScreen Is the report being printed to screen?
*
* @return string
*/
public function generate(
$report,
$showSources=false,
$width=80,
$toScreen=true
) {
$errorFiles = array();
$width = max($width, 70);
foreach ($report['files'] as $filename => $file) {
$numWarnings = $file['warnings'];
$numErrors = $file['errors'];
// If verbose output is enabled, we show the results for all files,
// but if not, we only show files that had errors or warnings.
if (PHP_CODESNIFFER_VERBOSITY > 0
|| $numErrors > 0
|| $numWarnings > 0
) {
$errorFiles[$filename] = array(
'warnings' => $numWarnings,
'errors' => $numErrors,
);
}//end if
}//end foreach
if (empty($errorFiles) === true) {
// Nothing to print.
return 0;
}
echo PHP_EOL.'PHP CODE SNIFFER REPORT SUMMARY'.PHP_EOL;
echo str_repeat('-', $width).PHP_EOL;
echo 'FILE'.str_repeat(' ', ($width - 20)).'ERRORS WARNINGS'.PHP_EOL;
echo str_repeat('-', $width).PHP_EOL;
$totalErrors = 0;
$totalWarnings = 0;
$totalFiles = 0;
foreach ($errorFiles as $file => $errors) {
$padding = ($width - 18 - strlen($file));
if ($padding < 0) {
$file = '...'.substr($file, (($padding * -1) + 3));
$padding = 0;
}
echo $file.str_repeat(' ', $padding).' ';
echo $errors['errors'];
echo str_repeat(' ', (8 - strlen((string) $errors['errors'])));
echo $errors['warnings'];
echo PHP_EOL;
$totalFiles++;
}//end foreach
echo str_repeat('-', $width).PHP_EOL;
echo 'A TOTAL OF '.$report['totals']['errors'].' ERROR(S) ';
echo 'AND '.$report['totals']['warnings'].' WARNING(S) ';
echo 'WERE FOUND IN '.$totalFiles.' FILE(S)'.PHP_EOL;
echo str_repeat('-', $width).PHP_EOL.PHP_EOL;
if ($showSources === true) {
$source = new PHP_CodeSniffer_Reports_Source();
$source->generate($report, $showSources, $width);
}
if ($toScreen === true
&& PHP_CODESNIFFER_INTERACTIVE === false
&& class_exists('PHP_Timer', false) === true
) {
echo PHP_Timer::resourceUsage().PHP_EOL.PHP_EOL;
}
return ($report['totals']['errors'] + $report['totals']['warnings']);
}//end generate()
}//end class
?>

View File

@@ -0,0 +1,100 @@
<?php
/**
* Svnblame report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Svnblame report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_Reports_Svnblame extends PHP_CodeSniffer_Reports_VersionControl
{
/**
* The name of the report we want in the output
*
* @var string
*/
protected $reportName = 'SVN';
/**
* Extract the author from a blame line.
*
* @param string $line Line to parse.
*
* @return mixed string or false if impossible to recover.
*/
protected function getAuthor($line)
{
$blameParts = array();
preg_match('|\s*([^\s]+)\s+([^\s]+)|', $line, $blameParts);
if (isset($blameParts[2]) === false) {
return false;
}
return $blameParts[2];
}//end getAuthor()
/**
* Gets the blame output.
*
* @param string $filename File to blame.
*
* @return array
*/
protected function getBlameContent($filename)
{
if (PHP_CODESNIFFER_VERBOSITY > 0) {
echo 'Getting SVN blame info for '.basename($filename).'... ';
}
$command = 'svn blame '.$filename;
$handle = popen($command, 'r');
if ($handle === false) {
echo 'ERROR: Could not execute "'.$command.'"'.PHP_EOL.PHP_EOL;
exit(2);
}
$rawContent = stream_get_contents($handle);
fclose($handle);
if (PHP_CODESNIFFER_VERBOSITY > 0) {
echo 'DONE'.PHP_EOL;
}
$blames = explode("\n", $rawContent);
return $blames;
}//end getBlameContent()
}//end class
?>

View File

@@ -0,0 +1,216 @@
<?php
/**
* Version control report base class for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Ben Selby <benmatselby@gmail.com>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Version control report base class for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Ben Selby <benmatselby@gmail.com>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.2.2
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
abstract class PHP_CodeSniffer_Reports_VersionControl implements PHP_CodeSniffer_Report
{
/**
* The name of the report we want in the output.
*
* @var string
*/
protected $reportName = 'VERSION CONTROL';
/**
* Prints the author of all errors and warnings, as given by "version control blame".
*
* @param array $report Prepared report.
* @param boolean $showSources Show sources?
* @param integer $width Maximum allowed lne width.
* @param boolean $toScreen Is the report being printed to screen?
*
* @return string
*/
public function generate(
$report,
$showSources=false,
$width=80,
$toScreen=true
) {
$authors = array();
$praise = array();
$sources = array();
$width = max($width, 70);
$errorsShown = 0;
foreach ($report['files'] as $filename => $file) {
$blames = $this->getBlameContent($filename);
foreach ($file['messages'] as $line => $lineErrors) {
$author = $this->getAuthor($blames[($line - 1)]);
if ($author === false) {
continue;
}
if (isset($authors[$author]) === false) {
$authors[$author] = 0;
$praise[$author] = array(
'good' => 0,
'bad' => 0,
);
}
$praise[$author]['bad']++;
foreach ($lineErrors as $column => $colErrors) {
foreach ($colErrors as $error) {
$errorsShown++;
$authors[$author]++;
if ($showSources === true) {
$source = $error['source'];
if (isset($sources[$author][$source]) === false) {
$sources[$author][$source] = 1;
} else {
$sources[$author][$source]++;
}
}
}
}
unset($blames[($line - 1)]);
}//end foreach
// No go through and give the authors some credit for
// all the lines that do not have errors.
foreach ($blames as $line) {
$author = $this->getAuthor($line);
if (false === $author) {
continue;
}
if (isset($authors[$author]) === false) {
// This author doesn't have any errors.
if (PHP_CODESNIFFER_VERBOSITY === 0) {
continue;
}
$authors[$author] = 0;
$praise[$author] = array(
'good' => 0,
'bad' => 0,
);
}
$praise[$author]['good']++;
}//end foreach
}//end foreach
if ($errorsShown === 0) {
// Nothing to show.
return 0;
}
arsort($authors);
echo PHP_EOL.'PHP CODE SNIFFER '.$this->reportName.' BLAME SUMMARY'.PHP_EOL;
echo str_repeat('-', $width).PHP_EOL;
if ($showSources === true) {
echo 'AUTHOR SOURCE'.str_repeat(' ', ($width - 43)).'(Author %) (Overall %) COUNT'.PHP_EOL;
echo str_repeat('-', $width).PHP_EOL;
} else {
echo 'AUTHOR'.str_repeat(' ', ($width - 34)).'(Author %) (Overall %) COUNT'.PHP_EOL;
echo str_repeat('-', $width).PHP_EOL;
}
foreach ($authors as $author => $count) {
if ($praise[$author]['good'] === 0) {
$percent = 0;
} else {
$total = ($praise[$author]['bad'] + $praise[$author]['good']);
$percent = round(($praise[$author]['bad'] / $total * 100), 2);
}
$overallPercent = '('.round((($count / $errorsShown) * 100), 2).')';
$authorPercent = '('.$percent.')';
$line = str_repeat(' ', (6 - strlen($count))).$count;
$line = str_repeat(' ', (12 - strlen($overallPercent))).$overallPercent.$line;
$line = str_repeat(' ', (11 - strlen($authorPercent))).$authorPercent.$line;
$line = $author.str_repeat(' ', ($width - strlen($author) - strlen($line))).$line;
echo $line.PHP_EOL;
if ($showSources === true && isset($sources[$author]) === true) {
$errors = $sources[$author];
asort($errors);
$errors = array_reverse($errors);
foreach ($errors as $source => $count) {
if ($source === 'count') {
continue;
}
$line = str_repeat(' ', (5 - strlen($count))).$count;
echo ' '.$source.str_repeat(' ', ($width - 14 - strlen($source))).$line.PHP_EOL;
}
}
}//end foreach
echo str_repeat('-', $width).PHP_EOL;
echo 'A TOTAL OF '.$errorsShown.' SNIFF VIOLATION(S) ';
echo 'WERE COMMITTED BY '.count($authors).' AUTHOR(S)'.PHP_EOL;
echo str_repeat('-', $width).PHP_EOL.PHP_EOL;
if ($toScreen === true
&& PHP_CODESNIFFER_INTERACTIVE === false
&& class_exists('PHP_Timer', false) === true
) {
echo PHP_Timer::resourceUsage().PHP_EOL.PHP_EOL;
}
return $errorsShown;
}//end generate()
/**
* Extract the author from a blame line.
*
* @param string $line Line to parse.
*
* @return mixed string or false if impossible to recover.
*/
abstract protected function getAuthor($line);
/**
* Gets the blame output.
*
* @param string $filename File to blame.
*
* @return array
*/
abstract protected function getBlameContent($filename);
}//end class
?>

View File

@@ -0,0 +1,107 @@
<?php
/**
* Xml report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Xml report for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Gabriele Santini <gsantini@sqli.com>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2009 SQLI <www.sqli.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_Reports_Xml implements PHP_CodeSniffer_Report
{
/**
* Prints all violations for processed files, in a proprietary XML format.
*
* Errors and warnings are displayed together, grouped by file.
*
* @param array $report Prepared report.
* @param boolean $showSources Show sources?
* @param int $width Maximum allowed lne width.
* @param boolean $toScreen Is the report being printed to screen?
*
* @return string
*/
public function generate(
$report,
$showSources=false,
$width=80,
$toScreen=true
) {
$out = new XMLWriter;
$out->openMemory();
$out->setIndent(true);
$out->startDocument('1.0', 'UTF-8');
$out->startElement('phpcs');
$out->writeAttribute('version', '1.3.3');
$errorsShown = 0;
foreach ($report['files'] as $filename => $file) {
if (empty($file['messages']) === true) {
continue;
}
$out->startElement('file');
$out->writeAttribute('name', $filename);
$out->writeAttribute('errors', $file['errors']);
$out->writeAttribute('warnings', $file['warnings']);
foreach ($file['messages'] as $line => $lineErrors) {
foreach ($lineErrors as $column => $colErrors) {
foreach ($colErrors as $error) {
$error['type'] = strtolower($error['type']);
if (PHP_CODESNIFFER_ENCODING !== 'utf-8') {
$error['message'] = iconv(PHP_CODESNIFFER_ENCODING, 'utf-8', $error['message']);
}
$out->startElement($error['type']);
$out->writeAttribute('line', $line);
$out->writeAttribute('column', $column);
$out->writeAttribute('source', $error['source']);
$out->writeAttribute('severity', $error['severity']);
$out->text($error['message']);
$out->endElement();
$errorsShown++;
}
}
}//end foreach
$out->endElement();
}//end foreach
$out->endElement();
echo $out->flush();
return $errorsShown;
}//end generate()
}//end class
?>

View File

@@ -0,0 +1,93 @@
<?php
/**
* Represents a PHP_CodeSniffer sniff for sniffing coding standards.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Represents a PHP_CodeSniffer sniff for sniffing coding standards.
*
* A sniff registers what token types it wishes to listen for, then, when
* PHP_CodeSniffer encounters that token, the sniff is invoked and passed
* information about where the token was found in the stack, and the
* PHP_CodeSniffer file in which the token was found.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
interface PHP_CodeSniffer_Sniff
{
/**
* Registers the tokens that this sniff wants to listen for.
*
* An example return value for a sniff that wants to listen for whitespace
* and any comments would be:
*
* <code>
* return array(
* T_WHITESPACE,
* T_DOC_COMMENT,
* T_COMMENT,
* );
* </code>
*
* @return array(int)
* @see Tokens.php
*/
public function register();
/**
* Called when one of the token types that this sniff is listening for
* is found.
*
* The stackPtr variable indicates where in the stack the token was found.
* A sniff can acquire information this token, along with all the other
* tokens within the stack by first acquiring the token stack:
*
* <code>
* $tokens = $phpcsFile->getTokens();
* echo 'Encountered a '.$tokens[$stackPtr]['type'].' token';
* echo 'token information: ';
* print_r($tokens[$stackPtr]);
* </code>
*
* If the sniff discovers an anomilty in the code, they can raise an error
* by calling addError() on the PHP_CodeSniffer_File object, specifying an error
* message and the position of the offending token:
*
* <code>
* $phpcsFile->addError('Encountered an error', $stackPtr);
* </code>
*
* @param PHP_CodeSniffer_File $phpcsFile The PHP_CodeSniffer file where the
* token was found.
* @param int $stackPtr The position in the PHP_CodeSniffer
* file's token stack where the token
* was found.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr);
}//end interface
?>

View File

@@ -0,0 +1,925 @@
<?php
/**
* Processes pattern strings and checks that the code conforms to the pattern.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (class_exists('PHP_CodeSniffer_Standards_IncorrectPatternException', true) === false) {
$error = 'Class PHP_CodeSniffer_Standards_IncorrectPatternException not found';
throw new PHP_CodeSniffer_Exception($error);
}
/**
* Processes pattern strings and checks that the code conforms to the pattern.
*
* This test essentially checks that code is correctly formatted with whitespace.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
abstract class PHP_CodeSniffer_Standards_AbstractPatternSniff implements PHP_CodeSniffer_Sniff
{
/**
* The current file being checked.
*
* @var string
*/
protected $currFile = '';
/**
* The parsed patterns array.
*
* @var array
*/
private $_parsedPatterns = array();
/**
* Tokens that this sniff wishes to process outside of the patterns.
*
* @var array(int)
* @see registerSupplementary()
* @see processSupplementary()
*/
private $_supplementaryTokens = array();
/**
* If true, comments will be ignored if they are found in the code.
*
* @var boolean
*/
private $_ignoreComments = false;
/**
* Positions in the stack where errors have occured.
*
* @var array()
*/
private $_errorPos = array();
/**
* Constructs a PHP_CodeSniffer_Standards_AbstractPatternSniff.
*
* @param boolean $ignoreComments If true, comments will be ignored.
*/
public function __construct($ignoreComments=false)
{
$this->_ignoreComments = $ignoreComments;
$this->_supplementaryTokens = $this->registerSupplementary();
}//end __construct()
/**
* Registers the tokens to listen to.
*
* Classes extending <i>AbstractPatternTest</i> should implement the
* <i>getPatterns()</i> method to register the patterns they wish to test.
*
* @return array(int)
* @see process()
*/
public final function register()
{
$listenTypes = array();
$patterns = $this->getPatterns();
foreach ($patterns as $pattern) {
$parsedPattern = $this->_parse($pattern);
// Find a token position in the pattern that we can use
// for a listener token.
$pos = $this->_getListenerTokenPos($parsedPattern);
$tokenType = $parsedPattern[$pos]['token'];
$listenTypes[] = $tokenType;
$patternArray = array(
'listen_pos' => $pos,
'pattern' => $parsedPattern,
'pattern_code' => $pattern,
);
if (isset($this->_parsedPatterns[$tokenType]) === false) {
$this->_parsedPatterns[$tokenType] = array();
}
$this->_parsedPatterns[$tokenType][] = $patternArray;
}//end foreach
return array_unique(array_merge($listenTypes, $this->_supplementaryTokens));
}//end register()
/**
* Returns the token types that the specified pattern is checking for.
*
* Returned array is in the format:
* <code>
* array(
* T_WHITESPACE => 0, // 0 is the position where the T_WHITESPACE token
* // should occur in the pattern.
* );
* </code>
*
* @param array $pattern The parsed pattern to find the acquire the token
* types from.
*
* @return array(int => int)
*/
private function _getPatternTokenTypes($pattern)
{
$tokenTypes = array();
foreach ($pattern as $pos => $patternInfo) {
if ($patternInfo['type'] === 'token') {
if (isset($tokenTypes[$patternInfo['token']]) === false) {
$tokenTypes[$patternInfo['token']] = $pos;
}
}
}
return $tokenTypes;
}//end _getPatternTokenTypes()
/**
* Returns the position in the pattern that this test should register as
* a listener for the pattern.
*
* @param array $pattern The pattern to acquire the listener for.
*
* @return int The postition in the pattern that this test should register
* as the listener.
* @throws PHP_CodeSniffer_Exception If we could not determine a token
* to listen for.
*/
private function _getListenerTokenPos($pattern)
{
$tokenTypes = $this->_getPatternTokenTypes($pattern);
$tokenCodes = array_keys($tokenTypes);
$token = PHP_CodeSniffer_Tokens::getHighestWeightedToken($tokenCodes);
// If we could not get a token.
if ($token === false) {
$error = 'Could not determine a token to listen for';
throw new PHP_CodeSniffer_Exception($error);
}
return $tokenTypes[$token];
}//end _getListenerTokenPos()
/**
* Processes the test.
*
* @param PHP_CodeSniffer_File $phpcsFile The PHP_CodeSniffer file where the
* token occured.
* @param int $stackPtr The postion in the tokens stack
* where the listening token type was
* found.
*
* @return void
* @see register()
*/
public final function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$file = $phpcsFile->getFilename();
if ($this->currFile !== $file) {
// We have changed files, so clean up.
$this->_errorPos = array();
$this->currFile = $file;
}
$tokens = $phpcsFile->getTokens();
if (in_array($tokens[$stackPtr]['code'], $this->_supplementaryTokens) === true) {
$this->processSupplementary($phpcsFile, $stackPtr);
}
$type = $tokens[$stackPtr]['code'];
// If the type is not set, then it must have been a token registered
// with registerSupplementary().
if (isset($this->_parsedPatterns[$type]) === false) {
return;
}
$allErrors = array();
// Loop over each pattern that is listening to the current token type
// that we are processing.
foreach ($this->_parsedPatterns[$type] as $patternInfo) {
// If processPattern returns false, then the pattern that we are
// checking the code with must not be designed to check that code.
$errors = $this->processPattern($patternInfo, $phpcsFile, $stackPtr);
if ($errors === false) {
// The pattern didn't match.
continue;
} else if (empty($errors) === true) {
// The pattern matched, but there were no errors.
break;
}
foreach ($errors as $stackPtr => $error) {
if (isset($this->_errorPos[$stackPtr]) === false) {
$this->_errorPos[$stackPtr] = true;
$allErrors[$stackPtr] = $error;
}
}
}
foreach ($allErrors as $stackPtr => $error) {
$phpcsFile->addError($error, $stackPtr);
}
}//end process()
/**
* Processes the pattern and verifies the code at $stackPtr.
*
* @param array $patternInfo Information about the pattern used
* for checking, which includes are
* parsed token representation of the
* pattern.
* @param PHP_CodeSniffer_File $phpcsFile The PHP_CodeSniffer file where the
* token occured.
* @param int $stackPtr The postion in the tokens stack where
* the listening token type was found.
*
* @return array(errors)
*/
protected function processPattern(
$patternInfo,
PHP_CodeSniffer_File $phpcsFile,
$stackPtr
) {
$tokens = $phpcsFile->getTokens();
$pattern = $patternInfo['pattern'];
$patternCode = $patternInfo['pattern_code'];
$errors = array();
$found = '';
$ignoreTokens = array(T_WHITESPACE);
if ($this->_ignoreComments === true) {
$ignoreTokens
= array_merge($ignoreTokens, PHP_CodeSniffer_Tokens::$commentTokens);
}
$origStackPtr = $stackPtr;
$hasError = false;
if ($patternInfo['listen_pos'] > 0) {
$stackPtr--;
for ($i = ($patternInfo['listen_pos'] - 1); $i >= 0; $i--) {
if ($pattern[$i]['type'] === 'token') {
if ($pattern[$i]['token'] === T_WHITESPACE) {
if ($tokens[$stackPtr]['code'] === T_WHITESPACE) {
$found = $tokens[$stackPtr]['content'].$found;
}
// Only check the size of the whitespace if this is not
// the first token. We don't care about the size of
// leading whitespace, just that there is some.
if ($i !== 0) {
if ($tokens[$stackPtr]['content'] !== $pattern[$i]['value']) {
$hasError = true;
}
}
} else {
// Check to see if this important token is the same as the
// previous important token in the pattern. If it is not,
// then the pattern cannot be for this piece of code.
$prev = $phpcsFile->findPrevious(
$ignoreTokens,
$stackPtr,
null,
true
);
if ($prev === false
|| $tokens[$prev]['code'] !== $pattern[$i]['token']
) {
return false;
}
// If we skipped past some whitespace tokens, then add them
// to the found string.
if (($stackPtr - $prev) > 1) {
for ($j = ($stackPtr - 1); $j > $prev; $j--) {
$found = $tokens[$j]['content'].$found;
}
}
$found = $tokens[$prev]['content'].$found;
if (isset($pattern[($i - 1)]) === true
&& $pattern[($i - 1)]['type'] === 'skip'
) {
$stackPtr = $prev;
} else {
$stackPtr = ($prev - 1);
}
}//end if
} else if ($pattern[$i]['type'] === 'skip') {
// Skip to next piece of relevant code.
if ($pattern[$i]['to'] === 'parenthesis_closer') {
$to = 'parenthesis_opener';
} else {
$to = 'scope_opener';
}
// Find the previous opener.
$next = $phpcsFile->findPrevious(
$ignoreTokens,
$stackPtr,
null,
true
);
if ($next === false || isset($tokens[$next][$to]) === false) {
// If there was not opener, then we must be
// using the wrong pattern.
return false;
}
if ($to === 'parenthesis_opener') {
$found = '{'.$found;
} else {
$found = '('.$found;
}
$found = '...'.$found;
// Skip to the opening token.
$stackPtr = ($tokens[$next][$to] - 1);
} else if ($pattern[$i]['type'] === 'string') {
$found = 'abc';
} else if ($pattern[$i]['type'] === 'newline') {
if ($tokens[$stackPtr]['code'] === T_WHITESPACE) {
if ($tokens[$stackPtr]['content'] !== $phpcsFile->eolChar) {
$found = $tokens[$stackPtr]['content'].$found;
// This may just be an indent that comes after a newline
// so check the token before to make sure. If it is a newline, we
// can ignore the error here.
if ($tokens[($stackPtr - 1)]['content'] !== $phpcsFile->eolChar) {
$hasError = true;
}
} else {
$found = 'EOL'.$found;
}
} else {
$found = $tokens[$stackPtr]['content'].$found;
$hasError = true;
}
}//end if
}//end for
}//end if
$stackPtr = $origStackPtr;
$lastAddedStackPtr = null;
$patternLen = count($pattern);
for ($i = $patternInfo['listen_pos']; $i < $patternLen; $i++) {
if ($pattern[$i]['type'] === 'token') {
if ($pattern[$i]['token'] === T_WHITESPACE) {
if ($this->_ignoreComments === true) {
// If we are ignoring comments, check to see if this current
// token is a comment. If so skip it.
if (in_array($tokens[$stackPtr]['code'], PHP_CodeSniffer_Tokens::$commentTokens) === true) {
continue;
}
// If the next token is a comment, the we need to skip the
// current token as we should allow a space before a
// comment for readability.
if (in_array($tokens[($stackPtr + 1)]['code'], PHP_CodeSniffer_Tokens::$commentTokens) === true) {
continue;
}
}
$tokenContent = '';
if ($tokens[$stackPtr]['code'] === T_WHITESPACE) {
if (isset($pattern[($i + 1)]) === false) {
// This is the last token in the pattern, so just compare
// the next token of content.
$tokenContent = $tokens[$stackPtr]['content'];
} else {
// Get all the whitespace to the next token.
$next = $phpcsFile->findNext(
PHP_CodeSniffer_Tokens::$emptyTokens,
$stackPtr,
null,
true
);
$tokenContent = $phpcsFile->getTokensAsString(
$stackPtr,
($next - $stackPtr)
);
$lastAddedStackPtr = $stackPtr;
$stackPtr = $next;
}
if ($stackPtr !== $lastAddedStackPtr) {
$found .= $tokenContent;
}
} else {
if ($stackPtr !== $lastAddedStackPtr) {
$found .= $tokens[$stackPtr]['content'];
$lastAddedStackPtr = $stackPtr;
}
}//end if
if (isset($pattern[($i + 1)]) === true
&& $pattern[($i + 1)]['type'] === 'skip'
) {
// The next token is a skip token, so we just need to make
// sure the whitespace we found has *at least* the
// whitespace required.
if (strpos($tokenContent, $pattern[$i]['value']) !== 0) {
$hasError = true;
}
} else {
if ($tokenContent !== $pattern[$i]['value']) {
$hasError = true;
}
}
} else {
// Check to see if this important token is the same as the
// next important token in the pattern. If it is not, then
// the pattern cannot be for this piece of code.
$next = $phpcsFile->findNext(
$ignoreTokens,
$stackPtr,
null,
true
);
if ($next === false
|| $tokens[$next]['code'] !== $pattern[$i]['token']
) {
// The next important token did not match the pattern.
return false;
}
if ($lastAddedStackPtr !== null) {
if (($tokens[$next]['code'] === T_OPEN_CURLY_BRACKET
|| $tokens[$next]['code'] === T_CLOSE_CURLY_BRACKET)
&& isset($tokens[$next]['scope_condition']) === true
&& $tokens[$next]['scope_condition'] > $lastAddedStackPtr
) {
// This is a brace, but the owner of it is after the current
// token, which means it does not belong to any token in
// our pattern. This means the pattern is not for us.
return false;
}
if (($tokens[$next]['code'] === T_OPEN_PARENTHESIS
|| $tokens[$next]['code'] === T_CLOSE_PARENTHESIS)
&& isset($tokens[$next]['parenthesis_owner']) === true
&& $tokens[$next]['parenthesis_owner'] > $lastAddedStackPtr
) {
// This is a bracket, but the owner of it is after the current
// token, which means it does not belong to any token in
// our pattern. This means the pattern is not for us.
return false;
}
}//end if
// If we skipped past some whitespace tokens, then add them
// to the found string.
if (($next - $stackPtr) > 0) {
$hasComment = false;
for ($j = $stackPtr; $j < $next; $j++) {
$found .= $tokens[$j]['content'];
if (in_array($tokens[$j]['code'], PHP_CodeSniffer_Tokens::$commentTokens) === true) {
$hasComment = true;
}
}
// If we are not ignoring comments, this additional
// whitespace or comment is not allowed. If we are
// ignoring comments, there needs to be at least one
// comment for this to be allowed.
if ($this->_ignoreComments === false
|| ($this->_ignoreComments === true
&& $hasComment === false)
) {
$hasError = true;
}
// Even when ignoring comments, we are not allowed to include
// newlines without the pattern specifying them, so
// everything should be on the same line.
if ($tokens[$next]['line'] !== $tokens[$stackPtr]['line']) {
$hasError = true;
}
}//end if
if ($next !== $lastAddedStackPtr) {
$found .= $tokens[$next]['content'];
$lastAddedStackPtr = $next;
}
if (isset($pattern[($i + 1)]) === true
&& $pattern[($i + 1)]['type'] === 'skip'
) {
$stackPtr = $next;
} else {
$stackPtr = ($next + 1);
}
}//end if
} else if ($pattern[$i]['type'] === 'skip') {
if ($pattern[$i]['to'] === 'unknown') {
$next = $phpcsFile->findNext(
$pattern[($i + 1)]['token'],
$stackPtr
);
if ($next === false) {
// Couldn't find the next token, sowe we must
// be using the wrong pattern.
return false;
}
$found .= '...';
$stackPtr = $next;
} else {
// Find the previous opener.
$next = $phpcsFile->findPrevious(
PHP_CodeSniffer_Tokens::$blockOpeners,
$stackPtr
);
if ($next === false
|| isset($tokens[$next][$pattern[$i]['to']]) === false
) {
// If there was not opener, then we must
// be using the wrong pattern.
return false;
}
$found .= '...';
if ($pattern[$i]['to'] === 'parenthesis_closer') {
$found .= ')';
} else {
$found .= '}';
}
// Skip to the closing token.
$stackPtr = ($tokens[$next][$pattern[$i]['to']] + 1);
}//end if
} else if ($pattern[$i]['type'] === 'string') {
if ($tokens[$stackPtr]['code'] !== T_STRING) {
$hasError = true;
}
if ($stackPtr !== $lastAddedStackPtr) {
$found .= 'abc';
$lastAddedStackPtr = $stackPtr;
}
$stackPtr++;
} else if ($pattern[$i]['type'] === 'newline') {
// Find the next token that contains a newline character.
$newline = 0;
for ($j = $stackPtr; $j < $phpcsFile->numTokens; $j++) {
if (strpos($tokens[$j]['content'], $phpcsFile->eolChar) !== false) {
$newline = $j;
break;
}
}
if ($newline === 0) {
// We didn't find a newline character in the rest of the file.
$next = ($phpcsFile->numTokens - 1);
$hasError = true;
} else {
if ($this->_ignoreComments === false) {
// The newline character cannot be part of a comment.
if (in_array($tokens[$newline]['code'], PHP_CodeSniffer_Tokens::$commentTokens) === true) {
$hasError = true;
}
}
if ($newline === $stackPtr) {
$next = ($stackPtr + 1);
} else {
// Check that there were no significant tokens that we
// skipped over to find our newline character.
$next = $phpcsFile->findNext(
$ignoreTokens,
$stackPtr,
null,
true
);
if ($next < $newline) {
// We skipped a non-ignored token.
$hasError = true;
} else {
$next = ($newline + 1);
}
}
}//end if
if ($stackPtr !== $lastAddedStackPtr) {
$found .= $phpcsFile->getTokensAsString(
$stackPtr,
($next - $stackPtr)
);
$diff = ($next - $stackPtr);
$lastAddedStackPtr = ($next - 1);
}
$stackPtr = $next;
}//end if
}//end for
if ($hasError === true) {
$error = $this->prepareError($found, $patternCode);
$errors[$origStackPtr] = $error;
}
return $errors;
}//end processPattern()
/**
* Prepares an error for the specified patternCode.
*
* @param string $found The actual found string in the code.
* @param string $patternCode The expected pattern code.
*
* @return string The error message.
*/
protected function prepareError($found, $patternCode)
{
$found = str_replace("\r\n", '\n', $found);
$found = str_replace("\n", '\n', $found);
$found = str_replace("\r", '\n', $found);
$found = str_replace('EOL', '\n', $found);
$expected = str_replace('EOL', '\n', $patternCode);
$error = "Expected \"$expected\"; found \"$found\"";
return $error;
}//end prepareError()
/**
* Returns the patterns that should be checked.
*
* @return array(string)
*/
protected abstract function getPatterns();
/**
* Registers any supplementary tokens that this test might wish to process.
*
* A sniff may wish to register supplementary tests when it wishes to group
* an arbitary validation that cannot be performed using a pattern, with
* other pattern tests.
*
* @return array(int)
* @see processSupplementary()
*/
protected function registerSupplementary()
{
return array();
}//end registerSupplementary()
/**
* Processes any tokens registered with registerSupplementary().
*
* @param PHP_CodeSniffer_File $phpcsFile The PHP_CodeSniffer file where to
* process the skip.
* @param int $stackPtr The position in the tokens stack to
* process.
*
* @return void
* @see registerSupplementary()
*/
protected function processSupplementary(
PHP_CodeSniffer_File $phpcsFile,
$stackPtr
) {
return;
}//end processSupplementary()
/**
* Parses a pattern string into an array of pattern steps.
*
* @param string $pattern The pattern to parse.
*
* @return array The parsed pattern array.
* @see _createSkipPattern()
* @see _createTokenPattern()
*/
private function _parse($pattern)
{
$patterns = array();
$length = strlen($pattern);
$lastToken = 0;
$firstToken = 0;
for ($i = 0; $i < $length; $i++) {
$specialPattern = false;
$isLastChar = ($i === ($length - 1));
$oldFirstToken = $firstToken;
if (substr($pattern, $i, 3) === '...') {
// It's a skip pattern. The skip pattern requires the
// content of the token in the "from" position and the token
// to skip to.
$specialPattern = $this->_createSkipPattern($pattern, ($i - 1));
$lastToken = ($i - $firstToken);
$firstToken = ($i + 3);
$i = ($i + 2);
if ($specialPattern['to'] !== 'unknown') {
$firstToken++;
}
} else if (substr($pattern, $i, 3) === 'abc') {
$specialPattern = array('type' => 'string');
$lastToken = ($i - $firstToken);
$firstToken = ($i + 3);
$i = ($i + 2);
} else if (substr($pattern, $i, 3) === 'EOL') {
$specialPattern = array('type' => 'newline');
$lastToken = ($i - $firstToken);
$firstToken = ($i + 3);
$i = ($i + 2);
}
if ($specialPattern !== false || $isLastChar === true) {
// If we are at the end of the string, don't worry about a limit.
if ($isLastChar === true) {
// Get the string from the end of the last skip pattern, if any,
// to the end of the pattern string.
$str = substr($pattern, $oldFirstToken);
} else {
// Get the string from the end of the last special pattern,
// if any, to the start of this special pattern.
if ($lastToken === 0) {
// Note that if the last special token was zero characters ago,
// there will be nothing to process so we can skip this bit.
// This happens if you have something like: EOL... in your pattern.
$str = '';
} else {
$str = substr($pattern, $oldFirstToken, $lastToken);
}
}
if ($str !== '') {
$tokenPatterns = $this->_createTokenPattern($str);
foreach ($tokenPatterns as $tokenPattern) {
$patterns[] = $tokenPattern;
}
}
// Make sure we don't skip the last token.
if ($isLastChar === false && $i === ($length - 1)) {
$i--;
}
}//end if
// Add the skip pattern *after* we have processed
// all the tokens from the end of the last skip pattern
// to the start of this skip pattern.
if ($specialPattern !== false) {
$patterns[] = $specialPattern;
}
}//end for
return $patterns;
}//end _parse()
/**
* Creates a skip pattern.
*
* @param string $pattern The pattern being parsed.
* @param string $from The token content that the skip pattern starts from.
*
* @return array The pattern step.
* @see _createTokenPattern()
* @see _parse()
*/
private function _createSkipPattern($pattern, $from)
{
$skip = array('type' => 'skip');
$nestedParenthesis = 0;
$nestedBraces = 0;
for ($start = $from; $start >= 0; $start--) {
switch ($pattern[$start]) {
case '(':
if ($nestedParenthesis === 0) {
$skip['to'] = 'parenthesis_closer';
}
$nestedParenthesis--;
break;
case '{':
if ($nestedBraces === 0) {
$skip['to'] = 'scope_closer';
}
$nestedBraces--;
break;
case '}':
$nestedBraces++;
break;
case ')':
$nestedParenthesis++;
break;
}
if (isset($skip['to']) === true) {
break;
}
}
if (isset($skip['to']) === false) {
$skip['to'] = 'unknown';
}
return $skip;
}//end _createSkipPattern()
/**
* Creates a token pattern.
*
* @param string $str The tokens string that the pattern should match.
*
* @return array The pattern step.
* @see _createSkipPattern()
* @see _parse()
*/
private function _createTokenPattern($str)
{
// Don't add a space after the closing php tag as it will add a new
// whitespace token.
$tokens = token_get_all('<?php '.$str.'?>');
// Remove the <?php tag from the front and the end php tag from the back.
$tokens = array_slice($tokens, 1, (count($tokens) - 2));
foreach ($tokens as &$token) {
$token = PHP_CodeSniffer::standardiseToken($token);
}
$patterns = array();
foreach ($tokens as $patternInfo) {
$patterns[] = array(
'type' => 'token',
'token' => $patternInfo['code'],
'value' => $patternInfo['content'],
);
}
return $patterns;
}//end _createTokenPattern()
}//end class
?>

View File

@@ -0,0 +1,238 @@
<?php
/**
* An AbstractScopeTest allows for tests that extend from this class to
* listen for tokens within a particluar scope.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* An AbstractScopeTest allows for tests that extend from this class to
* listen for tokens within a particluar scope.
*
* Below is a test that listens to methods that exist only within classes:
* <code>
* class ClassScopeTest extends PHP_CodeSniffer_Standards_AbstractScopeSniff
* {
* public function __construct()
* {
* parent::__construct(array(T_CLASS), array(T_FUNCTION));
* }
*
* protected function processTokenWithinScope(PHP_CodeSniffer_File $phpcsFile, $)
* {
* $className = $phpcsFile->getDeclarationName($currScope);
* echo 'encountered a method within class '.$className;
* }
* }
* </code>
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
abstract class PHP_CodeSniffer_Standards_AbstractScopeSniff implements PHP_CodeSniffer_Sniff
{
/**
* The token types that this test wishes to listen to within the scope.
*
* @var array()
*/
private $_tokens = array();
/**
* The type of scope opener tokens that this test wishes to listen to.
*
* @var string
*/
private $_scopeTokens = array();
/**
* The position in the tokens array that opened the current scope.
*
* @var array()
*/
protected $currScope = null;
/**
* The current file being checked.
*
* @var string
*/
protected $currFile = '';
/**
* True if this test should fire on tokens outside of the scope.
*
* @var boolean
*/
private $_listenOutside = false;
/**
* Constructs a new AbstractScopeTest.
*
* @param array $scopeTokens The type of scope the test wishes to listen to.
* @param array $tokens The tokens that the test wishes to listen to
* within the scope.
* @param boolean $listenOutside If true this test will also alert the
* extending class when a token is found outside
* the scope, by calling the
* processTokenOutideScope method.
*
* @see PHP_CodeSniffer.getValidScopeTokeners()
* @throws PHP_CodeSniffer_Test_Exception If the specified tokens array is empty.
*/
public function __construct(
array $scopeTokens,
array $tokens,
$listenOutside=false
) {
if (empty($scopeTokens) === true) {
$error = 'The scope tokens list cannot be empty';
throw new PHP_CodeSniffer_Test_Exception($error);
}
if (empty($tokens) === true) {
$error = 'The tokens list cannot be empty';
throw new PHP_CodeSniffer_Test_Exception($error);
}
$invalidScopeTokens = array_intersect($scopeTokens, $tokens);
if (empty($invalidScopeTokens) === false) {
$invalid = implode(', ', $invalidScopeTokens);
$error = "Scope tokens [$invalid] cant be in the tokens array";
throw new PHP_CodeSniffer_Test_Exception($error);
}
$this->_listenOutside = $listenOutside;
$this->_scopeTokens = $scopeTokens;
$this->_tokens = $tokens;
}//end __construct()
/**
* The method that is called to register the tokens this test wishes to
* listen to.
*
* DO NOT OVERRIDE THIS METHOD. Use the constructor of this class to register
* for the desired tokens and scope.
*
* @return array(int)
* @see __constructor()
*/
public final function register()
{
if ($this->_listenOutside === false) {
return $this->_scopeTokens;
} else {
return array_merge($this->_scopeTokens, $this->_tokens);
}
}//end register()
/**
* 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);
}
}//end process()
/**
* Processes a token that is found within the scope that this test is
* listening to.
*
* @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.
* @param int $currScope The position in the tokens array that
* opened the scope that this test is
* listening for.
*
* @return void
*/
protected abstract function processTokenWithinScope(
PHP_CodeSniffer_File $phpcsFile,
$stackPtr,
$currScope
);
/**
* Processes a token that is found within the scope that this test is
* listening to.
*
* @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
*/
protected function processTokenOutsideScope(
PHP_CodeSniffer_File $phpcsFile,
$stackPtr
) {
return;
}//end processTokenOutsideScope()
}//end class
?>

View File

@@ -0,0 +1,245 @@
<?php
/**
* A class to find T_VARIABLE tokens.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (class_exists('PHP_CodeSniffer_Standards_AbstractScopeSniff', true) === false) {
$error = 'Class PHP_CodeSniffer_Standards_AbstractScopeSniff not found';
throw new PHP_CodeSniffer_Exception($error);
}
/**
* A class to find T_VARIABLE tokens.
*
* This class can distingush between normal T_VARIABLE tokens, and those tokens
* that represent class members. If a class member is encountered, then then
* processMemberVar method is called so the extending class can process it. If
* the token is found to be a normal T_VARIABLE token, then processVariable is
* called.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
abstract class PHP_CodeSniffer_Standards_AbstractVariableSniff extends PHP_CodeSniffer_Standards_AbstractScopeSniff
{
/**
* The end token of the current function that we are in.
*
* @var int
*/
private $_endFunction = -1;
/**
* true if a function is currently open.
*
* @var boolean
*/
private $_functionOpen = false;
/**
* The current PHP_CodeSniffer file that we are processing.
*
* @var PHP_CodeSniffer_File
*/
protected $currentFile = null;
/**
* Constructs an AbstractVariableTest.
*/
public function __construct()
{
$scopes = array(
T_CLASS,
T_INTERFACE,
);
$listen = array(
T_FUNCTION,
T_VARIABLE,
T_DOUBLE_QUOTED_STRING,
T_HEREDOC,
);
parent::__construct($scopes, $listen, true);
}//end __construct()
/**
* Processes the token in the specified PHP_CodeSniffer_File.
*
* @param PHP_CodeSniffer_File $phpcsFile The PHP_CodeSniffer file where this
* token was found.
* @param int $stackPtr The position where the token was found.
* @param array $currScope The current scope opener token.
*
* @return void
*/
protected final function processTokenWithinScope(
PHP_CodeSniffer_File $phpcsFile,
$stackPtr,
$currScope
) {
if ($this->currentFile !== $phpcsFile) {
$this->currentFile = $phpcsFile;
$this->_functionOpen = false;
$this->_endFunction = -1;
}
$tokens = $phpcsFile->getTokens();
if ($stackPtr > $this->_endFunction) {
$this->_functionOpen = false;
}
if ($tokens[$stackPtr]['code'] === T_FUNCTION
&& $this->_functionOpen === false
) {
$this->_functionOpen = true;
$methodProps = $phpcsFile->getMethodProperties($stackPtr);
// If the function is abstract, or is in an interface,
// then set the end of the function to it's closing semicolon.
if ($methodProps['is_abstract'] === true
|| $tokens[$currScope]['code'] === T_INTERFACE
) {
$this->_endFunction
= $phpcsFile->findNext(array(T_SEMICOLON), $stackPtr);
} else {
if (isset($tokens[$stackPtr]['scope_closer']) === false) {
$error = 'Possible parse error: non-abstract method defined as abstract';
$phpcsFile->addWarning($error, $stackPtr);
return;
}
$this->_endFunction = $tokens[$stackPtr]['scope_closer'];
}
}
if ($tokens[$stackPtr]['code'] === T_DOUBLE_QUOTED_STRING
|| $tokens[$stackPtr]['code'] === T_HEREDOC
) {
// Check to see if this string has a variable in it.
$pattern = '|(?<!\\\\)(?:\\\\{2})*\${?[a-zA-Z0-9_]+}?|';
if (preg_match($pattern, $tokens[$stackPtr]['content']) !== 0) {
$this->processVariableInString($phpcsFile, $stackPtr);
}
return;
}
if ($this->_functionOpen === true) {
if ($tokens[$stackPtr]['code'] === T_VARIABLE) {
$this->processVariable($phpcsFile, $stackPtr);
}
} else {
// What if we assign a member variable to another?
// ie. private $_count = $this->_otherCount + 1;.
$this->processMemberVar($phpcsFile, $stackPtr);
}
}//end processTokenWithinScope()
/**
* Processes the token outside the scope in the file.
*
* @param PHP_CodeSniffer_File $phpcsFile The PHP_CodeSniffer file where this
* token was found.
* @param int $stackPtr The position where the token was found.
*
* @return void
*/
protected final function processTokenOutsideScope(
PHP_CodeSniffer_File $phpcsFile,
$stackPtr
) {
$tokens = $phpcsFile->getTokens();
// These variables are not member vars.
if ($tokens[$stackPtr]['code'] === T_VARIABLE) {
$this->processVariable($phpcsFile, $stackPtr);
} else if ($tokens[$stackPtr]['code'] === T_DOUBLE_QUOTED_STRING
|| $tokens[$stackPtr]['code'] === T_HEREDOC
) {
// Check to see if this string has a variable in it.
$pattern = '|(?<!\\\\)(?:\\\\{2})*\${?[a-zA-Z0-9_]+}?|';
if (preg_match($pattern, $tokens[$stackPtr]['content']) !== 0) {
$this->processVariableInString($phpcsFile, $stackPtr);
}
}
}//end processTokenOutsideScope()
/**
* Called to process class member vars.
*
* @param PHP_CodeSniffer_File $phpcsFile The PHP_CodeSniffer file where this
* token was found.
* @param int $stackPtr The position where the token was found.
*
* @return void
*/
abstract protected function processMemberVar(
PHP_CodeSniffer_File $phpcsFile,
$stackPtr
);
/**
* Called to process normal member vars.
*
* @param PHP_CodeSniffer_File $phpcsFile The PHP_CodeSniffer file where this
* token was found.
* @param int $stackPtr The position where the token was found.
*
* @return void
*/
abstract protected function processVariable(
PHP_CodeSniffer_File $phpcsFile,
$stackPtr
);
/**
* Called to process variables found in duoble quoted strings or heredocs.
*
* Note that there may be more than one variable in the string, which will
* result only in one call for the string or one call per line for heredocs.
*
* @param PHP_CodeSniffer_File $phpcsFile The PHP_CodeSniffer file where this
* token was found.
* @param int $stackPtr The position where the double quoted
* string was found.
*
* @return void
*/
abstract protected function processVariableInString(
PHP_CodeSniffer_File
$phpcsFile,
$stackPtr
);
}//end class
?>

View File

@@ -0,0 +1,7 @@
<documentation title="Line Length">
<standard>
<![CDATA[
It is recommended to keep lines at approximately 80 characters long for better code readability.
]]>
</standard>
</documentation>

View File

@@ -0,0 +1,56 @@
<documentation title="Aligning Blocks of Assignments">
<standard>
<![CDATA[
There should be one space on either side of an equals sign used to assign a value to a variable. In the case of a block of related assignments, more space may be inserted to promote readability.
]]>
</standard>
<code_comparison>
<code title="Equals signs aligned">
<![CDATA[
$shortVar <em>=</em> (1 + 2);
$veryLongVarName <em>=</em> 'string';
$var <em>=</em> foo($bar, $baz, $quux);
]]>
</code>
<code title="Not aligned; harder to read">
<![CDATA[
$shortVar <em>=</em> (1 + 2);
$veryLongVarName <em>=</em> 'string';
$var <em>=</em> foo($bar, $baz, $quux);
]]>
</code>
</code_comparison>
<standard>
<![CDATA[
When using plus-equals, minus-equals etc. still ensure the equals signs are aligned to one space after the longest variable name.
]]>
</standard>
<code_comparison>
<code title="Equals signs aligned; only one space after longest var name">
<![CDATA[
$shortVar <em>+= </em>1;
$veryLongVarName<em> = </em>1;
]]>
</code>
<code title="Two spaces after longest var name">
<![CDATA[
$shortVar <em> += </em>1;
$veryLongVarName<em> = </em>1;
]]>
</code>
</code_comparison>
<code_comparison>
<code title="Equals signs aligned">
<![CDATA[
$shortVar <em> = </em>1;
$veryLongVarName<em> -= </em>1;
]]>
</code>
<code title="Equals signs not aligned">
<![CDATA[
$shortVar <em> = </em>1;
$veryLongVarName<em> -= </em>1;
]]>
</code>
</code_comparison>
</documentation>

View File

@@ -0,0 +1,24 @@
<documentation title="Opening Brace in Function Declarations">
<standard>
<![CDATA[
Function declarations follow the "BSD/Allman style". The function brace is on the line following the function declaration and is indented to the same column as the start of the function declaration.
]]>
</standard>
<code_comparison>
<code title="Valid: brace on next line">
<![CDATA[
function fooFunction($arg1, $arg2 = '')
<em>{</em>
...
}
]]>
</code>
<code title="Invalid: brace on same line">
<![CDATA[
function fooFunction($arg1, $arg2 = '') <em>{</em>
...
}
]]>
</code>
</code_comparison>
</documentation>

View File

@@ -0,0 +1,24 @@
<documentation title="Opening Brace in Function Declarations">
<standard>
<![CDATA[
Function declarations follow the "Kernighan/Ritchie style". The function brace is on the same line as the function declaration. One space is required between the closing parenthesis and the brace.
]]>
</standard>
<code_comparison>
<code title="Valid: brace on same line">
<![CDATA[
function fooFunction($arg1, $arg2 = '')<em> {</em>
...
}
]]>
</code>
<code title="Invalid: brace on next line">
<![CDATA[
function fooFunction($arg1, $arg2 = '')
<em>{</em>
...
}
]]>
</code>
</code_comparison>
</documentation>

View File

@@ -0,0 +1,29 @@
<documentation title="Constant Names">
<standard>
<![CDATA[
Constants should always be all-uppercase, with underscores to separate words.
]]>
</standard>
<code_comparison>
<code title="Valid: all uppercase">
<![CDATA[
define('<em>FOO_CONSTANT</em>', 'foo');
class FooClass
{
const <em>FOO_CONSTANT</em> = 'foo';
}
]]>
</code>
<code title="Invalid: mixed case">
<![CDATA[
define('<em>Foo_Constant</em>', 'foo');
class FooClass
{
const <em>foo_constant</em> = 'foo';
}
]]>
</code>
</code_comparison>
</documentation>

View File

@@ -0,0 +1,7 @@
<documentation title="PHP Code Tags">
<standard>
<![CDATA[
Always use <?php ?> to delimit PHP code, not the <? ?> shorthand. This is the most portable way to include PHP code on differing operating systems and setups.
]]>
</standard>
</documentation>

View File

@@ -0,0 +1,23 @@
<documentation title="PHP Constants">
<standard>
<![CDATA[
The <em>true</em>, <em>false</em> and <em>null</em> constants must always be lowercase.
]]>
</standard>
<code_comparison>
<code title="Valid: lowercase constants">
<![CDATA[
if ($var === <em>false</em> || $var === <em>null</em>) {
$var = <em>true</em>;
}
]]>
</code>
<code title="Invalid: uppercase constants">
<![CDATA[
if ($var === <em>FALSE</em> || $var === <em>NULL</em>) {
$var = <em>TRUE</em>;
}
]]>
</code>
</code_comparison>
</documentation>

View File

@@ -0,0 +1,23 @@
<documentation title="PHP Constants">
<standard>
<![CDATA[
The <em>true</em>, <em>false</em> and <em>null</em> constants must always be uppercase.
]]>
</standard>
<code_comparison>
<code title="Valid: uppercase constants">
<![CDATA[
if ($var === <em>FALSE</em> || $var === <em>NULL</em>) {
$var = <em>TRUE</em>;
}
]]>
</code>
<code title="Invalid: lowercase constants">
<![CDATA[
if ($var === <em>false</em> || $var === <em>null</em>) {
$var = <em>true</em>;
}
]]>
</code>
</code_comparison>
</documentation>

View File

@@ -0,0 +1,97 @@
<?php
/**
* Reports errors if the same class or interface name is used in multiple files.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Reports errors if the same class or interface name is used in multiple files.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_Classes_DuplicateClassNameSniff implements PHP_CodeSniffer_MultiFileSniff
{
/**
* Called once per script run to allow for processing of this sniff.
*
* @param array(PHP_CodeSniffer_File) $files The PHP_CodeSniffer files processed
* during the script run.
*
* @return void
*/
public function process(array $files)
{
$foundClasses = array();
foreach ($files as $phpcsFile) {
$tokens = $phpcsFile->getTokens();
$namespace = '';
$stackPtr = $phpcsFile->findNext(array(T_CLASS, T_INTERFACE, T_NAMESPACE), 0);
while ($stackPtr !== false) {
// Keep track of what namespace we are in.
if ($tokens[$stackPtr]['code'] === T_NAMESPACE) {
$nsEnd = $phpcsFile->findNext(
array(T_NS_SEPARATOR, T_STRING, T_WHITESPACE),
($stackPtr + 1),
null,
true
);
$namespace = trim($phpcsFile->getTokensAsString(($stackPtr + 1), ($nsEnd - $stackPtr - 1)));
$stackPtr = $nsEnd;
} else {
$nameToken = $phpcsFile->findNext(T_STRING, $stackPtr);
$name = $tokens[$nameToken]['content'];
if ($namespace !== '') {
$name = $namespace.'\\'.$name;
}
$compareName = strtolower($name);
if (isset($foundClasses[$compareName]) === true) {
$type = strtolower($tokens[$stackPtr]['content']);
$file = $foundClasses[$compareName]['file'];
$line = $foundClasses[$compareName]['line'];
$error = 'Duplicate %s name "%s" found; first defined in %s on line %s';
$data = array(
$type,
$name,
$file,
$line,
);
$phpcsFile->addWarning($error, $stackPtr, 'Found', $data);
} else {
$foundClasses[$compareName] = array(
'file' => $phpcsFile->getFilename(),
'line' => $tokens[$stackPtr]['line'],
);
}
}
$stackPtr = $phpcsFile->findNext(array(T_CLASS, T_INTERFACE, T_NAMESPACE), ($stackPtr + 1));
}//end while
}//end foreach
}//end process()
}//end class
?>

View File

@@ -0,0 +1,128 @@
<?php
/**
* This file is part of the CodeAnalysis addon for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Manuel Pichler <mapi@manuel-pichler.de>
* @copyright 2007-2008 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* This sniff class detected empty statement.
*
* This sniff implements the common algorithm for empty statement body detection.
* A body is considered as empty if it is completely empty or it only contains
* whitespace characters and|or comments.
*
* <code>
* stmt {
* // foo
* }
* stmt (conditions) {
* // foo
* }
* </code>
*
* Statements covered by this sniff are <b>catch</b>, <b>do</b>, <b>else</b>,
* <b>elsif</b>, <b>for</b>, <b>foreach<b>, <b>if</b>, <b>switch</b>, <b>try</b>
* and <b>while</b>.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Manuel Pichler <mapi@manuel-pichler.de>
* @copyright 2007-2008 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_CodeAnalysis_EmptyStatementSniff implements PHP_CodeSniffer_Sniff
{
/**
* List of block tokens that this sniff covers.
*
* The key of this hash identifies the required token while the boolean
* value says mark an error or mark a warning.
*
* @var array
*/
protected $checkedTokens = array(
T_CATCH => true,
T_DO => false,
T_ELSE => false,
T_ELSEIF => false,
T_FOR => false,
T_FOREACH => false,
T_IF => false,
T_SWITCH => false,
T_TRY => false,
T_WHILE => false,
);
/**
* Registers the tokens that this sniff wants to listen for.
*
* @return array(integer)
*/
public function register()
{
return array_keys($this->checkedTokens);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
// Skip for-statements without body.
if (isset($token['scope_opener']) === false) {
return;
}
$next = ++$token['scope_opener'];
$end = --$token['scope_closer'];
$emptyBody = true;
for (; $next <= $end; ++$next) {
if (in_array($tokens[$next]['code'], PHP_CodeSniffer_Tokens::$emptyTokens) === false) {
$emptyBody = false;
break;
}
}
if ($emptyBody === true) {
// Get token identifier.
$name = $phpcsFile->getTokensAsString($stackPtr, 1);
$error = 'Empty %s statement detected';
$data = array(strtoupper($name));
if ($this->checkedTokens[$token['code']] === true) {
$phpcsFile->addError($error, $stackPtr, 'NotAllowed', $data);
} else {
$phpcsFile->addWarning($error, $stackPtr, 'NotAllowedWarning', $data);
}
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,100 @@
<?php
/**
* This file is part of the CodeAnalysis addon for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Manuel Pichler <mapi@manuel-pichler.de>
* @copyright 2007-2008 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Detects for-loops that can be simplified to a while-loop.
*
* This rule is based on the PMD rule catalog. Detects for-loops that can be
* simplified as a while-loop.
*
* <code>
* class Foo
* {
* public function bar($x)
* {
* for (;true;) true; // No Init or Update part, may as well be: while (true)
* }
* }
* </code>
*
* @category PHP
* @package PHP_CodeSniffer
* @author Manuel Pichler <mapi@manuel-pichler.de>
* @copyright 2007-2008 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_CodeAnalysis_ForLoopShouldBeWhileLoopSniff implements PHP_CodeSniffer_Sniff
{
/**
* Registers the tokens that this sniff wants to listen for.
*
* @return array(integer)
*/
public function register()
{
return array(T_FOR);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
// Skip invalid statement.
if (isset($token['parenthesis_opener']) === false) {
return;
}
$next = ++$token['parenthesis_opener'];
$end = --$token['parenthesis_closer'];
$parts = array(0, 0, 0);
$index = 0;
for (; $next <= $end; ++$next) {
$code = $tokens[$next]['code'];
if ($code === T_SEMICOLON) {
++$index;
} else if (in_array($code, PHP_CodeSniffer_Tokens::$emptyTokens) === false) {
++$parts[$index];
}
}
if ($parts[0] === 0 && $parts[2] === 0 && $parts[1] > 0) {
$error = 'This FOR loop can be simplified to a WHILE loop';
$phpcsFile->addWarning($error, $stackPtr, 'CanSimplify');
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,113 @@
<?php
/**
* This file is part of the CodeAnalysis addon for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Manuel Pichler <mapi@manuel-pichler.de>
* @copyright 2007-2008 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Detects for-loops that use a function call in the test expression.
*
* This rule is based on the PMD rule catalog. Detects for-loops that use a
* function call in the test expression.
*
* <code>
* class Foo
* {
* public function bar($x)
* {
* $a = array(1, 2, 3, 4);
* for ($i = 0; $i < count($a); $i++) {
* $a[$i] *= $i;
* }
* }
* }
* </code>
*
* @category PHP
* @package PHP_CodeSniffer
* @author Manuel Pichler <mapi@manuel-pichler.de>
* @copyright 2007-2008 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_CodeAnalysis_ForLoopWithTestFunctionCallSniff implements PHP_CodeSniffer_Sniff
{
/**
* Registers the tokens that this sniff wants to listen for.
*
* @return array(integer)
*/
public function register()
{
return array(T_FOR);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
// Skip invalid statement.
if (isset($token['parenthesis_opener']) === false) {
return;
}
$next = ++$token['parenthesis_opener'];
$end = --$token['parenthesis_closer'];
$position = 0;
for (; $next <= $end; ++$next) {
$code = $tokens[$next]['code'];
if ($code === T_SEMICOLON) {
++$position;
}
if ($position < 1) {
continue;
} else if ($position > 1) {
break;
} else if ($code !== T_VARIABLE && $code !== T_STRING) {
continue;
}
// Find next non empty token, if it is a open curly brace we have a
// function call.
$index = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($next + 1), null, true);
if ($tokens[$index]['code'] === T_OPEN_PARENTHESIS) {
$error = 'Avoid function calls in a FOR loop test part';
$phpcsFile->addWarning($error, $stackPtr, 'NotAllowed');
break;
}
}//end for
}//end process()
}//end class
?>

View File

@@ -0,0 +1,148 @@
<?php
/**
* This file is part of the CodeAnalysis addon for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Manuel Pichler <mapi@manuel-pichler.de>
* @copyright 2007-2008 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Detects incrementer jumbling in for loops.
*
* This rule is based on the PMD rule catalog. The jumbling incrementer sniff
* detects the usage of one and the same incrementer into an outer and an inner
* loop. Even it is intended this is confusing code.
*
* <code>
* class Foo
* {
* public function bar($x)
* {
* for ($i = 0; $i < 10; $i++)
* {
* for ($k = 0; $k < 20; $i++)
* {
* echo 'Hello';
* }
* }
* }
* }
* </code>
*
* @category PHP
* @package PHP_CodeSniffer
* @author Manuel Pichler <mapi@manuel-pichler.de>
* @copyright 2007-2008 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_CodeAnalysis_JumbledIncrementerSniff implements PHP_CodeSniffer_Sniff
{
/**
* Registers the tokens that this sniff wants to listen for.
*
* @return array(integer)
*/
public function register()
{
return array(T_FOR);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
// Skip for-loop without body.
if (isset($token['scope_opener']) === false) {
return;
}
// Find incrementors for outer loop.
$outer = $this->findIncrementers($tokens, $token);
// Skip if empty.
if (count($outer) === 0) {
return;
}
// Find nested for loops.
$start = ++$token['scope_opener'];
$end = --$token['scope_closer'];
for (; $start <= $end; ++$start) {
if ($tokens[$start]['code'] !== T_FOR) {
continue;
}
$inner = $this->findIncrementers($tokens, $tokens[$start]);
$diff = array_intersect($outer, $inner);
if (count($diff) !== 0) {
$error = 'Loop incrementor (%s) jumbling with inner loop';
$data = array(join(', ', $diff));
$phpcsFile->addWarning($error, $stackPtr, 'Found', $data);
}
}
}//end process()
/**
* Get all used variables in the incrementer part of a for statement.
*
* @param array(integer=>array) $tokens Array with all code sniffer tokens.
* @param array(string=>mixed) $token Current for loop token
*
* @return array(string) List of all found incrementer variables.
*/
protected function findIncrementers(array $tokens, array $token)
{
// Skip invalid statement.
if (isset($token['parenthesis_opener']) === false) {
return array();
}
$start = ++$token['parenthesis_opener'];
$end = --$token['parenthesis_closer'];
$incrementers = array();
$semicolons = 0;
for ($next = $start; $next <= $end; ++$next) {
$code = $tokens[$next]['code'];
if ($code === T_SEMICOLON) {
++$semicolons;
} else if ($semicolons === 2 && $code === T_VARIABLE) {
$incrementers[] = $tokens[$next]['content'];
}
}
return $incrementers;
}//end findIncrementers()
}//end class
?>

View File

@@ -0,0 +1,106 @@
<?php
/**
* This file is part of the CodeAnalysis addon for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Manuel Pichler <mapi@manuel-pichler.de>
* @copyright 2007-2008 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Detects unconditional if- and elseif-statements.
*
* This rule is based on the PMD rule catalog. The Unconditional If Statment
* sniff detects statement conditions that are only set to one of the constant
* values <b>true</b> or <b>false</b>
*
* <code>
* class Foo
* {
* public function close()
* {
* if (true)
* {
* // ...
* }
* }
* }
* </code>
*
* @category PHP
* @package PHP_CodeSniffer
* @author Manuel Pichler <mapi@manuel-pichler.de>
* @copyright 2007-2008 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_CodeAnalysis_UnconditionalIfStatementSniff implements PHP_CodeSniffer_Sniff
{
/**
* Registers the tokens that this sniff wants to listen for.
*
* @return array(integer)
*/
public function register()
{
return array(
T_IF,
T_ELSEIF,
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
// Skip for-loop without body.
if (isset($token['parenthesis_opener']) === false) {
return;
}
$next = ++$token['parenthesis_opener'];
$end = --$token['parenthesis_closer'];
$goodCondition = false;
for (; $next <= $end; ++$next) {
$code = $tokens[$next]['code'];
if (in_array($code, PHP_CodeSniffer_Tokens::$emptyTokens) === true) {
continue;
} else if ($code !== T_TRUE && $code !== T_FALSE) {
$goodCondition = true;
}
}
if ($goodCondition === false) {
$error = 'Avoid IF statements that are always true or false';
$phpcsFile->addWarning($error, $stackPtr, 'Found');
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,98 @@
<?php
/**
* This file is part of the CodeAnalysis addon for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Manuel Pichler <mapi@manuel-pichler.de>
* @copyright 2007-2008 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Detects unnecessary final modifiers inside of final classes.
*
* This rule is based on the PMD rule catalog. The Unnecessary Final Modifier
* sniff detects the use of the final modifier inside of a final class which
* is unnecessary.
*
* <code>
* final class Foo
* {
* public final function bar()
* {
* }
* }
* </code>
*
* @category PHP
* @package PHP_CodeSniffer
* @author Manuel Pichler <mapi@manuel-pichler.de>
* @copyright 2007-2008 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_CodeAnalysis_UnnecessaryFinalModifierSniff implements PHP_CodeSniffer_Sniff
{
/**
* Registers the tokens that this sniff wants to listen for.
*
* @return array(integer)
*/
public function register()
{
return array(T_CLASS);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
// Skip for-statements without body.
if (isset($token['scope_opener']) === false) {
return;
}
// Fetch previous token.
$prev = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr - 1), null, true);
// Skip for non final class.
if ($prev === false || $tokens[$prev]['code'] !== T_FINAL) {
return;
}
$next = ++$token['scope_opener'];
$end = --$token['scope_closer'];
for (; $next <= $end; ++$next) {
if ($tokens[$next]['code'] === T_FINAL) {
$error = 'Unnecessary FINAL modifier in FINAL class';
$phpcsFile->addWarning($error, $next, 'Found');
}
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,150 @@
<?php
/**
* This file is part of the CodeAnalysis addon for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Manuel Pichler <mapi@manuel-pichler.de>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Checks the for unused function parameters.
*
* This sniff checks that all function parameters are used in the function body.
* One exception is made for empty function bodies or function bodies that only
* contain comments. This could be usefull for the classes that implement an
* interface that defines multiple methods but the implementation only needs some
* of them.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Manuel Pichler <mapi@manuel-pichler.de>
* @copyright 2007-2008 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_CodeAnalysis_UnusedFunctionParameterSniff implements PHP_CodeSniffer_Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_FUNCTION);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
// Skip broken function declarations.
if (isset($token['scope_opener']) === false || isset($token['parenthesis_opener']) === false) {
return;
}
$params = array();
foreach ($phpcsFile->getMethodParameters($stackPtr) as $param) {
$params[$param['name']] = $stackPtr;
}
$next = ++$token['scope_opener'];
$end = --$token['scope_closer'];
$emptyBody = true;
for (; $next <= $end; ++$next) {
$token = $tokens[$next];
$code = $token['code'];
// Ingorable tokens.
if (in_array($code, PHP_CodeSniffer_Tokens::$emptyTokens) === true) {
continue;
} else if ($code === T_THROW && $emptyBody === true) {
// Throw statement and an empty body indicate an interface method.
return;
} else if ($code === T_RETURN && $emptyBody === true) {
// Return statement and an empty body indicate an interface method.
$tmp = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($next + 1), null, true);
if ($tmp === false) {
return;
}
// There is a return.
if ($tokens[$tmp]['code'] === T_SEMICOLON) {
return;
}
$tmp = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($tmp + 1), null, true);
// There is a return <token>.
if ($tmp !== false && $tokens[$tmp]['code'] === T_SEMICOLON) {
return;
}
}//end if
$emptyBody = false;
if ($code === T_VARIABLE && isset($params[$token['content']]) === true) {
unset($params[$token['content']]);
} else if ($code === T_DOUBLE_QUOTED_STRING || $code === T_HEREDOC) {
// Tokenize strings that can contain variables.
// Make sure the string is re-joined if it occurs over multiple lines.
$string = $token['content'];
for ($i = ($next + 1); $i <= $end; $i++) {
if ($tokens[$i]['code'] === $code) {
$string .= $tokens[$i]['content'];
$next++;
}
}
$strTokens = token_get_all(sprintf('<?php %s;?>', $string));
foreach ($strTokens as $tok) {
if (is_array($tok) === false || $tok[0] !== T_VARIABLE ) {
continue;
}
if (isset($params[$tok[1]]) === true) {
unset($params[$tok[1]]);
}
}
}//end if
}//end for
if ($emptyBody === false && count($params) > 0) {
foreach ($params as $paramName => $position) {
$error = 'The method parameter %s is never used';
$data = array($paramName);
$phpcsFile->addWarning($error, $position, 'Found', $data);
}
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,180 @@
<?php
/**
* This file is part of the CodeAnalysis addon for PHP_CodeSniffer.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Manuel Pichler <mapi@manuel-pichler.de>
* @copyright 2007-2008 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Detects unnecessary overriden methods that simply call their parent.
*
* This rule is based on the PMD rule catalog. The Useless Overriding Method
* sniff detects the use of methods that only call their parent classes's method
* with the same name and arguments. These methods are not required.
*
* <code>
* class FooBar {
* public function __construct($a, $b) {
* parent::__construct($a, $b);
* }
* }
* </code>
*
* @category PHP
* @package PHP_CodeSniffer
* @author Manuel Pichler <mapi@manuel-pichler.de>
* @copyright 2007-2008 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_CodeAnalysis_UselessOverridingMethodSniff implements PHP_CodeSniffer_Sniff
{
/**
* Registers the tokens that this sniff wants to listen for.
*
* @return array(integer)
*/
public function register()
{
return array(T_FUNCTION);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
// Skip function without body.
if (isset($token['scope_opener']) === false) {
return;
}
// Get function name.
$methodName = $phpcsFile->getDeclarationName($stackPtr);
// Get all parameters from method signature.
$signature = array();
foreach ($phpcsFile->getMethodParameters($stackPtr) as $param) {
$signature[] = $param['name'];
}
$next = ++$token['scope_opener'];
$end = --$token['scope_closer'];
for (; $next <= $end; ++$next) {
$code = $tokens[$next]['code'];
if (in_array($code, PHP_CodeSniffer_Tokens::$emptyTokens) === true) {
continue;
} else if ($code === T_RETURN) {
continue;
}
break;
}
// Any token except 'parent' indicates correct code.
if ($tokens[$next]['code'] !== T_PARENT) {
return;
}
// Find next non empty token index, should be double colon.
$next = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($next + 1), null, true);
// Skip for invalid code.
if ($next === false || $tokens[$next]['code'] !== T_DOUBLE_COLON) {
return;
}
// Find next non empty token index, should be the function name.
$next = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($next + 1), null, true);
// Skip for invalid code or other method.
if ($next === false || $tokens[$next]['content'] !== $methodName) {
return;
}
// Find next non empty token index, should be the open parenthesis.
$next = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($next + 1), null, true);
// Skip for invalid code.
if ($next === false || $tokens[$next]['code'] !== T_OPEN_PARENTHESIS) {
return;
}
$validParameterTypes = array(
T_VARIABLE,
T_LNUMBER,
T_CONSTANT_ENCAPSED_STRING,
);
$parameters = array('');
$parenthesisCount = 1;
$count = count($tokens);
for (++$next; $next < $count; ++$next) {
$code = $tokens[$next]['code'];
if ($code === T_OPEN_PARENTHESIS) {
++$parenthesisCount;
} else if ($code === T_CLOSE_PARENTHESIS) {
--$parenthesisCount;
} else if ($parenthesisCount === 1 && $code === T_COMMA) {
$parameters[] = '';
} else if (in_array($code, PHP_CodeSniffer_Tokens::$emptyTokens) === false) {
$parameters[(count($parameters) - 1)] .= $tokens[$next]['content'];
}
if ($parenthesisCount === 0) {
break;
}
}//end for
$next = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($next + 1), null, true);
if ($next === false || $tokens[$next]['code'] !== T_SEMICOLON) {
return;
}
// Check rest of the scope.
for (++$next; $next <= $end; ++$next) {
$code = $tokens[$next]['code'];
// Skip for any other content.
if (in_array($code, PHP_CodeSniffer_Tokens::$emptyTokens) === false) {
return;
}
}
$parameters = array_map('trim', $parameters);
$parameters = array_filter($parameters);
if (count($parameters) === count($signature) && $parameters === $signature) {
$phpcsFile->addWarning('Useless method overriding detected', $stackPtr, 'Found');
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,90 @@
<?php
/**
* Generic_Sniffs_Commenting_TodoSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_Commenting_TodoSniff.
*
* Warns about TODO comments.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_Commenting_TodoSniff implements PHP_CodeSniffer_Sniff
{
/**
* A list of tokenizers this sniff supports.
*
* @var array
*/
public $supportedTokenizers = array(
'PHP',
'JS',
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return PHP_CodeSniffer_Tokens::$commentTokens;
}//end register()
/**
* Processes this sniff, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$content = $tokens[$stackPtr]['content'];
$matches = Array();
if (preg_match('|[^a-z]+todo[^a-z]+(.*)|i', $content, $matches) !== 0) {
// Clear whitespace and some common characters not required at
// the end of a to-do message to make the warning more informative.
$type = 'CommentFound';
$todoMessage = trim($matches[1]);
$todoMessage = trim($todoMessage, '[]().');
$error = 'Comment refers to a TODO task';
$data = array($todoMessage);
if ($todoMessage !== '') {
$type = 'TaskFound';
$error .= ' "%s"';
}
$phpcsFile->addWarning($error, $stackPtr, $type, $data);
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,120 @@
<?php
/**
* Generic_Sniffs_ControlStructures_InlineControlStructureSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_ControlStructures_InlineControlStructureSniff.
*
* Verifies that inline control statements are not present.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_ControlStructures_InlineControlStructureSniff implements PHP_CodeSniffer_Sniff
{
/**
* A list of tokenizers this sniff supports.
*
* @var array
*/
public $supportedTokenizers = array(
'PHP',
'JS',
);
/**
* If true, an error will be thrown; otherwise a warning.
*
* @var bool
*/
public $error = true;
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_IF,
T_ELSE,
T_FOREACH,
T_WHILE,
T_DO,
T_SWITCH,
T_FOR,
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in the
* stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if (isset($tokens[$stackPtr]['scope_opener']) === false) {
// Ignore the ELSE in ELSE IF. We'll process the IF part later.
if (($tokens[$stackPtr]['code'] === T_ELSE) && ($tokens[($stackPtr + 2)]['code'] === T_IF)) {
return;
}
if ($tokens[$stackPtr]['code'] === T_WHILE) {
// This could be from a DO WHILE, which doesn't have an opening brace.
$lastContent = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
if ($tokens[$lastContent]['code'] === T_CLOSE_CURLY_BRACKET) {
$brace = $tokens[$lastContent];
if (isset($brace['scope_condition']) === true) {
$condition = $tokens[$brace['scope_condition']];
if ($condition['code'] === T_DO) {
return;
}
}
}
}
// This is a control structure without an opening brace,
// so it is an inline statement.
if ($this->error === true) {
$phpcsFile->addError('Inline control structures are not allowed', $stackPtr, 'NotAllowed');
} else {
$phpcsFile->addWarning('Inline control structures are discouraged', $stackPtr, 'Discouraged');
}
return;
}//end if
}//end process()
}//end class
?>

View File

@@ -0,0 +1,139 @@
<?php
/**
* Generic_Sniffs_Debug_ClosureLinterSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_Debug_ClosureLinterSniff.
*
* Runs gjslint on the file.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_Debug_ClosureLinterSniff implements PHP_CodeSniffer_Sniff
{
/**
* A list of error codes that should show errors.
*
* All other error codes will show warnings.
*
* @var int
*/
public $errorCodes = array();
/**
* A list of error codes to ignore.
*
* @var int
*/
public $ignoreCodes = array();
/**
* A list of tokenizers this sniff supports.
*
* @var array
*/
public $supportedTokenizers = array('JS');
/**
* Returns the token types that this sniff is interested in.
*
* @return array(int)
*/
public function register()
{
return array(T_OPEN_TAG);
}//end register()
/**
* Processes the tokens that this sniff is interested in.
*
* @param PHP_CodeSniffer_File $phpcsFile The file where the token was found.
* @param int $stackPtr The position in the stack where
* the token was found.
*
* @return void
* @throws PHP_CodeSniffer_Exception If jslint.js could not be run
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$fileName = $phpcsFile->getFilename();
$lintPath = PHP_CodeSniffer::getConfigData('gjslint_path');
if ($lintPath === null) {
return;
}
$cmd = "$lintPath --nosummary --notime --unix_mode \"$fileName\"";
$msg = exec($cmd, $output, $retval);
if (is_array($output) === false) {
return;
}
$tokens = $phpcsFile->getTokens();
foreach ($output as $finding) {
$matches = array();
$numMatches = preg_match('/^(.*):([0-9]+):\(([0-9]+)\)(.*)$/', $finding, $matches);
if ($numMatches === 0) {
continue;
}
// Skip error codes we are ignoring.
$code = $matches[3];
if (in_array($code, $this->ignoreCodes) === true) {
continue;
}
$line = (int) $matches[2];
$error = trim($matches[4]);
// Find the token at the start of the line.
$lineToken = null;
foreach ($tokens as $ptr => $info) {
if ($info['line'] === $line) {
$lineToken = $ptr;
break;
}
}
if ($lineToken !== null) {
$message = 'gjslint says: (%s) %s';
$data = array(
$code,
$error,
);
if (in_array($code, $this->errorCodes) === true) {
$phpcsFile->addError($message, $lineToken, 'ExternalToolError', $data);
} else {
$phpcsFile->addWarning($message, $lineToken, 'ExternalTool', $data);
}
}
}//end foreach
}//end process()
}//end class
?>

View File

@@ -0,0 +1,109 @@
<?php
/**
* Generic_Sniffs_Debug_JSHintSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Alexander Wei<65> <aweisswa@gmx.de>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_Debug_JSHintSniff.
*
* Runs jshint.js on the file.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Alexander Wei<65> <aweisswa@gmx.de>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_Debug_JSHintSniff implements PHP_CodeSniffer_Sniff
{
/**
* A list of tokenizers this sniff supports.
*
* @var array
*/
public $supportedTokenizers = array('JS');
/**
* Returns the token types that this sniff is interested in.
*
* @return array(int)
*/
public function register()
{
return array(T_OPEN_TAG);
}//end register()
/**
* Processes the tokens that this sniff is interested in.
*
* @param PHP_CodeSniffer_File $phpcsFile The file where the token was found.
* @param int $stackPtr The position in the stack where
* the token was found.
*
* @return void
* @throws PHP_CodeSniffer_Exception If jshint.js could not be run
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$fileName = $phpcsFile->getFilename();
$rhinoPath = PHP_CodeSniffer::getConfigData('rhino_path');
$jshintPath = PHP_CodeSniffer::getConfigData('jshint_path');
if ($rhinoPath === null || $jshintPath === null) {
return;
}
$cmd = "$rhinoPath \"$jshintPath\" \"$fileName\"";
$msg = exec($cmd, $output, $retval);
if (is_array($output) === true) {
$tokens = $phpcsFile->getTokens();
foreach ($output as $finding) {
$matches = array();
$numMatches = preg_match('/^(.+)\(.+:([0-9]+).*:[0-9]+\)$/', $finding, $matches);
if ($numMatches === 0) {
continue;
}
$line = (int) $matches[2];
$message = 'jshint says: '.trim($matches[1]);
// Find the token at the start of the line.
$lineToken = null;
foreach ($tokens as $ptr => $info) {
if ($info['line'] === $line) {
$lineToken = $ptr;
break;
}
}
if ($lineToken !== null) {
$phpcsFile->addWarning($message, $lineToken, 'ExternalTool');
}
}//end foreach
}//end if
}//end process()
}//end class
?>

View File

@@ -0,0 +1,93 @@
<?php
/**
* Generic_Sniffs_Files_ByteOrderMarkSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_Files_ByteOrderMarkSniff.
*
* A simple sniff for detecting BOMs that may corrupt application work.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Piotr Karas <office@mediaself.pl>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2010-2011 mediaSELF Sp. z o.o.
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
* @see http://en.wikipedia.org/wiki/Byte_order_mark
*/
class Generic_Sniffs_Files_ByteOrderMarkSniff implements PHP_CodeSniffer_Sniff
{
/**
* List of supported BOM definitions.
*
* Use encoding names as keys and hex BOM representations as values.
*
* @var array
*/
public $bomDefinitions = array(
'UTF-8' => 'efbbbf',
'UTF-16 (BE)' => 'feff',
'UTF-16 (LE)' => 'fffe',
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_INLINE_HTML);
}//end register()
/**
* Processes this sniff, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr )
{
// The BOM will be the very first token in the file.
if ($stackPtr !== 0) {
return;
}
$tokens = $phpcsFile->getTokens();
foreach ($this->bomDefinitions as $bomName => $expectedBomHex) {
$bomByteLength = (strlen($expectedBomHex) / 2);
$htmlBomHex = bin2hex(substr($tokens[$stackPtr]['content'], 0, $bomByteLength));
if ($htmlBomHex === $expectedBomHex) {
$errorData = array($bomName);
$error = 'File contains %s byte order mark, which may corrupt your application';
$phpcsFile->addError($error, $stackPtr, 'Found', $errorData);
break;
}
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,103 @@
<?php
/**
* Generic_Sniffs_Files_LineEndingsSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_Files_LineEndingsSniff.
*
* Checks that end of line characters are correct.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_Files_LineEndingsSniff implements PHP_CodeSniffer_Sniff
{
/**
* A list of tokenizers this sniff supports.
*
* @var array
*/
public $supportedTokenizers = array(
'PHP',
'JS',
'CSS',
);
/**
* The valid EOL character.
*
* @var string
*/
public $eolChar = '\n';
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_OPEN_TAG);
}//end register()
/**
* Processes this sniff, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
// We are only interested if this is the first open tag.
if ($stackPtr !== 0) {
if ($phpcsFile->findPrevious(T_OPEN_TAG, ($stackPtr - 1)) !== false) {
return;
}
}
$found = $phpcsFile->eolChar;
$found = str_replace("\n", '\n', $found);
$found = str_replace("\r", '\r', $found);
if ($found !== $this->eolChar) {
$error = 'End of line character is invalid; expected "%s" but found "%s"';
$expected = $this->eolChar;
$expected = str_replace("\n", '\n', $expected);
$expected = str_replace("\r", '\r', $expected);
$data = array(
$expected,
$found,
);
$phpcsFile->addError($error, $stackPtr, 'InvalidEOLChar', $data);
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,161 @@
<?php
/**
* Generic_Sniffs_Files_LineLengthSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_Files_LineLengthSniff.
*
* Checks all lines in the file, and throws warnings if they are over 80
* characters in length and errors if they are over 100. Both these
* figures can be changed by extending this sniff in your own standard.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_Files_LineLengthSniff implements PHP_CodeSniffer_Sniff
{
/**
* The limit that the length of a line should not exceed.
*
* @var int
*/
public $lineLimit = 80;
/**
* The limit that the length of a line must not exceed.
*
* Set to zero (0) to disable.
*
* @var int
*/
public $absoluteLineLimit = 100;
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_OPEN_TAG);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// Make sure this is the first open tag.
$previousOpenTag = $phpcsFile->findPrevious(T_OPEN_TAG, ($stackPtr - 1));
if ($previousOpenTag !== false) {
return;
}
$tokenCount = 0;
$currentLineContent = '';
$currentLine = 1;
$trim = (strlen($phpcsFile->eolChar) * -1);
for (; $tokenCount < $phpcsFile->numTokens; $tokenCount++) {
if ($tokens[$tokenCount]['line'] === $currentLine) {
$currentLineContent .= $tokens[$tokenCount]['content'];
} else {
$currentLineContent = substr($currentLineContent, 0, $trim);
$this->checkLineLength($phpcsFile, ($tokenCount - 1), $currentLineContent);
$currentLineContent = $tokens[$tokenCount]['content'];
$currentLine++;
}
}
$currentLineContent = substr($currentLineContent, 0, $trim);
$this->checkLineLength($phpcsFile, ($tokenCount - 1), $currentLineContent);
}//end process()
/**
* Checks if a line is too long.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The token at the end of the line.
* @param string $lineContent The content of the line.
*
* @return void
*/
protected function checkLineLength(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $lineContent)
{
// If the content is a CVS or SVN id in a version tag, or it is
// a license tag with a name and URL, there is nothing the
// developer can do to shorten the line, so don't throw errors.
if (preg_match('|@version[^\$]+\$Id|', $lineContent) !== 0) {
return;
}
if (preg_match('|@license|', $lineContent) !== 0) {
return;
}
if (PHP_CODESNIFFER_ENCODING !== 'iso-8859-1') {
// Not using the detault encoding, so take a bit more care.
$lineLength = iconv_strlen($lineContent, PHP_CODESNIFFER_ENCODING);
if ($lineLength === false) {
// String contained invalid characters, so revert to default.
$lineLength = strlen($lineContent);
}
} else {
$lineLength = strlen($lineContent);
}
if ($this->absoluteLineLimit > 0
&& $lineLength > $this->absoluteLineLimit
) {
$data = array(
$this->absoluteLineLimit,
$lineLength,
);
$error = 'Line exceeds maximum limit of %s characters; contains %s characters';
$phpcsFile->addError($error, $stackPtr, 'MaxExceeded', $data);
} else if ($lineLength > $this->lineLimit) {
$data = array(
$this->lineLimit,
$lineLength,
);
$warning = 'Line exceeds %s characters; contains %s characters';
$phpcsFile->addWarning($warning, $stackPtr, 'TooLong', $data);
}
}//end checkLineLength()
}//end class

View File

@@ -0,0 +1,88 @@
<?php
/**
* Generic_Sniffs_Formatting_DisallowMultipleStatementsSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_Formatting_DisallowMultipleStatementsSniff.
*
* Ensures each statement is on a line by itself.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_Formatting_DisallowMultipleStatementsSniff implements PHP_CodeSniffer_Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_SEMICOLON);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$prev = $phpcsFile->findPrevious(T_SEMICOLON, ($stackPtr - 1));
if ($prev === false) {
return;
}
// Ignore multiple statements in a FOR condition.
if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) {
foreach ($tokens[$stackPtr]['nested_parenthesis'] as $bracket) {
if (isset($tokens[$bracket]['parenthesis_owner']) === false) {
// Probably a closure sitting inside a function call.
continue;
}
$owner = $tokens[$bracket]['parenthesis_owner'];
if ($tokens[$owner]['code'] === T_FOR) {
return;
}
}
}
if ($tokens[$prev]['line'] === $tokens[$stackPtr]['line']) {
$error = 'Each PHP statement must be on a line by itself';
$phpcsFile->addError($error, $stackPtr, 'SameLine');
return;
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,304 @@
<?php
/**
* Generic_Sniffs_Formatting_MultipleStatementAlignmentSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_Formatting_MultipleStatementAlignmentSniff.
*
* Checks alignment of assignments. If there are multiple adjacent assignments,
* it will check that the equals signs of each assignment are aligned. It will
* display a warning to advise that the signs should be aligned.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_Formatting_MultipleStatementAlignmentSniff implements PHP_CodeSniffer_Sniff
{
/**
* A list of tokenizers this sniff supports.
*
* @var array
*/
public $supportedTokenizers = array(
'PHP',
'JS',
);
/**
* If true, an error will be thrown; otherwise a warning.
*
* @var bool
*/
public $error = false;
/**
* The maximum amount of padding before the alignment is ignored.
*
* If the amount of padding required to align this assignment with the
* surrounding assignments exceeds this number, the assignment will be
* ignored and no errors or warnings will be thrown.
*
* @var int
*/
public $maxPadding = 1000;
/**
* If true, multi-line assignments are not checked.
*
* @var int
*/
public $ignoreMultiLine = false;
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return PHP_CodeSniffer_Tokens::$assignmentTokens;
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// Ignore assignments used in a condition, like an IF or FOR.
if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) {
foreach ($tokens[$stackPtr]['nested_parenthesis'] as $start => $end) {
if (isset($tokens[$start]['parenthesis_owner']) === true) {
return;
}
}
}
/*
By this stage, it is known that there is an assignment on this line.
We only want to process the block once we reach the last assignment,
so we need to determine if there are more to follow.
*/
// The assignment may span over multiple lines, so look for the
// end of the assignment so we can check assignment blocks correctly.
$lineEnd = $phpcsFile->findNext(T_SEMICOLON, ($stackPtr + 1));
$nextAssign = $phpcsFile->findNext(
PHP_CodeSniffer_Tokens::$assignmentTokens,
($lineEnd + 1)
);
if ($nextAssign !== false) {
$isAssign = true;
if ($tokens[$nextAssign]['line'] === ($tokens[$lineEnd]['line'] + 1)) {
// Assignment may be in the same block as this one. Just make sure
// it is not used in a condition, like an IF or FOR.
if (isset($tokens[$nextAssign]['nested_parenthesis']) === true) {
foreach ($tokens[$nextAssign]['nested_parenthesis'] as $start => $end) {
if (isset($tokens[$start]['parenthesis_owner']) === true) {
// Not an assignment.
$isAssign = false;
break;
}
}
}
if ($isAssign === true) {
return;
}
}
}
// Getting here means that this is the last in a block of statements.
$assignments = array();
$assignments[] = $stackPtr;
$prevAssignment = $stackPtr;
$lastLine = $tokens[$stackPtr]['line'];
while (($prevAssignment = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$assignmentTokens, ($prevAssignment - 1))) !== false) {
// We are not interested in double arrows as they assign values inside
// arrays and loops and do not use the same indentation rules.
if ($tokens[$prevAssignment]['code'] === T_DOUBLE_ARROW) {
continue;
}
// The assignment's end token must be on the line directly
// above the current one to be in the same assignment block.
$lineEnd = $phpcsFile->findNext(T_SEMICOLON, ($prevAssignment + 1));
// And the end token must actually belong to this assignment.
$nextOpener = $phpcsFile->findNext(
PHP_CodeSniffer_Tokens::$scopeOpeners,
($prevAssignment + 1)
);
if ($nextOpener !== false && $nextOpener < $lineEnd) {
break;
}
if ($tokens[$lineEnd]['line'] !== ($lastLine - 1)) {
break;
}
// Make sure it is not assigned inside a condition (eg. IF, FOR).
if (isset($tokens[$prevAssignment]['nested_parenthesis']) === true) {
foreach ($tokens[$prevAssignment]['nested_parenthesis'] as $start => $end) {
if (isset($tokens[$start]['parenthesis_owner']) === true) {
break(2);
}
}
}
$assignments[] = $prevAssignment;
$lastLine = $tokens[$prevAssignment]['line'];
}//end while
$assignmentData = array();
$maxAssignmentLength = 0;
$maxVariableLength = 0;
foreach ($assignments as $assignment) {
$prev = $phpcsFile->findPrevious(
PHP_CodeSniffer_Tokens::$emptyTokens,
($assignment - 1),
null,
true
);
$endColumn = $tokens[($prev + 1)]['column'];
if ($maxVariableLength < $endColumn) {
$maxVariableLength = $endColumn;
}
if ($maxAssignmentLength < strlen($tokens[$assignment]['content'])) {
$maxAssignmentLength = strlen($tokens[$assignment]['content']);
}
$assignmentData[$assignment]
= array(
'variable_length' => $endColumn,
'assignment_length' => strlen($tokens[$assignment]['content']),
);
}//end foreach
foreach ($assignmentData as $assignment => $data) {
if ($data['assignment_length'] === $maxAssignmentLength) {
if ($data['variable_length'] === $maxVariableLength) {
// The assignment is the longest possible, so the column that
// everything has to align to is based on it.
$column = ($maxVariableLength + 1);
break;
} else {
// The assignment token is the longest out of all of the
// assignments, but the variable name is not, so the column
// the start at can go back more to cover the space
// between the variable name and the assigment operator.
$column = ($maxVariableLength - ($maxAssignmentLength - 1) + 1);
}
}
}
// Determine the actual position that each equals sign should be in.
foreach ($assignments as $assignment) {
// Actual column takes into account the length of the assignment operator.
$actualColumn = ($column + $maxAssignmentLength - strlen($tokens[$assignment]['content']));
if ($tokens[$assignment]['column'] !== $actualColumn) {
$prev = $phpcsFile->findPrevious(
PHP_CodeSniffer_Tokens::$emptyTokens,
($assignment - 1),
null,
true
);
$expected = ($actualColumn - $tokens[($prev + 1)]['column']);
if ($tokens[$assignment]['line'] !== $tokens[$prev]['line']) {
// Instead of working out how many spaces there are
// across new lines, the error message becomes more
// generic below.
$found = null;
} else {
$found = ($tokens[$assignment]['column'] - $tokens[($prev + 1)]['column']);
}
// If the expected number of spaces for alignment exceeds the
// maxPadding rule, we just check for a single space as no
// alignment is required.
if ($expected > $this->maxPadding) {
if ($found === 1) {
continue;
} else {
$expected = 1;
}
}
// Skip multi-line assignments if required.
if ($found === null && $this->ignoreMultiLine === true) {
continue;
}
$expected .= ($expected === 1) ? ' space' : ' spaces';
if ($found === null) {
$found = 'a new line';
} else {
$found .= ($found === 1) ? ' space' : ' spaces';
}
if (count($assignments) === 1) {
$type = 'Incorrect';
$error = 'Equals sign not aligned correctly; expected %s but found %s';
} else {
$type = 'NotSame';
$error = 'Equals sign not aligned with surrounding assignments; expected %s but found %s';
}
$errorData = array(
$expected,
$found,
);
if ($this->error === true) {
$phpcsFile->addError($error, $assignment, $type, $errorData);
} else {
$phpcsFile->addWarning($error, $assignment, $type.'Warning', $errorData);
}
}//end if
}//end foreach
}//end process()
}//end class
?>

View File

@@ -0,0 +1,69 @@
<?php
/**
* Generic_Sniffs_Formatting_NoSpaceAfterCastSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_Formatting_NoSpaceAfterCastSniff.
*
* Ensures there is no space after cast tokens.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_Formatting_NoSpaceAfterCastSniff implements PHP_CodeSniffer_Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return PHP_CodeSniffer_Tokens::$castTokens;
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if ($tokens[($stackPtr + 1)]['code'] === T_WHITESPACE) {
$error = 'A cast statement must not be followed by a space';
$phpcsFile->addError($error, $stackPtr, 'SpaceFound');
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,75 @@
<?php
/**
* Generic_Sniffs_Formatting_SpaceAfterCastSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_Formatting_SpaceAfterCastSniff.
*
* Ensures there is a single space after cast tokens.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_Formatting_SpaceAfterCastSniff implements PHP_CodeSniffer_Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return PHP_CodeSniffer_Tokens::$castTokens;
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if ($tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE) {
$error = 'A cast statement must be followed by a single space';
$phpcsFile->addError($error, $stackPtr, 'NoSpace');
return;
}
if ($tokens[($stackPtr + 1)]['content'] !== ' ') {
$error = 'A cast statement must be followed by a single space';
$phpcsFile->addError($error, $stackPtr, 'TooMuchSpace');
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,148 @@
<?php
/**
* Generic_Sniffs_Functions_CallTimePassByReferenceSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Florian Grandel <jerico.dev@gmail.com>
* @copyright 2009 Florian Grandel
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_Functions_CallTimePassByReferenceSniff.
*
* Ensures that variables are not passed by reference when calling a function.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Florian Grandel <jerico.dev@gmail.com>
* @copyright 2009 Florian Grandel
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_Functions_CallTimePassByReferenceSniff implements PHP_CodeSniffer_Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_STRING);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// Skip tokens that are the names of functions or classes
// within their definitions. For example: function myFunction...
// "myFunction" is T_STRING but we should skip because it is not a
// function or method *call*.
$functionName = $stackPtr;
$findTokens = array_merge(
PHP_CodeSniffer_Tokens::$emptyTokens,
array(T_BITWISE_AND)
);
$functionKeyword = $phpcsFile->findPrevious(
$findTokens,
($stackPtr - 1),
null,
true
);
if ($tokens[$functionKeyword]['code'] === T_FUNCTION
|| $tokens[$functionKeyword]['code'] === T_CLASS
) {
return;
}
// If the next non-whitespace token after the function or method call
// is not an opening parenthesis then it cant really be a *call*.
$openBracket = $phpcsFile->findNext(
PHP_CodeSniffer_Tokens::$emptyTokens,
($functionName + 1),
null,
true
);
if ($tokens[$openBracket]['code'] !== T_OPEN_PARENTHESIS) {
return;
}
$closeBracket = $tokens[$openBracket]['parenthesis_closer'];
$nextSeparator = $openBracket;
while (($nextSeparator = $phpcsFile->findNext(T_VARIABLE, ($nextSeparator + 1), $closeBracket)) !== false) {
// Make sure the variable belongs directly to this function call
// and is not inside a nested function call or array.
$brackets = $tokens[$nextSeparator]['nested_parenthesis'];
$lastBracket = array_pop($brackets);
if ($lastBracket !== $closeBracket) {
continue;
}
// Checking this: $value = my_function(...[*]$arg...).
$tokenBefore = $phpcsFile->findPrevious(
PHP_CodeSniffer_Tokens::$emptyTokens,
($nextSeparator - 1),
null,
true
);
if ($tokens[$tokenBefore]['code'] === T_BITWISE_AND) {
// Checking this: $value = my_function(...[*]&$arg...).
$tokenBefore = $phpcsFile->findPrevious(
PHP_CodeSniffer_Tokens::$emptyTokens,
($tokenBefore - 1),
null,
true
);
// We have to exclude all uses of T_BITWISE_AND that are not
// references. We use a blacklist approach as we prefer false
// positives to not identifiying a pass-by-reference call at all.
// The blacklist may not yet be complete.
switch ($tokens[$tokenBefore]['code']) {
case T_VARIABLE:
case T_CLOSE_PARENTHESIS:
// In these cases T_BITWISE_AND represents
// the bitwise and operator.
continue;
break;
default:
// T_BITWISE_AND represents a pass-by-reference.
$error = 'Call-time pass-by-reference calls are prohibited';
$phpcsFile->addError($error, $tokenBefore, 'NotAllowed');
break;
}
}//end if
}//end while
}//end process()
}//end class
?>

View File

@@ -0,0 +1,136 @@
<?php
/**
* Generic_Sniffs_Functions_FunctionCallArgumentSpacingSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_Functions_FunctionCallArgumentSpacingSniff.
*
* Checks that calls to methods and functions are spaced correctly.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_Functions_FunctionCallArgumentSpacingSniff implements PHP_CodeSniffer_Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_STRING);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in the
* stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// Skip tokens that are the names of functions or classes
// within their definitions. For example:
// function myFunction...
// "myFunction" is T_STRING but we should skip because it is not a
// function or method *call*.
$functionName = $stackPtr;
$ignoreTokens = PHP_CodeSniffer_Tokens::$emptyTokens;
$ignoreTokens[] = T_BITWISE_AND;
$functionKeyword = $phpcsFile->findPrevious($ignoreTokens, ($stackPtr - 1), null, true);
if ($tokens[$functionKeyword]['code'] === T_FUNCTION || $tokens[$functionKeyword]['code'] === T_CLASS) {
return;
}
// If the next non-whitespace token after the function or method call
// is not an opening parenthesis then it cant really be a *call*.
$openBracket = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($functionName + 1), null, true);
if ($tokens[$openBracket]['code'] !== T_OPEN_PARENTHESIS) {
return;
}
$closeBracket = $tokens[$openBracket]['parenthesis_closer'];
$nextSeperator = $openBracket;
while (($nextSeperator = $phpcsFile->findNext(array(T_COMMA, T_VARIABLE), ($nextSeperator + 1), $closeBracket)) !== false) {
// Make sure the comma or variable belongs directly to this function call,
// and is not inside a nested function call or array.
$brackets = $tokens[$nextSeperator]['nested_parenthesis'];
$lastBracket = array_pop($brackets);
if ($lastBracket !== $closeBracket) {
continue;
}
if ($tokens[$nextSeperator]['code'] === T_COMMA) {
if ($tokens[($nextSeperator - 1)]['code'] === T_WHITESPACE) {
$error = 'Space found before comma in function call';
$phpcsFile->addError($error, $stackPtr, 'SpaceBeforeComma');
}
if ($tokens[($nextSeperator + 1)]['code'] !== T_WHITESPACE) {
$error = 'No space found after comma in function call';
$phpcsFile->addError($error, $stackPtr, 'NoSpaceAfterComma');
} else {
// If there is a newline in the space, then the must be formatting
// each argument on a newline, which is valid, so ignore it.
if (strpos($tokens[($nextSeperator + 1)]['content'], $phpcsFile->eolChar) === false) {
$space = strlen($tokens[($nextSeperator + 1)]['content']);
if ($space > 1) {
$error = 'Expected 1 space after comma in function call; %s found';
$data = array($space);
$phpcsFile->addError($error, $stackPtr, 'TooMuchSpaceAfterComma', $data);
}
}
}
} else {
// Token is a variable.
$nextToken = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($nextSeperator + 1), $closeBracket, true);
if ($nextToken !== false) {
if ($tokens[$nextToken]['code'] === T_EQUAL) {
if (($tokens[($nextToken - 1)]['code']) !== T_WHITESPACE) {
$error = 'Expected 1 space before = sign of default value';
$phpcsFile->addError($error, $stackPtr, 'NoSpaceBeforeEquals');
}
if ($tokens[($nextToken + 1)]['code'] !== T_WHITESPACE) {
$error = 'Expected 1 space after = sign of default value';
$phpcsFile->addError($error, $stackPtr, 'NoSpaceAfterEquals');
}
}
}
}//end if
}//end while
}//end process()
}//end class
?>

View File

@@ -0,0 +1,121 @@
<?php
/**
* Generic_Sniffs_Methods_OpeningMethodBraceBsdAllmanSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_Functions_OpeningFunctionBraceBsdAllmanSniff.
*
* Checks that the opening brace of a function is on the line after the
* function declaration.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_Functions_OpeningFunctionBraceBsdAllmanSniff implements PHP_CodeSniffer_Sniff
{
/**
* Registers the tokens that this sniff wants to listen for.
*
* @return void
*/
public function register()
{
return array(T_FUNCTION);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in the
* stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if (isset($tokens[$stackPtr]['scope_opener']) === false) {
return;
}
$openingBrace = $tokens[$stackPtr]['scope_opener'];
// The end of the function occurs at the end of the argument list. Its
// like this because some people like to break long function declarations
// over multiple lines.
$functionLine = $tokens[$tokens[$stackPtr]['parenthesis_closer']]['line'];
$braceLine = $tokens[$openingBrace]['line'];
$lineDifference = ($braceLine - $functionLine);
if ($lineDifference === 0) {
$error = 'Opening brace should be on a new line';
$phpcsFile->addError($error, $openingBrace, 'BraceOnSameLine');
return;
}
if ($lineDifference > 1) {
$error = 'Opening brace should be on the line after the declaration; found %s blank line(s)';
$data = array(($lineDifference - 1));
$phpcsFile->addError($error, $openingBrace, 'BraceSpacing', $data);
return;
}
// We need to actually find the first piece of content on this line,
// as if this is a method with tokens before it (public, static etc)
// or an if with an else before it, then we need to start the scope
// checking from there, rather than the current token.
$lineStart = $stackPtr;
while (($lineStart = $phpcsFile->findPrevious(array(T_WHITESPACE), ($lineStart - 1), null, false)) !== false) {
if (strpos($tokens[$lineStart]['content'], $phpcsFile->eolChar) !== false) {
break;
}
}
// We found a new line, now go forward and find the first non-whitespace
// token.
$lineStart = $phpcsFile->findNext(array(T_WHITESPACE), $lineStart, null, true);
// The opening brace is on the correct line, now it needs to be
// checked to be correctly indented.
$startColumn = $tokens[$lineStart]['column'];
$braceIndent = $tokens[$openingBrace]['column'];
if ($braceIndent !== $startColumn) {
$error = 'Opening brace indented incorrectly; expected %s spaces, found %s';
$data = array(
($startColumn - 1),
($braceIndent - 1),
);
$phpcsFile->addError($error, $openingBrace, 'BraceIndent', $data);
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,109 @@
<?php
/**
* Generic_Sniffs_Functions_OpeningFunctionBraceKernighanRitchieSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_Functions_OpeningFunctionBraceKernighanRitchieSniff.
*
* Checks that the opening brace of a function is on the same line
* as the function declaration.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_Functions_OpeningFunctionBraceKernighanRitchieSniff implements PHP_CodeSniffer_Sniff
{
/**
* Registers the tokens that this sniff wants to listen for.
*
* @return void
*/
public function register()
{
return array(T_FUNCTION);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in the
* stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if (isset($tokens[$stackPtr]['scope_opener']) === false) {
return;
}
$openingBrace = $tokens[$stackPtr]['scope_opener'];
// The end of the function occurs at the end of the argument list. Its
// like this because some people like to break long function declarations
// over multiple lines.
$functionLine = $tokens[$tokens[$stackPtr]['parenthesis_closer']]['line'];
$braceLine = $tokens[$openingBrace]['line'];
$lineDifference = ($braceLine - $functionLine);
if ($lineDifference > 0) {
$error = 'Opening brace should be on the same line as the declaration';
$phpcsFile->addError($error, $openingBrace, 'BraceOnNewLine');
return;
}
// Checks that the closing parenthesis and the opening brace are
// separated by a whitespace character.
$closerColumn = $tokens[$tokens[$stackPtr]['parenthesis_closer']]['column'];
$braceColumn = $tokens[$openingBrace]['column'];
$columnDifference = ($braceColumn - $closerColumn);
if ($columnDifference !== 2) {
$error = 'Expected 1 space between the closing parenthesis and the opening brace; found %s';
$data = array(($columnDifference - 1));
$phpcsFile->addError($error, $openingBrace, 'SpaceBeforeBrace', $data);
return;
}
// Check that a tab was not used instead of a space.
$spaceTokenPtr = ($tokens[$stackPtr]['parenthesis_closer'] + 1);
$spaceContent = $tokens[$spaceTokenPtr]['content'];
if ($spaceContent !== ' ') {
$error = 'Expected a single space character between closing parenthesis and opening brace; found %s';
$data = array($spaceContent);
$phpcsFile->addError($error, $openingBrace, 'SpaceBeforeBrace', $data);
return;
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,131 @@
<?php
/**
* Checks the cyclomatic complexity (McCabe) for functions.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Checks the cyclomatic complexity (McCabe) for functions.
*
* The cyclomatic complexity (also called McCabe code metrics)
* indicates the complexity within a function by counting
* the different paths the function includes.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Johann-Peter Hartmann <hartmann@mayflower.de>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2007 Mayflower GmbH
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_Metrics_CyclomaticComplexitySniff implements PHP_CodeSniffer_Sniff
{
/**
* A complexity higher than this value will throw a warning.
*
* @var int
*/
public $complexity = 10;
/**
* A complexity higer than this value will throw an error.
*
* @var int
*/
public $absoluteComplexity = 20;
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_FUNCTION);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$this->currentFile = $phpcsFile;
$tokens = $phpcsFile->getTokens();
// Ignore abstract methods.
if (isset($tokens[$stackPtr]['scope_opener']) === false) {
return;
}
// Detect start and end of this function definition.
$start = $tokens[$stackPtr]['scope_opener'];
$end = $tokens[$stackPtr]['scope_closer'];
// Predicate nodes for PHP.
$find = array(
'T_CASE',
'T_DEFAULT',
'T_CATCH',
'T_IF',
'T_FOR',
'T_FOREACH',
'T_WHILE',
'T_DO',
'T_ELSEIF',
);
$complexity = 1;
// Iterate from start to end and count predicate nodes.
for ($i = ($start + 1); $i < $end; $i++) {
if (in_array($tokens[$i]['type'], $find) === true) {
$complexity++;
}
}
if ($complexity > $this->absoluteComplexity) {
$error = 'Function\'s cyclomatic complexity (%s) exceeds allowed maximum of %s';
$data = array(
$complexity,
$this->absoluteComplexity,
);
$phpcsFile->addError($error, $stackPtr, 'MaxExceeded', $data);
} else if ($complexity > $this->complexity) {
$warning = 'Function\'s cyclomatic complexity (%s) exceeds %s; consider refactoring the function';
$data = array(
$complexity,
$this->complexity,
);
$phpcsFile->addWarning($warning, $stackPtr, 'TooHigh', $data);
}
return;
}//end process()
}//end class
?>

View File

@@ -0,0 +1,114 @@
<?php
/**
* Checks the nesting level for methods.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Checks the nesting level for methods.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Johann-Peter Hartmann <hartmann@mayflower.de>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2007 Mayflower GmbH
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_Metrics_NestingLevelSniff implements PHP_CodeSniffer_Sniff
{
/**
* A nesting level than this value will throw a warning.
*
* @var int
*/
public $nestingLevel = 5;
/**
* A nesting level than this value will throw an error.
*
* @var int
*/
public $absoluteNestingLevel = 10;
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_FUNCTION);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// Ignore abstract methods.
if (isset($tokens[$stackPtr]['scope_opener']) === false) {
return;
}
// Detect start and end of this function definition.
$start = $tokens[$stackPtr]['scope_opener'];
$end = $tokens[$stackPtr]['scope_closer'];
$nestingLevel = 0;
// Find the maximum nesting level of any token in the function.
for ($i = ($start + 1); $i < $end; $i++) {
$level = $tokens[$i]['level'];
if ($nestingLevel < $level) {
$nestingLevel = $level;
}
}
// We subtract the nesting level of the function itself.
$nestingLevel = ($nestingLevel - $tokens[$stackPtr]['level'] - 1);
if ($nestingLevel > $this->absoluteNestingLevel) {
$error = 'Function\'s nesting level (%s) exceeds allowed maximum of %s';
$data = array(
$nestingLevel,
$this->absoluteNestingLevel,
);
$phpcsFile->addError($error, $stackPtr, 'MaxExceeded', $data);
} else if ($nestingLevel > $this->nestingLevel) {
$warning = 'Function\'s nesting level (%s) exceeds %s; consider refactoring the function';
$data = array(
$nestingLevel,
$this->nestingLevel,
);
$phpcsFile->addWarning($warning, $stackPtr, 'TooHigh', $data);
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,101 @@
<?php
/**
* Generic_Sniffs_NamingConventions_ConstructorNameSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Leif Wickland <lwickland@rightnow.com>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (class_exists('PHP_CodeSniffer_Standards_AbstractScopeSniff', true) === false) {
$error = 'Class PHP_CodeSniffer_Standards_AbstractScopeSniff not found';
throw new PHP_CodeSniffer_Exception($error);
}
/**
* Generic_Sniffs_NamingConventions_ConstructorNameSniff.
*
* Favor PHP 5 constructor syntax, which uses "function __construct()".
* Avoid PHP 4 constructor syntax, which uses "function ClassName()".
*
* @category PHP
* @package PHP_CodeSniffer
* @author Leif Wickland <lwickland@rightnow.com>
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_NamingConventions_ConstructorNameSniff extends PHP_CodeSniffer_Standards_AbstractScopeSniff
{
/**
* Constructs the test with the tokens it wishes to listen for.
*
* @return void
*/
public function __construct()
{
parent::__construct(array(T_CLASS, T_INTERFACE), array(T_FUNCTION), true);
}//end __construct()
/**
* Processes this test when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
* @param int $currScope A pointer to the start of the scope.
*
* @return void
*/
protected function processTokenWithinScope(
PHP_CodeSniffer_File $phpcsFile,
$stackPtr,
$currScope
) {
$className = $phpcsFile->getDeclarationName($currScope);
$methodName = $phpcsFile->getDeclarationName($stackPtr);
if (strcasecmp($methodName, $className) === 0) {
$error = 'PHP4 style constructors are not allowed; use "__construct()" instead';
$phpcsFile->addError($error, $stackPtr, 'OldStyle');
} else if (strcasecmp($methodName, '__construct') !== 0) {
// Not a constructor.
return;
}
$tokens = $phpcsFile->getTokens();
$parentClassName = $phpcsFile->findExtendedClassName($currScope);
if ($parentClassName === false) {
return;
}
$endFunctionIndex = $tokens[$stackPtr]['scope_closer'];
$startIndex = $stackPtr;
while ($doubleColonIndex = $phpcsFile->findNext(array(T_DOUBLE_COLON), $startIndex, $endFunctionIndex)) {
if ($tokens[($doubleColonIndex + 1)]['code'] === T_STRING
&& $tokens[($doubleColonIndex + 1)]['content'] === $parentClassName
) {
$error = 'PHP4 style calls to parent constructors are not allowed; use "parent::__construct()" instead';
$phpcsFile->addError($error, ($doubleColonIndex + 1), 'OldStyleCall');
}
$startIndex = ($doubleColonIndex + 1);
}
}//end processTokenWithinScope()
}//end class
?>

View File

@@ -0,0 +1,198 @@
<?php
/**
* Generic_Sniffs_NamingConventions_UpperCaseConstantNameSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_NamingConventions_UpperCaseConstantNameSniff.
*
* Ensures that constant names are all uppercase.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_NamingConventions_UpperCaseConstantNameSniff implements PHP_CodeSniffer_Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_STRING);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in the
* stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$constName = $tokens[$stackPtr]['content'];
// If this token is in a heredoc, ignore it.
if ($phpcsFile->hasCondition($stackPtr, T_START_HEREDOC) === true) {
return;
}
// Special case for PHPUnit.
if ($constName === 'PHPUnit_MAIN_METHOD') {
return;
}
// If the next non-whitespace token after this token
// is not an opening parenthesis then it is not a function call.
$openBracket = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);
if ($tokens[$openBracket]['code'] !== T_OPEN_PARENTHESIS) {
$functionKeyword = $phpcsFile->findPrevious(array(T_WHITESPACE, T_COMMA, T_COMMENT, T_STRING, T_NS_SEPARATOR), ($stackPtr - 1), null, true);
$declarations = array(
T_FUNCTION,
T_CLASS,
T_INTERFACE,
T_IMPLEMENTS,
T_EXTENDS,
T_INSTANCEOF,
T_NEW,
T_NAMESPACE,
T_USE,
T_AS,
);
if (in_array($tokens[$functionKeyword]['code'], $declarations) === true) {
// This is just a declaration; no constants here.
return;
}
if ($tokens[$functionKeyword]['code'] === T_CONST) {
// This is a class constant.
if (strtoupper($constName) !== $constName) {
$error = 'Class constants must be uppercase; expected %s but found %s';
$data = array(
strtoupper($constName),
$constName,
);
$phpcsFile->addError($error, $stackPtr, 'ClassConstantNotUpperCase', $data);
}
return;
}
// Is this a class name?
$nextPtr = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);
if ($tokens[$nextPtr]['code'] === T_DOUBLE_COLON) {
return;
}
// Is this a namespace name?
if ($tokens[$nextPtr]['code'] === T_NS_SEPARATOR) {
return;
}
// Is this a type hint?
if ($tokens[$nextPtr]['code'] === T_VARIABLE
|| $phpcsFile->isReference($nextPtr) === true
) {
return;
}
// Is this a member var name?
$prevPtr = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
if ($tokens[$prevPtr]['code'] === T_OBJECT_OPERATOR) {
return;
}
// Is this a namespace name?
if ($tokens[$prevPtr]['code'] === T_NS_SEPARATOR) {
return;
}
// Is this an instance of declare()
$prevPtr = $phpcsFile->findPrevious(array(T_WHITESPACE, T_OPEN_PARENTHESIS), ($stackPtr - 1), null, true);
if ($tokens[$prevPtr]['code'] === T_DECLARE) {
return;
}
// This is a real constant.
if (strtoupper($constName) !== $constName) {
$error = 'Constants must be uppercase; expected %s but found %s';
$data = array(
strtoupper($constName),
$constName,
);
$phpcsFile->addError($error, $stackPtr, 'ConstantNotUpperCase', $data);
}
} else if (strtolower($constName) === 'define' || strtolower($constName) === 'constant') {
/*
This may be a "define" or "constant" function call.
*/
// Make sure this is not a method call.
$prev = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
if ($tokens[$prev]['code'] === T_OBJECT_OPERATOR
|| $tokens[$prev]['code'] === T_DOUBLE_COLON
) {
return;
}
// The next non-whitespace token must be the constant name.
$constPtr = $phpcsFile->findNext(T_WHITESPACE, ($openBracket + 1), null, true);
if ($tokens[$constPtr]['code'] !== T_CONSTANT_ENCAPSED_STRING) {
return;
}
$constName = $tokens[$constPtr]['content'];
// Check for constants like self::CONSTANT.
$prefix = '';
$splitPos = strpos($constName, '::');
if ($splitPos !== false) {
$prefix = substr($constName, 0, ($splitPos + 2));
$constName = substr($constName, ($splitPos + 2));
}
if (strtoupper($constName) !== $constName) {
$error = 'Constants must be uppercase; expected %s but found %s';
$data = array(
$prefix.strtoupper($constName),
$prefix.$constName,
);
$phpcsFile->addError($error, $stackPtr, 'ConstantNotUpperCase', $data);
}
}//end if
}//end process()
}//end class
?>

View File

@@ -0,0 +1,94 @@
<?php
/**
* Generic_Sniffs_PHP_DeprecatedFunctionsSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_PHP_DeprecatedFunctionsSniff.
*
* Discourages the use of deprecated functions that are kept in PHP for
* compatibility with older versions.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Sebastian Bergmann <sb@sebastian-bergmann.de>
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_PHP_DeprecatedFunctionsSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff
{
/**
* A list of forbidden functions with their alternatives.
*
* The value is NULL if no alternative exists. IE, the
* function should just not be used.
*
* @var array(string => string|null)
*/
protected $forbiddenFunctions = array();
/**
* Constructor.
*
* Uses the Reflection API to get a list of deprecated functions.
*/
public function __construct()
{
$functions = get_defined_functions();
foreach ($functions['internal'] as $functionName) {
$function = new ReflectionFunction($functionName);
if ($function->isDeprecated() === true) {
$this->forbiddenFunctions[$functionName] = null;
}
}
}//end __construct()
/**
* Generates the error or wanrning for this sniff.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the forbidden function
* in the token array.
* @param string $function The name of the forbidden function.
* @param string $pattern The pattern used for the match.
*
* @return void
*/
protected function addError($phpcsFile, $stackPtr, $function, $pattern=null)
{
$data = array($function);
$error = 'Function %s() has been deprecated';
$type = 'Deprecated';
if ($this->error === true) {
$phpcsFile->addError($error, $stackPtr, $type, $data);
} else {
$phpcsFile->addWarning($error, $stackPtr, $type, $data);
}
}//end addError()
}//end class
?>

View File

@@ -0,0 +1,85 @@
<?php
/**
* Generic_Sniffs_PHP_DisallowShortOpenTagSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_PHP_DisallowShortOpenTagSniff.
*
* Makes sure that shorthand PHP open tags are not used.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_PHP_DisallowShortOpenTagSniff implements PHP_CodeSniffer_Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_OPEN_TAG,
T_OPEN_TAG_WITH_ECHO,
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$openTag = $tokens[$stackPtr];
if ($openTag['content'] === '<?') {
$error = 'Short PHP opening tag used; expected "<?php" but found "%s"';
$data = array($openTag['content']);
$phpcsFile->addError($error, $stackPtr, 'Found', $data);
}
if ($openTag['code'] === T_OPEN_TAG_WITH_ECHO) {
$nextVar = $tokens[$phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr + 1), null, true)];
$error = 'Short PHP opening tag used with echo; expected "<?php echo %s ..." but found "%s %s ..."';
$data = array(
$nextVar['content'],
$openTag['content'],
$nextVar['content'],
);
$phpcsFile->addError($error, $stackPtr, 'EchoFound', $data);
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,191 @@
<?php
/**
* Generic_Sniffs_PHP_ForbiddenFunctionsSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_PHP_ForbiddenFunctionsSniff.
*
* Discourages the use of alias functions that are kept in PHP for compatibility
* with older versions. Can be used to forbid the use of any function.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_PHP_ForbiddenFunctionsSniff implements PHP_CodeSniffer_Sniff
{
/**
* A list of forbidden functions with their alternatives.
*
* The value is NULL if no alternative exists. IE, the
* function should just not be used.
*
* @var array(string => string|null)
*/
protected $forbiddenFunctions = array(
'sizeof' => 'count',
'delete' => 'unset',
);
/**
* A cache of forbidden function names, for faster lookups.
*
* @var array(string)
*/
protected $forbiddenFunctionNames = array();
/**
* If true, forbidden functions will be considered regular expressions.
*
* @var bool
*/
protected $patternMatch = false;
/**
* If true, an error will be thrown; otherwise a warning.
*
* @var bool
*/
public $error = true;
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
// Everyone has had a chance to figure out what forbidden functions
// they want to check for, so now we can cache out the list.
$this->forbiddenFunctionNames = array_keys($this->forbiddenFunctions);
if ($this->patternMatch === true) {
foreach ($this->forbiddenFunctionNames as $i => $name) {
$this->forbiddenFunctionNames[$i] = '/'.$name.'/i';
}
}
return array(T_STRING);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$ignore = array(
T_DOUBLE_COLON,
T_OBJECT_OPERATOR,
T_FUNCTION,
T_CONST,
);
$prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
if (in_array($tokens[$prevToken]['code'], $ignore) === true) {
// Not a call to a PHP function.
return;
}
$function = strtolower($tokens[$stackPtr]['content']);
$pattern = null;
if ($this->patternMatch === true) {
$count = 0;
$pattern = preg_replace(
$this->forbiddenFunctionNames,
$this->forbiddenFunctionNames,
$function,
1,
$count
);
if ($count === 0) {
return;
}
// Remove the pattern delimiters and modifier.
$pattern = substr($pattern, 1, -2);
} else {
if (in_array($function, $this->forbiddenFunctionNames) === false) {
return;
}
}
$this->addError($phpcsFile, $stackPtr, $function, $pattern);
}//end process()
/**
* Generates the error or wanrning for this sniff.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the forbidden function
* in the token array.
* @param string $function The name of the forbidden function.
* @param string $pattern The pattern used for the match.
*
* @return void
*/
protected function addError($phpcsFile, $stackPtr, $function, $pattern=null)
{
$data = array($function);
$error = 'The use of function %s() is ';
if ($this->error === true) {
$type = 'Found';
$error .= 'forbidden';
} else {
$type = 'Discouraged';
$error .= 'discouraged';
}
if ($pattern === null) {
$pattern = $function;
}
if ($this->forbiddenFunctions[$pattern] !== null) {
$type .= 'WithAlternative';
$data[] = $this->forbiddenFunctions[$pattern];
$error .= '; use %s() instead';
}
if ($this->error === true) {
$phpcsFile->addError($error, $stackPtr, $type, $data);
} else {
$phpcsFile->addWarning($error, $stackPtr, $type, $data);
}
}//end addError()
}//end class
?>

View File

@@ -0,0 +1,93 @@
<?php
/**
* Generic_Sniffs_PHP_LowerCaseConstantSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_PHP_LowerCaseConstantSniff.
*
* Checks that all uses of true, false and null are lowerrcase.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_PHP_LowerCaseConstantSniff implements PHP_CodeSniffer_Sniff
{
/**
* A list of tokenizers this sniff supports.
*
* @var array
*/
public $supportedTokenizers = array(
'PHP',
'JS',
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_TRUE,
T_FALSE,
T_NULL,
);
}//end register()
/**
* Processes this sniff, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in the
* stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// Is this a member var name?
$prevPtr = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
if ($tokens[$prevPtr]['code'] === T_OBJECT_OPERATOR) {
return;
}
$keyword = $tokens[$stackPtr]['content'];
if (strtolower($keyword) !== $keyword) {
$error = 'TRUE, FALSE and NULL must be lowercase; expected "%s" but found "%s"';
$data = array(
strtolower($keyword),
$keyword,
);
$phpcsFile->addError($error, $stackPtr, 'Found', $data);
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,81 @@
<?php
/**
* Generic_Sniffs_PHP_NoSilencedErrorsSniff
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Andy Brockhurst <abrock@yahoo-inc.com>
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_PHP_NoSilencedErrorsSniff.
*
* Throws an error or warning when any code prefixed with an asperand is encountered.
*
* <code>
* if (@in_array($array, $needle))
* {
* doSomething();
* }
* </code>
*
* @category PHP
* @package PHP_CodeSniffer
* @author Andy Brockhurst <abrock@yahoo-inc.com>
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_PHP_NoSilencedErrorsSniff implements PHP_CodeSniffer_Sniff
{
/**
* If true, an error will be thrown; otherwise a warning.
*
* @var bool
*/
public $error = false;
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_ASPERAND);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$error = 'Silencing errors is forbidden';
if ($this->error === true) {
$error = 'Silencing errors is forbidden';
$phpcsFile->addError($error, $stackPtr, 'Forbidden');
} else {
$error = 'Silencing errors is discouraged';
$phpcsFile->addWarning($error, $stackPtr, 'Discouraged');
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,84 @@
<?php
/**
* Generic_Sniffs_PHP_UpperCaseConstantSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_PHP_UpperCaseConstantSniff.
*
* Checks that all uses of TRUE, FALSE and NULL are uppercase.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_PHP_UpperCaseConstantSniff implements PHP_CodeSniffer_Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_TRUE,
T_FALSE,
T_NULL,
);
}//end register()
/**
* Processes this sniff, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in the
* stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// Is this a member var name?
$prevPtr = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
if ($tokens[$prevPtr]['code'] === T_OBJECT_OPERATOR) {
return;
}
$keyword = $tokens[$stackPtr]['content'];
if (strtoupper($keyword) !== $keyword) {
$error = 'TRUE, FALSE and NULL must be uppercase; expected "%s" but found "%s"';
$data = array(
strtoupper($keyword),
$keyword,
);
$phpcsFile->addError($error, $stackPtr, 'Found', $data);
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,125 @@
<?php
/**
* Generic_Sniffs_Strings_UnnecessaryStringConcatSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_Strings_UnnecessaryStringConcatSniff.
*
* Checks that two strings are not concatenated together; suggests
* using one string instead.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_Strings_UnnecessaryStringConcatSniff implements PHP_CodeSniffer_Sniff
{
/**
* A list of tokenizers this sniff supports.
*
* @var array
*/
public $supportedTokenizers = array(
'PHP',
'JS',
);
/**
* If true, an error will be thrown; otherwise a warning.
*
* @var bool
*/
public $error = true;
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_STRING_CONCAT,
T_PLUS,
);
}//end register()
/**
* Processes this sniff, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
// Work out which type of file this is for.
$tokens = $phpcsFile->getTokens();
if ($tokens[$stackPtr]['code'] === T_STRING_CONCAT) {
if ($phpcsFile->tokenizerType === 'JS') {
return;
}
} else {
if ($phpcsFile->tokenizerType === 'PHP') {
return;
}
}
$prev = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
$next = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);
if ($prev === false || $next === false) {
return;
}
$stringTokens = PHP_CodeSniffer_Tokens::$stringTokens;
if (in_array($tokens[$prev]['code'], $stringTokens) === true
&& in_array($tokens[$next]['code'], $stringTokens) === true
) {
if ($tokens[$prev]['content'][0] === $tokens[$next]['content'][0]) {
// Before we throw an error for PHP, allow strings to be
// combined if they would have < and ? next to each other because
// this trick is sometimes required in PHP strings.
if ($phpcsFile->tokenizerType === 'PHP') {
$prevChar = substr($tokens[$prev]['content'], -2, 1);
$nextChar = $tokens[$next]['content'][1];
$combined = $prevChar.$nextChar;
if ($combined === '?'.'>' || $combined === '<'.'?') {
return;
}
}
$error = 'String concat is not required here; use a single string instead';
if ($this->error === true) {
$phpcsFile->addError($error, $stackPtr, 'Found');
} else {
$phpcsFile->addWarning($error, $stackPtr, 'Found');
}
}
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,206 @@
<?php
/**
* Generic_Sniffs_VersionControl_SubversionPropertiesSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Jack Bates <ms419@freezone.co.uk>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_VersionControl_SubversionPropertiesSniff.
*
* Tests that the correct Subversion properties are set.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Jack Bates <ms419@freezone.co.uk>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_VersionControl_SubversionPropertiesSniff implements PHP_CodeSniffer_Sniff
{
/**
* The Subversion properties that should be set.
*
* Key of array is the SVN property and the value is the
* exact value the property should have or NULL if the
* property should just be set but the value is not fixed.
*
* @var array
*/
protected $properties = array(
'svn:keywords' => 'Author Id Revision',
'svn:eol-style' => 'native',
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_OPEN_TAG);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// Make sure this is the first PHP open tag so we don't process the
// same file twice.
$prevOpenTag = $phpcsFile->findPrevious(T_OPEN_TAG, ($stackPtr - 1));
if ($prevOpenTag !== false) {
return;
}
$path = $phpcsFile->getFileName();
$properties = $this->getProperties($path);
if ($properties === null) {
// Not under version control.
return;
}
$properties += $this->properties;
foreach ($properties as $key => $value) {
if (isset($properties[$key]) === true
&& isset($this->properties[$key]) === false
) {
$error = 'Unexpected Subversion property "%s" = "%s"';
$data = array(
$key,
$properties[$key],
);
$phpcsFile->addError($error, $stackPtr, 'Unexpected', $data);
continue;
}
if (isset($properties[$key]) === false
&& isset($this->properties[$key]) === true
) {
$error = 'Missing Subversion property "%s" = "%s"';
$data = array(
$key,
$this->properties[$key],
);
$phpcsFile->addError($error, $stackPtr, 'Missing', $data);
continue;
}
if ($properties[$key] !== null
&& $properties[$key] !== $this->properties[$key]
) {
$error = 'Subversion property "%s" = "%s" does not match "%s"';
$data = array(
$key,
$properties[$key],
$this->properties[$key],
);
$phpcsFile->addError($error, $stackPtr, 'NoMatch', $data);
}
}//end foreach
}//end process()
/**
* Returns the Subversion properties which are actually set on a path.
*
* Returns NULL if the file is not under version control.
*
* @param string $path The path to return Subversion properties on.
*
* @return array
* @throws PHP_CodeSniffer_Exception If Subversion properties file could
* not be opened.
*/
protected function getProperties($path)
{
$properties = array();
$paths = array();
$paths[] = dirname($path).'/.svn/props/'.basename($path).'.svn-work';
$paths[] = dirname($path).'/.svn/prop-base/'.basename($path).'.svn-base';
$foundPath = false;
foreach ($paths as $path) {
if (file_exists($path) === true) {
$foundPath = true;
$handle = fopen($path, 'r');
if ($handle === false) {
$error = 'Error opening file; could not get Subversion properties';
throw new PHP_CodeSniffer_Exception($error);
}
while (feof($handle) === false) {
// Read a key length line. Might be END, though.
$buffer = trim(fgets($handle));
// Check for the end of the hash.
if ($buffer === 'END') {
break;
}
// Now read that much into a buffer.
$key = fread($handle, substr($buffer, 2));
// Suck up extra newline after key data.
fgetc($handle);
// Read a value length line.
$buffer = trim(fgets($handle));
// Now read that much into a buffer.
$length = substr($buffer, 2);
if ($length === '0') {
// Length of value is ZERO characters, so
// value is actually empty.
$value = '';
} else {
$value = fread($handle, $length);
}
// Suck up extra newline after value data.
fgetc($handle);
$properties[$key] = $value;
}//end while
fclose($handle);
}//end if
}//end foreach
if ($foundPath === false) {
return null;
}
return $properties;
}//end getProperties()
}//end class
?>

View File

@@ -0,0 +1,86 @@
<?php
/**
* Generic_Sniffs_WhiteSpace_DisallowTabIndentSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_WhiteSpace_DisallowTabIndentSniff.
*
* Throws errors if tabs are used for indentation.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_WhiteSpace_DisallowTabIndentSniff implements PHP_CodeSniffer_Sniff
{
/**
* A list of tokenizers this sniff supports.
*
* @var array
*/
public $supportedTokenizers = array(
'PHP',
'JS',
'CSS',
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_WHITESPACE);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile All the tokens found in the document.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// Make sure this is whitespace used for indentation.
$line = $tokens[$stackPtr]['line'];
if ($stackPtr > 0 && $tokens[($stackPtr - 1)]['line'] === $line) {
return;
}
if (strpos($tokens[$stackPtr]['content'], "\t") !== false) {
$error = 'Spaces must be used to indent lines; tabs are not allowed';
$phpcsFile->addError($error, $stackPtr, 'TabsUsed');
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,346 @@
<?php
/**
* Generic_Sniffs_Whitespace_ScopeIndentSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_Whitespace_ScopeIndentSniff.
*
* Checks that control structures are structured correctly, and their content
* is indented correctly. This sniff will throw errors if tabs are used
* for indentation rather than spaces.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_WhiteSpace_ScopeIndentSniff implements PHP_CodeSniffer_Sniff
{
/**
* The number of spaces code should be indented.
*
* @var int
*/
public $indent = 4;
/**
* Does the indent need to be exactly right.
*
* If TRUE, indent needs to be exactly $ident spaces. If FALSE,
* indent needs to be at least $ident spaces (but can be more).
*
* @var bool
*/
public $exact = false;
/**
* Any scope openers that should not cause an indent.
*
* @var array(int)
*/
protected $nonIndentingScopes = array();
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return PHP_CodeSniffer_Tokens::$scopeOpeners;
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile All the tokens found in the document.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// If this is an inline condition (ie. there is no scope opener), then
// return, as this is not a new scope.
if (isset($tokens[$stackPtr]['scope_opener']) === false) {
return;
}
if ($tokens[$stackPtr]['code'] === T_ELSE) {
$next = $phpcsFile->findNext(
PHP_CodeSniffer_Tokens::$emptyTokens,
($stackPtr + 1),
null,
true
);
// We will handle the T_IF token in another call to process.
if ($tokens[$next]['code'] === T_IF) {
return;
}
}
// Find the first token on this line.
$firstToken = $stackPtr;
for ($i = $stackPtr; $i >= 0; $i--) {
// Record the first code token on the line.
if (in_array($tokens[$i]['code'], PHP_CodeSniffer_Tokens::$emptyTokens) === false) {
$firstToken = $i;
}
// It's the start of the line, so we've found our first php token.
if ($tokens[$i]['column'] === 1) {
break;
}
}
// Based on the conditions that surround this token, determine the
// indent that we expect this current content to be.
$expectedIndent = $this->calculateExpectedIndent($tokens, $firstToken);
// Don't process the first token if it is a closure because they have
// different indentation rules as they are often used as function arguments
// for multi-line function calls. But continue to process the content of the
// closure because it should be indented as normal.
if ($tokens[$firstToken]['code'] !== T_CLOSURE
&& $tokens[$firstToken]['column'] !== $expectedIndent
) {
$error = 'Line indented incorrectly; expected %s spaces, found %s';
$data = array(
($expectedIndent - 1),
($tokens[$firstToken]['column'] - 1),
);
$phpcsFile->addError($error, $stackPtr, 'Incorrect', $data);
}
$scopeOpener = $tokens[$stackPtr]['scope_opener'];
$scopeCloser = $tokens[$stackPtr]['scope_closer'];
// Some scopes are expected not to have indents.
if (in_array($tokens[$firstToken]['code'], $this->nonIndentingScopes) === false) {
$indent = ($expectedIndent + $this->indent);
} else {
$indent = $expectedIndent;
}
$newline = false;
$commentOpen = false;
$inHereDoc = false;
// Only loop over the content between the opening and closing brace, not
// the braces themselves.
for ($i = ($scopeOpener + 1); $i < $scopeCloser; $i++) {
// If this token is another scope, skip it as it will be handled by
// another call to this sniff.
if (in_array($tokens[$i]['code'], PHP_CodeSniffer_Tokens::$scopeOpeners) === true) {
if (isset($tokens[$i]['scope_opener']) === true) {
$i = $tokens[$i]['scope_closer'];
// If the scope closer is followed by a semi-colon, the semi-colon is part
// of the closer and should also be ignored. This most commonly happens with
// CASE statements that end with "break;", where we don't want to stop
// ignoring at the break, but rather at the semi-colon.
$nextToken = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($i + 1), null, true);
if ($tokens[$nextToken]['code'] === T_SEMICOLON) {
$i = $nextToken;
}
} else {
// If this token does not have a scope_opener indice, then
// it's probably an inline scope, so let's skip to the next
// semicolon. Inline scopes include inline if's, abstract
// methods etc.
$nextToken = $phpcsFile->findNext(T_SEMICOLON, $i, $scopeCloser);
if ($nextToken !== false) {
$i = $nextToken;
}
}
continue;
}//end if
// If this is a HEREDOC then we need to ignore it as the
// whitespace before the contents within the HEREDOC are
// considered part of the content.
if ($tokens[$i]['code'] === T_START_HEREDOC) {
$inHereDoc = true;
continue;
} else if ($inHereDoc === true) {
if ($tokens[$i]['code'] === T_END_HEREDOC) {
$inHereDoc = false;
}
continue;
}
if ($tokens[$i]['column'] === 1) {
// We started a newline.
$newline = true;
}
if ($newline === true && $tokens[$i]['code'] !== T_WHITESPACE) {
// If we started a newline and we find a token that is not
// whitespace, then this must be the first token on the line that
// must be indented.
$newline = false;
$firstToken = $i;
$column = $tokens[$firstToken]['column'];
// Special case for non-PHP code.
if ($tokens[$firstToken]['code'] === T_INLINE_HTML) {
$trimmedContentLength
= strlen(ltrim($tokens[$firstToken]['content']));
if ($trimmedContentLength === 0) {
continue;
}
$contentLength = strlen($tokens[$firstToken]['content']);
$column = ($contentLength - $trimmedContentLength + 1);
}
// Check to see if this constant string spans multiple lines.
// If so, then make sure that the strings on lines other than the
// first line are indented appropriately, based on their whitespace.
if (in_array($tokens[$firstToken]['code'], PHP_CodeSniffer_Tokens::$stringTokens) === true) {
if (in_array($tokens[($firstToken - 1)]['code'], PHP_CodeSniffer_Tokens::$stringTokens) === true) {
// If we find a string that directly follows another string
// then its just a string that spans multiple lines, so we
// don't need to check for indenting.
continue;
}
}
// This is a special condition for T_DOC_COMMENT and C-style
// comments, which contain whitespace between each line.
$comments = array(
T_COMMENT,
T_DOC_COMMENT
);
if (in_array($tokens[$firstToken]['code'], $comments) === true) {
$content = trim($tokens[$firstToken]['content']);
if (preg_match('|^/\*|', $content) !== 0) {
// Check to see if the end of the comment is on the same line
// as the start of the comment. If it is, then we don't
// have to worry about opening a comment.
if (preg_match('|\*/$|', $content) === 0) {
// We don't have to calculate the column for the
// start of the comment as there is a whitespace
// token before it.
$commentOpen = true;
}
} else if ($commentOpen === true) {
if ($content === '') {
// We are in a comment, but this line has nothing on it
// so let's skip it.
continue;
}
$contentLength = strlen($tokens[$firstToken]['content']);
$trimmedContentLength
= strlen(ltrim($tokens[$firstToken]['content']));
$column = ($contentLength - $trimmedContentLength + 1);
if (preg_match('|\*/$|', $content) !== 0) {
$commentOpen = false;
}
}//end if
}//end if
// The token at the start of the line, needs to have its' column
// greater than the relative indent we set above. If it is less,
// an error should be shown.
if ($column !== $indent) {
if ($this->exact === true || $column < $indent) {
$type = 'IncorrectExact';
$error = 'Line indented incorrectly; expected ';
if ($this->exact === false) {
$error .= 'at least ';
$type = 'Incorrect';
}
$error .= '%s spaces, found %s';
$data = array(
($indent - 1),
($column - 1),
);
$phpcsFile->addError($error, $firstToken, $type, $data);
}
}//end if
}//end if
}//end for
}//end process()
/**
* Calculates the expected indent of a token.
*
* Returns the column at which the token should be indented to, so 1 means
* that the token should not be indented at all.
*
* @param array $tokens The stack of tokens for this file.
* @param int $stackPtr The position of the token to get indent for.
*
* @return int
*/
protected function calculateExpectedIndent(array $tokens, $stackPtr)
{
$conditionStack = array();
// Empty conditions array (top level structure).
if (empty($tokens[$stackPtr]['conditions']) === true) {
if (isset($tokens[$stackPtr]['nested_parenthesis']) === true
&& empty($tokens[$stackPtr]['nested_parenthesis']) === false
) {
// Wrapped in parenthesis means it is probably in a
// function call (like a closure) so we have to assume indent
// is correct here and someone else will check it more
// carefully in another sniff.
return $tokens[$stackPtr]['column'];
} else {
return 1;
}
}
$tokenConditions = $tokens[$stackPtr]['conditions'];
foreach ($tokenConditions as $id => $condition) {
// If it's an indenting scope ie. it's not in our array of
// scopes that don't indent, add it to our condition stack.
if (in_array($condition, $this->nonIndentingScopes) === false) {
$conditionStack[$id] = $condition;
}
}
$indent = ((count($conditionStack) * $this->indent) + 1);
return $indent;
}//end calculateExpectedIndent()
}//end class
?>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0"?>
<ruleset name="Generic">
<description>A collection of generic sniffs. This standard is not designed to be used to check code.</description>
</ruleset>

View File

@@ -0,0 +1,35 @@
<?php
/**
* An exception thrown if the pattern being processed is not supposed to be
* validating the code in question.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* An exception thrown if the pattern being processed is not supposed to be
* validating the code in question.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer_Standards_IncorrectPatternException extends Exception
{
}//end class
?>

View File

@@ -0,0 +1,102 @@
<?php
/**
* MySource_Sniffs_CSS_BrowserSpecificStylesSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* MySource_Sniffs_CSS_BrowserSpecificStylesSniff.
*
* Ensure that browser-specific styles are not used.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class MySource_Sniffs_CSS_BrowserSpecificStylesSniff implements PHP_CodeSniffer_Sniff
{
/**
* A list of tokenizers this sniff supports.
*
* @var array
*/
public $supportedTokenizers = array('CSS');
/**
* A list of specific stylsheet suffixes we allow.
*
* These stylsheets contain browser specific styles
* so this sniff ignore them files in the form:
* *_moz.css and *_ie7.css etc.
*
* @var array
*/
protected $specificStylesheets = array(
'moz',
'ie',
'ie7',
'ie8',
'webkit',
);
/**
* Returns the token types that this sniff is interested in.
*
* @return array(int)
*/
public function register()
{
return array(T_STYLE);
}//end register()
/**
* Processes the tokens that this sniff is interested in.
*
* @param PHP_CodeSniffer_File $phpcsFile The file where the token was found.
* @param int $stackPtr The position in the stack where
* the token was found.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
// Ignore files with browser-specific suffixes.
$filename = $phpcsFile->getFilename();
$breakChar = strrpos($filename, '_');
if ($breakChar !== false && substr($filename, -4) === '.css') {
$specific = substr($filename, ($breakChar + 1), -4);
if (in_array($specific, $this->specificStylesheets) === true) {
return;
}
}
$tokens = $phpcsFile->getTokens();
$content = $tokens[$stackPtr]['content'];
if ($content{0} === '-') {
$error = 'Browser-specific styles are not allowed';
$phpcsFile->addError($error, $stackPtr, 'ForbiddenStyle');
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,76 @@
<?php
/**
* Ensures that all action classes throw ChannelExceptions only.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Ensures that all action classes throw ChannelExceptions only.
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class MySource_Sniffs_Channels_ChannelExceptionSniff implements PHP_CodeSniffer_Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_THROW);
}//end register()
/**
* Processes this sniff, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$fileName = strtolower($phpcsFile->getFilename());
$matches = array();
if (preg_match('|/systems/(.*)/([^/]+)?actions.inc$|', $fileName, $matches) === 0) {
// This is not an actions.inc file.
return;
}
$tokens = $phpcsFile->getTokens();
$exception = $phpcsFile->findNext(array(T_STRING, T_VARIABLE), ($stackPtr + 1));
$exceptionName = $tokens[$exception]['content'];
if ($exceptionName !== 'ChannelException') {
$data = array($exceptionName);
$error = 'Channel actions can only throw ChannelException; found "%s"';
$phpcsFile->addError($error, $exception, 'WrongExceptionType', $data);
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,131 @@
<?php
/**
* Ensures that self is not used to call public method in action classes.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Ensures that self is not used to call public method in action classes.
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class MySource_Sniffs_Channels_DisallowSelfActionsSniff implements PHP_CodeSniffer_Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_CLASS);
}//end register()
/**
* Processes this sniff, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// We are not interested in abstract classes.
$prev = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
if ($prev !== false && $tokens[$prev]['code'] === T_ABSTRACT) {
return;
}
// We are only interested in Action classes.
$classNameToken = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);
$className = $tokens[$classNameToken]['content'];
if (substr($className, -7) !== 'Actions') {
return;
}
$foundFunctions = array();
$foundCalls = array();
// Find all static method calls in the form self::method() in the class.
$classEnd = $tokens[$stackPtr]['scope_closer'];
for ($i = ($classNameToken + 1); $i < $classEnd; $i++) {
if ($tokens[$i]['code'] !== T_DOUBLE_COLON) {
if ($tokens[$i]['code'] === T_FUNCTION) {
// Cache the function information.
$funcName = $phpcsFile->findNext(T_STRING, ($i + 1));
$funcScope = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$scopeModifiers, ($i - 1));
$foundFunctions[$tokens[$funcName]['content']] = strtolower($tokens[$funcScope]['content']);
}
continue;
}
$prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($i - 1), null, true);
if ($tokens[$prevToken]['content'] !== 'self') {
continue;
}
$funcNameToken = $phpcsFile->findNext(T_WHITESPACE, ($i + 1), null, true);
if ($tokens[$funcNameToken]['code'] === T_VARIABLE) {
// We are only interested in function calls.
continue;
}
$funcName = $tokens[$funcNameToken]['content'];
// We've found the function, now we need to find it and see if it is
// public, private or protected. If it starts with an underscore we
// can assume it is private.
if ($funcName{0} === '_') {
continue;
}
$foundCalls[$i] = $funcName;
}//end for
$errorClassName = substr($className, 0, -7);
foreach ($foundCalls as $token => $funcName) {
if (isset($foundFunctions[$funcName]) === false) {
// Function was not in this class, might have come from the parent.
// Either way, we can't really check this.
continue;
} else if ($foundFunctions[$funcName] === 'public') {
$error = 'Static calls to public methods in Action classes must not use the self keyword; use %s::%s() instead';
$data = array(
$errorClassName,
$funcName,
);
$phpcsFile->addError($error, $token, 'Found', $data);
}
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,329 @@
<?php
/**
* Ensures that systems, asset types and libs are included before they are used.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (class_exists('PHP_CodeSniffer_Standards_AbstractScopeSniff', true) === false) {
$error = 'Class PHP_CodeSniffer_Standards_AbstractScopeSniff not found';
throw new PHP_CodeSniffer_Exception($error);
}
/**
* Ensures that systems, asset types and libs are included before they are used.
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class MySource_Sniffs_Channels_IncludeSystemSniff extends PHP_CodeSniffer_Standards_AbstractScopeSniff
{
/**
* A list of classes that don't need to be included.
*
* @var array(string)
*/
private $_ignore = array(
'self',
'parent',
'channels',
'basesystem',
'dal',
'init',
'pdo',
'util',
'ziparchive',
'phpunit_framework_assert',
'abstractmysourceunittest',
'abstractdatacleanunittest',
'exception',
'abstractwidgetwidgettype',
'domdocument',
);
/**
* Constructs a Squiz_Sniffs_Scope_MethodScopeSniff.
*/
public function __construct()
{
parent::__construct(array(T_FUNCTION), array(T_DOUBLE_COLON, T_EXTENDS), true);
}//end __construct()
/**
* Processes the function tokens within the class.
*
* @param PHP_CodeSniffer_File $phpcsFile The file where this token was found.
* @param integer $stackPtr The position where the token was found.
* @param integer $currScope The current scope opener token.
*
* @return void
*/
protected function processTokenWithinScope(
PHP_CodeSniffer_File $phpcsFile,
$stackPtr,
$currScope
) {
$tokens = $phpcsFile->getTokens();
// Determine the name of the class that the static function
// is being called on.
$classNameToken = $phpcsFile->findPrevious(
T_WHITESPACE,
($stackPtr - 1),
null,
true
);
$className = $tokens[$classNameToken]['content'];
if (in_array(strtolower($className), $this->_ignore) === true) {
return;
}
$includedClasses = array();
$fileName = strtolower($phpcsFile->getFilename());
$matches = array();
if (preg_match('|/systems/(.*)/([^/]+)?actions.inc$|', $fileName, $matches) !== 0) {
// This is an actions file, which means we don't
// have to include the system in which it exists.
$includedClasses[] = $matches[2];
// Or a system it implements.
$class = $phpcsFile->getCondition($stackPtr, T_CLASS);
$implements = $phpcsFile->findNext(T_IMPLEMENTS, $class, ($class + 10));
if ($implements !== false) {
$implementsClass = $phpcsFile->findNext(T_STRING, $implements);
$implementsClassName = strtolower($tokens[$implementsClass]['content']);
if (substr($implementsClassName, -7) === 'actions') {
$includedClasses[] = substr($implementsClassName, 0, -7);
}
}
}
// Go searching for includeSystem and includeAsset calls within this
// function, or the inclusion of .inc files, which
// would be library files.
for ($i = ($currScope + 1); $i < $stackPtr; $i++) {
$name = $this->getIncludedClassFromToken($phpcsFile, $tokens, $i);
if ($name !== false) {
$includedClasses[] = $name;
// Special case for Widgets cause they are, well, special.
} else if (strtolower($tokens[$i]['content']) === 'includewidget') {
$typeName = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, ($i + 1));
$typeName = trim($tokens[$typeName]['content'], " '");
$includedClasses[] = strtolower($typeName).'widgettype';
}
}
// Now go searching for includeSystem, includeAsset or require/include
// calls outside our scope. If we are in a class, look outside the
// class. If we are not, look outside the function.
$condPtr = $currScope;
if ($phpcsFile->hasCondition($stackPtr, T_CLASS) === true) {
foreach ($tokens[$stackPtr]['conditions'] as $condPtr => $condType) {
if ($condType === T_CLASS) {
break;
}
}
}
for ($i = 0; $i < $condPtr; $i++) {
// Skip other scopes.
if (isset($tokens[$i]['scope_closer']) === true) {
$i = $tokens[$i]['scope_closer'];
continue;
}
$name = $this->getIncludedClassFromToken($phpcsFile, $tokens, $i);
if ($name !== false) {
$includedClasses[] = $name;
}
}//end for
// If we are in a testing class, we might have also included
// some systems and classes in our setUp() method.
$setupFunction = null;
if ($phpcsFile->hasCondition($stackPtr, T_CLASS) === true) {
foreach ($tokens[$stackPtr]['conditions'] as $condPtr => $condType) {
if ($condType === T_CLASS) {
// Is this is a testing class?
$name = $phpcsFile->findNext(T_STRING, $condPtr);
$name = $tokens[$name]['content'];
if (substr($name, -8) === 'UnitTest') {
// Look for a method called setUp().
$end = $tokens[$condPtr]['scope_closer'];
$function = $phpcsFile->findNext(T_FUNCTION, ($condPtr + 1), $end);
while ($function !== false) {
$name = $phpcsFile->findNext(T_STRING, $function);
if ($tokens[$name]['content'] === 'setUp') {
$setupFunction = $function;
break;
}
$function = $phpcsFile->findNext(T_FUNCTION, ($function + 1), $end);
}
}
}
}//end foreach
}//end if
if ($setupFunction !== null) {
$start = ($tokens[$setupFunction]['scope_opener'] + 1);
$end = $tokens[$setupFunction]['scope_closer'];
for ($i = $start; $i < $end; $i++) {
$name = $this->getIncludedClassFromToken($phpcsFile, $tokens, $i);
if ($name !== false) {
$includedClasses[] = $name;
}
}
}//end if
if (in_array(strtolower($className), $includedClasses) === false) {
$error = 'Static method called on non-included class or system "%s"; include system with Channels::includeSystem() or include class with require_once';
$data = array($className);
$phpcsFile->addError($error, $stackPtr, 'NotIncludedCall', $data);
}
}//end processTokenWithinScope()
/**
* Processes a token within the scope that this test is listening to.
*
* @param PHP_CodeSniffer_File $phpcsFile The file where the token was found.
* @param int $stackPtr The position in the stack where
* this token was found.
*
* @return void
*/
protected function processTokenOutsideScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if ($tokens[$stackPtr]['code'] === T_EXTENDS) {
// Find the class name.
$classNameToken = $phpcsFile->findNext(T_STRING, ($stackPtr + 1));
$className = $tokens[$classNameToken]['content'];
} else {
// Determine the name of the class that the static function
// is being called on.
$classNameToken = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
$className = $tokens[$classNameToken]['content'];
}
// Some systems are always available.
if (in_array(strtolower($className), $this->_ignore) === true) {
return;
}
$includedClasses = array();
$fileName = strtolower($phpcsFile->getFilename());
$matches = array();
if (preg_match('|/systems/([^/]+)/([^/]+)?actions.inc$|', $fileName, $matches) !== 0) {
// This is an actions file, which means we don't
// have to include the system in which it exists
// We know the system from the path.
$includedClasses[] = $matches[1];
}
// Go searching for includeSystem, includeAsset or require/include
// calls outside our scope.
for ($i = 0; $i < $stackPtr; $i++) {
// Skip classes and functions as will we never get
// into their scopes when including this file, although
// we have a chance of getting into IF's, WHILE's etc.
$ignoreTokens = array(
T_CLASS,
T_INTERFACE,
T_FUNCTION,
);
if (in_array($tokens[$i]['code'], $ignoreTokens) === true
&& isset($tokens[$i]['scope_closer']) === true
) {
$i = $tokens[$i]['scope_closer'];
continue;
}
$name = $this->getIncludedClassFromToken($phpcsFile, $tokens, $i);
if ($name !== false) {
$includedClasses[] = $name;
// Special case for Widgets cause they are, well, special.
} else if (strtolower($tokens[$i]['content']) === 'includewidget') {
$typeName = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, ($i + 1));
$typeName = trim($tokens[$typeName]['content'], " '");
$includedClasses[] = strtolower($typeName).'widgettype';
}
}//end for
if (in_array(strtolower($className), $includedClasses) === false) {
if ($tokens[$stackPtr]['code'] === T_EXTENDS) {
$error = 'Class extends non-included class or system "%s"; include system with Channels::includeSystem() or include class with require_once';
$data = array($className);
$phpcsFile->addError($error, $stackPtr, 'NotIncludedExtends', $data);
} else {
$error = 'Static method called on non-included class or system "%s"; include system with Channels::includeSystem() or include class with require_once';
$data = array($className);
$phpcsFile->addError($error, $stackPtr, 'NotIncludedCall', $data);
}
}
}//end processTokenOutsideScope()
/**
* Determines the included class name from given token.
*
* @param PHP_CodeSniffer_File $phpcsFile The file where this token was found.
* @param array $tokens The array of file tokens.
* @param int $stackPtr The position in the tokens array of the
* potentially included class.
*
* @return string
*/
protected function getIncludedClassFromToken(
PHP_CodeSniffer_File $phpcsFile,
array $tokens,
$stackPtr
) {
if (strtolower($tokens[$stackPtr]['content']) === 'includesystem') {
$systemName = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, ($stackPtr + 1));
$systemName = trim($tokens[$systemName]['content'], " '");
return strtolower($systemName);
} else if (strtolower($tokens[$stackPtr]['content']) === 'includeasset') {
$typeName = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, ($stackPtr + 1));
$typeName = trim($tokens[$typeName]['content'], " '");
return strtolower($typeName).'assettype';
} else if (in_array($tokens[$stackPtr]['code'], PHP_CodeSniffer_Tokens::$includeTokens) === true) {
$filePath = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, ($stackPtr + 1));
$filePath = $tokens[$filePath]['content'];
$filePath = trim($filePath, " '");
$filePath = basename($filePath, '.inc');
return strtolower($filePath);
}
return false;
}//end getIncludedClassFromToken()
}//end class
?>

View File

@@ -0,0 +1,157 @@
<?php
/**
* Ensures that systems, asset types and libs are included before they are used.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Ensures that systems and asset types are used if they are included.
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class MySource_Sniffs_Channels_UnusedSystemSniff implements PHP_CodeSniffer_Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_DOUBLE_COLON);
}//end register()
/**
* Processes this sniff, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// Check if this is a call to includeSystem, includeAsset or includeWidget.
$methodName = strtolower($tokens[($stackPtr + 1)]['content']);
if (in_array($methodName, array('includesystem', 'includeasset', 'includewidget')) === true) {
$systemName = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 3), null, true);
if ($systemName === false || $tokens[$systemName]['code'] !== T_CONSTANT_ENCAPSED_STRING) {
// Must be using a variable instead of a specific system name.
// We can't accurately check that.
return;
}
$systemName = trim($tokens[$systemName]['content'], " '");
} else {
return;
}
if ($methodName === 'includeasset') {
$systemName .= 'assettype';
} else if ($methodName === 'includewidget') {
$systemName .= 'widgettype';
}
$systemName = strtolower($systemName);
// Now check if this system is used anywhere in this scope.
$level = $tokens[$stackPtr]['level'];
for ($i = ($stackPtr + 1); $i < $phpcsFile->numTokens; $i++) {
if ($tokens[$i]['level'] < $level) {
// We have gone out of scope.
// If the original include was inside an IF statement that
// is checking if the system exists, check the outer scope
// as well.
if ($tokens[$stackPtr]['level'] === $level) {
// We are still in the base level, so this is the first
// time we have got here.
$conditions = array_keys($tokens[$stackPtr]['conditions']);
if (empty($conditions) === false) {
$cond = array_pop($conditions);
if ($tokens[$cond]['code'] === T_IF) {
$i = $tokens[$cond]['scope_closer'];
$level--;
continue;
}
}
}
break;
}//end if
$validTokens = array(
T_DOUBLE_COLON,
T_EXTENDS,
T_IMPLEMENTS,
);
if (in_array($tokens[$i]['code'], $validTokens) === false) {
continue;
}
switch ($tokens[$i]['code']) {
case T_DOUBLE_COLON:
$usedName = strtolower($tokens[($i - 1)]['content']);
if ($usedName === $systemName) {
// The included system was used, so it is fine.
return;
}
break;
case T_EXTENDS:
$classNameToken = $phpcsFile->findNext(T_STRING, ($i + 1));
$className = strtolower($tokens[$classNameToken]['content']);
if ($className === $systemName) {
// The included system was used, so it is fine.
return;
}
break;
case T_IMPLEMENTS:
$endImplements = $phpcsFile->findNext(array(T_EXTENDS, T_OPEN_CURLY_BRACKET), ($i + 1));
for ($x = ($i + 1); $x < $endImplements; $x++) {
if ($tokens[$x]['code'] === T_STRING) {
$className = strtolower($tokens[$x]['content']);
if ($className === $systemName) {
// The included system was used, so it is fine.
return;
}
}
}
break;
}//end switch
}//end for
// If we get to here, the system was not use.
$error = 'Included system "%s" is never used';
$data = array($systemName);
$phpcsFile->addError($error, $stackPtr, 'Found', $data);
}//end process()
}//end class
?>

View File

@@ -0,0 +1,134 @@
<?php
/**
* Parses and verifies the doc comments for functions.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
if (class_exists('Squiz_Sniffs_Commenting_FunctionCommentSniff', true) === false) {
$error = 'Class Squiz_Sniffs_Commenting_FunctionCommentSniff not found';
throw new PHP_CodeSniffer_Exception($error);
}
/**
* Parses and verifies the doc comments for functions.
*
* Same as the Squiz standard, but adds support for API tags.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class MySource_Sniffs_Commenting_FunctionCommentSniff extends Squiz_Sniffs_Commenting_FunctionCommentSniff
{
/**
* Process a list of unknown tags.
*
* @param int $commentStart The position in the stack where the comment started.
* @param int $commentEnd The position in the stack where the comment ended.
*
* @return void
*/
protected function processUnknownTags($commentStart, $commentEnd)
{
$unknownTags = $this->commentParser->getUnknown();
$words = $this->commentParser->getWords();
$hasApiTag = false;
$apiLength = 3;
foreach ($unknownTags as $errorTag) {
$pos = $errorTag['pos'];
if ($errorTag['tag'] === 'api') {
if ($hasApiTag === true) {
// We've come across an API tag already, which means
// we were not the first tag in the API list.
$error = 'The @api tag must come first in the @api tag list in a function comment';
$this->currentFile->addError($error, ($commentStart + $errorTag['line']), 'ApiNotFirst');
}
$hasApiTag = true;
// There needs to be a blank line before the @api tag.
// So expect a single space before the tag, then 2 newlines before
// that, then some content.
if (trim($words[($pos - 2)]) !== ''
|| strpos($words[($pos - 2)], $this->currentFile->eolChar) === false
|| strpos($words[($pos - 3)], $this->currentFile->eolChar) === false
|| trim($words[($pos - 4)]) === ''
) {
$error = 'There must be one blank line before the @api tag in a function comment';
$this->currentFile->addError($error, ($commentStart + $errorTag['line']), 'ApiSpacing');
}
} else if (substr($errorTag['tag'], 0, 4) === 'api-') {
$hasApiTag = true;
$tagLength = strlen($errorTag['tag']);
if ($tagLength > $apiLength) {
$apiLength = $tagLength;
}
if (trim($words[($pos - 2)]) !== ''
|| strpos($words[($pos - 2)], $this->currentFile->eolChar) === false
|| trim($words[($pos - 3)]) === ''
) {
$error = 'There must be no blank line before the @%s tag in a function comment';
$data = array($errorTag['tag']);
$this->currentFile->addError($error, ($commentStart + $errorTag['line']), 'ApiTagSpacing', $data);
}
} else {
$error = '@%s tag is not allowed in function comment';
$data = array($errorTag['tag']);
$this->currentFile->addWarning($error, ($commentStart + $errorTag['line']), 'TagNotAllowed', $data);
}//end if
}//end foreach
if ($hasApiTag === true) {
// API tags must be the last tags in a function comment.
$order = $this->commentParser->getTagOrders();
$lastTag = array_pop($order);
if ($lastTag !== 'api'
&& substr($lastTag, 0, 4) !== 'api-'
) {
$error = 'The @api tags must be the last tags in a function comment';
$this->currentFile->addError($error, $commentEnd, 'ApiNotLast');
}
// Check API tag indenting.
foreach ($unknownTags as $errorTag) {
if ($errorTag['tag'] === 'api'
|| substr($errorTag['tag'], 0, 4) === 'api-'
) {
$expected = ($apiLength - strlen($errorTag['tag']) + 1);
$found = strlen($words[($errorTag['pos'] + 1)]);
if ($found !== $expected) {
$error = '@%s tag indented incorrectly; expected %s spaces but found %s';
$data = array(
$errorTag['tag'],
$expected,
$found,
);
$this->currentFile->addError($error, ($commentStart + $errorTag['line']), 'ApiTagIndent', $data);
}
}
}
}//end if
}//end processUnknownTags()
}//end class
?>

View File

@@ -0,0 +1,68 @@
<?php
/**
* Warns about the use of debug code.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Warns about the use of debug code.
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class MySource_Sniffs_Debug_DebugCodeSniff implements PHP_CodeSniffer_Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_DOUBLE_COLON);
}//end register()
/**
* Processes this sniff, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$className = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
if (strtolower($tokens[$className]['content']) === 'debug') {
$method = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);
$error = 'Call to debug function Debug::%s() must be removed';
$data = array($tokens[$method]['content']);
$phpcsFile->addError($error, $stackPtr, 'Found', $data);
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,77 @@
<?php
/**
* Ensures that console is not used for function or var names.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Ensures that console is not used for function or var names.
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class MySource_Sniffs_Debug_FirebugConsoleSniff implements PHP_CodeSniffer_Sniff
{
/**
* A list of tokenizers this sniff supports.
*
* @var array
*/
public $supportedTokenizers = array('JS');
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_STRING,
T_PROPERTY,
T_LABEL,
T_OBJECT,
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if (strtolower($tokens[$stackPtr]['content']) === 'console') {
$error = 'Variables, functions and labels must not be named "console"; name may conflict with Firebug internal variable';
$phpcsFile->addError($error, $stackPtr, 'ConflictFound');
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,94 @@
<?php
/**
* Ensures this is not assigned to any other var but self.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Ensures this is not assigned to any other var but self.
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class MySource_Sniffs_Objects_AssignThisSniff implements PHP_CodeSniffer_Sniff
{
/**
* A list of tokenizers this sniff supports.
*
* @var array
*/
public $supportedTokenizers = array('JS');
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_THIS);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// Ignore this.something and other uses of "this" that are not
// direct assignments.
$next = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);
if ($tokens[$next]['code'] !== T_SEMICOLON) {
if ($tokens[$next]['line'] === $tokens[$stackPtr]['line']) {
return;
}
}
// Something must be assigned to "this".
$prev = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
if ($tokens[$prev]['code'] !== T_EQUAL) {
return;
}
// A variable needs to be assigned to "this".
$prev = $phpcsFile->findPrevious(T_WHITESPACE, ($prev - 1), null, true);
if ($tokens[$prev]['code'] !== T_STRING) {
return;
}
// We can only assign "this" to a var called "self".
if ($tokens[$prev]['content'] !== 'self' && $tokens[$prev]['content'] !== '_self') {
$error = 'Keyword "this" can only be assigned to a variable called "self" or "_self"';
$phpcsFile->addError($error, $prev, 'NotSelf');
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,228 @@
<?php
/**
* Ensures the create() method of widget types properly uses callbacks.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Ensures the create() method of widget types properly uses callbacks.
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class MySource_Sniffs_Objects_CreateWidgetTypeCallbackSniff implements PHP_CodeSniffer_Sniff
{
/**
* A list of tokenizers this sniff supports.
*
* @var array
*/
public $supportedTokenizers = array('JS');
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_OBJECT);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$className = $tokens[$stackPtr]['content'];
if (substr(strtolower($className), -10) !== 'widgettype') {
return;
}
// Search for a create method.
$start = ($tokens[$stackPtr]['scope_opener'] + 1);
$end = ($tokens[$stackPtr]['scope_closer'] - 1);
$create = $phpcsFile->findNext(T_PROPERTY, $start, $end, null, 'create');
if ($create === false) {
return;
}
$function = $phpcsFile->findNext(array(T_WHITESPACE, T_COLON), ($create + 1), null, true);
if ($tokens[$function]['code'] !== T_FUNCTION) {
continue;
}
$start = ($tokens[$function]['scope_opener'] + 1);
$end = ($tokens[$function]['scope_closer'] - 1);
// Check that the first argument is called "callback".
$arg = $phpcsFile->findNext(T_WHITESPACE, ($tokens[$function]['parenthesis_opener'] + 1), null, true);
if ($tokens[$arg]['content'] !== 'callback') {
$error = 'The first argument of the create() method of a widget type must be called "callback"';
$phpcsFile->addError($error, $arg, 'FirstArgNotCallback');
}
/*
Look for return statements within the function. They cannot return
anything and must be preceeded by the callback.call() line. The
callback itself must contain "self" or "this" as the first argument
and there needs to be a call to the callback function somewhere
in the create method. All calls to the callback function must be
followed by a return statement or the end of the method.
*/
$foundCallback = false;
$passedCallback = false;
$nestedFunction = null;
for ($i = $start; $i <= $end; $i++) {
// Keep track of nested functions.
if ($nestedFunction !== null) {
if ($i === $nestedFunction) {
$nestedFunction = null;
continue;
}
} else if ($tokens[$i]['code'] === T_FUNCTION
&& isset($tokens[$i]['scope_closer']) === true
) {
$nestedFunction = $tokens[$i]['scope_closer'];
continue;
}
if ($nestedFunction === null && $tokens[$i]['code'] === T_RETURN) {
// Make sure return statements are not returning anything.
if ($tokens[($i + 1)]['code'] !== T_SEMICOLON) {
$error = 'The create() method of a widget type must not return a value';
$phpcsFile->addError($error, $i, 'ReturnValue');
}
continue;
} else if ($tokens[$i]['code'] !== T_STRING
|| $tokens[$i]['content'] !== 'callback'
) {
continue;
}
// If this is the form "callback.call(" then it is a call
// to the callback function.
if ($tokens[($i + 1)]['code'] !== T_OBJECT_OPERATOR
|| $tokens[($i + 2)]['content'] !== 'call'
|| $tokens[($i + 3)]['code'] !== T_OPEN_PARENTHESIS
) {
// One last chance; this might be the callback function
// being passed to another function, like this
// "this.init(something, callback, something)".
if (isset($tokens[$i]['nested_parenthesis']) === false) {
continue;
}
// Just make sure those brackets dont belong to anyone,
// like an IF or FOR statement.
foreach ($tokens[$i]['nested_parenthesis'] as $bracket) {
if (isset($tokens[$bracket]['parenthesis_owner']) === true) {
continue(2);
}
}
// Note that we use this endBracket down further when checking
// for a RETURN statement.
$endBracket = end($tokens[$i]['nested_parenthesis']);
$bracket = key($tokens[$i]['nested_parenthesis']);
$prev = $phpcsFile->findPrevious(
PHP_CodeSniffer_Tokens::$emptyTokens,
($bracket - 1),
null,
true
);
if ($tokens[$prev]['code'] !== T_STRING) {
// This is not a function passing the callback.
continue;
}
$passedCallback = true;
}//end if
$foundCallback = true;
if ($passedCallback === false) {
// The first argument must be "this" or "self".
$arg = $phpcsFile->findNext(T_WHITESPACE, ($i + 4), null, true);
if ($tokens[$arg]['content'] !== 'this'
&& $tokens[$arg]['content'] !== 'self'
) {
$error = 'The first argument passed to the callback function must be "this" or "self"';
$phpcsFile->addError($error, $arg, 'FirstArgNotSelf');
}
}
// Now it must be followed by a return statement or the end of the function.
if ($passedCallback === false) {
$endBracket = $tokens[($i + 3)]['parenthesis_closer'];
}
for ($next = $endBracket; $next <= $end; $next++) {
// Skip whitespace so we find the next content after the call.
if (in_array($tokens[$next]['code'], PHP_CodeSniffer_Tokens::$emptyTokens) === true) {
continue;
}
// Skip closing braces like END IF because it is not executable code.
if ($tokens[$next]['code'] === T_CLOSE_CURLY_BRACKET) {
continue;
}
// We don't care about anything on the current line, like a
// semicolon. It doesn't matter if there are other statements on the
// line because another sniff will check for those.
if ($tokens[$next]['line'] === $tokens[$endBracket]['line']) {
continue;
}
break;
}
if ($next !== $tokens[$function]['scope_closer']
&& $tokens[$next]['code'] !== T_RETURN
) {
$error = 'The call to the callback function must be followed by a return statement if it is not the last statement in the create() method';
$phpcsFile->addError($error, $i, 'NoReturn');
}
}//end for
if ($foundCallback === false) {
$error = 'The create() method of a widget type must call the callback function';
$phpcsFile->addError($error, $create, 'CallbackNotCalled');
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,72 @@
<?php
/**
* Ensures that widgets are not manually created.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Ensures that widgets are not manually created.
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class MySource_Sniffs_Objects_DisallowNewWidgetSniff implements PHP_CodeSniffer_Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_NEW);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$className = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);
if ($tokens[$className]['code'] !== T_STRING) {
return;
}
if (substr(strtolower($tokens[$className]['content']), -10) === 'widgettype') {
$widgetType = substr($tokens[$className]['content'], 0, -10);
$error = 'Manual creation of widget objects is banned; use Widget::getWidget(\'%s\'); instead';
$data = array($widgetType);
$phpcsFile->addError($error, $stackPtr, 'Found', $data);
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,126 @@
<?php
/**
* Ensures that eval() is not used to create objects.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Ensures that eval() is not used to create objects.
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class MySource_Sniffs_PHP_EvalObjectFactorySniff implements PHP_CodeSniffer_Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_EVAL);
}//end register()
/**
* Processes this sniff, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
/*
We need to find all strings that will be in the eval
to determine if the "new" keyword is being used.
*/
$openBracket = $phpcsFile->findNext(T_OPEN_PARENTHESIS, ($stackPtr + 1));
$closeBracket = $tokens[$openBracket]['parenthesis_closer'];
$strings = array();
$vars = array();
for ($i = ($openBracket + 1); $i < $closeBracket; $i++) {
if (in_array($tokens[$i]['code'], PHP_CodeSniffer_Tokens::$stringTokens) === true) {
$strings[$i] = $tokens[$i]['content'];
} else if ($tokens[$i]['code'] === T_VARIABLE) {
$vars[$i] = $tokens[$i]['content'];
}
}
/*
We now have some variables that we need to expand into
the strings that were assigned to them, if any.
*/
foreach ($vars as $varPtr => $varName) {
while (($prev = $phpcsFile->findPrevious(T_VARIABLE, ($varPtr - 1))) !== false) {
// Make sure this is an assignment of the variable. That means
// it will be the first thing on the line.
$prevContent = $phpcsFile->findPrevious(T_WHITESPACE, ($prev - 1), null, true);
if ($tokens[$prevContent]['line'] === $tokens[$prev]['line']) {
$varPtr = $prevContent;
continue;
}
if ($tokens[$prev]['content'] !== $varName) {
// This variable has a different name.
$varPtr = $prevContent;
continue;
}
// We found one.
break;
}//end while
if ($prev !== false) {
// Find all strings on the line.
$lineEnd = $phpcsFile->findNext(T_SEMICOLON, ($prev + 1));
for ($i = ($prev + 1); $i < $lineEnd; $i++) {
if (in_array($tokens[$i]['code'], PHP_CodeSniffer_Tokens::$stringTokens) === true) {
$strings[$i] = $tokens[$i]['content'];
}
}
}
}//end foreach
foreach ($strings as $string) {
// If the string has "new" in it, it is not allowed.
// We don't bother checking if the word "new" is echo'd
// because that is unlikely to happen. We assume the use
// of "new" is for object instantiation.
if (strstr($string, ' new ') !== false) {
$error = 'Do not use eval() to create objects dynamically; use reflection instead';
$phpcsFile->addWarning($error, $stackPtr, 'Found');
}
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,119 @@
<?php
/**
* Ensures that getRequestData() is used to access super globals.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Ensures that getRequestData() is used to access super globals.
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class MySource_Sniffs_PHP_GetRequestDataSniff implements PHP_CodeSniffer_Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_VARIABLE);
}//end register()
/**
* Processes this sniff, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$varName = $tokens[$stackPtr]['content'];
if ($varName !== '$_REQUEST'
&& $varName !== '$_GET'
&& $varName !== '$_POST'
&& $varName !== '$_FILES'
) {
return;
}
// The only place these super globals can be accessed directly is
// in the getRequestData() method of the Security class.
$inClass = false;
foreach ($tokens[$stackPtr]['conditions'] as $i => $type) {
if ($tokens[$i]['code'] === T_CLASS) {
$className = $phpcsFile->findNext(T_STRING, $i);
$className = $tokens[$className]['content'];
if (strtolower($className) === 'security') {
$inClass = true;
} else {
// We don't have nested classes.
break;
}
} else if ($inClass === true && $tokens[$i]['code'] === T_FUNCTION) {
$funcName = $phpcsFile->findNext(T_STRING, $i);
$funcName = $tokens[$funcName]['content'];
if (strtolower($funcName) === 'getrequestdata') {
// This is valid.
return;
} else {
// We don't have nested functions.
break;
}
}//end if
}//end foreach
// If we get to here, the super global was used incorrectly.
// First find out how it is being used.
$globalName = strtolower(substr($varName, 2));
$usedVar = '';
$openBracket = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);
if ($tokens[$openBracket]['code'] === T_OPEN_SQUARE_BRACKET) {
$closeBracket = $tokens[$openBracket]['bracket_closer'];
$usedVar = $phpcsFile->getTokensAsString(($openBracket + 1), ($closeBracket - $openBracket - 1));
}
$type = 'SuperglobalAccessed';
$error = 'The %s super global must not be accessed directly; use Security::getRequestData(';
$data = array($varName);
if ($usedVar !== '') {
$type .= 'WithVar';
$error .= '%s, \'%s\'';
$data[] = $usedVar;
$data[] = $globalName;
}
$error .= ') instead';
$phpcsFile->addError($error, $stackPtr, $type, $data);
}//end process()
}//end class
?>

View File

@@ -0,0 +1,76 @@
<?php
/**
* Warns when function values are returned directly.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Warns when function values are returned directly.
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class MySource_Sniffs_PHP_ReturnFunctionValueSniff implements PHP_CodeSniffer_Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_RETURN);
}//end register()
/**
* Processes this sniff, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$functionName = $phpcsFile->findNext(T_STRING, ($stackPtr + 1), null, false, null, true);
while ($functionName !== false) {
// Check if this is really a function.
$bracket = $phpcsFile->findNext(T_WHITESPACE, ($functionName + 1), null, true);
if ($tokens[$bracket]['code'] !== T_OPEN_PARENTHESIS) {
// Not a function call.
$functionName = $phpcsFile->findNext(T_STRING, ($functionName + 1), null, false, null, true);
continue;
}
$error = 'The result of a function call should be assigned to a variable before being returned';
$phpcsFile->addWarning($error, $stackPtr, 'NotAssigned');
break;
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,88 @@
<?php
/**
* Ensures that strings are not joined using array.join().
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Ensures that strings are not joined using array.join().
*
* @category PHP
* @package PHP_CodeSniffer_MySource
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: 1.3.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class MySource_Sniffs_Strings_JoinStringsSniff implements PHP_CodeSniffer_Sniff
{
/**
* A list of tokenizers this sniff supports.
*
* @var array
*/
public $supportedTokenizers = array('JS');
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_STRING);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param integer $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if ($tokens[$stackPtr]['content'] !== 'join') {
return;
}
$prev = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr - 1), null, true);
if ($tokens[$prev]['code'] !== T_OBJECT_OPERATOR) {
return;
}
$prev = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$emptyTokens, ($prev - 1), null, true);
if ($tokens[$prev]['code'] === T_CLOSE_SQUARE_BRACKET) {
$opener = $tokens[$prev]['bracket_opener'];
if ($tokens[($opener - 1)]['code'] !== T_STRING) {
// This means the array is declared inline, like x = [a,b,c].join()
// and not elsewhere, like x = y[a].join()
// The first is not allowed while the second is.
$error = 'Joining strings using inline arrays is not allowed; use the + operator instead';
$phpcsFile->addError($error, $stackPtr, 'ArrayNotAllowed');
}
}
}//end process()
}//end class
?>

View File

@@ -0,0 +1,15 @@
<?xml version="1.0"?>
<ruleset name="MySource">
<description>The MySource coding standard builds on the Squiz coding standard. Currently used for MySource Mini development.</description>
<exclude-pattern>*/Tests/*</exclude-pattern>
<exclude-pattern>*/Oven/*</exclude-pattern>
<exclude-pattern>*/data/*</exclude-pattern>
<exclude-pattern>DALConf.inc</exclude-pattern>
<!-- Include the whole Squiz standard except FunctionComment, which we override -->
<rule ref="Squiz">
<exclude name="Squiz.Commenting.FunctionComment"/>
</rule>
</ruleset>

View File

@@ -0,0 +1,24 @@
<documentation title="Including Code">
<standard>
<![CDATA[
Anywhere you are unconditionally including a class file, use <em>require_once</em>. Anywhere you are conditionally including a class file (for example, factory methods), use <em>include_once</em>. Either of these will ensure that class files are included only once. They share the same file list, so you don't need to worry about mixing them - a file included with <em>require_once</em> will not be included again by <em>include_once</em>.
]]>
</standard>
<standard>
<![CDATA[
Note that <em>include_once</em> and <em>require_once</em> are statements, not functions. Parentheses should not surround the subject filename.
]]>
</standard>
<code_comparison>
<code title="Valid: used as statement">
<![CDATA[
require_once 'PHP/CodeSniffer.php';
]]>
</code>
<code title="Invalid: used as function">
<![CDATA[
require_once<em>(</em>'PHP/CodeSniffer.php'<em>)</em>;
]]>
</code>
</code_comparison>
</documentation>

Some files were not shown because too many files have changed in this diff Show More