|
22 | 22 | class ValidHookNameSniff implements Sniff
|
23 | 23 | {
|
24 | 24 |
|
| 25 | + /** |
| 26 | + * List of hooks that should not be fixed. |
| 27 | + * |
| 28 | + * @var string[] |
| 29 | + */ |
| 30 | + public array $hookExceptions = ['hook_info']; |
| 31 | + |
25 | 32 |
|
26 | 33 | /**
|
27 | 34 | * Returns an array of tokens this test wants to listen for.
|
@@ -51,17 +58,31 @@ public function register()
|
51 | 58 | */
|
52 | 59 | public function process(File $phpcsFile, $stackPtr)
|
53 | 60 | {
|
54 |
| - $tokens = $phpcsFile->getTokens(); |
55 |
| - |
56 |
| - if ($tokens[($stackPtr + 1)]['type'] === 'T_STRING' |
57 |
| - && $tokens[($stackPtr + 1)]['content'] === 'Hook' |
58 |
| - && $tokens[($stackPtr + 3)]['type'] === 'T_CONSTANT_ENCAPSED_STRING' |
59 |
| - && str_contains($tokens[($stackPtr + 3)]['content'], 'hook_') |
| 61 | + $tokens = $phpcsFile->getTokens(); |
| 62 | + $attributeName = $phpcsFile->findNext(T_STRING, ($stackPtr + 1)); |
| 63 | + if ($attributeName !== false |
| 64 | + && $tokens[$attributeName]['content'] === 'Hook' |
60 | 65 | ) {
|
61 |
| - $hookName = $tokens[($stackPtr + 3)]['content']; |
62 |
| - $phpcsFile->addFixableWarning('Hook name should not start with "hook_" prefix. Hook name used:'.$hookName, ($stackPtr + 3), 'AttributePrefixHookName'); |
63 |
| - $phpcsFile->fixer->replaceToken(($stackPtr + 3), str_replace('hook_', '', $hookName)); |
64 |
| - } |
| 66 | + $hookName = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, ($attributeName + 2)); |
| 67 | + if ($hookName !== false |
| 68 | + ) { |
| 69 | + // Remove outer quotes. |
| 70 | + $hookNameValue = trim($tokens[$hookName]['content'], '"\''); |
| 71 | + |
| 72 | + if (in_array($hookNameValue, $this->hookExceptions) === false |
| 73 | + && strpos($hookNameValue, 'hook_') === 0 |
| 74 | + ) { |
| 75 | + $fix = $phpcsFile->addFixableWarning("Hook name should not start with 'hook_'. Hook name used: $hookNameValue", $hookName, 'HookPrefix'); |
| 76 | + if ($fix === true && strlen($hookNameValue) > 5) { |
| 77 | + // Remove "hook_" prefix. |
| 78 | + $hookNameValueFixed = substr($hookNameValue, 5); |
| 79 | + // Return outer quotes. |
| 80 | + $hookNameValueFixed = str_replace($hookNameValue, $hookNameValueFixed, $tokens[$hookName]['content']); |
| 81 | + $phpcsFile->fixer->replaceToken($hookName, $hookNameValueFixed); |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + }//end if |
65 | 86 |
|
66 | 87 | }//end process()
|
67 | 88 |
|
|
0 commit comments