Table of Contents
php-cs-fixer - PHP coding formatting tool
Installation and Update
Usage
Custom configuration
Editor plug-in
Formatting options
Home Backend Development PHP Tutorial Don't you know how to use this php-cs-fixer encoding and formatting tool?

Don't you know how to use this php-cs-fixer encoding and formatting tool?

Sep 14, 2021 pm 03:31 PM
php

php-cs-fixer - PHP coding formatting tool

php-cs-fixer is a code formatting tool. The formatting standards are PSR-1, PSR-2 and some symfony ones. standard. This tool also comes from the same family as symfony, twig and other excellent PHP libraries.

Installation and Update

Requires PHP 5.3.6 or above.

You can download the encapsulated phar package directly: php-cs-fixer.phar;

or download it through wget (the following are the usage on OSX and Linux):

wget http://get.sensiolabs.org/php-cs-fixer.phar -O php-cs-fixer
Copy after login

Or download through curl:

curl http://get.sensiolabs.org/php-cs-fixer.phar -o php-cs-fixer
Copy after login

After the download is completed, give executable permissions, and then move to the bin directory:

sudo chmod a+x php-cs-fixer
sudo mv php-cs-fixer /usr/local/bin/php-cs-fixer
Copy after login

This way you can use it directly anywherephp-cs-fixer command is called.

You can also use Composer to install:

composer global require fabpot/php-cs-fixer
Copy after login

If you are a Mac user, homebrew user and have taped homebrew/php, you can also directly:

brew install php-cs-fixer
Copy after login

Or :

brew install homebrew/php/php-cs-fixer
Copy after login

If you need to update later:

php-cs-fixer self-update
Copy after login

If it is installed through homebrew:

brew upgrade php-cs-fixer
Copy after login

If the executable file is not placed in the bin directory or needs to be used in Windows php php-cs-fixer.phar replaces php-cs-fixer.

Usage

The usage is also very simple. The most basic command parameter is fix. When executed directly, the code will be formatted according to the default standard as much as possible:

# 格式化目录 如果是当前目录的话可以省略目录
php-cs-fixer fix /path/to/dir
# 格式化文件
php-cs-fixer.phar fix /path/to/file
Copy after login

--verbose option is used to display the applied rules. The default is text (txt) format.

--level option is used to control the level of rules to be used:

php-cs-fixer fix /path/to/project --level=psr0
php-cs-fixer fix /path/to/project --level=psr1
php-cs-fixer fix /path/to/project --level=psr2
php-cs-fixer fix /path/to/project --level=symfony
Copy after login

By default, all options of PSR-2 and some additional options are executed (mainly is symfony related). There are also some options that belong to the "contribution level". You can add them selectively through --fixers. Multiple conditions of --fixers must be separated by commas:

php-cs-fixer fix /path/to/dir --fixers=linefeed,short_tag,indentation
Copy after login

If necessary, you can also use -name_of_fixer to set which options are disabled by using a blacklist. If both --fixers and -name_of_fixer are set, the former has higher priority.

Using the --dry-run and --diff commands simultaneously can display the summary that needs to be modified, but does not actually modify it.

You can also check what content will be modified through the following method, but the file will not actually be changed:

cat foo.php | php-cs-fixer fix --diff -
Copy after login

Custom configuration

--config The option can be used to set the selected directory and files for analysis and formatting, but this option can only set some common known projects, such as symfony:

# For the Symfony 2.3+ branch
php-cs-fixer fix /path/to/sf23 --config=sf23
Copy after login

Existing options:

  • default default configuration

  • magento magento project

  • sf23 symfony project

More often, we can customize formatting options and search directories and files through configuration files. Custom configuration is achieved by adding a .php_cs file in the project root directory.

The setting itself is PHP code, and finally returns an instance of Symfony\CS\ConfigInterface. You can set formatting options, levels, files, and directories.

The following is a simple example:

<?php

$finder = Symfony\CS\Finder\DefaultFinder::create()
    ->exclude('somedir') // 忽略 somedir
    ->in(__DIR__) // 当前目录
;

return Symfony\CS\Config\Config::create()
    ->fixers(['strict_param', 'short_array_syntax']) // 添加两个选项
    ->finder($finder)
;
Copy after login

If you want to completely customize the formatting options, you need to clear the formatting level and specify all the required options:

<?php

$finder = Symfony\CS\Finder\DefaultFinder::create()
    ->in(__DIR__)
;

return Symfony\CS\Config\Config::create()
    ->level(Symfony\CS\FixerInterface::NONE_LEVEL)
    ->fixers(['trailing_spaces', 'encoding'])
    ->finder($finder)
;
Copy after login

You can also disable certain options by adding - in front of the option. For example, the following example does not use PSR-0:

<?php

$finder = Symfony\CS\Finder\DefaultFinder::create()
    ->exclude('somedir')
    ->in(__DIR__)
;

return Symfony\CS\Config\Config::create()
    ->fixers(['-psr0'])
    ->finder($finder)
;
Copy after login

Formatting level under default conditions It is symfony (the most strict), you can modify this level:

<?php

return Symfony\CS\Config\Config::create()
    ->level(Symfony\CS\FixerInterface::PSR2_LEVEL)
;
Copy after login

Through the combination of these setting options, you can easily customize the effect you want.

You can also specify the location of the .php_cs file through the --config-file option.

Enabling caching can speed up subsequent executions. Set it by the following method:

<?php

return Symfony\CS\Config\Config::create()
    ->setUsingCache(true)
;
Copy after login

Editor plug-in

The following editor/IDE plug-ins can help you simplify Formatting works:

  • Atom

  • NetBeans

  • PhpStorm

  • Sublime Text

  • Vim

Formatting options

  • psr0 [PSR-0]
    Path and namespace standards for PSR-0

  • ##encoding [PSR-1] The file must be UTF-8 encoded without BOM;


  • short_tag [PSR-1] Only two PHP code tags,
    and , can be used;

  • ##braces [PSR-2]

    All statement blocks must be enclosed in curly braces, and the position and indentation are in compliance with standards;


  • class_definition [PSR-2]

    There can only be one space between class, traits, interfaces keywords and names;


  • elseif [PSR-2]

    Use elseif
    instead of else if;

  • eof_ending [PSR-2]

    The file must end with a blank line;

  • function_call_space [PSR-2]
    When calling functions and methods, there must be no spaces between the function name, method name and parameter expansion;

  • function_declaration [PSR-2]
    The use of spaces when declaring functions needs to comply with PSR-2;

  • indentation [PSR-2]
    Code must be indented using four spaces instead of tabs;

  • line_after_namespace [PSR-2]
    There must be a blank line after the namespace declaration;

  • ##linefeed [PSR-2] All PHP files can only use LF (Unix) ending;


  • lowercase_constants [PSR-2 ] PHP constants true, false and null must be lowercase;


  • lowercase_keywords [PSR-2] PHP keywords must all be lowercase;


  • method_argument_space [PSR-2] When the method is declared and called, the parameters There must be no space before the comma, and there must be one space after the comma;


  • ##multiple_use [PSR-2]

    Each use can only declare one element;


  • ##parenthesis [PSR-2]
  • There cannot be spaces on both sides of the parentheses;


    ##php_closing_tag [PSR-2]
  • Pure PHP files must omit the

    ?> tag;


    single_line_after_imports [PSR-2]
  • Each use statement must be on a separate line, and there must be a blank line after the use statement block;




    ##trailing_spaces [PSR-2]

  • Delete extra spaces after non-blank lines;



  • visibility [PSR-2]

  • Each property and method must specify a scope of
  • public

    , protected Or
    private, abstract and final must be before the scope keyword, static must be after the scope;
    ##array_element_no_space_before_comma [symfony]

    In the array declaration, there cannot be a space before the comma;


  • array_element_white_space_after_comma [symfony]

    In the array declaration, there must be a space after the comma;

  • ##blankline_after_open_tag [symfony]

    There cannot be code on the same line of the PHP start tag, and there must be a blank line below;

  • ##concat_without_spaces [ symfony]

    There cannot be extra spaces on the left and right sides of the dot connector;

  • ##double_arrow_multiline_whitespaces [symfony]

    =>
    There cannot be multiple blank lines at both ends of the operator;

  • ##duplicate_semicolon [symfony]
    Delete duplicate semicolons;

  • ##empty_return [symfony]

    If the return statement does not return anything, just write return. (No need to return null);


  • extra_empty_lines [symfony]

    Delete extra blank lines;


  • function_typehint_space [symfony]

    Fix the missing space problem between function parameters and type hints;


  • include [symfony]

    include
    There needs to be a space between the file path and the file path. The file path does not need to be enclosed in parentheses;

  • join_function [symfony]
    Use join to replace the
    implode
    function;


  • list_commas [symfony] Delete the extra commas in the list statement;

  • method_argument_default_value [symfony]
    Parameters with default values ​​in function parameters cannot be placed before parameters without default values;

  • multiline_array_trailing_comma [symfony]

    The last element of the multiline array should also have a comma;


  • namespace_no_leading_whitespace [symfony]

    There should be no spaces in front of the namespace;


  • ##new_with_braces [symfony]
  • Use New should be followed by parentheses when creating a new instance;


  • no_blank_lines_after_class_opening [symfony]
  • There should be no blank space after the class start tag Line;


    ##no_empty_lines_after_phpdocs [symfony]
  • There should be no blank lines below the beginning of the PHP documentation block;




    object_operator [symfony]
  • T_OBJECT_OPERATOR (->
    ) There should be no Space;

  • operators_spaces [symfony]
    Binary operators have at least one space at both ends;

  • phpdoc_indent [symfony]
    phpdoc should remain indented;

  • ##phpdoc_inline_tag [symfony] Correct the phpdoc inline tag format so that the tag and subsequent content are always on the same line;


  • ##phpdoc_no_access [symfony]

    @access
    should not appear in phpdoc;

  • phpdoc_no_empty_return [symfony]

    @return void
    and @return null should not appear in phpdoc;

  • ##phpdoc_no_package [symfony]
  • @package and
    @subpackage should not appear in phpdoc;

    ##phpdoc_params [symfony]
  • @param, @throws
    , @return, @var, and @type phpdoc tags must be vertically aligned;

    ##phpdoc_scalar [symfony]

  • phpdoc scalar type declaration should use
  • int

    instead of integer,
    bool instead of boolean, float instead of real or double
    ##phpdoc_separation [symfony]

    Comments with the same attributes in phpdoc should be put together, and different attributes There should be a blank line separating them;


  • phpdoc_short_description [symfony]

    The brief description of phpdoc should be separated by
  • .
  • ,

    ! or ?
    ending; ##phpdoc_to_comment [symfony]

    Document blocks should all be structured elements;


  • phpdoc_trim [symfony]

    Except for the very beginning of the document block And the last part, phpdoc should have content at the beginning and end;

  • ##phpdoc_type_to_var [symfony]


    @type

    needs to be replaced by
  • @var
  • ;


    ##phpdoc_types [symfony] in phpdoc Case should be used correctly;

  • phpdoc_var_without_name [symfony]

    @var
    and

    @ type
  • Variable names should not be included in comments;

  • pre_increment [symfony] should not be used
    i
    or

    --i
  • usage;

  • ##print_to_echo [symfony] if possible , use echo
    instead of
    print

    statement;

  • ##remove_leading_slash_use [symfony] Delete the empty line before use;

  • remove_lines_between_uses [symfony]
    Delete use Empty lines in statement blocks;

  • return [symfony]
    return should be preceded by A blank line;

  • self_accessor [symfony]
    Use self in the current class instead of the class name ;

  • ##short_bool_cast [symfony]
    bool Two exclamation marks should not be used before type data;

  • ##single_array_no_trailing_comma [symfony]

    There should be no space after the last element of a PHP single-line array;


    single_blank_line_before_namespace [symfony]
  • There should be a blank line before the namespace declaration;




    single_quote [symfony]
  • Simple strings should use single quotes instead of double quotes;




    ##spaces_after_semicolon [symfony]

  • Repair the spaces after the semicolon;


  • ##spaces_before_semicolon [symfony]

    Disable single-line spaces and separators How to write the number;


  • spaces_cast [symfony]

    There should be a space between the variable and the modifier;

  • ##standardize_not_equal [symfony]

    Use

    <>
  • instead of
  • !=

    ;


  • ternary_spaces [symfony]
  • Standardize the spaces between ternary operators;
    trim_array_spaces [symfony]

    The array needs to be formatted similar to function/method parameters, with no blank lines above and below;


  • unalign_double_arrow [symfony]

    Unalign

    =>


  • ## unalign_equals [symfony]

    Does not equal the sign;
  • unary_operators_spaces [symfony]
    Unary operators and operands need to be adjacent;

  • unneeded_control_parentheses [symfony]
    Remove excess parentheses in control structure statements;

  • ##unused_use [symfony] Delete unused use statements;


  • whitespacy_lines [symfony] Delete extra spaces in blank lines;

In addition to the above options, there are also some user-contributed options, which will not be introduced one by one here.

Every person and every team may have their own opinions on whether the coding style is unified and what standards should be implemented. Here is just an introduction to this tool. As for how to choose it, it is up to you. If it is an open source project, you can also try StyleCI.

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of Don't you know how to use this php-cs-fixer encoding and formatting tool?. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles