Skip to content
Snippets Groups Projects
Commit 2ddb5081 authored by Klaus Purer's avatar Klaus Purer
Browse files

feat(GlobalClassSniff): Detect Node::load() calls in service classes (#2847690)

parent 39dc7b2b
No related branches found
No related tags found
No related merge requests found
......@@ -8,7 +8,8 @@
*/
/**
* Checks that Node::load() calls and friends are not used in forms or controllers.
* Checks that Node::load() calls and friends are not used in forms, controllers or
* services.
*
* @category PHP
* @package PHP_CodeSniffer
......@@ -81,7 +82,10 @@ class DrupalPractice_Sniffs_Objects_GlobalClassSniff implements PHP_CodeSniffer_
$classPtr = key($tokens[$stackPtr]['conditions']);
$extendsName = $phpcsFile->findExtendedClassName($classPtr);
if ($extendsName === false || in_array($extendsName, DrupalPractice_Sniffs_Objects_GlobalDrupalSniff::$baseClasses) === false) {
if (($extendsName === false
|| in_array($extendsName, DrupalPractice_Sniffs_Objects_GlobalDrupalSniff::$baseClasses) === false)
&& DrupalPractice_Project::isServiceClass($phpcsFile, $classPtr) === false
) {
return;
}
......
......@@ -29,9 +29,23 @@ class DrupalPractice_Sniffs_Objects_GlobalClassUnitTest extends CoderSniffUnitTe
*/
protected function getWarningList($testFile)
{
return array(8 => 1);
switch ($testFile) {
case 'GlobalClassUnitTest.inc':
return array(8 => 1);
case 'ExampleService.php':
return array(23 => 1);
}
}//end getWarningList()
/**
* Returns a list of test files that should be checked.
*
* @return array The list of test files.
*/
protected function getTestFiles() {
return [__DIR__.'/GlobalClassUnitTest.inc', __DIR__.'/src/ExampleService.php'];
}
}//end class
......@@ -33,9 +33,8 @@ class DrupalPractice_Sniffs_Objects_GlobalDrupalUnitTest extends CoderSniffUnitT
case 'GlobalDrupalUnitTest.inc':
return array(6 => 1);
case 'ExampleService.php':
return array(14 => 1);
return array(16 => 1);
}
print $testFile;
}//end getWarningList()
......
......@@ -2,6 +2,8 @@
namespace Drupal\testmodule;
use Drupal\node\Entity\Node;
/**
* Some service.
*/
......@@ -14,4 +16,11 @@ class ExampleService {
return \Drupal::configFactory();
}
/**
* Loading nodes should be done from an injected service.
*/
public function test2() {
return Node::load(1);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment