Visual studio code php formatter

kokororin

The missing phpfmt extension for Visual Studio Code.

Installation

Open command palette F1 and select Extensions: Install Extension , then search for phpfmt.

Note: PHP >= 5.6 is required.

Usage

F1 -> phpfmt: Format This File

or keyboard shortcut Ctrl + Shift + I which is Visual Studio Code default formatter shortcut

or right mouse context menu Format Document or Format Selection

Format On Save

Respects editor.formatOnSave setting.

You can turn off format-on-save on a per-language basis by scoping the setting:

Q: How to use phpfmt.php_bin with spaces such as C:Program Filesphpphp.exe ?
A: Wrap your path with quotes like:

It is recommended to add the directory of the php.exe to the PATH environment variable on Windows.
If it still not working, refer to #1 and Stack Overflow Related.

Q: How use tabs instead of spaces with PSR2 enabled ?
A: For PSR2, code MUST use 4 spaces for indenting, not tabs. But if you like PSR2, and do not like 4 spaces for indentation, add following configuration:

Q: Is fmt.phar (phpfmt itself) still maintained ?
A: Since phpfmt has no maintainers, only Serious bugs will be fixed.

Configuration

Key Type Description Default
phpfmt.php_bin string php executable path "php"
phpfmt.detect_indent boolean auto detecting indent type and size (will ignore indent_with_space) false
phpfmt.psr1 boolean activate PSR1 style false
phpfmt.psr1_naming boolean activate PSR1 style — Section 3 and 4.3 — Class and method names case. false
phpfmt.psr2 boolean activate PSR2 style true
phpfmt.indent_with_space integer | boolean use spaces instead of tabs for indentation. Default 4 4
phpfmt.enable_auto_align boolean enable auto align of ST_EQUAL and T_DOUBLE_ARROW false
phpfmt.visibility_order boolean fixes visibiliy order for method in classes — PSR-2 4.2 false
phpfmt.passes array call specific compiler pass []
phpfmt.exclude array disable specific passes []
phpfmt.smart_linebreak_after_curly boolean convert multistatement blocks into multiline blocks false
phpfmt.yoda boolean yoda-style comparisons false
phpfmt.cakephp boolean Apply CakePHP coding style false
phpfmt.custom_arguments string provide custom arguments to overwrite default arguments generated by config ""
Читайте также:  Hp p2015 индикация ошибок

Supported Transformations

F1 -> phpfmt: List Transformations to get the example of each transformation.

PHP Debug

PHP Debug — расширение для отладки кода.
Основные возможности:

  • Линейные, условные и функциональные брейкпоинты
  • Пошаговая отладка (Шаг с обходом, шаг с заходом, шаг с выходом)
  • Трассировки стека
  • Наблюдаемые значения переменных, определенные пользователем
  • Отладочная консоль

В моем блоге есть запись о настройке отладки PHP в Visual Studio Code и OpenServer

PHP Intelephense

PHP Intelephense — система автодополнения PHP кода "здорового человека".
При использовании следует выключать встроенную систему автодополнения кода "php.suggest.basic": false . Основные возможности:

  • Интуитивный помощник автодополнения кода
  • Форматирование кода ( Alt+Shift+F )
  • Поиск символов (через @ внутри файла или # по рабочей области)
  • Удобная команда для добавления класса в use .

PHP DocBlocker

PHP DocBlocker. Документирование PHP кода. Имеется сниппет для /** , используемый перед классом, функцией или свойством класса.

Class Helper

Class Helper.
Расширение не только для PHP, предоставляет ряд полезных команд:

  • Добавление класса, конструктора и свойств ( ALT+C )
  • Добавление приватных свойств ( CTRL+ALT+C )
  • Добавление метода ( ALT+M )
  • Добавление приватного метода CTRL+ALT+M
  • Добавление геттера и сеттера ( ALT+M когда курсор (не мышь) находится на свойстве)

I’m using Laravel so all the views are .blade.php files. Visual Studio Code won’t format the HTML because of the PHP extension. I removed the blade part of the filename, but it still isn’t formatting the files properly (via Alt + Shift + F ).

I also tried about five extensions but none of them do the reformatting.

How can I format .blade.php files in Visual Studio Code?

7 Answers 7

The extension beautify just do it very well, either add php and any other file extension type to the config as said above here is an example :

  1. go to user settings ( CTRL + SHIFT + P > user settings (UI) or CTRL + , (comma))
  2. search for beautify in the field above. And click on edit on settings.json .
  3. for html section just add php and blade .
Читайте также:  Wordpress добавить html страницу

OTHERWISE: you can also do it directly, type F1 then write beautify, the auto completion give you two choices beautify selection or beautify file. Choose the one you need, and it will do the job. that’s a straight direct way.

You can also add a keybinding to have a keyboard shortcut, here how to do it:

  1. open keybindings.json (go file>preferences>keyboard shortcuts)
  2. click in above open and edit keybindings.json

add the following into the closed brackets []

<
"key": "alt+b",
"command": "HookyQR.beautify",
"when": "editorFocus"
>

choose any key you want, and make sure you don’t override and existing one, search first in the left side if it exist or not.

note that all of those things are well documented on the description of the extension.

Rate this post

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

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