PHPStan static analysis PHPStan static analysis

October 28, 2022

laravel

Today I took the plunge and installed PHPStan, or rather larastan which is a static analysis tool to check code for errors and missing return types.

composer require nunomaduro/larastan:^2.0 --dev

create a rules file called 'phpstan.neon'

includes:
    - ./vendor/nunomaduro/larastan/extension.neon

parameters:

    paths:
        - app/

    # Level 9 is the highest level
    level: 0

#    ignoreErrors:
#        - '#PHPDoc tag @var#'
#
#    excludePaths:
#        - ./*/*/FileToBeExcluded.php
#
#    checkMissingIterableValueType: false

So i started at level 0, which is the lowest level and ran it thus:

./vendor/bin/phpstan analyse

and it passed

phpstan level 0

level 1 was my first failure

phpstan level 1

so i added

        if (!isset($prefix)) {
            abort(404);
        }

and its green

how cool :)

level 5 started with more errors

phpstan level 5

so i added a return type for the views

use Illuminate\Contracts\View\View;

class BrandController extends Controller
{
    public function index(): View

phpstan level 5b

There was also redirects which needed

use Illuminate\Http\RedirectResponse;

class NWRController extends Controller
{
    public function index(Request $request, $id): View|RedirectResponse

I added a few types in the function arguments and it is all green!

Level 8

phpstan level 8

this error is caused by this code

14        $route = (\Route::current());

16        $data['brand'] = $route->wheres['brand'];

and I am not sure of the solution to this as (string) doesnt work. Any ideas appreciated...


If you would like to contact me with this form on londinium.com, ilminster.net or via Twitter @andylondon