comparison vendor/drupal/coder/coder_sniffer/Drupal/Sniffs/Semantics/ConstantNameSniff.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children 129ea1e6d783
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2 /**
3 * Drupal_Sniffs_Semantics_ConstantNameSniff
4 *
5 * @category PHP
6 * @package PHP_CodeSniffer
7 * @link http://pear.php.net/package/PHP_CodeSniffer
8 */
9
10 /**
11 * Checks that constants introduced with define() in module or install files start
12 * with the module's name.
13 *
14 * @category PHP
15 * @package PHP_CodeSniffer
16 * @link http://pear.php.net/package/PHP_CodeSniffer
17 */
18 class Drupal_Sniffs_Semantics_ConstantNameSniff extends Drupal_Sniffs_Semantics_FunctionCall
19 {
20
21
22 /**
23 * Returns an array of function names this test wants to listen for.
24 *
25 * @return array
26 */
27 public function registerFunctionNames()
28 {
29 return array('define');
30
31 }//end registerFunctionNames()
32
33
34 /**
35 * Processes this function call.
36 *
37 * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
38 * @param int $stackPtr The position of the function call in
39 * the stack.
40 * @param int $openBracket The position of the opening
41 * parenthesis in the stack.
42 * @param int $closeBracket The position of the closing
43 * parenthesis in the stack.
44 *
45 * @return void
46 */
47 public function processFunctionCall(
48 PHP_CodeSniffer_File $phpcsFile,
49 $stackPtr,
50 $openBracket,
51 $closeBracket
52 ) {
53 $nameParts = explode('.', basename($phpcsFile->getFilename()));
54 $fileExtension = end($nameParts);
55 // Only check in *.module files.
56 if ($fileExtension !== 'module' && $fileExtension !== 'install') {
57 return;
58 }
59
60 $tokens = $phpcsFile->getTokens();
61 $argument = $this->getArgument(1);
62 if ($tokens[$argument['start']]['code'] !== T_CONSTANT_ENCAPSED_STRING) {
63 // Not a string literal, so this is some obscure constant that we ignore.
64 return;
65 }
66
67 $moduleName = reset($nameParts);
68 $expectedStart = strtoupper($moduleName);
69 // Remove the quotes around the string litral.
70 $constant = substr($tokens[$argument['start']]['content'], 1, -1);
71 if (strpos($constant, $expectedStart) !== 0) {
72 $warning = 'All constants defined by a module must be prefixed with the module\'s name, expected "%s" but found "%s"';
73 $data = array(
74 $expectedStart."_$constant",
75 $constant,
76 );
77 $phpcsFile->addWarning($warning, $stackPtr, 'ConstantStart', $data);
78 }
79
80 }//end processFunctionCall()
81
82
83 }//end class