View source
<?php
namespace Drupal\Sniffs\Commenting;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Util\Tokens;
class HookCommentSniff implements Sniff {
public function register() {
return array(
T_FUNCTION,
);
}
public function process(File $phpcsFile, $stackPtr) {
$tokens = $phpcsFile
->getTokens();
$find = Tokens::$methodPrefixes;
$find[] = T_WHITESPACE;
$commentEnd = $phpcsFile
->findPrevious($find, $stackPtr - 1, null, true);
if ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG && $tokens[$commentEnd]['code'] !== T_COMMENT) {
return;
}
if ($tokens[$commentEnd]['code'] === T_COMMENT) {
return;
}
$commentStart = $tokens[$commentEnd]['comment_opener'];
$empty = array(
T_DOC_COMMENT_WHITESPACE,
T_DOC_COMMENT_STAR,
);
$short = $phpcsFile
->findNext($empty, $commentStart + 1, $commentEnd, true);
if ($short === false) {
return;
}
$shortContent = $tokens[$short]['content'];
$shortEnd = $short;
for ($i = $short + 1; $i < $commentEnd; $i++) {
if ($tokens[$i]['code'] === T_DOC_COMMENT_STRING) {
if ($tokens[$i]['line'] === $tokens[$shortEnd]['line'] + 1) {
$shortContent .= $tokens[$i]['content'];
$shortEnd = $i;
}
else {
break;
}
}
}
if (preg_match('/^[\\s]*Implement[^\\n]+?hook_[^\\n]+/i', $shortContent, $matches) === 1) {
if (strstr($matches[0], 'Implements ') === false || strstr($matches[0], 'Implements of') !== false || preg_match('/ (drush_)?hook_[a-zA-Z0-9_]+\\(\\)( for .+)?\\.$/', $matches[0]) !== 1) {
$phpcsFile
->addWarning('Format should be "* Implements hook_foo().", "* Implements hook_foo_BAR_ID_bar() for xyz_bar().",, "* Implements hook_foo_BAR_ID_bar() for xyz-bar.html.twig.", "* Implements hook_foo_BAR_ID_bar() for xyz-bar.tpl.php.", or "* Implements hook_foo_BAR_ID_bar() for block templates."', $short, 'HookCommentFormat');
}
else {
foreach ($tokens[$commentStart]['comment_tags'] as $pos => $tag) {
if ($tokens[$tag]['content'] === '@param') {
$warn = 'Hook implementations should not duplicate @param documentation';
$phpcsFile
->addWarning($warn, $tag, 'HookParamDoc');
}
if ($tokens[$tag]['content'] === '@return') {
$warn = 'Hook implementations should not duplicate @return documentation';
$phpcsFile
->addWarning($warn, $tag, 'HookReturnDoc');
}
}
}
}
}
}