Codesniffer phpstorm не работает

Drupal Русскоязычное сообщество

Кто-нибудь работал с PHP_CodeSniffer в phpstorm?
Пытался поставить как рекомендовано через composer https://github.com/squizlabs/PHP_CodeSniffer#installation, но не получилось потому внёс изменения вручную так как там описано, команда ./vendor/bin/phpcs -h

PHP Fatal error: Uncaught Error: Class ‘PHP_CodeSniffer\Runner’ not found in /home/altron/drupal/mysite/vendor/bin/phpcs:17
Stack trace:
#0

if ( is_file ( __DIR__ . ‘/../autoload.php’ ) === true ) <
include_once __DIR__ . ‘/../autoload.php’ ;
> else <
include_once ‘PHP/CodeSniffer/autoload.php’ ;
>

$runner = new PHP_CodeSniffer \ Runner ();
$exitCode = $runner -> runPHPCS ();
exit( $exitCode );
?>

  • Drupal8
  • Есть вопрос
  • Решение проблем
  • Блог
  • Войдите или зарегистрируйтесь, чтобы отправлять комментарии

Лучший ответ

Что бы применялось ко всем файлам нужно убрать все галочки с выборки расширений файлов.
Спасибо думаю тему можно закрыть)

Комментарии

Чёт вы не то делаете. Конкретно для друпала в phpstorm не настраивал, но в целом достаточно установить глобально
composer global require «squizlabs/php_codesniffer=*» , а затем просто указать путь до файла phpcs в настройках phpstorm и в inspections выбрать профиль подходящий.

Короче, я делал по доке — всё заработало без проблем.

  • Войдите или зарегистрируйтесь, чтобы отправлять комментарии

[ErrorException]
file_put_contents(./composer.json): failed to open stream: Permission denied
результат команды

  • Войдите или зарегистрируйтесь, чтобы отправлять комментарии

искал решение нашёл это

sudo chown -R $altron

команда выдала ошибку

chown: пропущен операнд после «/home/altron /.composer/»
По команде «chown —help» можно получить дополнительную информацию.

  • Войдите или зарегистрируйтесь, чтобы отправлять комментарии

Согласен, какая-то непонятная рекомендация по исправлению ошибки..
что она хотела этим сказать??

  • Войдите или зарегистрируйтесь, чтобы отправлять комментарии

вы путь указывали к phpcs в нутри проекта или к его глобальному расположению?

  • Войдите или зарегистрируйтесь, чтобы отправлять комментарии

Вообщем создал новый проект указал путь, кнопка validate ошибок не выдала всё ок, осталась одна проблема в coding standard нет пункта drupal, что сделать что бы он там появился?

Источник

PHP Code Sniffer in PhpStorm

You are viewing an old version of this page. View the current version.

« Previous Version 5 Next »

In addition to the coding assistance provided by PhpStorm, additional code style checks can be performed using the PHP Code Sniffer tool integration. In this tutorial, we’ll have a look at how we can validate our code for consistence with a coding standard of choice.

PHP Code Sniffer is a PHP5 script that «sniffs» PHP, JavaScript and CSS files to detect violations of a defined coding standard. By default, it will warn us whenever violations are encountered against the PEAR coding standards, but we can also specify other coding standards like PEAR, PHPCS, PSR1, PSR2, Squiz and Zend. PhpStorm supports PHP Code Sniffer integration so that its warnings and errors can be shown in the same way PhpStorm displays warnings and errors in project files.

Читайте также:  Что делать если не работает микрофон вот xbox one

Prerequisites

To make use of PHP Code Sniffer, we first have to install it on our system.

Installing via PEAR

One way to install PHP Code Sniffer is by using PEAR:

This will install the PHP Code Sniffer classes into our PEAR installation folder (for example C:\PHP\5.5\pear\PHP\CodeSniffer.php and will create a bash / batch script in the PHP installation folder (for example C:\PHP\5.5\phpcs.bat).

Installing via Composer

A Composer package is available as well if you prefer not to use PEAR. A system-wide install can be done using the following command:

If you prefer to install into the vendor directory, a dependency can be added to composer.json instead. This can be done using Composer Support in PhpStorm or manually. Composer will install PHP Code Sniffer under the following path in your project: ./vendor/bin/phpcs.

Use the Composer | Add dependency. context menu on your project:

Add the following to the composer.json file:

1. Enable PHP Code Sniffer integration in PhpStorm

1.1. Specifying the path to PHP Code Sniffer

Through Project Settings | PHP | Code Sniffer, we can specify the path to PHP Code Sniffer, as well as some additional options (such as timeout) or files to ignore.

1.2. Configure PHP Code Sniffer as a PhpStorm inspection

Once PhpStorm knows the path to the PHP Code Sniffer executable, we can configure it as a PhpStorm inspection throuh Project Settings | Inspections and then enabling the PHP Code Sniffer validation inspection.

We can configure several additional parameters:

  • Severity: the severity of the inspection that will be shown in PhpStorm. This defaults to Weak warning, in the screenshot above we bumped it up to be a Warning instead.
  • Show warnings as: how should PHP Code Sniffer warnings be shown? This defaults to Warning, in the screenshot above we bumped it up to be a Error instead.
  • Coding standard: the coding standard PHP Code Sniffer should check. PHP Code Sniffer ships with support for PEAR, PHPCS, PSR1, PSR2, Squiz, Zend coding standards and can easily be extended with your own coding standard or well-known standards like Drupal, WordPress, Joomla, Symfony2 and many more.

2. Viewing phpcs warnings and errors in the editor

Results of running the PHP Code Sniffer validation inspection will immediately be visible in the editor when opening a PHP, JavaScript or CSS file. Just like regular PhpStorm inspections, warnings and errors that were captured by PHP Code Sniffer will be shown in the right gutter and as tooltips inside our code:

3. (optional) Running phpcs in batch mode

Whenever we want to learn about how good (or bad) we are adhering to the selected coding standard, we can run PHP Code Sniffer in «batch mode». Using the Code | Inspect code menu, we can let PhpStorm run the PHP Code Sniffer validation on all files in our project (or on a subset). We will have to specify the inspection profile to use, which defaults to the inspection profile that is active for the current project.

Читайте также:  Как настроить пагинацию wordpress

In the screenshot above, I have created a customized inspection profile which will only run PHP Code Sniffer and skips all other PhpStorm inspections.

  1. From the Specify Inspection Scope dialog, click the . button to open the available inspection profiles.
  2. In the toolbar, click Add to create a new Inspection Profile.
  3. Give the custom Inspection Profile a name and click OK.
  4. Disable all inspections that are not required, enable the ones that are.

Once PhpStorm and PHP Code Sniffer finish their work, the inspection results will be shown. Warnings and errors found by PHP Code Sniffer will be listed, grouped by folder. Clicking a warning on the left will display details on the right.

Using the toolbar on the left, we can change filtering and grouping options, as well as export the inspection results as XML or HTML.

4. (optional) Sharing phpcs code style with the team

When working in a development team, it may make sense to share code styles and PHP Code Sniffer settings with the team. Sharing these can be done as follows:

  1. Install PHP Code Sniffer using Composer or copy the PHP Code Sniffer coding standard into the PhpStorm project.
  2. Enable PHP Code Sniffer integration in PhpStorm
  3. Configure the PHP Code Sniffer validation inspection (specify inspection severity and select the code style that should be used)
  4. From Project Settings | Inspections, enable the Share Profile checkbox.
  5. Make sure the .idea\inspectionProfiles folder is added to source control so that team members have the same configuration when they pull the latest changes.

Источник

Настройка PHP CodeSniffer в PhpStorm с помощью стандартов кодирования WordPress | Келлен Мейс

Шаги ниже показывают, как настроить PHP CodeSniffer в PhpStorm с наборами правил WordPress Coding Standards. Это может быть очень полезно для выявления нарушений стандартов кодирования WP при написании кода, поэтому вы можете исправить их на месте. В этом руководстве предполагается, что вы работаете в Mac OS X или Linux, используете Vagrant для локальной разработки, у вас надеюсь установлен Composer + вам удобно пользоваться командной строкой. Видео-пошаговое руководство по этим шагам также доступно здесь.

1. Настройте PHP Remote Interpreter

Перейдите в «Настройки

Preferences > Languages & Frameworks > PHP

, затем нажмите […] кнопку. Введите эти настройки:

  • Переключатель SSH Credentials
  • IP-адрес вашего хоста вместо показанного (вы можете получить его, запустив ping example.dev один из ваших сайтов в командной строке)
  • vagrant для имени пользователя и пароля
  • /usr/bin/php для пути интерпретатора PHP

Затем выберите только что созданного переводчика:

2. Установите PHP CodeSniffer

composer global require «squizlabs/php_codesniffer=*»

Читайте также:  Пежо 308 не работает вентилятор отопителя

Затем убедитесь, что phpcs псевдоним доступен в

3. Установите наборы стандартов WordPress

composer create-project wp-coding-standards/wpcs:dev-master —no-dev

Затем убедитесь, что стандарты WP доступны в

4. Добавьте путь набора правил WordPress в конфигурацию PHP_CodeSniffer.

/.composer/vendor/bin phpcs —config-set installed_paths

5. Добавьте phpcs в ваш путь

/.zshrc если вы используете ZSH). Вставить в: PATH=$PATH:

/.composer/vendor/bin . Теперь вы сможете cd войти в любой корневой каталог WP и запустить его phpcs —standard=WordPress wp-load.php . Если вы увидите такой вывод, вы поймете, что phpcs работает правильно:

6. Настройте PHP CodeSniffer

В PhpStorm, перейдите к Preferences > Languages & Frameworks > PHP > Code Sniffer .

Выберите этот файл:

7. Настройте PHP CodeSniffer как проверку PhpStorm

В PhpStorm, перейдите Preferences > Editor > Inspections . Перейдите к PHP > PHP Code Sniffer Validation и установите флажок. Выберите стандарт кодирования WordPress из выпадающего меню и сохраните его.

Попробуйте это

Теперь попробуйте ввести что-то, что является допустимым PHP, но является нарушением стандартов кодирования WordPress, например:

PhpStorm должен дать вам знать, что это нарушение, подчеркнув это волнистым подчеркиванием. Вы можете навести на него курсор и получить всплывающее окно с дополнительной информацией, указывающей, что с ним не так. После этого вы можете установить его вручную, или использовать Code > Reformat Code (Cmd + Option + L на Mac), чтобы автоматически переформатировать код – просто убедитесь, что вы установили предопределенный стиль для WordPress в PhpStorm – х Preferences > Editor > Code Style > PHP > Set From > Predefined Style > WordPress .

Идти вперед

Чтобы включить PHP CodeSniffer со стандартами кодирования WP для любых будущих проектов, вам просто нужно выполнить шаги 1 и 7 выше.

Источник

PhpStorm не может запустить PHP Code CodeSniffer

Я пытаюсь использовать CodeSniffer в PhpStorm.

В Настройки-> PHP-> Интерпретатор CLI
Я связался с php.exe, который я использую https://windows.php.net/ но также попробовал это с Cygwin и XAMPP.

PhpStorm показывает мне правильную версию PHP 7.2.5 и php.ini

В конфигурации CodeSniffer я выбрал phpcs.bat
Когда я нажимаю на Подтвердить, я только что получил

Также добавил все в PATH

Я что-то пропустил?

Решение

Вы должны положить phpcs.bat а также phpcs в вашей папке PHP — например, d:\program\php\phpcs , Сам CodeSniffer должен находиться в d:\program\php\PEAR\PHP\CodeSniffer — будет скрипт autoload.php и подпапка src ,

Затем в Settings -> Languages & Frameworks -> PHP -> Code Sniffer вы указываете путь к phpcs.bat а также Validate Это.

Затем в Settings -> Editor -> Inspections вы найдете узел PHP Code Sniffer validation и включите его. После его включения вы сможете настроить его — конкретно выберите стандарт кодирования.


Это мое phpcs.bat

Это мое PEAR_ENV.reg который я импортировал в реестр Windows

Другие решения

Я использую OpenServer с PHP 7.0-64x
У меня есть только композитор и PHP в моем Env. вары.

но прежде чем я проверил это в консоли, и все было просто отлично
версия phpcs: 3.3.2 (последняя за эти дни)
что-то вроде этого:

C: \ OpenServer \ домены \ phpWorkingWithFiles \ поставщика \ Bin> phpcs
—standard = PSR2 C: \ OpenServer \ domains \ phpWorkingWithFiles \ classes \ Recipe.php

C: \ OpenServer \ domains \ phpWorkingWithFiles> vendor \ bin \ phpcs classes /
—цвета

была та же ошибка, я перезапустил Phpstorm, и он начал работать

Источник

Оцените статью