I’m working on a PHP project where we want to ensure that all include, require, include_once, and require_once statements use the __DIR__ constant for path resolution.
I couldn’t find an existing sniff that enforces this rule, so I decided to write my own.
1. Creating the Custom Sniff File
First, create a file that defines your custom sniff. In my project, I placed it in a folder named _dev
(which I later exclude from production). I named the file IncludeUsingDirSniff.php
and used the namespace MyCustom
.
Below is the code for the custom sniff:
getTokens();
// Determine the end of the current statement (typically until the semicolon)
$end = $phpcsFile->findEndOfStatement($stackPtr);
if ($end === false) {
$end = count($tokens) - 1;
}
$foundDir = false;
for ($i = $stackPtr; $i <= $end; $i++) {
if (strpos($tokens[$i]['content'], '__DIR__') !== false) {
$foundDir = true;
break;
}
}
if (!$foundDir) {
$error="The %s statement must use __DIR__ for the file path.";
$phpcsFile->addError(sprintf($error, $tokens[$stackPtr]['content']), $stackPtr, 'MissingDirUsage');
}
}
}
2. Setting Up the Ruleset
To ensure that PHP CodeSniffer uses my custom sniff, I added a ruleset that explicitly loads my sniff file. I created a ruleset file (e.g., phpcs.xml
) in the project root with the following content:
My Stuff
Key Points:
3. Running PHP CodeSniffer
Now, when running PHP CodeSniffer from the project root:
$phpcs --standard=_dev/phpcs.xml /var/www/buero
ERROR: Referenced sniff "MyCustom.IncludeUsingDirSniff" does not exist
What am I doing wrong?