Composer Scripts

Introduction to Composer Scripts and Static Analysis in Laravel

Composer scripts are a powerful feature that allows you to automate common tasks in your PHP projects. They provide a convenient way to run frequently used commands, such as testing, linting, or analyzing your code, without having to remember and type the full command each time. By defining these scripts in your composer.json file, you can streamline your development workflow, save time, and reduce the risk of errors caused by running incomplete or incorrect commands.

In this lesson, we’ll enhance our project by adding a test script to composer.json. This script will run two critical tools in a single step:

  1. PHPStan: Performs static analysis to identify type errors, undefined variables, and other issues in your code.
  2. Artisan Test Runner: Executes your Laravel test suite to verify the functionality and behavior of your application.

With this setup, you’ll be able to run both static analysis and functionality tests with a single command:

composer test

This makes it easier to ensure your code meets high-quality standards every time you run the script.

PHPStan Configuration

Along with the script, we’ll create a phpstan.neon file to configure PHPStan for our project. This file defines parameters that tailor PHPStan’s behavior, such as:

  • Level: We’ve set the analysis level to 9, the strictest setting, to catch as many potential issues as possible.
  • Paths: PHPStan will focus its analysis on the app/ directory, where most of your Laravel application logic resides.
  • Exclusions: Certain paths, such as bootstrap/cache and storage, are excluded since they contain generated or runtime files that don’t require analysis.

This configuration ensures that PHPStan focuses on the relevant parts of your application, providing meaningful feedback while ignoring unnecessary files.

By the end of this lesson, you’ll understand the benefits of Composer scripts and how to leverage them to simplify your workflow. You’ll also see how PHPStan and Laravel’s test runner can work together to maintain both the structural integrity and functionality of your codebase. This small addition will help you enforce best practices and catch errors early in your development process.

Branch: https://github.com/GaryClarke/laravel-microservice/tree/3-composer-scripts

Complete and Continue  
Discussion

1 comments