php cs fixer phar
Php cs fixer phar
Автоформатирование кода: PHP CodeSniffer и PHP CS Fixer
На laracasts есть замечательное видео по этой теме в контексте PhpStorm, здесь же пойдёт речь о том, чего не рассказывал в том видео Джефри (ну а если хотите настроить фиксер под Sublime, смотрите эту статью).
PHP CodeSniffer
Давайте начнём с PHP CodeSniffer. Этот инструмент поможет выявить нарушения форматирования, при надлежащей настройке PhpStorm будет вас об этом информировать путём выделения проблемных частей кода. Кроме всего прочего мы можем воспользоваться консолью для вывода информации об ошибках.
Установка
Используемый стандарт
Также хорошенько подумайте о том, достаточно ли набора правил стандарта. Вполне возможно, что ответ будет отрицательным. Перечитайте документацию, и добавьте те, которые Вам понадобятся.
Можно каждый раз в консоли руками пописывать какие-то дополнительные правила или условия, указывать стандарт и т.д. Но, мы же понимаем, что это не оптимальный вариант. Поэтому, в корне проекта создадим файл phpcs.xml и добавим туда следующее (в качестве примера использую код из текущего проекта):
Пояснения:
Основные команды
Вывести список установленных стандартов:
Вывести список снифов, используемых в конкретном стандарте:
Проверить форматирование файла file.php :
Проверить весь проект :
Проверить весь проект с выводом информации о том, где конткретно были встречены ошибки:
Вывести код-репорт, т.е. отчёт со сниппетами кода, где были обнаружены ошибки:
Есть ещё и другие команды, но, по моему мнению, вполне хватает перечисленных. Справедливости ради стоит отметить, что PHP CoedSniffer также включает и code beautifier fixer, т.е. можно исправить ошибки (читай отформатировать) командой:
но я всё же предпочитаю php-cs-fixer
PHP CS Fixer
Установка
Опять-таки подумайте устанвливать интсрумент глобально, или для каждого проекта. Второй вариант:
Если выбираете глобальную установку, убедитесь, что в переменную PATH добавлен путь к бинарным файлам composer-a. Проверьте это командой:
Пользовательские правила
Автоформат
Основные команды
Вывести список команд:
Вывести описание правил входящих в конкретный стандарт:
И, как уже был сказано, отформатировать (для разнообразия укажем стандарт Symfony):
В случае с fixer-ом я предпочитаю использовать не консоль, а настроить PhpStorm для использования этого инструмента, добавить горячие клавиши и использовать по месту в конкретных файлах.
Git pre-commit hook
Подведём итоги. Мы используем:
Внимание: php-cs-fixer исправит только те ошибки, которые он может исправить, не более. Например, если у Вас не написан phpdoc, fixer за вас его не напишет. Помните об этом.
realrashid / Install PHP-CS-Fixer.md
Installing PHP-CS-Fixer for VsCode on Windows
Install PHP-CS-FIXER Using Composer
composer global require friendsofphp/php-cs-fixer
after successfully installation of PHP-CS-FIXER
now install PHP-CS-FIXER VSCODE Extension
in VSCODE User Settings press Ctrl+, to get VSCODE User Settings
That’s all! Hope this will help you!
This comment has been minimized.
Copy link Quote reply
ryanbriscall commented Apr 6, 2018
There’s no php-cs-fixer.bat, and that executablePath wouldn’t work unless the environment variable PATH is updated. This gist is lacking a lot of information.
This comment has been minimized.
Copy link Quote reply
realrashid commented Apr 9, 2018
share your issue what issue are you facing and your os info.
This comment has been minimized.
Copy link Quote reply
trevorhawes commented May 25, 2018
We need a full step by step instructions on how to install php cs fixer in windows, including the fact that PHP needs to be installed (how, where, what to set up) then exactly what to do next. No luck for me so far. So hard to find good info.
This comment has been minimized.
Copy link Quote reply
trevorhawes commented May 26, 2018
Is there a way to get it to work without having to install composer. I just want to format some php, not have the whole composer thing
This comment has been minimized.
Copy link Quote reply
jaimecosme commented Jun 23, 2018
I extracted both php and php-cs-fixer on the same folder without installing composer.
Php cs fixer phar
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.
It can modernize your code (like converting the pow function to the ** operator on PHP 5.6) and (micro) optimize it.
If you are already using a linter to identify coding standards problems in your code, you know that fixing them by hand is tedious, especially on large projects. This tool does not only detect them, but also fixes them for you.
The recommended way to install PHP CS Fixer is to use Composer in a dedicated composer.json file in your project, for example in the tools/php-cs-fixer directory:
For more details and other installation methods, see installation instructions.
Assuming you installed PHP CS Fixer as instructed above, you can run the following command to fix the files PHP files in the src directory:
See usage, list of built-in rules, list of rule sets and configuration file documentation for more details.
If you need to apply code styles that are not supported by the tool, you can create custom rules.
Dedicated plugins exist for:
The PHP CS Fixer is maintained on GitHub at https://github.com/FriendsOfPHP/PHP-CS-Fixer. Bug reports and ideas about new features are welcome there.
You can reach us at https://gitter.im/PHP-CS-Fixer/Lobby about the project, configuration, possible improvements, ideas and questions, please visit us!
The tool comes with quite a few built-in fixers, but everyone is more than welcome to contribute more of them.
About
A tool to automatically fix PHP Coding Standards issues
PHP CS Fixer
In addition to built-in coding assistance, PhpStorm provides checking the source code through integration with the PHP CS Fixer tool, which detects coding standards problems in your code.
To use PHP CS Fixer from PhpStorm instead of command line, you need to register it in PhpStorm and configure it as a PhpStorm code inspection. Once installed and enabled in PhpStorm, the tool is available in any opened PHP file, and no additional steps are required to launch it. The on-the-fly code check is activated upon every update in the file thus making it easy to get rid of discovered problems.
Errors and warnings reported by PHP CS Fixer on-the-fly are displayed as popup messages. When the tool is run in the batch mode, the errors and warnings are displayed in the Inspection Results tool window. Each message has the PHP CS Fixer prefix to distinguish it from PhpStorm internal inspections.
You can have predefined rules applied or define your own custom set of rules.
Prerequisites
Prior to integrating PHP CS Fixer in PhpStorm, make sure the following prerequisites are met:
You are working with PHP CS Fixer version 2.8.0 and later.
For Docker Compose-based remote interpreters, make sure to use exec mode to avoid spawning additional containers.
Install and configure PHP CS Fixer
PHP CS Fixer scripts can be used as local scripts, the scripts associated with PHP interpreters, or scripts declared as project dependencies and installed via Composer, which is the preferable and recommended way.
Install PHP CS Fixer with Composer
Before you start, make sure Composer is installed on your machine and initialized in the current project as described in Composer dependency manager.
When you install PHP CS Fixer with Composer, PhpStorm automatically downloads the necessary scripts, registers them in the IDE, and, optionally, enables and configures the corresponding code inspection.
Do one of the following:
Click the Install shortcut link on top of the editor panel.
If the Non-installed Composer packages inspection is enabled, PhpStorm will highlight the declared dependencies that are not currently installed. Press Alt+Enter and select whether you want to install a specific dependency or all dependencies at once.
Reset PHP CS Fixer configuration
After PHP CS Fixer is initially configured, further modifications in composer.json will not affect the inspection configuration. To apply newer changes, reset the PHP CS Fixer configuration.
In the PHP CS Fixer dialog that opens, empty the PHP CS Fixer path field.
Update the project Composer dependencies by clicking Update on top of the composer.json editor panel. See Update dependencies for details.
Configure PHP CS Fixer manually
Choose a PHP CS Fixer script to use
On the Quality Tools page that opens, expand the PHP CS Fixer area. From the Configuration list, choose the PHP CS Fixer script:
To use the script associated with a specific remote PHP interpreter, choose the name of this interpreter.
Configure a local PHP CS Fixer script
Download and install the PHP CS Fixer scripts.
To check the PHP CS Fixer installation, switch to the installation directory and run the following command:
If the tool is available, you will get a message in the following format:
Register the local PHP CS Fixer script in PhpStorm:
If necessary, in the Tool process timeout field, specify how long you want PhpStorm to wait for a result from PHP CS Fixer, whereupon the process is terminated to prevent excessive CPU and memory usage.
Configure a PHP CS Fixer script associated with a PHP interpreter
If necessary, in the Tool process timeout field, specify how long you want PhpStorm to wait for a result from PHP CS Fixer, whereupon the process is terminated to prevent excessive CPU and memory usage.
Configure PHP CS Fixer as a PhpStorm inspection
Configure the PHP CS Fixer inspection with Composer
After PHP CS Fixer is initially configured, further modifications in composer.json will not affect the inspection configuration. To apply newer changes, reset the PHP CS Fixer configuration on the PHP | Quality Tools page of the Settings/Preferences dialog Ctrl+Alt+S and update project dependencies.
Configure the PHP CS Fixer inspection manually
On the right-hand pane of the page, configure the PHP CS Fixer tool using the controls in the Options area:
From the Severity list, choose the severity degree for the PHP CS Fixer inspection. The selected value determines how serious the detected discrepancies will be treated by PhpStorm and presented in the inspection results.
From the Scope list, choose the scope to limit the inspection application to.
To allow risky rules, that is, the rules that can change code behavior, select the Allow risky rules for built-in rulesets checkbox. By default, risky rules are not allowed.
Appoint the coding standard to apply.
To use one of the predefined coding standards, select it the Coding standard list, appoint the coding style to check your code against. The list contains all the coding standards declared inside the main php-cs-fixer directory structure.
Share a custom coding style with the team
Put the root directory of your coding standard under the project root.
Run PHP CS Fixer in the batch mode
View the inspection results in the Inspection results tool window. Errors and warnings reported by PHP CS Fixer are prefixed with PHP CS Fixer to distinguish them from PhpStorm internal inspections.
Exclude files from PHP CS Fixer inspection
On the Quality Tools page that opens, expand the PHP CS Fixer area and click the Show ignored files link.
Php cs fixer phar
Docker image for php-cs-fixer
ansible-lint • ansible • awesome-ci • bandit • black • checkmake • eslint • file-lint • gofmt • goimports • golint • jsonlint • linkcheck • mypy • php-cs-fixer • phpcbf • phpcs • phplint • pycodestyle • pydocstyle • pylint • terraform-docs • terragrunt-fmt • terragrunt • yamlfmt • yamllint
Visit cytopia/makefiles for seamless project integration, minimum required best-practice code linting and CI.
View Dockerfile on GitHub.
Available Docker image versions
Docker images for PHP Coding Standards Fixer come with all available PHP versions. In doubt use latest tag.
Latest stable php-cs-fixer version
Docker tag | php-cs-fixer version | PHP version |
---|---|---|
latest | latest stable | latest stable |
latest-php8.0 | latest stable | latest stable 8.0.x |
latest-php7.4 | latest stable | latest stable 7.4.x |
latest-php7.3 | latest stable | latest stable 7.3.x |
latest-php7.2 | latest stable | latest stable 7.2.x |
latest-php7.1 | latest stable | latest stable 7.1.x |
Latest stable php-cs-fixer 3.x.x version
Docker tag | php-cs-fixer version | PHP version |
---|---|---|
3 | latest stable 3.x.x | latest stable |
3-php8.0 | latest stable 3.x.x | latest stable 8.0.x |
3-php7.4 | latest stable 3.x.x | latest stable 7.4.x |
3-php7.3 | latest stable 3.x.x | latest stable 7.3.x |
3-php7.2 | latest stable 3.x.x | latest stable 7.2.x |
3-php7.1 | latest stable 3.x.x | latest stable 7.1.x |
Latest stable php-cs-fixer 2.x.x version
Docker tag | php-cs-fixer version | PHP version |
---|---|---|
2 | latest stable 2.x.x | latest stable |
2-php8.0 | latest stable 2.x.x | latest stable 8.0.x |
2-php7.4 | latest stable 2.x.x | latest stable 7.4.x |
2-php7.3 | latest stable 2.x.x | latest stable 7.3.x |
2-php7.2 | latest stable 2.x.x | latest stable 7.2.x |
2-php7.1 | latest stable 2.x.x | latest stable 7.1.x |
2-php7.0 | latest stable 2.x.x | latest stable 7.0.x |
2-php5.6 | latest stable 2.x.x | latest stable 5.6.x |
Latest stable php-cs-fixer 1.x.x version
Docker tag | php-cs-fixer version | PHP version |
---|---|---|
1 | latest stable 1.x.x | latest stable supported version |
1-php7.1 | latest stable 1.x.x | latest stable 7.1.x |
1-php7.0 | latest stable 1.x.x | latest stable 7.0.x |
1-php5.6 | latest stable 1.x.x | latest stable 5.6.x |
The working directory inside the Docker container is /data/ and should be mounted locally to the root of your project.
You can add the following Makefile to your project for easy generation of php-cs-fixer.
Travis CI integration
Save yourself from installing lot’s of dependencies and pick a dockerized version of your favourite linter below for reproducible local or remote CI tests:
GitHub | DockerHub | Type | Description |
---|---|---|---|
awesome-ci | Basic | Tools for git, file and static source code analysis | |
file-lint | Basic | Baisc source code analysis | |
linkcheck | Basic | Search for URLs in files and validate their HTTP status code | |
ansible | Ansible | Multiple versions and flavours of Ansible | |
ansible-lint | Ansible | Lint Ansible | |
gofmt | Go | Format Go source code [1] | |
goimports | Go | Format Go source code [1] | |
golint | Go | Lint Go code | |
eslint | Javascript | Lint Javascript code | |
jsonlint | JSON | Lint JSON files [1] | |
checkmake | Make | Lint Makefiles | |
phpcbf | PHP | PHP Code Beautifier and Fixer | |
phpcs | PHP | PHP Code Sniffer | |
phplint | PHP | PHP Code Linter [1] | |
php-cs-fixer | PHP | PHP Coding Standards Fixer | |
bandit | Python | A security linter from PyCQA | |
black | Python | The uncompromising Python code formatter | |
mypy | Python | Static source code analysis | |
pycodestyle | Python | Python style guide checker | |
pydocstyle | Python | Python docstyle checker | |
pylint | Python | Python source code, bug and quality checker | |
terraform-docs | Terraform | Terraform doc generator (TF 0.12 ready) [1] | |
terragrunt | Terraform | Terragrunt and Terraform | |
terragrunt-fmt | Terraform | terraform fmt for Terragrunt files [1] | |
yamlfmt | Yaml | Format Yaml files [1] | |
yamllint | Yaml | Lint Yaml files |
[1] Uses a shell wrapper to add enhanced functionality not available by original project.
Visit cytopia/makefiles for dependency-less, seamless project integration and minimum required best-practice code linting for CI. The provided Makefiles will only require GNU Make and Docker itself removing the need to install anything else.