是否有PHP linter规则来防止出现明显的注释?

是否有PHP linter规则来防止出现明显的注释?,php,comments,linter,Php,Comments,Linter,我在一个多语言软件代码库(python、JS、java、PHP、C)上工作,我以前的同事在这里对所有内容都发表了评论。 然而,绝大多数的评论是完全无用的。 例: 我想设置linter规则,以确保不会再次写入此类注释。 您知道有这种特性的过梁吗,或者可以轻松添加这种特性的过梁?(最好是与非英语注释兼容的Linter)这是一个需要向同事传授注释的目的和应撰写的注释类型的问题 如果您只是自动阻止与该方法同名的注释,则最终会出现轻微变化: /** * Get warning file info */

我在一个多语言软件代码库(python、JS、java、PHP、C)上工作,我以前的同事在这里对所有内容都发表了评论。 然而,绝大多数的评论是完全无用的。 例:

我想设置linter规则,以确保不会再次写入此类注释。
您知道有这种特性的过梁吗,或者可以轻松添加这种特性的过梁?(最好是与非英语注释兼容的Linter)

这是一个需要向同事传授注释的目的和应撰写的注释类型的问题

如果您只是自动阻止与该方法同名的注释,则最终会出现轻微变化:

/**
 * Get warning file info
 */
function getWarningFileInfos() {
   ...
}
变成:

/**
 * Get the warning file info
 */
function getWarningFileInfos() {
   ...
}
。。。林特法则会接受它。这并不是一个真正的问题,将得到解决与林廷规则

如果你可以要求你的同事给出正确的评论,要求他们正确地重写评论是一个很好的练习,可以教他们应该写什么评论

没有任何一个linter可以将无用的评论转换成有用的评论

如果您只想删除所有糟糕的评论,可以使用regex:

/\*.{1,50}\*/
将找到所有少于50个字符的注释(编辑器必须支持regex设置“.matches newline”)


替换为nothing并手动检查文件,以检查您是否正在删除任何有价值的内容。假设这些愚蠢的评论大部分都很简短。50个字符是任意的,请将其更改为最适合您的字符。

如果您确实需要它,您可以使用以下疯狂的字符:

$c = '/**
 * Get warning file info
 */
function getWarningFileInfos() {
   ...
}

/**
 * Compute the speed
 */
function computeSpeed() {
    ...
}';

preg_match_all('~\*/[ \t]*\r?\n(?:[ \t]|\w)*function[ \t]+(\S+)[ \t]*\(~isu', $c, $matchesAll);
foreach ($matchesAll[1] as $n) {
    $words = preg_split('~(?=\p{Lu})~', $n);
    $regex = '~/\*(?:\s|\*)*' . implode('', array_map(function($w) {
        return '(?:(?:a|the)\s+)?' . preg_quote(preg_replace('~e?s$~is', '', $w), '~') . '(?:e?s)?' . '\s+';
    }, $words)) . '(?:\s|\*)*\*+/[ \t]*(?=\r?\n(?:[ \t]|\w)*function[ \t]+' . preg_quote($n, '~') . '[ \t]*\()~isu';
    var_dump($regex);
    $c = preg_replace($regex, '', $c);
}

var_dump($c);
示例输出:

string(231) "~/\*(?:\s|\*)*(?:(?:a|the)\s+)?get(?:e?s)?\s+(?:(?:a|the)\s+)?Warning(?:e?s)?\s+(?:(?:a|the)\s+)?File(?:e?s)?\s+(?:(?:a|the)\s+)?Info(?:e?s)?\s+(?:\s|\*)*\*+/[ \t]*(?=\r?\n(?:[ \t]|\w)*function[ \t]+getWarningFileInfos[ \t]*\()~isu"
string(162) "~/\*(?:\s|\*)*(?:(?:a|the)\s+)?compute(?:e?s)?\s+(?:(?:a|the)\s+)?Speed(?:e?s)?\s+(?:\s|\*)*\*+/[ \t]*(?=\r?\n(?:[ \t]|\w)*function[ \t]+computeSpeed[ \t]*\()~isu"
string(88) "
function getWarningFileInfos() {
   ...
}


function computeSpeed() {
    ...
}"

除了教育程序员之外,可能没有其他工具,上面的代码对您有帮助吗?

GitHub上没有这样的工具,所以您必须自己编写一个

在PHP世界中,linter是最有名、功能最强大的,因此这里有一个基于PHP_CodeSniffer 3.5.2的快速而肮脏的实现。出于您的目的,它使用函数来比较函数名和注释字符串,如果百分比超过60%,它将用消息“包含异常注释”将此函数标记为错误

文件
src/Standards/StackOverflow/Sniffs/comment/UnusualCommentSniff.php

<?php

namespace PHP_CodeSniffer\Standards\StackOverflow\Sniffs\Commenting;

use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Util\Tokens;

class UnusualCommentSniff implements Sniff
{
    public function register()
    {
        return [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) {
            return;
        }
        $commentStart = $tokens[$commentEnd]['comment_opener'];

        $shortDesc = $this->findShortDescriptionInComment($phpcsFile, $commentStart, $commentEnd);
        $funcName = $phpcsFile->getDeclarationName($stackPtr);
        similar_text($funcName, $shortDesc, $percent);
        if ($percent > 60) {
            $error = 'Contains unusual comment';
            $fix = $phpcsFile->addFixableError($error, $stackPtr, 'code');
            if ($fix) {
                $fixer = $phpcsFile->fixer;
                for ($i = $commentStart; $i < $commentEnd + 1; $i++) {
                    $fixer->replaceToken($i, '');
                }
            }
        }
    }

    protected function findShortDescriptionInComment($phpcsFile, $commentStart, $commentEnd)
    {
        $tokens = $phpcsFile->getTokens();

        $empty = [
            T_DOC_COMMENT_WHITESPACE,
            T_DOC_COMMENT_STAR,
        ];

        $short = $phpcsFile->findNext($empty, $commentStart + 1, $commentEnd, true);
        if ($short === false) {
            return;
        }
        $shortContent = null;
        if ($tokens[$short]['code'] === T_DOC_COMMENT_STRING) {
            $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;
                    }
                }
            }
        }

        return $shortContent;
    }
}
通过命令
phpcbf

$ bin/phpcbf --standard=Stackoverflow ./input.php

PHPCBF RESULT SUMMARY
-----------------------------------------------------------------------------
FILE                                                         FIXED  REMAINING
-----------------------------------------------------------------------------
/data1/home/admin/gasolwu/Code/PHP_CodeSniffer/input.php     2      0
-----------------------------------------------------------------------------
A TOTAL OF 2 ERRORS WERE FIXED IN 1 FILE
-----------------------------------------------------------------------------

Time: 52ms; Memory: 3.75MB

$ cat input.php
<?php

class Foo
{


    private function getWarningFileInfos() {
    }


    public function computeSpeed() {
    }

    /**
     * This comment contains some useful information
     * So that should not be deleted
     */
    public function shoot() {
    }
}
$bin/phpcbf--standard=Stackoverflow./input.php
PHPCBF结果摘要
-----------------------------------------------------------------------------
文件固定剩余
-----------------------------------------------------------------------------
/data1/home/admin/gasolwu/Code/PHP\u CodeSniffer/input.PHP 2 0
-----------------------------------------------------------------------------
在1个文件中修复了总共2个错误
-----------------------------------------------------------------------------
时间:52ms;内存:3.75MB
$cat input.php

+1因为这很好,但是除非你训练开发人员写正确的注释,否则你会得到类似“计算速度”而不是“计算速度”的注释,而linter会接受这些注释。这并没有解决根本问题,即他的同事不知道在评论中写什么。此外,修复包括删除注释,它不会生成正确的注释,因此最终结果是“无注释”而不是“无用的注释”。@Sylverdrag你是对的,这种方法根本解决不了问题。我认为最好的方法是由两种方法组成,首先,编写一些编码指南并教给你的同事。第二,在CI管道上自动检查。为您的团队编写一些规则,无论是过梁还是文档。非常感谢!我会尽快测试它。当然,第一步是与我的同事交谈,我们计划下周召开一次关于编码标准的会议
$ pwd
/home/gasolwu/Code/PHP_CodeSniffer/src/Standards
$ git describe
3.5.2-89-g80ebd4a1a
$ tree -C StackOverflow/
StackOverflow/
├── ruleset.xml
└── Sniffs
    └── Commenting
        └── UnusualCommentSniff.php

2 directories, 2 files
$ cat StackOverflow/ruleset.xml
<?xml version="1.0"?>
<ruleset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="Zend" xsi:noNamespaceSchemaLocation="../../../phpcs.xsd">
</ruleset>
$ cat input.php
<?php

class Foo
{

    /**
     * Get warning file info
     */
    private function getWarningFileInfos() {
    }

    /**
     * Compute the speed
     */
    public function computeSpeed() {
    }

    /**
     * This comment contains some useful information
     * So that should not be deleted
     */
    public function shoot() {
    }
}
$ bin/phpcs --standard=Stackoverflow ./input.php

FILE: /data1/home/admin/gasolwu/Code/PHP_CodeSniffer/input.php
----------------------------------------------------------------------
FOUND 2 ERRORS AFFECTING 2 LINES
----------------------------------------------------------------------
  9 | ERROR | [x] Contains unusual comment
 15 | ERROR | [x] Contains unusual comment
----------------------------------------------------------------------
PHPCBF CAN FIX THE 2 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------

Time: 44ms; Memory: 3.75MB
$ bin/phpcbf --standard=Stackoverflow ./input.php

PHPCBF RESULT SUMMARY
-----------------------------------------------------------------------------
FILE                                                         FIXED  REMAINING
-----------------------------------------------------------------------------
/data1/home/admin/gasolwu/Code/PHP_CodeSniffer/input.php     2      0
-----------------------------------------------------------------------------
A TOTAL OF 2 ERRORS WERE FIXED IN 1 FILE
-----------------------------------------------------------------------------

Time: 52ms; Memory: 3.75MB

$ cat input.php
<?php

class Foo
{


    private function getWarningFileInfos() {
    }


    public function computeSpeed() {
    }

    /**
     * This comment contains some useful information
     * So that should not be deleted
     */
    public function shoot() {
    }
}