- Saved searches
- Use saved searches to filter your results more quickly
- License
- PHPCheckstyle/phpcheckstyle
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- Автоматическая проверка кода за 5 минут
- Шаг 1 — Делаем инициализацию composer (у кого он уже настроен, пропускаем)
- Шаг 2 — Добавляем .gitignore
- Шаг 3 — Добавляем нужные библиотеки
- Шаг 4 — Добавляем обработчик хука
- Шаг 5 — Конфигурируем composer для реализации автозапуска проверки на pre-commit
- 5.1 Создаем сам обработчик который будет копировать файлик pre-commit.php в папку хуков гита
- Analyse or fix PHP script online
- Submit your PHP scripts in 3 steps
- Why use Coding Styles checker is needed?
- Can I update the code style automatically?
- What is the goal of static analysis to upgrading the code?
- What are the tools available to execute style code analysis?
- What are the tools available to upgrade the code?
- The static analysis is sufficient to upgrading code to new PHP version?
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
PHPCheckstyle is an open-source tool that helps PHP programmers adhere to certain coding conventions.
License
PHPCheckstyle/phpcheckstyle
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
PHPCheckstyle is an open-source tool that helps PHP programmers adhere to certain coding conventions. The tools checks the input PHP source code and reports any deviations from the coding convention.
The tool uses the PEAR Coding Standards as the default coding convention. But it allows you to configure it to suit your coding standards.
Please visit https://github.com/PHPCheckstyle/phpcheckstyle/wiki for more information and documentation
- PHP 5.0 or newer.
- Web browser to view the checkstyle report (only for html view)
- That’s all.
Installation with Composer
composer require phpcheckstyle/phpcheckstyle
or Add phpcheckstyle/phpcheckstyle as a requirement to composer.json :
< "require": < "phpcheckstyle/phpcheckstyle": "dev-master" > >
Update your packages with composer update or if installing from fresh, with composer install .
This will create a directory called phpcheckstyle and expand all files in it.
- install VirtualBox
- install Vagrant
- launch vagrant up in the project root directory to start the VM
- In case of problem with the «guest additions», launch :
vagrant plugin install vagrant-vbguest
- to run PHPCheckstyle on itself, type vagrant provision —provision-with run_phpcheckstyle
- to run PHPUnit, type vagrant provision —provision-with run_phpunit
- to log inside the VM, type vagrant ssh
$> php run.php --src php source directory/file>
Автоматическая проверка кода за 5 минут
Данная инструкция показывает как автоматизировать проверку на code style в вашем php проекте.
Давайте посмотрим как будет выглядеть настройка в новом проекте.
Шаг 1 — Делаем инициализацию composer (у кого он уже настроен, пропускаем)
Для этого в корне вашего проекта запускаем команду. Если у вас не установлен composer, то можете обратиться к официальной документации getcomposer.org
Шаг 2 — Добавляем .gitignore
###> phpstorm ### .idea ### < phpstorm ### /vendor/ ###>friendsofphp/php-cs-fixer ### /.php_cs /.php_cs.cache ###< friendsofphp/php-cs-fixer ###
Шаг 3 — Добавляем нужные библиотеки
composer require --dev friendsofphp/php-cs-fixer symfony/process symfony/console squizlabs/php_codesniffer
Шаг 4 — Добавляем обработчик хука
Сам обработчик можно написать на чем угодно, но так как статься про php то будем писать код на нем.
#!/usr/bin/php /** * @param InputInterface $input * @param OutputInterface $output * * @return void * @throws \Exception */ public function doRun(InputInterface $input, OutputInterface $output) < $this->input = $input; $this->output = $output; $output->writeln('Code Quality Tool '); $output->writeln('Fetching files '); $files = $this->extractCommitedFiles(); $output->writeln('Running PHPLint '); if (! $this->phpLint($files)) < throw new \Exception('There are some PHP syntax errors!'); >$output->writeln('Checking code style with PHPCS '); if (! $this->codeStylePsr($files)) < throw new \Exception(sprintf('There are PHPCS coding standards violations!')); >$output->writeln('Well done! '); > /** * @return array */ private function extractCommitedFiles() < $output = array(); $against = 'HEAD'; exec("git diff-index --cached --name-status $against | egrep '^(A|M)' | awk ''", $output); return $output; > /** * @param array $files * * @return bool * * @throws \Exception */ private function phpLint($files) < $needle = '/(\.php)|(\.inc)$/'; $succeed = true; foreach ($files as $file) < if (! preg_match($needle, $file)) < continue; >$process = new Process(['php', '-l', $file]); $process->run(); if (! $process->isSuccessful()) < $this->output->writeln($file); $this->output->writeln(sprintf('%s ', trim($process->getErrorOutput()))); if ($succeed) < $succeed = false; >> > return $succeed; > /** * @param array $files * * @return bool */ private function codeStylePsr(array $files) < $succeed = true; $needle = self::PHP_FILES_IN_SRC; $standard = 'PSR2'; foreach ($files as $file) < if (! preg_match($needle, $file)) < continue; >$phpCsFixer = new Process([ 'php', VENDOR_DIR.'/bin/phpcs', '-n', '--standard='.$standard, $file, ]); $phpCsFixer->setWorkingDirectory(__DIR__.'/../../'); $phpCsFixer->run(); if (! $phpCsFixer->isSuccessful()) < $this->output->writeln(sprintf('%s ', trim($phpCsFixer->getOutput()))); if ($succeed) < $succeed = false; >> > return $succeed; > > $console = new CodeQualityTool(); $console->run();
В данном примере код будет проходить 3 проверки:
— проверка на синтаксические ошибки
— проверка на PSR2 через code sniffer
PSR2 можно заменить на любой другой который поддерживает code sniffer. Список поддерживаемых стандартов можно увидеть введя команду
Шаг 5 — Конфигурируем composer для реализации автозапуска проверки на pre-commit
Для того чтобы код проверки запускался на pre commit хук нам необходимо положить файлик с кодом, который сделали в 3 пункте положить в папку .git/hooks/pre-commit. Это можно сделать вручную но куда удобнее это дело автоматизировать. Для этого нам нужно написать обработчик, который будет копировать этот файлик и повешать его на событие которые вызывается после composer install. Для этого делаем следующее.
5.1 Создаем сам обработчик который будет копировать файлик pre-commit.php в папку хуков гита
getIO(); $gitHook = '.git/hooks/pre-commit'; if (file_exists($gitHook)) < unlink($gitHook); $io->write('Pre-commit hook removed! '); > return true; > /** * @param Event $event * * @return bool * * @throws \Exception */ public static function postHooks(Event $event) < /** @var array $extras */ $extras = $event->getComposer()->getPackage()->getExtra(); if (! array_key_exists('hooks', $extras)) < throw new \InvalidArgumentException('The parameter handler needs to be configured through the extra.hooks setting.'); >$configs = $extras['hooks']; if (! array_key_exists('pre-commit', $configs)) < throw new \InvalidArgumentException('The parameter handler needs to be configured through the extra.hooks.pre-commit setting.'); >if (file_exists('.git/hooks')) < /** @var \Composer\IO\IOInterface $io */ $io = $event->getIO(); $gitHook = '.git/hooks/pre-commit'; $docHook = $configs['pre-commit']; copy($docHook, $gitHook); chmod($gitHook, 0777); $io->write('Pre-commit hook created! '); > return true; > >
5.2 Настраиваем composer чтобы запускался обработчик
в composer.json добавляем следующую секцию
pre-update-cmd, pre-install-cmd — перед install и update удаляется старый обработчик
post-install-cmd, post-update-cmd — после install и update будет устанавливаться обработчик на pre commit
В итоге файлкик composer.json примет следующий вид
< "name": "admin/test", "authors": [ < "name": "vitaly.gorbunov", "email": "cezar62882@gmail.com" >], "minimum-stability": "stable", "require": <>, "autoload": < "psr-4": < "App\\": "src/" >>, "scripts": < "post-install-cmd": [ "App\\Composer\\ScriptHandler::postHooks" ], "post-update-cmd": [ "App\\Composer\\ScriptHandler::postHooks" ], "pre-update-cmd": "App\\Composer\\ScriptHandler::preHooks", "pre-install-cmd": "App\\Composer\\ScriptHandler::preHooks" >, "require-dev": < "friendsofphp/php-cs-fixer": "^2.16", "symfony/process": "^5.0", "symfony/console": "^5.0", "squizlabs/php_codesniffer": "^3.5" >, "extra": < "hooks": < "pre-commit": "hooks/pre-commit.php" >> >
Запускаем еще раз composer install чтобы файлик скопировался куда надо.
Все готово, теперь если вы попытаетесь закомитить код с кривым code style то git console вам об этом скажет.
В качестве примере давайте создадим в папке src файлик MyClass.php по следующим содержаением.
Пытаемся закомитить и получаем ошибки проверки кода.
MBP-Admin:test admin$ git commit -am 'test' Code Quality Tool Fetching files Running PHPLint Checking code style with PHPCS FILE: /Users/admin/projects/test/src/MyClass.php ---------------------------------------------------------------------- FOUND 5 ERRORS AFFECTING 5 LINES ---------------------------------------------------------------------- 8 | ERROR | [x] Each PHP statement must be on a line by itself 10 | ERROR | [x] Opening brace should be on a new line 13 | ERROR | [x] Opening brace should be on a new line 15 | ERROR | [x] Function closing brace must go on the next line | | following the body; found 1 blank lines before | | brace 16 | ERROR | [x] Expected 1 newline at end of file; 0 found ---------------------------------------------------------------------- PHPCBF CAN FIX THE 5 MARKED SNIFF VIOLATIONS AUTOMATICALLY ---------------------------------------------------------------------- Time: 49ms; Memory: 6MB In pre-commit line 53: There are PHPCS coding standards violations!
Analyse or fix PHP script online
This form help you to analyse your script code for selected coding standard (PSR2, PSR1, PSR12, Zend, Squiz, MySource, . ).
Also, you can check your source code compatibility with most recent version of PHP. The check uses the static analysis to perform audits. The exhaustivity is not guarantee without run of code in real condition on the targeted PHP version.
Submit your PHP scripts in 3 steps
Why use Coding Styles checker is needed?
The code source style helps you and other developers to read the code most easily. This php code checker and fixer online service is available free of charge.
Can I update the code style automatically?
Yes, you can (it's recommended) run PHP CS or PHP CS Fixer on your code to apply all rules of style code. You must configure the tool before running to define the main code style between PSR 1, PSR 2, PSR 12, Symfony, PEAR, Zend or your custom rules.
You can use a GIT hook to apply only to updated files.
This php code analyzer online is available to help you to test the effect of the style code rules on your snippet code.
What is the goal of static analysis to upgrading the code?
The static analysis help the developer to check and list all necessary change in code sources.
This php compatibility checker online help you to check your codes snippets.
What are the tools available to execute style code analysis?
This online PHP code checker and fixer uses "PHP Code Style" (PHPCS) with some rules sets or "Phan" to analyze your code snippet. Otherwise, use "PHP CS Fixer" to analyze and patch your code snippet.
What are the tools available to upgrade the code?
This online PHP code analyzer uses "Rector" to change your snippet code. The rules selected are the default rules to upgrade code to the targeted PHP version.
The static analysis is sufficient to upgrading code to new PHP version?
No, you must run your code with the targeted PHP version to run unit tests and all other tests. The manual test is needed to complete the test.