DEV Community

Cover image for VSCode PHP CS Fixer
Antonio Silva
Antonio Silva

Posted on

VSCode PHP CS Fixer

PHP Coding Standards Fixer

The PHP Coding Standards Fixer (PHP CS Fixer) tool fixes your code to follow standards; whether you want to follow PHP coding standards as defined in the PSR-1, PSR-2, etc., or other community driven ones like the Symfony one. You can also define your (team's) style through configuration.

Requirements

PHP needs to be a minimum version of PHP 7.4.

Installation

Globally (Composer)

To install PHP CS Fixer, install Composer and issue the following command:

composer global require friendsofphp/php-cs-fixer
Enter fullscreen mode Exit fullscreen mode

Globally (homebrew)

brew install php-cs-fixer
Enter fullscreen mode Exit fullscreen mode

Update

Globally (Composer)

You can update php-cs-fixer through this command:

./composer.phar global update friendsofphp/php-cs-fixer
Enter fullscreen mode Exit fullscreen mode

Globally (homebrew)

You can update php-cs-fixer through this command:

brew upgrade php-cs-fixer
Enter fullscreen mode Exit fullscreen mode

Install extension

Extension

Config File

Create the file .php-cs-fixer.php inside the .vscode/ directory and add the content below to the file:

<?php

$config = new PhpCsFixer\Config();

return $config
    ->setRules([
        '@PSR12' => true,
        'new_with_braces' => false,
        'array_indentation' => true,
        'array_syntax' => ['syntax' => 'short'],
        'combine_consecutive_unsets' => true,
        'multiline_whitespace_before_semicolons' => true,
        'single_quote' => true,
        'blank_line_before_statement' => true,
        'braces' => [
            'allow_single_line_closure' => true,
        ],
        'concat_space' => ['spacing' => 'one'],
        'declare_equal_normalize' => true,
        'function_typehint_space' => true,
        'include' => true,
        'lowercase_cast' => true,
        'no_multiline_whitespace_around_double_arrow' => true,
        'no_spaces_around_offset' => true,
        'no_unused_imports' => true,
        'no_whitespace_before_comma_in_array' => true,
        'no_whitespace_in_blank_line' => true,
        'object_operator_without_whitespace' => true,
        'single_blank_line_before_namespace' => true,
        'ternary_operator_spaces' => true,
        'trailing_comma_in_multiline' => true,
        'trim_array_spaces' => true,
        'unary_operator_spaces' => true,
        'binary_operator_spaces' => true,
        'whitespace_after_comma_in_array' => true,
        'single_trait_insert_per_statement' => false,
    ])
    ->setLineEnding("\n");
Enter fullscreen mode Exit fullscreen mode

That's it, every time a file is saved the fixer will be executed.

To install PHP-Cs-Fixer on Windows, just follow this tutorial windows.

Top comments (0)