public function GlobalClassSniff::process in Coder 8.3.x
Same name and namespace in other branches
- 8.3 coder_sniffer/DrupalPractice/Sniffs/Objects/GlobalClassSniff.php \DrupalPractice\Sniffs\Objects\GlobalClassSniff::process()
- 8.2 coder_sniffer/DrupalPractice/Sniffs/Objects/GlobalClassSniff.php \DrupalPractice\Sniffs\Objects\GlobalClassSniff::process()
Processes this test, when one of its tokens is encountered.
Parameters
\PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.:
int $stackPtr The position of the current token: in the stack passed in $tokens.
Return value
void|int
File
- coder_sniffer/
DrupalPractice/ Sniffs/ Objects/ GlobalClassSniff.php, line 111
Class
- GlobalClassSniff
- Checks that Node::load() calls and friends are not used in forms, controllers or services.
Namespace
DrupalPractice\Sniffs\ObjectsCode
public function process(File $phpcsFile, $stackPtr) {
$tokens = $phpcsFile
->getTokens();
// We are only interested in static class method calls, not in the global
// scope.
if ($tokens[$stackPtr + 1]['code'] !== T_DOUBLE_COLON || isset($tokens[$stackPtr + 2]) === false || $tokens[$stackPtr + 2]['code'] !== T_STRING || in_array($tokens[$stackPtr + 2]['content'], [
'load',
'loadMultiple',
]) === false || isset($tokens[$stackPtr + 3]) === false || $tokens[$stackPtr + 3]['code'] !== T_OPEN_PARENTHESIS || empty($tokens[$stackPtr]['conditions']) === true) {
return;
}
// Check that this statement is not in a static function.
foreach ($tokens[$stackPtr]['conditions'] as $conditionPtr => $conditionCode) {
if ($conditionCode === T_FUNCTION && $phpcsFile
->getMethodProperties($conditionPtr)['is_static'] === true) {
return;
}
}
$fullName = $this
->getFullyQualifiedName($phpcsFile, $tokens[$stackPtr]['content']);
if (in_array($fullName, $this->coreClasses) === false && in_array($fullName, $this->classes) === false) {
return;
}
// Check if the class extends another class and get the name of the class
// that is extended.
$classPtr = key($tokens[$stackPtr]['conditions']);
$extendsName = $phpcsFile
->findExtendedClassName($classPtr);
// Check if the class implements a container injection interface.
$containerInterfaces = [
'ContainerInjectionInterface',
'ContainerFactoryPluginInterface',
'ContainerDeriverInterface',
];
$implementedInterfaceNames = $phpcsFile
->findImplementedInterfaceNames($classPtr);
$canAccessContainer = !empty($implementedInterfaceNames) && !empty(array_intersect($containerInterfaces, $implementedInterfaceNames));
if (($extendsName === false || in_array($extendsName, GlobalDrupalSniff::$baseClasses) === false) && Project::isServiceClass($phpcsFile, $classPtr) === false && $canAccessContainer === false) {
return $phpcsFile->numTokens + 1;
}
$warning = '%s::%s calls should be avoided in classes, use dependency injection instead';
$data = [
$tokens[$stackPtr]['content'],
$tokens[$stackPtr + 2]['content'],
];
$phpcsFile
->addWarning($warning, $stackPtr, 'GlobalClass', $data);
}