Skip to content

Commit 30325a5

Browse files
author
Nikolay Shapovalov
committed
refactor
1 parent db01ca3 commit 30325a5

File tree

1 file changed

+31
-10
lines changed

1 file changed

+31
-10
lines changed

coder_sniffer/Drupal/Sniffs/Attributes/ValidHookNameSniff.php

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,13 @@
2222
class ValidHookNameSniff implements Sniff
2323
{
2424

25+
/**
26+
* List of hooks that should not be fixed.
27+
*
28+
* @var string[]
29+
*/
30+
public array $hookExceptions = ['hook_info'];
31+
2532

2633
/**
2734
* Returns an array of tokens this test wants to listen for.
@@ -51,17 +58,31 @@ public function register()
5158
*/
5259
public function process(File $phpcsFile, $stackPtr)
5360
{
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'
6065
) {
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
6586

6687
}//end process()
6788

0 commit comments

Comments
 (0)