Joomla CodeSniffer

From Joomla! Documentation

Revision as of 11:21, 3 September 2018 by B2z (talk | contribs) (Created page with "К счастью, для PhpStorm, Eclipse и Netbeans существует плагин, который интегрирует CodeSniffer в вашу любимую IDE, п...")

Нос для Joomla

Это кастомный стандарт оформления кода для PHP CodeSniffer, который пытается привести всё к единому стандарту оформления кода в Joomla. В этом материале описывается, как настроить автоматическую проверку стиля оформления кода.

  1. Установка PHP CodeSniffer (phpcs).
  2. Клонирование Joomla Code Style (для использования с phpcs).
  3. Настройки вашей IDE для работы с PHP CodeSniffer и Joomla Code Style.
PHP Code Sniffer in action

Зачем?

  • Понятная и устойчивая практика написания кода заставляет выглядеть файлы более профессионально. Конфликтующие стили в том же проекте (или ещё хуже, в том же файле) не только выглядят небрежно, но и поощряют ещё большую небрежность.
  • Когда весь код соответствует единому стандарту, плохой код намного легче обнаружить.
  • Для того, кто только начал разбираться с файлом в проекте, намного проще найти и исправить ошибки или расширить функциональность.
  • Если нет постоянно поддерживаемого стандарта, разработчики будут форматировать текст как им удобнее. Это приводит к широкому диапазону изменений в репозитории с кодом. Если проблема обнаружится на последней стадии, то значительная часть изменений может быть утеряна при выборке во время diff.

1. Установка PHP Code Sniffer (phpcs)

Composer

PHP Code Sniffer доступен через Composer. Он может быть установлен в рамках всей системы следующей командой:
composer global require squizlabs/php_codesniffer "~2.8" На Linux PHP Code Sniffer (phpcs) будет установлен в папку вашего пользователя:

  • Символическая ссылка: ~/.composer/vendor/bin/phpcs
  • Файл: ~/.composer/vendor/squizlabs/php_codesniffer/scripts/phpcs

Для создания символической ссылки, используйте командную строку: $ sudo ln -s ~/.config/composer/vendor/squizlabs/php_codesniffer/scripts /usr/bin/phpcs

или (например OpenSuse)

  • Символическая ссылка: ~/.config/composer/vendor/bin/phpcs
  • Файл: ~/.config/composer/vendor/squizlabs/php_codesniffer/scripts/phpcs

На Windows PHP Code Sniffer (phpcs) будет установлен в папку вашего пользователя:

  • Символическая ссылка: c:\Users\Username\AppData\Roaming\Composer\vendor\bin\phpcs
  • Файл: c:\Users\Username\AppData\Roaming\Composer\vendor\squizlabs\php_codesniffer\scripts\phpcs


Добавление директории bin composer к переменной $PATH

Для того, чтобы запускать PHP Code sniffer откуда угодно в командной строке Linux или Mac, необходимо добавить .composer/vendor/bin к вашей переменной $PATH. Для того, чтобы зафиксировать это на постоянной основе, отредактируйте стартовый файл оболочки, например .profile или .bash_profile, в зависимости от того, какую оболочку вы используете (echo $SHELL покажет вам, какую вы используете).

Добавьте следующую строку в файл: export PATH=$PATH:~/.composer/vendor/bin

В качестве альтернативы вы можете создать симовлическую ссылку в папке bin: ln -s ~/.composer/vendor/bin/phpcs /usr/local/bin/phpcs

2. Установка Joomla Coding Standards

Для того, чтобы PHP Code Sniffer (phpcs) начал "нюхать" (проверять) ваши проекты Joomla на правильный стиль оформления кода, вам необходимо установить Joomla Coding Standards (стандарты оформления кода в Joomla).

Используя composer, мы можем запустить: composer global require joomla/coding-standards "~2.0@alpha"

Обратите внимание на @alpha. Всё потому, что стандарт всё ещё в стадии альфа, и мы должны позволить установку кода, со статусом alpha. Если мы не укажем @alpha, то стандарты не будут установлены и выкинут ошибку.

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package joomla/coding-standards ~2.0 is satisfiable by joomla/coding-standards[2.0.0-alpha, 2.0.0-alpha2, 2.x-dev] but these conflict with your requirements or minimum-stability.

Как только установка завершится, стандарт оформления кода будет установлен в глобальную папку composer. Расположение этой папки зависит от вашей операционной системы. Вот некоторые популярные места расположения:

Mac / Linux

~/.composer/vendor/joomla/coding-standards/
~/.config/composer/vendor/joomla/coding-standards/

Windows

c:\Users\Username\AppData\Roaming\Composer\vendor\joomla\coding-standards\

Так это выглядит при использовании Composer в Windows.

Если вы не можете найти ни одну из выше указанных папок, то учите, что папка, которую вы ищите, заканчивается на \joomla\coding-standards\ И наконец, мы должны дать понятьCode Sniffer, что стандарты оформления кода Joomla существуют.

Установка Joomla Coding Standards

  1. Проверьте, пути установлены или нет, запустив команду phpcs --config-show
  2. Вы можете получить ответ, который выглядит вот так: installed_paths: /path/to/installation
  3. На шаге 2, если вы видите installed_paths, скопируйте их
  4. Установите путь Joomla Coding Standards в phpcs вызовом команды phpcs --config-set installed_paths /Users/user/.composer/vendor/joomla/coding-standards. Если вы скопировали пути на шаге 2, включите их здесь, разделяя запятой. Команда будет выглядеть как phpcs --config-set installed_paths [/to/path1],[/to/path2],[/Users/user/.composer/vendor/joomla/coding-standards]
  5. Убедитесь, что путь установлен верно, запустив команду phpcs --config-show
  6. Убедитесь, что phpcs видит стандарт оформления кода Joomla, запустив команду phpcs -i
  7. Вывод должен выглядеть вот так: The installed coding standards are MySource, PEAR, PHPCS, PSR1, PSR2, Squiz, Zend and Joomla

Использование

Вы вызываете кастомный стандарт через phpcs --standard=Joomla file/to/sniff

Для тестирования файлов platform со стандартом разработки platform, используйте phpcs --standard=build/phpcs/Joomla path/to/file/or/folder

Дополнительная документация по использованию phpcs доступна здесь: [1]

3. Интеграция с IDE

Все любять консоль. Это, без сомнения, самый эффективный путь делать то, что захочется. Но иногда и гуру Linux нуждаются в небольшом комфорте.

К счастью, для PhpStorm, Eclipse и Netbeans существует плагин, который интегрирует CodeSniffer в вашу любимую IDE, поэтому нарушения стандартов оформления кода показываются как "обычные" ошибки.

PhpStorm

Code Sniffer is supported out of the box in PhpStorm. Go to Settings and under Editor    Inspections you will see the list of sniffers you have installed.

Set Path to Code Sniffer

  1. Open Settings (CTRL-ALT-S / CMD-,)
  2. Go to Languages & Frameworks
  3. Click on PHP
  4. Click on Code Sniffer
  5. The configuration is set to Local by default
  6. Click on the 3 dots behind it to open the configuration screen
  7. The first option is the PHP Code Sniffer (phpcs) path
  8. Click on the 3 dots behind the path to select the location of the phpcs file. See above on where phpcs may be installed on your site
  9. Click on Validate to make sure the path is correct and phpcs is working
  10. Click OK
Activating the Joomla Code Style
  1. Open Settings (CTRL-ALT-S / CMD-,)
  2. Go to Editor
  3. Click on Inspections
  4. In the list, go to PHP
  5. Click on PHP Code Sniffer Validation
  6. Click on the check box behind it to activate it
  7. Click the Reload button (2 arrows) to force a reload of rules from disk
  8. Joomla should now be available in the list. See following image:
    PHPStorm CodeSniffer
  9. Click OK


PHP PSR-0, PSR-1 and PSR-2

Using PHP PSR-1 and PSR-2 Sniff

A CodeSniffer sniff to check against the PSR-x Coding Standard can be used as well. In that case you can select a different standard than Joomla.

Using Joomla Code style

It's nice to be able to check that the standards are respected. It's even nicer if PhpStorm helps you format properly too as you are coding. To use the Joomla code style in PhpStorm

  1. Open Settings (CTRL-ALT-S / CMD-,)
  2. Go to Editor
  3. Click on Code Style
  4. Select Joomla from the Scheme select box

PhpStorm / Alternative Method

NOTE: This method is outdated, but it might be useful if you are looking for a different integration. It also demonstrates the use of external tools in PhpStorm - so it shouldn't be deleted.

The Code Sniffer can also be integrated easily as an external tool. PhpStorm will display the output in the console, including click-able links containing line and column numbers to the files that contain errors.

  • Click on "Settings" and search for "External tools"
  • Click "Add..."
  • Choose a "Name", "Group" and "Description".
  • Click "Output Filters"
    • Click "Add...", Choose a name and enter under "Regular expression to match output" the value: $FILE_PATH$:$LINE$:$COLUMN$
  • "Program": Search for the phpcs executable on your system. You have to set the path to the phpcs.bat from the installed PHP_CodeSniffer PEAR package
    • For Unix based systems, the path is something like /usr/bin/phpcs
    • In XAMPP (windows), you can find the file in the PHP root folder (e.g. C:\xampp\php\phpcs.bat)
  • "Parameters":
    • --standard=<path/to/joomla-platform>/build/phpcs/Joomla The path to the Joomla! coding standards.
    • --report=emacs The will generate a simple list containing links to the error files
    • Optionally you may want to specify -p for "progress" or -n for "errors only".
    • The last parameter has to be $FilePath$ specifying the file or folder you want to sniff.

A typical "Parameters" line on a Linux system might look like this:

-np --standard=/home/elkuku/libs/joomla/build/phpcs/Joomla --report=emacs $FilePath$

You may now right click any file or folder and choose the sniffer from the context menu or add a new tool bar button with a nice Joomla! logo .

Netbeans

Netbeans has the sniffer functionality integrated into the core system.

  1. Start your Netbeans IDE
  2. Open Tools => Options => PHP => Code Analysis => Code Sniffer
  3. You have to set the path to phpcs.bat from the installed PHP_CodeSniffer PEAR package
    • For Unix based systems the path is something like /usr/bin/phpcs
    • In XAMPP (windows) you can find the file in the PHP root folder (e.g. C:\xampp\php\phpcs.bat)
  4. As "Default Standard," choose "Joomla" to use the Joomla! standard
  5. Now you can click OK to start sniffing
  6. Open from the top menu Source => Inspect...
  7. Enjoy

Eclipse

1) Eclipse PTI

Installation is a breeze and follows the usual pattern:

  1. Help => Install New Software...
  2. Work with: Fill in one of the update site URLs found here: http://www.phpsrc.org/eclipse/pti/
  3. Select the desired tools
  4. Restart Eclipse.
2) Eclipse PTI settings

You are now able to sniff for code violations against common standards like PEAR or Zend etc.

To sniff against your own standards, specify their location and activate them (see screen shot 2)

  1. Window => Preferences
  2. PHP Tools => PHP CodeSniffer

Happy sniffing.


Geany

  • Open a PHP file. (Otherwise the build menu is not accessible.) See this Screenshot
  • On the top menu, select Build->Set Build Commands.
  • Select the second field and name it as you wish. Enter this code in the Command: phpcs --standard=Joomla "%f" | sed -e 's/^/%f |/' | egrep 'WARNING|ERROR'
  • Enter this code in the Error Regular Expression field: (.+) [|]\s+([0-9]+) See this Screenshot
  • Select OK.
  • If the Message Window is not open, display it by selecting it in the top View menu.
  • When viewing any PHP file, press F9 to see the errors found. Screenshot

References