View source
<?php
namespace Drupal\Sniffs\NamingConventions;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions\CamelCapsFunctionNameSniff;
use PHP_CodeSniffer\Util\Common;
class ValidFunctionNameSniff extends CamelCapsFunctionNameSniff {
protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope) {
$methodName = $phpcsFile
->getDeclarationName($stackPtr);
if ($methodName === null) {
return;
}
$className = $phpcsFile
->getDeclarationName($currScope);
$errorData = array(
$className . '::' . $methodName,
);
if (preg_match('|^__|', $methodName) !== 0) {
$magicPart = strtolower(substr($methodName, 2));
if (isset($this->magicMethods[$magicPart]) === false && isset($this->methodsDoubleUnderscore[$magicPart]) === false) {
$error = 'Method name "%s" is invalid; only PHP magic methods should be prefixed with a double underscore';
$phpcsFile
->addError($error, $stackPtr, 'MethodDoubleUnderscore', $errorData);
}
return;
}
$methodProps = $phpcsFile
->getMethodProperties($stackPtr);
if (Common::isCamelCaps($methodName, false, true, $this->strict) === false) {
if ($methodProps['scope_specified'] === true) {
$error = '%s method name "%s" is not in lowerCamel format';
$data = array(
ucfirst($methodProps['scope']),
$errorData[0],
);
$phpcsFile
->addError($error, $stackPtr, 'ScopeNotCamelCaps', $data);
}
else {
$error = 'Method name "%s" is not in lowerCamel format';
$phpcsFile
->addError($error, $stackPtr, 'NotCamelCaps', $errorData);
}
$phpcsFile
->recordMetric($stackPtr, 'CamelCase method name', 'no');
return;
}
else {
$phpcsFile
->recordMetric($stackPtr, 'CamelCase method name', 'yes');
}
}
protected function processTokenOutsideScope(File $phpcsFile, $stackPtr) {
$functionName = $phpcsFile
->getDeclarationName($stackPtr);
if ($functionName === null) {
return;
}
$isApiFile = substr($phpcsFile
->getFilename(), -8) === '.api.php';
$isHookExample = substr($functionName, 0, 5) === 'hook_';
if ($isApiFile === true && $isHookExample === true) {
return;
}
if ($functionName !== strtolower($functionName)) {
$expected = strtolower(preg_replace('/([^_])([A-Z])/', '$1_$2', $functionName));
$error = 'Invalid function name, expected %s but found %s';
$data = array(
$expected,
$functionName,
);
$phpcsFile
->addError($error, $stackPtr, 'InvalidName', $data);
}
}
}