diff --git a/coder_sniffer/Drupal/Sniffs/Attributes/ValidHookNameSniff.php b/coder_sniffer/Drupal/Sniffs/Attributes/ValidHookNameSniff.php new file mode 100644 index 00000000..1f8791f8 --- /dev/null +++ b/coder_sniffer/Drupal/Sniffs/Attributes/ValidHookNameSniff.php @@ -0,0 +1,82 @@ + + */ + public function register() + { + return [T_ATTRIBUTE]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\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|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return $phpcsFile->numTokens + 1 to skip + * the rest of the file. + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $attributeName = $phpcsFile->findNext(T_STRING, ($stackPtr + 1)); + if ($attributeName !== false + && $tokens[$attributeName]['content'] === 'Hook' + ) { + $hookName = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, ($attributeName + 2)); + if ($hookName !== false) { + // Remove outer quotes. + $hookNameValue = trim($tokens[$hookName]['content'], '"\''); + + if (strpos($hookNameValue, 'hook_') === 0 && $hookNameValue !== 'hook_') { + // Remove "hook_" prefix. + $hookNameValueFixed = substr($hookNameValue, 5); + $message = sprintf("The hook name should not start with 'hook_', expected '%s' but found '%s'", $hookNameValueFixed, $hookNameValue); + + $fix = $phpcsFile->addFixableWarning($message, $hookName, 'HookPrefix'); + if ($fix === true) { + // Return outer quotes. + $hookNameValueFixed = str_replace($hookNameValue, $hookNameValueFixed, $tokens[$hookName]['content']); + $phpcsFile->fixer->replaceToken($hookName, $hookNameValueFixed); + } + } + } + }//end if + + }//end process() + + +}//end class diff --git a/tests/Drupal/Attributes/ValidHookNameUnitTest.inc b/tests/Drupal/Attributes/ValidHookNameUnitTest.inc new file mode 100644 index 00000000..5a65eabd --- /dev/null +++ b/tests/Drupal/Attributes/ValidHookNameUnitTest.inc @@ -0,0 +1,117 @@ + + */ + protected function getErrorList(string $testFile): array + { + return []; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + protected function getWarningList(string $testFile): array + { + return [ + 19 => 1, + 27 => 1, + 43 => 1, + 51 => 1, + 59 => 1, + 69 => 1, + 92 => 1, + 107 => 1, + ]; + + }//end getWarningList() + + +}//end class