Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 16 additions & 23 deletions coder_sniffer/Drupal/Sniffs/Scope/MethodScopeSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
* Verifies that class/interface/trait methods have scope modifiers.
*
* Largely copied from
* \PHP_CodeSniffer\Standards\Squiz\Sniffs\Scope\MethodScopeSniff to work on
* traits and have a fixer.
* \PHP_CodeSniffer\Standards\Squiz\Sniffs\Scope\MethodScopeSniff to have a
* fixer.
*
* @category PHP
* @package PHP_CodeSniffer
Expand All @@ -29,12 +29,11 @@ class MethodScopeSniff extends AbstractScopeSniff


/**
* Constructs a
* \PHP_CodeSniffer\Standards\Squiz\Sniffs\Scope\MethodScopeSniff.
* Constructor.
*/
public function __construct()
{
parent::__construct([T_CLASS, T_INTERFACE, T_TRAIT, T_ENUM], [T_FUNCTION]);
parent::__construct(Tokens::OO_SCOPE_TOKENS, [T_FUNCTION]);
}


Expand All @@ -47,32 +46,26 @@ public function __construct()
*
* @return void
*/
protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope)
protected function processTokenWithinScope(File $phpcsFile, int $stackPtr, int $currScope)
{
$tokens = $phpcsFile->getTokens();

$methodName = $phpcsFile->getDeclarationName($stackPtr);
if ($methodName === '') {
// Ignore closures.
// Determine if this is a function which needs to be examined.
$conditions = $tokens[$stackPtr]['conditions'];
end($conditions);
$deepestScope = key($conditions);
if ($deepestScope !== $currScope) {
return;
}

if ($phpcsFile->hasCondition($stackPtr, T_FUNCTION) === true) {
// Ignore nested functions.
$methodName = $phpcsFile->getDeclarationName($stackPtr);
if ($methodName === '') {
// Ignore live coding.
return;
}

$modifier = null;
for ($i = ($stackPtr - 1); $i > 0; $i--) {
if ($tokens[$i]['line'] < $tokens[$stackPtr]['line']) {
break;
} elseif (isset(Tokens::SCOPE_MODIFIERS[$tokens[$i]['code']]) === true) {
$modifier = $i;
break;
}
}

if ($modifier === null) {
$properties = $phpcsFile->getMethodProperties($stackPtr);
if ($properties['scope_specified'] === false) {
$error = 'Visibility must be declared on method "%s"';
$data = [$methodName];
$fix = $phpcsFile->addFixableError($error, $stackPtr, 'Missing', $data);
Expand All @@ -96,7 +89,7 @@ protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScop
*
* @return void
*/
protected function processTokenOutsideScope(File $phpcsFile, $stackPtr)
protected function processTokenOutsideScope(File $phpcsFile, int $stackPtr)
{
}
}