You are here

public static function Project::isServiceClass in Coder 8.2

Same name and namespace in other branches
  1. 8.3 coder_sniffer/DrupalPractice/Project.php \DrupalPractice\Project::isServiceClass()
  2. 8.3.x coder_sniffer/DrupalPractice/Project.php \DrupalPractice\Project::isServiceClass()

Return true if the given class is a Drupal service registered in *.services.yml.

Parameters

\PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.:

int $classPtr The position of the class declaration: in the token stack.

Return value

bool

3 calls to Project::isServiceClass()
GlobalClassSniff::process in coder_sniffer/DrupalPractice/Sniffs/Objects/GlobalClassSniff.php
Processes this test, when one of its tokens is encountered.
GlobalDrupalSniff::process in coder_sniffer/DrupalPractice/Sniffs/Objects/GlobalDrupalSniff.php
Processes this test, when one of its tokens is encountered.
GlobalFunctionSniff::process in coder_sniffer/DrupalPractice/Sniffs/Objects/GlobalFunctionSniff.php
Processes this test, when one of its tokens is encountered.

File

coder_sniffer/DrupalPractice/Project.php, line 162

Class

Project
Helper class to retrieve project information like module/theme name for a file.

Namespace

DrupalPractice

Code

public static function isServiceClass(File $phpcsFile, $classPtr) {

  // Cache the information per file as this might get called often.
  static $cache;
  if (isset($cache[$phpcsFile
    ->getFilename()]) === true) {
    return $cache[$phpcsFile
      ->getFilename()];
  }

  // Get the namespace of the class if there is one.
  $namespacePtr = $phpcsFile
    ->findPrevious(T_NAMESPACE, $classPtr - 1);
  if ($namespacePtr === false) {
    $cache[$phpcsFile
      ->getFilename()] = false;
    return false;
  }
  $ymlFile = static::getServicesYmlFile($phpcsFile);
  if ($ymlFile === false) {
    $cache[$phpcsFile
      ->getFilename()] = false;
    return false;
  }
  $services = Yaml::parse(file_get_contents($ymlFile));
  if (isset($services['services']) === false) {
    $cache[$phpcsFile
      ->getFilename()] = false;
    return false;
  }
  $nsEnd = $phpcsFile
    ->findNext([
    T_NS_SEPARATOR,
    T_STRING,
    T_WHITESPACE,
  ], $namespacePtr + 1, null, true);
  $namespace = trim($phpcsFile
    ->getTokensAsString($namespacePtr + 1, $nsEnd - $namespacePtr - 1));
  $classNameSpaced = ltrim($namespace . '\\' . $phpcsFile
    ->getDeclarationName($classPtr), '\\');
  foreach ($services['services'] as $service) {
    if (isset($service['class']) === true && $classNameSpaced === ltrim($service['class'], '\\')) {
      $cache[$phpcsFile
        ->getFilename()] = true;
      return true;
    }
  }
  return false;
}