View source
<?php
namespace DrupalPractice\Sniffs\Objects;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use DrupalPractice\Sniffs\Objects\GlobalDrupalSniff;
use DrupalPractice\Project;
class GlobalFunctionSniff implements Sniff {
protected $functions = array(
'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',
);
public function register() {
return array(
T_STRING,
);
}
public function process(File $phpcsFile, $stackPtr) {
$tokens = $phpcsFile
->getTokens();
if (isset($this->functions[$tokens[$stackPtr]['content']]) === false || isset($tokens[$stackPtr + 1]) === false || $tokens[$stackPtr + 1]['code'] !== T_OPEN_PARENTHESIS || empty($tokens[$stackPtr]['conditions']) === true) {
return;
}
$previous = $phpcsFile
->findPrevious(T_WHITESPACE, $stackPtr - 1, null, true);
if ($tokens[$previous]['code'] === T_OBJECT_OPERATOR) {
return;
}
foreach ($tokens[$stackPtr]['conditions'] as $conditionPtr => $conditionCode) {
if ($conditionCode === T_FUNCTION && $phpcsFile
->getMethodProperties($conditionPtr)['is_static'] === true) {
return;
}
}
$classPtr = key($tokens[$stackPtr]['conditions']);
$extendsName = $phpcsFile
->findExtendedClassName($classPtr);
if (($extendsName === false || in_array($extendsName, GlobalDrupalSniff::$baseClasses) === false) && Project::isServiceClass($phpcsFile, $classPtr) === false) {
return;
}
$warning = '%s() calls should be avoided in classes, use dependency injection and %s instead';
$data = array(
$tokens[$stackPtr]['content'],
$this->functions[$tokens[$stackPtr]['content']],
);
$phpcsFile
->addWarning($warning, $stackPtr, 'GlobalFunction', $data);
}
}