Skip to content

Instantly share code, notes, and snippets.

@Koopzington
Created December 6, 2018 09:02
Show Gist options
  • Save Koopzington/47714abe4bb9a629f39e8bec37d8c3ab to your computer and use it in GitHub Desktop.
Save Koopzington/47714abe4bb9a629f39e8bec37d8c3ab to your computer and use it in GitHub Desktop.
<?php declare(strict_types = 1);
namespace MyCodingStandard\Sniffs\Formatting;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class StringClassReferenceSniff implements Sniff
{
public function register()
{
return [T_CONSTANT_ENCAPSED_STRING];
}
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if (strpos($tokens[$stackPtr]['content'], '\\') !== false) {
// Remove quotes from string
$className = str_replace(['"', "'"], '', $tokens[$stackPtr]['content']);
if (class_exists($className) || interface_exists($className)) {
$error = 'String containing class reference found, use ::class instead.';
$data = [trim($tokens[$stackPtr]['content'])];
$phpcsFile->addError($error, $stackPtr, 'Found', $data);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment