3
* PEAR_Sniffs_NamingConventions_ValidClassNameSniff.
8
* @package PHP_CodeSniffer
9
* @author Greg Sherwood <gsherwood@squiz.net>
10
* @author Marc McIntyre <mmcintyre@squiz.net>
11
* @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600)
12
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
13
* @link http://pear.php.net/package/PHP_CodeSniffer
17
* PEAR_Sniffs_NamingConventions_ValidClassNameSniff.
19
* Ensures class and interface names start with a capital letter
20
* and use _ separators.
23
* @package PHP_CodeSniffer
24
* @author Greg Sherwood <gsherwood@squiz.net>
25
* @author Marc McIntyre <mmcintyre@squiz.net>
26
* @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600)
27
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
28
* @version Release: 1.5.0RC2
29
* @link http://pear.php.net/package/PHP_CodeSniffer
31
class PEAR_Sniffs_NamingConventions_ValidClassNameSniff implements PHP_CodeSniffer_Sniff
36
* Returns an array of tokens this test wants to listen for.
40
public function register()
51
* Processes this test, when one of its tokens is encountered.
53
* @param PHP_CodeSniffer_File $phpcsFile The current file being processed.
54
* @param int $stackPtr The position of the current token
55
* in the stack passed in $tokens.
59
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
61
$tokens = $phpcsFile->getTokens();
63
$className = $phpcsFile->findNext(T_STRING, $stackPtr);
64
$name = trim($tokens[$className]['content']);
65
$errorData = array(ucfirst($tokens[$stackPtr]['content']));
67
// Make sure the first letter is a capital.
68
if (preg_match('|^[A-Z]|', $name) === 0) {
69
$error = '%s name must begin with a capital letter';
70
$phpcsFile->addError($error, $stackPtr, 'StartWithCapital', $errorData);
73
// Check that each new word starts with a capital as well, but don't
74
// check the first word, as it is checked above.
76
$nameBits = explode('_', $name);
77
$firstBit = array_shift($nameBits);
78
foreach ($nameBits as $bit) {
79
if ($bit === '' || $bit{0} !== strtoupper($bit{0})) {
85
if ($validName === false) {
86
// Strip underscores because they cause the suggested name
88
$nameBits = explode('_', trim($name, '_'));
89
$firstBit = array_shift($nameBits);
90
if ($firstBit === '') {
91
$error = '%s name is not valid';
92
$phpcsFile->addError($error, $stackPtr, 'Invalid', $errorData);
94
$newName = strtoupper($firstBit{0}).substr($firstBit, 1).'_';
95
foreach ($nameBits as $bit) {
97
$newName .= strtoupper($bit{0}).substr($bit, 1).'_';
101
$newName = rtrim($newName, '_');
102
$error = '%s name is not valid; consider %s instead';
105
$phpcsFile->addError($error, $stackPtr, 'Invalid', $data);