Перейти к содержимому

Php cs fixer что это

  • автор:

Validating your PHP code on the fly

It’s amazing how much time you can loose while running PHP tests. First you alter your code or test. Next you start your test and wait for it to finish. Finally you find out you messed up and start the process all over again. In this article I am going to show you how to automate PHP testing, so you can focus on adding business value to your application.

For this article I created a simple Zend Framework 2 application with Phpspec tests. Even though this article focuses on these 2 packages, it is possible to create this kind of automation for every possible package.

Application structure

First, let’s take a look at the directory structure. In the representation below, you can see a default ZF2 skeleton. The root folder contains the directories config, module, public and vendor. The `config` folder provides the application configuration. In the `module` folder you can see 2 modules that should be tested: Export and Import. Next you can find the public directory which will bootstrap the application. And finally there is the vendor folder that will be filled with dependencies by Composer.

Configuring composer

Because nobody wants to download all the dependencies manually, we will be using composer to get the required packages. We also want to configure composer to automatically load our custom modules: Export and Import. This way, no additional autoloading is required and Phpspec will be able to find all classes by itself.

composer.json

As you can see, composer will download Zend Framework 2 to the vendor directory. When you add the option `—dev` during the installation, Phpspec and PHP-CS-Fixer will also be downloaded. The last part of this configuration file will provide autoloading for the custom Export and Import module. To download and install all the dependencies, one command is being used:

Configuring phpspec

As you can see in the directory overview, there is already a spec folder available. The Phpspec tests will be placed in this directory. This way, every module has it’s own scope and can be tested separately.

Now the tricky part: let’s tell Phpspec where to find the custom source and spec files. Because we need to test multiple modules on multiple locations, we need to add multiple test suites to Phpspec. This is done by creating a phpspec.yml file in the root folder of the application. A test suite describes where the source and spec files of a custom namespace are located. Let’s take a look at the configuration file for our application:

phpspec.yml

One of the downsides of Phpspec is that, at the moment, you can not run suites based on suite name. To test this configuration, you can run following commands:

Configuring php-cs-fixer

Everybody wants clean, readable and maintainable code. That is why the code of the modules should be validated against the desired PHP standards. In this case, we want to check our classes against the PSR2 standard. Per module, you should add a file called .php_cs in the root directory of the module. In this file you can tell the Php-CS-Fixer which paths to check and add some default configuration settings.

.php_cs

To test this configuration, you can run following commands:

Automate the testing process

Before the automation, every time you change a file in your module, you need to run Phpspec and occasionally the Php-CS-Fixer to validate your code. Because you have to define which module to check every time you run the command, you will spend some time searching for the right command in your console. A better way is to automate this process, so that a file change will trigger the command to test your code. This will save you some time and will give you an indication of when and where you messed up. What was that tool again to automate tasks? Exactly: Grunt!

There are some grunt plugins that can be used to automate PHP validation. In this article we are using Phpspec, but there are also plugins for other testing libraries like Phpunit and Behat. In the next part, I will tell you how to test your code on syntax errors, coding standard errors and bad functionality.

Grunt-Phpspec

For validating bad functionality we use grunt-phpspec. This tool will run Phpspec on our custom modules. For every PHP module we need to check, an entry in the configuration is required. Here is the sample configuration for the current project:

To run spec tests, you can use following commands:

Grunt-php-cs-fixer

The tool for validating PHP coding standards is grunt-php-cs-fixer. As the name suggests: it does not only check for issues, it also fixes them. Therefore it must be possible to validate and fix errors with Grunt. This can be done by adding the parameter `—fixcs`. Here is the sample configuration for the current project:

To run the cs fixer, you can use following commands:

Grunt-Phplint

To validate PHP files for syntax errors you can use the commnd `php -l`. For automation, there is also a Grunt plugin available named grunt-phplint. This tool is added to the test suite to make sure the CS-fixer and spec tests only run when there is no syntax error. Here is the sample configuration for the current project:

To run PHP lint, you can use following commands:

Grunt-watch

Now that we configured all tasks to validate the PHP code, we want the tests to run every time we change a class or spec test in our module. This is where grunt-contrib-watch comes in to play. This task will listen for file changes and will configured tasks for these files. When one of the tasks fail, the other tasks will not run. This is why I decided to run the tests in the order: lint, csfixer, phpspec. Here is the sample configuration for the current project:

To start the watcher and automate the tests, you only have to use one command:

Run all tests in one

For Continious Integration it would be nice if all tests could be run in one command. Well off course this is possible! It is just one line of configuration:

To start the complete test, you can use following command:

Conclusion

As you can see there are some tools to configure. Once the tools are configured, this set-up will save you some valuable time while testing your code. I highly recommend you to use a similar set-up because it is very easy to use yet very powerful. You won’t regret!

whois VeeWee

Hi there!

Glad you made it to my blog. Please feel free to take a look around. You will find some interesting stuff, mostly about web development and PHP.

PHP CS Fixer (Prettier for PHP)

This extension requires almost zero configuration to format .php files. It uses v3.15.1 of cs.symfony.com by default but that’s easily replaceable. As long as PHP 7+ is installed on your system and in your PATH, the extension should work out of the box.

Extension Optional Settings

This extension contributes the following settings:

  • php-cs-fixer.toolPath : The path to the php-cs-fixer tool (default: "")
  • php-cs-fixer.useCache : Use a cache file when fixing files (—using-cache) (default: false)
  • php-cs-fixer.allowRisky : Determines whether risky rules are allowed (—allow-risky) (default: false)
  • php-cs-fixer.config : Path to a config file (—config) (default: "WorkspaceFolder/.php-cs-fixer.php" OR "WorkspaceFolder/.php-cs-fixer.dist.php")
  • php-cs-fixer.rules : Rules to use when fixing files (—rules) (default: "@PSR12,@PSR1,@PSR2,@Symfony,-yoda_style")
  • php-cs-fixer.fixOnSave : Runs fix command on save (default: true)

Adding PHP CS Fixer from a composer dependency

You can require PHP CS Fixer as composer dependency in your project and the extension will load it automatically for you.

If extension could not find/load the binary from /vendor/bin/php-cs-fixer , it would default to the binary included in extension.

Manually adding PHP CS Fixer binary file?

Download the required file version from above link and provide the file path to the extension.

Open settings.json file (Ctrl + Shift + P) and add the following setting:

Config File

This extension formats .php files based on specified rules. Commonly these rules are defined in a .php-cs-fixer.dist.php OR .php-cs-fixer.php config file inside your project root path. The extension would try to pick a config file with above filenames, if not found it uses default rules.

You can also define a global config file which can be used accross all projects.

Open settings.json file (Ctrl + Shift + P) and add the following setting:

Not sure which rules to add?

Try out following config rules. Try to remove a rule and observe the changes.

PHP Coding Standards fixer

Khaydarov Murod

Стандарты оформления — это набор правил, в которых оговаривается внешний вид кода: где ставятся пробелы, где нужны пустые строки, какие кавычки использовать и так далее.

Они помогают приводить код к единому виду. Это важно для командной работы, изучения или доработки open-source программ — разбираться в чужом коде проще и быстрее. Потратив немного времени на внедрение стандартов оформления в вашей работе вы получите гарантированный выигрыш в продуктивности: читать чужой код будет так же легко, как и свой.

Существует несколько стандартов оформления кода. Для PHP наиболее распространены — Zend Coding Standard, PEAR и PSR. В статье рассмотрим способ автоматического оформления кода по стандарту PSR. Для этого существует удобная библиотека php-cs-fixer.

Установка

Установить php-cs-fixer можно глобально или локально. При локальной установке библиотека будет сохранена в папке vendor вашего проекта.

Cкачать программу можно напрямую из репозитория, но мы для удобства воспользуемся менеджером пакетов Composer.

Глобальная установка бывает удобна для использования в нескольких проектах, но с разными стилистическими правилами. Чтобы в терминале использовать команду php-cs-fixer, необходимо указать путь в переменной окружения PATH. Пользователи Unix систем могут это сделать прямо в терминале с помощью команды. Пакеты, установленные глобально, находятся в папке $HOME/.composer/vendor/

Способ задания переменной окружения PATH для пользователей Windows описан здесь.

Запуск

Исправить оформление кода можно либо в отдельном файле, либо во всех файлах указанной папки. Делается это с помощью команды fix. По умолчанию используются стандарты PSR-1 и PSR-2.

При глобальной установке:

В случае локальной установки вам необходимо обратиться к скомпилированному файлу:

Настройка

Для описания правил оформления кода существует параметр —rules, который можно передать в консоли при выполнении команды.

Чтобы каждый раз не передавать —rules, создадим конфигурационный файл .php_cs в корне проекта, в котором перечислим набор правил.

Пример базового файла с настройками.

setRules задает набор правил оформления. Список доступных правил описан здесь.

setUsingCache ускоряет выполнение программы, запоминая время и список файлов, чтобы в следующий раз при запуске исправлять только те файлы, которые менялись.

setFinder определяет папку, в которой будут исправлены файлы. Если нужно исключить папку, то для этого добавляется параметр exclude(‘somedir’).

Теперь при запуске скрипта применятся набор правил оформления, заданный в .php_cs. Пример исходного файла до автоисправления

Удобство восприятия — важное качество создаваемого кода. Эффективность командной работы повышается, когда все разработчики пишут в едином стиле. Изучать сторонние библиотеки и решения проще, если их код соответствует стандартам.

Следить за оформлением и автоматически исправлять ошибки помогают скрипты, такие как PHP CS Fixer. Также рекомендуется настроить автоматическую проверку стиля в своей среде разработки. Об этом поговорим в следующих статьях.

Read more

We talk about interesting technologies and share our experience of using them.

Why PHP-CS-Fixer for VS Code?

Raja Palanivel

VS Code needs third party extensions like PHP-CS-Fixer to lint / format PHP code to coding standards. This guide will help with the installation of PHP-CS-Fixer in VS Code (2020). It is assumed that you have already used VS Code for PHP development and Composer.

Installation

(Come back after browsing this link to get an idea of what steps are involved.)

  1. Install php-cs-fixer globally using Composer.

2. Set the PATH for Composer’s bin folder from VS Code’s terminal if required. I used Git Bash terminal for this example. If you are already using Composer for your PHP projects, the bin folder should already be in your PATH. So, this step is optional. Bit more info on this here.

3. Install php cs fixer extension by junstyle in VS Code.

Settings

4. Add these settings to your existing VS Code’s settings.json file. Replace your_user_name_here in these settings with yours in three places.

Leave "php-cs-fixer.allowRisky": as false, More on this setting is at Step:9.

5. Download this zip file and extract the config.php_cs file. Place the config.php_cs file in your Composer’s bin folder. (This is not the best practice to place a config file in Composer’s binary folder. You can place the config.php_cs file anywhere including your PHP Projects folder, but make sure you change the location path at "php-cs-fixer.config": in your VS Code’s settings.json file (Step:4) to match where you placed the config.php_cs file.)

Usage

6. That’s all. Now restart VS Code and format a PHP file in VS Code to see the results. (With the given settings at Step:4, VS Code should also automatically format the file on every save.)

7. If you see “php-cs-fixer is formatting and finishing” in the status bar but your PHP file is not formatting to your standards, then play with the rules in your config.php_cs file. At this point, all you need to get right is the config.php_cs file. See Step:8 for what rules worked for me.

8. My config.php_cs file. I tested few PHP-CS-Fixer rules and added comments in this file.

H int: Edit your config.php_cs file in NotePad++ rather than VS Code, to see Syntax highlighting, so you don’t make any mistakes like missing a comma or semi-colon. VS Code did not do Syntax highlighting for .php_cs files. config.php_cs file is basically a PHP file and NotePad++ recognizes it.

9. Risky Rules (from Step: 4): For example, PHP-CS-Fixer can automatically change && in your PHP code to and but this is one of those Risky rules. Risky rules may/may not break your code, so research each rule before using them in your PHP-CS-Fixer. Learn more about Risky rules here.

Conclusion

Hope this tutorial is helpful for you and saved you hours trying to figure-out how to install if you are new to PHP-CS-Fixer. Let me know in the comments how you go with your PHP-CS-Fixer install.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *