View source
<?php
namespace DrupalPractice\Sniffs\Objects;
use PHP_CodeSniffer\Files\File;
use DrupalPractice\Project;
use Drupal\Sniffs\Semantics\FunctionCall;
class GlobalFunctionSniff extends FunctionCall {
protected $functions = [
'drupal_get_destination' => 'the "redirect.destination" service',
'drupal_render' => 'the "renderer" service',
'entity_load' => 'the "entity_type.manager" service',
'file_load' => 'the "entity_type.manager" service',
'format_date' => 'the "date.formatter" service',
'node_load' => 'the "entity_type.manager" service',
'node_load_multiple' => 'the "entity_type.manager" service',
'node_type_load' => 'the "entity_type.manager" service',
't' => '$this->t()',
'taxonomy_term_load' => 'the "entity_type.manager" service',
'taxonomy_vocabulary_load' => 'the "entity_type.manager" service',
'user_load' => 'the "entity_type.manager" service',
'user_role_load' => 'the "entity_type.manager" service',
];
protected $traitFunctions = [
't' => '\\Drupal\\Core\\StringTranslation\\StringTranslationTrait',
];
public function process(File $phpcsFile, $stackPtr) {
$tokens = $phpcsFile
->getTokens();
if (Project::getCoreVersion($phpcsFile) < 8) {
return $phpcsFile->numTokens + 1;
}
if ($this
->isFunctionCall($phpcsFile, $stackPtr) === false || empty($tokens[$stackPtr]['conditions']) === true || isset($this->functions[$tokens[$stackPtr]['content']]) === false) {
return;
}
foreach ($tokens[$stackPtr]['conditions'] as $conditionPtr => $conditionCode) {
if ($conditionCode === T_FUNCTION && $phpcsFile
->getMethodProperties($conditionPtr)['is_static'] === true) {
return;
}
}
$classPtr = key($tokens[$stackPtr]['conditions']);
if ($tokens[$classPtr]['code'] !== T_CLASS) {
return;
}
if (isset($this->traitFunctions[$tokens[$stackPtr]['content']]) === false) {
$extendsName = $phpcsFile
->findExtendedClassName($classPtr);
$implementedInterfaceNames = $phpcsFile
->findImplementedInterfaceNames($classPtr);
$canAccessContainer = !empty($implementedInterfaceNames) && in_array('ContainerInjectionInterface', $implementedInterfaceNames);
if (($extendsName === false || in_array($extendsName, GlobalDrupalSniff::$baseClasses) === false) && Project::isServiceClass($phpcsFile, $classPtr) === false && $canAccessContainer === false) {
return;
}
$warning = '%s() calls should be avoided in classes, use dependency injection and %s instead';
$data = [
$tokens[$stackPtr]['content'],
$this->functions[$tokens[$stackPtr]['content']],
];
}
else {
$warning = '%s() calls should be avoided in classes, use %s and %s instead';
$data = [
$tokens[$stackPtr]['content'],
$this->traitFunctions[$tokens[$stackPtr]['content']],
$this->functions[$tokens[$stackPtr]['content']],
];
}
$phpcsFile
->addWarning($warning, $stackPtr, 'GlobalFunction', $data);
}
}