How to run code analysis using Larastan in Laravel

Overview

In this shot, we’ll learn to debug our Laravel application.

We can equate Larastan to PHPStan, except in this instance, Larastan actually works in a PHP framework.

Larastan can be seen as a tool for code analysis that helps find errors in our code blocks. It finds errors that can only be found at runtime.

Larastan is a good tool to debug our application’s errors before deployment.

We’ll run code analysis on our Laravel application using the steps below.

Requirements

  • PHP 7.2+
  • Laravel 6.0+

Procedure

  • Step 1: Run the code below to install larastan as a development dependency.
composer require nunomaduro/larastan --dev
  • Step 2: Create a phpstan.neon or phpstan.neon.dist file in the root directory:
includes:
    - ./vendor/nunomaduro/larastan/extension.neon

parameters:

    paths:
        - app

    # The level 9 is the highest level
    level: 5

    ignoreErrors:
        - '#Unsafe usage of new static#'

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

    checkMissingIterableValueType: false

Note: Please refer to PHPStan documentation for more options.

  • Step 3: Run code analysis using the phpstan console command:
./vendor/bin/phpstan analyse

If we get the Allowed memory size exhausted error, we should use --memory-limit to fix it:

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

Free Resources