How do I lint and format PHP code (PHP_CodeSniffer, PHP-CS-Fixer)?

Linting and formatting PHP code is essential for maintaining code quality and consistency. Two popular tools for this purpose are PHP_CodeSniffer and PHP-CS-Fixer. Below, you will find examples of how to use both tools effectively.

PHP_CodeSniffer

PHP_CodeSniffer helps detect violations of coding standards in PHP code. It not only highlights issues but can also automatically fix some of them.

// Install PHP_CodeSniffer using Composer composer global require "squizlabs/php_codesniffer=*" // Run PHP_CodeSniffer on your PHP file phpcs /path/to/your/file.php // To automatically fix issues, use the following command phpcbf /path/to/your/file.php

PHP-CS-Fixer

PHP-CS-Fixer is a tool that automatically formats PHP code according to predefined standards.

// Install PHP-CS-Fixer using Composer composer global require "friendsofphp/php-cs-fixer" // Create a .php_cs configuration file (optional) touch .php_cs // In the .php_cs file, specify the rules and files to be fixed // Run PHP-CS-Fixer on your PHP file php-cs-fixer fix /path/to/your/file.php

Keywords: PHP_CodeSniffer PHP-CS-Fixer Linting PHP Formatting PHP Code PHP Coding Standards