Home Backend Development PHP Tutorial How to use PHP-CS-Fixer for code style checking in PHP

How to use PHP-CS-Fixer for code style checking in PHP

Jun 27, 2023 pm 01:27 PM
coding style php-cs-fixer examine

During the development process, good coding style is an important factor in improving code quality and readability. As one of the most widely used programming languages ​​in the market today, PHP's code style inspection is also particularly important. Here, we will introduce a PHP code style checking tool-PHP-CS-Fixer, and explain in detail how to perform code style checking on it.

First of all, we need to understand what PHP-CS-Fixer is. PHP-CS-Fixer is a PHP code style checking tool created by the Symfony framework. Through this tool, we can easily maintain the consistency and high-quality coding style of PHP projects, thereby improving the readability and maintainability of the code.

So, how to use PHP-CS-Fixer for code style checking? The following are the detailed steps:

Step 1: Install PHP-CS-Fixer

First, we need to use Composer to install PHP-CS-Fixer. Composer is the most popular dependency manager in PHP and can be used to install and manage PHP dependencies.

Run the following command in the command line to install PHP-CS-Fixer:

composer require --dev friendsofphp/php-cs-fixer
Copy after login

Step 2: Create the PHP-CS-Fixer configuration file

Next, We need to create a PHP-CS-Fixer configuration file. This configuration file will specify details such as idioms, indentation, spaces, newlines, etc., as well as the rules that need to be followed, etc. Rules can be modified or added based on individual or team needs.

Create the file ".php_cs" in the project root directory and paste the following code into it:

<?php

$finder = SymfonyComponentFinderFinder::create()
    ->exclude('vendor')
    ->exclude('node_modules')
    ->exclude('storage')
    ->exclude('public')
    ->in(__DIR__)
    ->name('*.php')
    ->notName('*.blade.php')
    ->ignoreDotFiles(true)
    ->ignoreVCS(true);

return SymfonyCSConfigConfig::create()
    ->level(SymfonyCSFixerInterface::PSR2_LEVEL)
    ->fixers([
        'array_syntax' => ['syntax' => 'short'],
        'blank_line_after_opening_tag',
        'braces',
        'cast_spaces',
        'class_definition',
        'concat_without_spaces',
        'declare_equal_normalize',
        'function_call_space',
        'function_declaration',
        'indentation',
        'line_after_namespace',
        'linefeed',
        'lowercase_constants',
        'lowercase_keywords',
        'method_argument_space',
        'native_function_casing',
        'new_with_braces',
        'no_blank_lines_after_class_opening',
        'no_empty_phpdoc',
        'no_empty_statement',
        'no_extra_blank_lines',
        'no_leading_import_slash',
        'no_leading_namespace_whitespace',
        'no_mixed_echo_print',
        'no_multiline_whitespace_before_semicolons',
        'no_short_bool_cast',
        'no_spaces_after_function_name',
        'no_spaces_inside_parenthesis',
        'no_trailing_comma_in_list_call',
        'no_trailing_comma_in_singleline_array',
        'no_trailing_whitespace',
        'no_trailing_whitespace_in_comment',
        'no_unneeded_control_parentheses',
        'no_unused_imports',
        'no_whitespace_before_comma_in_array',
        'no_whitespace_in_blank_line',
        'normalize_index_brace',
        'object_operator', 
        'operators_spaces',
        'php_closing_tag',
        'phpdoc_align',
        'phpdoc_no_access',
        'phpdoc_no_empty_return',
        'phpdoc_no_package',
        'phpdoc_scalar',
        'phpdoc_single_line_var_spacing',
        'phpdoc_summary',
        'phpdoc_to_comment',
        'phpdoc_trim',
        'phpdoc_type_to_var',
        'phpdoc_var_without_name',
        'remove_leading_slash_use',
        'remove_lines_between_uses',
        'return',
        'self_accessor',
        'short_array_syntax',
        'single_array_no_trailing_comma',
        'single_blank_line_before_namespace',
        'single_quote',
        'spaces_before_semicolon',
        'spaces_cast',
        'standardize_not_equals',
        'ternary_spaces',
        'trim_array_spaces',
        'unalign_double_arrow',
        'unalign_equals',
        'unary_operators_spaces',
        'unused_use',
    ])
    ->finder($finder);
Copy after login

The above configuration contains a series of rules, such as:

  • Use PSR-2 code style specifications;
  • prohibit the use of useless spaces;
  • prohibit the occurrence of multiple namespaces in a single file;
  • prohibit the use of array initialization Extra commas, etc.

These rules can be modified according to personal preference. In this example, we use some rules recommended by the Symfony framework.

Step 3: Run PHP-CS-Fixer

Finally, we can use PHP-CS-Fixer to check our PHP code. Just enter the following command on the command line:

vendor/bin/php-cs-fixer fix
Copy after login

This command will find all PHP files in the entire project and modify the improper code format used in them. Of course, this command can also take some parameters to check the code style according to the specified rules, for example:

vendor/bin/php-cs-fixer fix src/ --rules=@PSR2
Copy after login

The above command will check the PSR-2 style of the code in the "src" folder.

Summary:

PHP-CS-Fixer is a very practical PHP code style checking tool, which can help programmers maintain the consistency and readability of project code. Using the steps introduced above, we can easily use PHP-CS-Fixer to perform code style checking, thereby improving the quality of the code.

The above is the detailed content of How to use PHP-CS-Fixer for code style checking in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to check if application is open in Python? How to check if application is open in Python? Aug 26, 2023 pm 06:49 PM

The program being executed is called a process. A process can be an application running on the current operating system or an application related to the operating system. If an application is tied to the operating system, it first creates a process to execute itself. Other applications rely on operating system services for execution. Most applications are operating system services and background applications that maintain the operating system, software, and hardware. In python we have different methods to check if application is open or not. Let’s learn about them in detail one by one. Using the psutil.process_iter() function psutil is a module in Python that provides users with an interface to retrieve information about running processes and system utilization.

How to check if an object is iterable in Python? How to check if an object is iterable in Python? Aug 25, 2023 pm 10:05 PM

An iterable object is an object whose all elements can be iterated over using a loop or iterable function. Lists, strings, dictionaries, tuples, etc. are all called iterable objects. In Python language, there are various ways to check whether an object is iterable. Let’s take a look one by one. Using Loops In Python, we have two looping techniques, one is using "for" loop and the other is using "while" loop. Using either of these two loops, we can check if a given object is iterable. Example In this example, we will try to iterate an object using "for" loop and check if it is iterated or not. Below is the code. l=["apple",22,"orang

Spellcheck not working in Teams [Fixed] Spellcheck not working in Teams [Fixed] Mar 06, 2024 am 09:10 AM

We've started noticing that sometimes spellcheck stops working for Teams. Spell check is an essential tool for effective communication, and any attack on it can cause considerable disruption to workflow. In this article, we'll explore common reasons why spell check might not be working as expected, and how to restore it to its previous state. So, if spell check is not working in Teams, follow the solutions mentioned in this article. Why doesn't Microsoft spell check work? There may be several reasons why Microsoft spell check is not working properly. These reasons include incompatible language settings, disabled spell check function, damaged MSTeam or MSOffice installation, etc. Also, outdated MSTeams and MSOf

How to check SSD health status in Windows 11? How to check SSD health status on Win11 How to check SSD health status in Windows 11? How to check SSD health status on Win11 Feb 14, 2024 pm 08:21 PM

How to check SSD health status in Windows 11? For their fast read, write, and access speeds, SSDs are quickly replacing HDDs, but even though they are more reliable, you still need to check the health of your SSDs in Windows 11. How to operate it? In this tutorial, the editor will share with you the method. Method 1: Use WMIC1, use the key combination Win+R, type wmic, and then press or click OK. Enter2. Now, type or paste the following command to check the SSD health status: diskdrivegetstatus If you receive the "Status: OK" message, your SSD drive is operating normally.

How to check if a string starts with a specific character in Golang? How to check if a string starts with a specific character in Golang? Mar 12, 2024 pm 09:42 PM

How to check if a string starts with a specific character in Golang? When programming in Golang, you often encounter situations where you need to check whether a string begins with a specific character. To meet this requirement, we can use the functions provided by the strings package in Golang to achieve this. Next, we will introduce in detail how to use Golang to check whether a string starts with a specific character, with specific code examples. In Golang, we can use HasPrefix from the strings package

How to check if ArrayList contains a certain element in Java? How to check if ArrayList contains a certain element in Java? Sep 03, 2023 pm 04:09 PM

You can use the contains() method of the List interface to check whether an object exists in the list. contains() method booleancontains(Objecto) Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null?e==null:o.equals(e)). Parameter c - the element whose presence in this list is to be tested. Return Value Returns true if this list contains the specified element. Throws ClassCastException - if the specified element's type is incompatible with this list (optional). NullP

Write a program in C language to check if a given year is a leap year or not Write a program in C language to check if a given year is a leap year or not Sep 20, 2023 pm 03:33 PM

A leap year has 366 days, while an ordinary year has 365 days. The task is to check whether a given year is a leap year through a program. The logic of the judgment can be implemented by checking whether the year is divisible by 400 or 4, but if it is not divisible by these two numbers, it is an ordinary year. ExampleInput-:year=2000Output-:2000isaLeapYearInput-:year=101Output-:101isnotaLeapyear algorithmStartStep1-&gt;declarefunctionbooltocheckifyearifaleapyearornotboolcheck(intye

Detailed introduction to the tutorial of changing win11 to win10 system Detailed introduction to the tutorial of changing win11 to win10 system Jul 08, 2023 pm 09:21 PM

Microsoft officially announced the win11 system on June 24. You can see that the user interface, start menu, etc. are very similar to those found in Windows 10X. Some friends found that they were not used to using the preview version and wanted to change it to win10 system. So how do we do it? Let’s take a look at the tutorial on changing win11 to win10 system and learn it together. 1. The first step is to open new settings from Windows 11. Here you need to go to the system settings shown in the image. 2. Under System Settings, select the "Recovery" option. Here, you will be able to see the “Previous versions of windows” option. You will also see a "Back" button next to it, click this button. 3. You can specify to return

See all articles