google_forms/custom_sniffs/Sniffs/NamespaceSniff.php

58 lines
1.6 KiB
PHP

<?php
namespace CustomSniffs\Sniffs;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
/**
* Custom sniff to check if the namespace matches the directory structure.
*/
class NamespaceSniff implements Sniff
{
public function register()
{
return [T_NAMESPACE];
}
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$namespace = $this->getNamespace($phpcsFile, $stackPtr);
// Get the file path relative to the project root
$filePath = $phpcsFile->getFilename();
$projectRoot = '/var/www/html/google_forms/'; // Adjust this path as necessary
$relativePath = str_replace([$projectRoot, '.php'], '', $filePath);
// Convert the file path to a namespace-like format
$expectedNamespace = str_replace('/', '\\', $relativePath);
// Compare the file path with the namespace
if ($namespace !== $expectedNamespace) {
$error = sprintf(
'Namespace "%s" does not match file path. Expected namespace: "%s"',
$namespace,
$expectedNamespace
);
$phpcsFile->addError($error, $stackPtr, 'InvalidNamespace');
}
}
private function getNamespace(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$namespace = '';
for ($i = $stackPtr + 2; $i < $phpcsFile->numTokens; $i++) {
$namespace .= $tokens[$i]['content'];
if ($tokens[$i]['code'] === T_SEMICOLON) {
break;
}
}
return trim($namespace);
}
}