Configure PHP Quality Tools: A Step-by-Step Guide
As developers, ensuring code quality is paramount. Configuring PHP code quality tools is essential for maintaining code that adheres to Laravel conventions and industry best practices. This guide will walk you through setting up Laravel Pint for code formatting and PHPStan for static analysis, integrating them into your workflow for a robust development process.
Why Configure PHP Code Quality Tools?
PHP code quality tools play a crucial role in modern software development. By integrating these tools into your workflow, you can automate the process of identifying and fixing code style issues, potential bugs, and security vulnerabilities. This not only saves time but also ensures consistency and maintainability across your codebase. Consistent code style makes it easier for teams to collaborate, as everyone is working with code that follows the same standards. Furthermore, early detection of issues reduces the risk of costly bugs making their way into production. Using tools like Laravel Pint and PHPStan can significantly improve the overall quality and reliability of your applications. This proactive approach ensures that the codebase remains clean, efficient, and aligned with best practices, ultimately leading to more robust and scalable software.
Acceptance Criteria
To ensure we successfully configure our PHP code quality tools, we need to meet the following criteria:
- [x] Installed Laravel Pint via Composer for code formatting.
- [x] Installed PHPStan for static analysis.
- [x] Configured
.github/workflows/lint.ymlto run on pull requests (PRs). - [x] Created documentation file:
docs/development/code-quality.md.
These criteria provide a clear roadmap for setting up and integrating the tools into our development workflow.
Files to Create/Modify
To achieve our goal, we'll need to create and modify specific files within our project:
pint.json(create): This file will hold the configuration settings for Laravel Pint, defining the code styling rules and formatting preferences.phpstan.neon.dist(create): This configuration file is for PHPStan, specifying the rules and levels of analysis for static code analysis..github/workflows/lint.yml(create): This YAML file will define a GitHub Actions workflow that automatically runs Laravel Pint and PHPStan on pull requests, ensuring code quality is checked before merging.docs/development/code-quality.md(create): This markdown file will serve as documentation for our code quality setup, explaining how to use and maintain the tools.composer.json(update): We'll update this file to include Laravel Pint and PHPStan as development dependencies, making them easily installable via Composer.
Creating and modifying these files will set the foundation for our code quality workflow, allowing us to automate checks and maintain consistency.
Dependencies
Before we dive into the configuration, it's important to note the dependencies for this task:
- Depends On: M1-1
- Blocks: None
Understanding these dependencies ensures that we proceed in the correct order and avoid potential issues down the line. Ensuring that all dependencies are met before proceeding will make the entire process smoother and more efficient.
Installing Laravel Pint
Laravel Pint is a fantastic tool for automatically formatting your PHP code according to Laravel's style guide. To install it, we'll use Composer, the PHP dependency manager.
-
Open your terminal and navigate to your project's root directory.
-
Run the following command:
composer require laravel/pint --devThis command adds Laravel Pint as a development dependency, meaning it's only used during development and not in production.
-
Once the installation is complete, you can run Pint using the following command:
./vendor/bin/pintThis will format your entire codebase according to Laravel's style guide. Laravel Pint streamlines code formatting, ensuring your project adheres to a consistent style, which enhances readability and collaboration.
Configuring Laravel Pint
To configure Laravel Pint, we'll create a pint.json file in the root of our project. This file allows us to customize Pint's behavior, such as excluding specific directories or files from formatting. Customizing Laravel Pint ensures that it aligns perfectly with your project's specific needs and coding standards, providing tailored code formatting.
-
Create a new file named
pint.jsonin your project's root directory. -
Add the following basic configuration:
{ "preset": "laravel" }This configuration tells Pint to use the default Laravel preset, which includes the standard Laravel coding style rules.
-
If you want to exclude certain files or directories, you can add an
excludearray:{ "preset": "laravel", "exclude": [ "vendor", "bootstrap/cache", "node_modules" ] }This will prevent Pint from formatting files in the
vendor,bootstrap/cache, andnode_modulesdirectories. -
You can also specify the directories to format using the
pathsarray:{ "preset": "laravel", "paths": [ "app", "config", "routes", "database", "tests" ] }This configuration tells Pint to only format files in the specified directories. Properly configuring
pint.jsonallows you to fine-tune Laravel Pint's behavior, ensuring it formats your code exactly as needed and maintains consistency throughout your project.
Installing PHPStan
PHPStan is a static analysis tool that helps you find errors in your code without running it. It's an invaluable tool for catching potential bugs and improving code quality. Static analysis with PHPStan helps catch errors early, reducing the risk of bugs in production and improving overall code robustness.
-
To install PHPStan, use Composer:
composer require phpstan/phpstan --devThis command adds PHPStan as a development dependency.
-
Once installed, you can run PHPStan using the following command:
./vendor/bin/phpstan analyseThis will analyze your codebase and report any errors or potential issues.
Configuring PHPStan
To configure PHPStan, we'll create a phpstan.neon.dist file in the root of our project. This file allows us to customize PHPStan's analysis, such as setting the level of analysis and excluding specific files or directories.
-
Create a new file named
phpstan.neon.distin your project's root directory. -
Add the following basic configuration:
parameters: level: 5 paths: - appThis configuration sets the analysis level to 5 and tells PHPStan to analyze files in the
appdirectory. The level parameter determines the strictness of the analysis, with higher levels reporting more potential issues. Configuringphpstan.neon.distallows you to tailor PHPStan's analysis to your project's specific needs, ensuring comprehensive static analysis and improved code quality. -
You can exclude specific files or directories using the
excludePathsoption:parameters: level: 5 paths: - app excludePaths: - app/ExceptionsThis will exclude the
app/Exceptionsdirectory from analysis. -
You can also specify the error format using the
errorFormatoption:parameters: level: 5 paths: - app errorFormat: tableThis will display errors in a table format, making them easier to read.
Setting Up GitHub Actions for Linting
To automate our code quality checks, we'll set up a GitHub Actions workflow that runs Laravel Pint and PHPStan on every pull request. This ensures that our code is always formatted and analyzed before it's merged into the main branch. Automating code quality checks with GitHub Actions ensures consistent code standards and early detection of potential issues, leading to a more robust and maintainable codebase.
-
Create a new directory named
.github/workflowsin your project's root directory if it doesn't already exist. -
Inside this directory, create a new file named
lint.yml. -
Add the following configuration to
lint.yml:name: Lint on: pull_request: branches: - main jobs: lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Install Dependencies run: composer install --no-interaction --no-progress --no-scripts - name: Run Pint run: ./vendor/bin/pint - name: Run PHPStan run: ./vendor/bin/phpstan analyseThis workflow will:
- Run on every pull request to the
mainbranch. - Use the latest Ubuntu environment.
- Checkout the code.
- Install Composer dependencies.
- Run Laravel Pint to format the code.
- Run PHPStan to analyze the code.
- Run on every pull request to the
-
Commit and push this file to your repository. Now, every pull request will automatically trigger this workflow, ensuring your code quality is always in check.
Documenting Code Quality Setup
Creating documentation for our code quality setup is essential for maintaining and understanding the tools we've configured. A docs/development/code-quality.md file will serve as a central resource for developers to learn about our code quality practices. Documenting your code quality setup ensures that the team understands and follows the established practices, leading to consistent code quality and easier maintenance.
-
Create a new directory named
docsin your project's root directory if it doesn't already exist. -
Inside the
docsdirectory, create another directory nameddevelopment. -
Inside the
developmentdirectory, create a new file namedcode-quality.md. -
Add the following content to
code-quality.md:# Code Quality This document outlines the code quality tools and practices used in this project. ## Laravel Pint Laravel Pint is used for code formatting. It automatically formats the code according to the Laravel style guide. To run Pint locally, use the following command: ```shell ./vendor/bin/pintThe configuration file for Pint is
pint.json.PHPStan
PHPStan is used for static analysis. It helps identify potential errors and bugs in the code without running it.
To run PHPStan locally, use the following command:
./vendor/bin/phpstan analyseThe configuration file for PHPStan is
phpstan.neon.dist.GitHub Actions
Code quality checks are automated using GitHub Actions. The
lint.ymlworkflow runs Pint and PHPStan on every pull request. -
Customize this documentation with any additional information specific to your project.
Testing
To ensure our code quality tools are working correctly, we need to perform local testing. This involves running Laravel Pint and PHPStan locally to verify that they are formatting and analyzing our code as expected. Local testing ensures that your code quality tools are properly configured and functioning correctly before integrating them into your workflow.
-
Run Pint formatting locally:
./vendor/bin/pintCheck if your code is formatted according to the Laravel style guide.
-
Run PHPStan analysis locally:
./vendor/bin/phpstan analyseReview the output for any errors or potential issues.
By performing these tests, you can confirm that your code quality tools are set up correctly and are helping you maintain a clean and robust codebase.
Conclusion
Configuring PHP code quality tools like Laravel Pint and PHPStan is a crucial step in building robust and maintainable applications. By automating code formatting and static analysis, we can ensure that our codebase adheres to best practices and is free of common errors. This guide has walked you through the process of installing, configuring, and integrating these tools into your workflow, setting you up for success in your Laravel projects.
For more information on code quality best practices, visit PHP-FIG.