PHP项目对代码的基本检查

1、安装phpstan

composer require --dev phpstan/phpstan

2、在项目的根目录增加配置文件phpstan.neon,如果没有的话,检查的太过严格

parameters:
    # 只检查 app 目录
    paths:
        - app

    # 检查强度:1 = 只抓明显错误
    level: 5

    treatPhpDocTypesAsCertain: false
    reportUnmatchedIgnoredErrors: false

    # 忽略掉一些“无伤大雅”的错误
    ignoreErrors:
        # 框架/魔术属性
        - '#Access to an undefined property .*#'
        - '#Call to an undefined method Illuminate\\.*#'
        - '#Call to an undefined static method Webman\\.*#'
        - '#Call to an undefined method think\\db\\BaseQuery::group#'
        - '#Call to an undefined method think\\db\\BaseQuery::join#'
        - '#Call to an undefined method think\\db\\BaseQuery::chunk#'
        - '#Call to an undefined method think\\db\\BaseQuery::fieldRaw#'
        - '#Call to an undefined method .*::chunk\(\).#'

        # instanceof 恒真/恒假
        - '#instanceof between .* will always evaluate to (true|false)#'

        # nullsafe 永远非空
        - '#nullsafe.neverNull#'

        # 访问可能为数组/模型的属性
        - '#Cannot access property \$.* on array\|.*#'

        # 恒真/恒假布尔判断
        - '#booleanNot.always(False|True)#'

        # 属性只写不读
        - '#Property .* is never read, only written#'

        # 不可达代码
        - '#Unreachable statement#'

        # 匿名函数 use 未使用
        - '#Anonymous function has an unused use#'

        # 静态调用实例方法
        - '#Static call to instance method .*#'

        # 未使用
        - '#Constant .* is unused#'
        - '#Variable .* is assigned but never used#'
        - '#Static method .* is unused#'

        - '#AopCertClient#'
        - '#TopClient#'
        - '#ItemsOnsaleGetRequest#'
        - '#ItemSkusGetRequest#'
        - '#OpenTradesSoldGetRequest#'

3、尝试执行看看

./vendor/bin/phpstan analyse --memory-limit=1G  

4、如果用的webman,可以自己写一个command文件,来执行上面的命令

在app/command新建Phpstan.php文件,内容如下

<?php

namespace app\command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;


class Phpstan extends Command
{
    protected static $defaultName = 'phpstan';
    protected static $defaultDescription = 'phpstan';

    /**
     * @return void
     */
    protected function configure()
    {
        $this->addArgument('name', InputArgument::OPTIONAL, 'Name description');
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $cmd = base_path() . '/vendor/bin/phpstan analyse --memory-limit=1G --ansi';
        passthru($cmd, $status);
        return $status;
    }

}

5、忽略特定的代码,加上这个注释后,下一行代码不检查

/** @phpstan-ignore-next-line */

文章作者: Wind
本文链接:
版权声明: 本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 雕刻时光
喜欢就支持一下吧