DEV Community

Alpha Olomi
Alpha Olomi

Posted on

Static Code analysis in Laravel with Larastan

PHPStan focuses on finding errors in your code. It catches whole classes of bugs even before you write tests for the code.

  • Adds static typing to Laravel to improve developer productivity and code quality
  • Supports most of Laravel's beautiful magic
  • Discovers bugs in your code

larastan logo

Larastan is a phpstan/phpstan wrapper for Laravel. Discover bugs in your code without running it.

Installation

composer require nunomaduro/larastan:^2.0 --dev
Enter fullscreen mode Exit fullscreen mode

Configure

touch phpstan.neon
Enter fullscreen mode Exit fullscreen mode
includes:
    - ./vendor/nunomaduro/larastan/extension.neon

parameters:

    paths:
        - app

    # The level 9 is the highest level
    level: 5

    ignoreErrors:

    excludePaths:
        - ./*/*/FileToBeExcluded.php

    checkMissingIterableValueType: false
Enter fullscreen mode Exit fullscreen mode

Add format script

Update composer.json, add a format script

"scripts": {
  "analyse": "vendor/bin/phpstan analyse",
    "post-autoload-dump": [
        "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
        "@php artisan package:discover --ansi"
    ],
}
Enter fullscreen mode Exit fullscreen mode

More

Ignoring errors

Ignoring a specific error can be done either with a php comment or in the configuration file:

// @phpstan-ignore-next-line
$test->badMethod();

$test->badMethod(); // @phpstan-ignore-line
Enter fullscreen mode Exit fullscreen mode

When ignoring errors in PHPStan's configuration file, they are ignored by writing a regex based on error messages:

file: phpstan.neon

parameters:
    ignoreErrors:
        - '#Call to an undefined method .*badMethod\(\)#'
Enter fullscreen mode Exit fullscreen mode

Run analyse

composer analyse
Enter fullscreen mode Exit fullscreen mode

analyse terminal logs

Further (Optional)

Try levelling up the stan level from 5 to 6 and fix the code

# from
level: 5
# to
level: 6
Enter fullscreen mode Exit fullscreen mode

Run analyse

composer analyse
Enter fullscreen mode Exit fullscreen mode

Happy Coding!

Top comments (0)