Home  >  Article  >  Backend Development  >  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?

藏色散人
藏色散人forward
2021-09-14 15:31:294487browse

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

Or download through curl:

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

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

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

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

brew install php-cs-fixer

Or :

brew install homebrew/php/php-cs-fixer

If you need to update later:

php-cs-fixer self-update

If it is installed through homebrew:

brew upgrade php-cs-fixer

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

--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

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

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 -

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

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)
;

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)
;

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)
;

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)
;

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)
;

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:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete