PHPStan Setup

Posted: 2018-08-05 12:53:17

There is a good episode here https://www.phproundtable.com/episode/using-static-analyzers-to-improve-our-php-codebases that talks about this.

The short of it is that it can easily catch some issues that your tests or IDE did not. For example I had a class name overlap due to a typo and it found it. From there it will output tons of other info that may just help guide you in your work.

The install is super easy as seen in the docs https://github.com/phpstan/phpstan

For me I did

composer global require phpstan/phpstan

then in my composer.json I added

"scripts": {
                //see last row but here are some other nice quick shortcuts
                "check-style": "phpcs -p --standard=PSR2 --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 app",
        "fix-style": "phpcbf -p --standard=PSR2 --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 app",
        "check-metrics": "phpmetrics --report-json=report.json app && vendor/bin/quality_run_check.py report.json",
        "check-metrics-html": "phpmetrics --report-json=report.json --report-html=report app && open report/index.html",
        "phpstan": "phpstan analyse app"
}

The initial run found this

Cannot declare class App\Observers\QualityReport because the name is already in use in /Users/alfrednutile/Code/cat-quality-service/app/Observers/QualityReport.php on line 7

which was great since I did not catch that in my tests. Another run found a missing variable for my printf which was in an exception area I did not test.

This may help as well https://github.com/nunomaduro/larastan for Laravel

This will avoid some Facade and other issues. Even just trying

php artisan code:analyse --paths=app --level=0

Found some issues I did not see, for example object properties I did not define at the top of the Class.