PHP Classes

PHP Code formatter: Reformat PHP code according to standard options

Recommend this page to a friend!
  Info   View files View files (157)   DownloadInstall with Composer Download .zip   Reputation   Support forum (1)   Blog    
Ratings Unique User Downloads Download Rankings
Not enough user ratingsTotal: 283 All time: 7,560 This week: 182Up
Version License PHP version Categories
phpcf 1.0.1GNU Lesser Genera...5.4PHP 5, Tools, Text processing
Description 

Author

This package can reformat PHP code according to standard options.

It can parse PHP code files and replace spaces, tabs and line breaks so they match formatting rules defined by format standard configuration options defined in style files.

It can also replace Cyrillic letter characters to equivalent transliterated that uses only the ASCII alphabet.

The package can either just report formatting issues in the original PHP source file or automatically fix the code to match the formatting styles.

The package also comes with an alternative implementation as a PHP extension written in C, so it can process a large number of PHP source files if the extension is installed in your PHP environment.

Innovation Award
PHP Programming Innovation award nominee
August 2014
Number 4


Prize: One book of choice by Packt
Formatting PHP code is a task that requires parsing the code text and rewrite it according to given rules.

This package provides a solution to reformat PHP code that comes with an alternative C based PHP extension, so it can work much faster when it is necessary to process a large amount of code.

Manuel Lemos
Picture of Alex Krash
  Performance   Level  
Name: Alex Krash <contact>
Classes: 1 package by
Country: Russian Federation Russian Federation
Age: ???
All time rank: 3871110 in Russian Federation Russian Federation
Week rank: 312 Up13 in Russian Federation Russian Federation Up
Innovation award
Innovation award
Nominee: 1x

Details

phpcf

Форматер был создан для того, чтобы в основном менять пробельные символы: переносы строк, отступы, пробелы вокруг операторов, и т.д. Таким образом, phpcf не заменяет другие схожие утилиты, такие как вышеупомянутый PHP Code Sniffer и PHP Coding Standards Fixer (http://cs.sensiolabs.org) от Фабьена Потенцьера. Он дополняет их, выполняя «грязную работу» по правильной расстановке пробелов и переносов строк в файле. Важно отметить, что наша утилита учитывает изначальное форматирование в файле и меняет только те пробелы, которые не соответствуют выбранному стандарту (в отличие от некоторых других решений, которые сначала удаляют все пробельные токены, а потом начинают форматирование).

Утилита расширяема и поддерживает произвольные наборы стилей. Можно достаточно легко определить свой стиль форматирования, который будет реализовать другой стандарт, отличный от нашего (стандарт кодирования в нашей компании очень близок к PSR).

Пример использования (команда “phpcf apply <filename>” форматирует указанный файл, а “phpcf check <filename>” проверяет форматирование и возвращает ненулевой exit-код в случае наличия неотформатированных фрагментов):

$ cat minifier.php
<?php
$tokens=token_get_all(file_get_contents($argv[1]));$contents='';foreach($tokens as $tok){if($tok[0]===T_WHITESPACE||$tok[0]===T_COMMENT)continue;if($tok[0]===T_AS||$tok[0]===T_ELSE)$contents.=' '.$tok[1].' '; else $contents.=is_array($tok)?$tok[1]:$tok;}echo$contents."\n";

$ phpcf apply minifier.php
minifier.php formatted successfully

$ cat minifier.php
<?php
$tokens = token_get_all(file_get_contents($argv[1]));
$contents = '';
foreach ($tokens as $tok) {
    if ($tok[0] === T_WHITESPACE || $tok[0] === T_COMMENT) continue;
    if ($tok[0] === T_AS || $tok[0] === T_ELSE) $contents .= ' ' . $tok[1] . ' ';
    else $contents .= is_array($tok) ? $tok[1] : $tok;
}
echo $contents . "\n";

$ phpcf check minifier.php; echo $?
minifier.php does not need formatting
0

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

$ cat zebra.php 
<?php
echo "White "."strip".PHP_EOL;
echo "Black "."strip".PHP_EOL; // not formatted
echo "Arse".PHP_EOL;

$ phpcf apply zebra.php:1-2,4
zebra.php formatted successfully

$ cat zebra.php 
<?php
echo "White " . "strip" . PHP_EOL;
echo "Black "."strip".PHP_EOL; // not formatted
echo "Arse" . PHP_EOL;

$ phpcf check zebra.php
zebra.php issues:
        Expected one space before binary operators (= < > * . etc)   on line 3 column 14
        Expected one space after binary operators (= < > * . etc)   on line 3 column 15
        ...

$ echo $?
1

Даже несмотря на то, что утилита написана на PHP, форматирование большинства файлов проходит за доли секунды. Но у нас большой репозиторий и много кода, так что мы написали расширение, которое, будучи подключенным, увеличивает производительность работы в сотню раз: весь наш репозиторий в 2 миллиона строк форматируется за 8 секунд на «ноутбучном» Core i7. Для использования расширения требуется его собрать из директории “ext/”, установить, включить “enable_dl = On” в php.ini или прописать его как extension.

Хотелось бы еще раз подчеркнуть, что phpcf прежде всего меняет пробельные символы и умеет делать лишь простейшие преобразования над кодом: например, заменять короткий открывающий тег на длинный или убирать последний закрывающий тег из файла. Помимо этого, phpcf умеет автоматически исправлять кириллицу в названиях функций на английские символы. Также не трогаются выражения, выровненные вручную с помощью пробелов. Это происходит из-за архитектуры — форматер работает как конечный автомат с правилами, которые задает пользователь, а не как набор «захардкоженных» замен (форматер поставляется с «конфигом по умолчанию», соответствующим нашим правилам форматирования). Поэтому, если вы хотите автоматическую замену “var” на “public” или похожих вещей, рекомендуем обратить внимание на PHP-CS-Fixer — он мало внимания уделяет пробельным символам (в отличие от phpcf), но зато умеет переписывать токены.


  Files folder image Files  
File Role Description
Files folder imagephpcf-src (1 file, 4 directories)
Accessible without login Plain text file phpcf Appl. Auxiliary data
Accessible without login Plain text file README.md Data Auxiliary data

  Files folder image Files  /  phpcf-src  
File Role Description
Files folder imageext (4 files)
Files folder imagesrc (9 files, 3 directories)
Files folder imagestyles (2 directories)
Files folder imagetest (2 files, 3 directories)
  Accessible without login Plain text file phpcf.php Example Application script

  Files folder image Files  /  phpcf-src  /  ext  
File Role Description
  Accessible without login Plain text file config.m4 Data Auxiliary data
  Accessible without login Plain text file CREDITS Data Auxiliary data
  Accessible without login Plain text file phpcf.c Data Auxiliary data
  Accessible without login Plain text file php_phpcf.h Data Auxiliary data

  Files folder image Files  /  phpcf-src  /  src  
File Role Description
Files folder imagecli (8 files, 1 directory)
Files folder imagefilter (3 files)
Files folder imageimpl (2 files)
  Plain text file ClassLoader.php Class Class source
  Accessible without login Plain text file defines.php Conf. Configuration script
  Plain text file ExecStat.php Class Class source
  Plain text file Formatter.php Class Class source
  Plain text file FormattingResult.php Class Class source
  Plain text file Helper.php Class Class source
  Plain text file IFormatter.php Class Class source
  Accessible without login Plain text file init.php Conf. Configuration script
  Plain text file Options.php Class Class source

  Files folder image Files  /  phpcf-src  /  src  /  cli  
File Role Description
Files folder imagegit (5 files)
  Plain text file AbstractAction.php Class Class source
  Plain text file ActionApply.php Class Class source
  Plain text file ActionCheck.php Class Class source
  Plain text file ActionPreview.php Class Class source
  Plain text file ActionStdin.php Class Class source
  Plain text file Ctx.php Class Class source
  Plain text file Handler.php Class Class source
  Plain text file IAction.php Class Class source

  Files folder image Files  /  phpcf-src  /  src  /  cli  /  git  
File Role Description
  Plain text file ActionApply.php Class Class source
  Plain text file ActionCheck.php Class Class source
  Plain text file ActionPreview.php Class Class source
  Plain text file GitCallback.php Class Class source
  Plain text file Helper.php Class Class source

  Files folder image Files  /  phpcf-src  /  src  /  filter  
File Role Description
  Plain text file StringAscii.php Class Class source
  Plain text file StringAsciiMap.php Class Class source
  Plain text file StringAsciiMapCyr.php Class Class source

  Files folder image Files  /  phpcf-src  /  src  /  impl  
File Role Description
  Plain text file Fsm.php Class Class source
  Plain text file Pure.php Class Class source

  Files folder image Files  /  phpcf-src  /  styles  
File Role Description
Files folder imagedefault (2 files)
Files folder imageexample (5 files)

  Files folder image Files  /  phpcf-src  /  styles  /  default  
File Role Description
  Accessible without login Plain text file context-rules.php Conf. Configuration script
  Accessible without login Plain text file formatting-rules.php Conf. Configuration script

  Files folder image Files  /  phpcf-src  /  styles  /  example  
File Role Description
  Accessible without login Plain text file context-rules.php Conf. Configuration script
  Accessible without login Plain text file formatting-rules.php Conf. Configuration script
  Plain text file phpcf-class.php Class Class source
  Accessible without login Plain text file test-in.php Test Unit test script
  Accessible without login Plain text file test-out.php Test Unit test script

  Files folder image Files  /  phpcf-src  /  test  
File Role Description
Files folder imageexpected (55 files)
Files folder imagefunctional_dirty (4 files)
Files folder imageoriginal (55 files)
  Accessible without login Plain text file PhpCfFunctional.php Test Unit test script
  Accessible without login Plain text file PhpCfTest.php Test Unit test script

  Files folder image Files  /  phpcf-src  /  test  /  expected  
File Role Description
  Accessible without login Plain text file alignment.php Test Unit test script
  Accessible without login Plain text file anonymous.php Test Unit test script
  Accessible without login Plain text file binary-operators.php Test Unit test script
  Accessible without login Plain text file brace-after-comma.php Test Unit test script
  Accessible without login Plain text file broken-switch.php Test Unit test script
  Accessible without login Plain text file class-comm.php Test Unit test script
  Accessible without login Plain text file classref-function.php Test Unit test script
  Accessible without login Plain text file classref.php Test Unit test script
  Accessible without login Plain text file close-tag-safe1.php Test Unit test script
  Accessible without login Plain text file close-tag-safe2.php Test Unit test script
  Accessible without login Plain text file close-tag-safe3.php Test Unit test script
  Accessible without login Plain text file close-tag-unsafe1.php Test Unit test script
  Accessible without login Plain text file closure.php Test Unit test script
  Accessible without login Plain text file comments.php Test Unit test script
  Accessible without login Plain text file const-comment.php Test Unit test script
  Accessible without login Plain text file const-nl.php Test Unit test script
  Accessible without login Plain text file cyrillic.php Test Unit test script
  Accessible without login Plain text file declare.php Test Unit test script
  Accessible without login Plain text file deref.php Test Unit test script
  Accessible without login Plain text file empty-call.php Test Unit test script
  Accessible without login Plain text file empty-method.php Test Unit test script
  Accessible without login Plain text file empty-while-foreach.php Test Unit test script
  Accessible without login Plain text file end-space.php Test Unit test script
  Accessible without login Plain text file expression-static-call.php Test Unit test script
  Accessible without login Plain text file finally.php Test Unit test script
  Accessible without login Plain text file function-name.php Test Unit test script
  Accessible without login Plain text file heredoc.php Test Unit test script
  Accessible without login Plain text file if-comment.php Test Unit test script
  Accessible without login Plain text file if.php Test Unit test script
  Accessible without login Plain text file implements.php Test Unit test script
  Accessible without login Plain text file increment.php Test Unit test script
  Accessible without login Plain text file instanceof.php Test Unit test script
  Accessible without login Plain text file long-arr.php Test Unit test script
  Accessible without login Plain text file long-classdef.php Test Unit test script
  Accessible without login Plain text file long-expr.php Test Unit test script
  Accessible without login Plain text file long-params.php Test Unit test script
  Accessible without login Plain text file long-signature-array.php Test Unit test script
  Accessible without login Plain text file long-with-hint.php Test Unit test script
  Accessible without login Plain text file longdef.php Test Unit test script
  Accessible without login Plain text file ma-inst.php Test Unit test script
  Accessible without login Plain text file multiline-concat.php Test Unit test script
  Accessible without login Plain text file namespaces.php Test Unit test script
  Accessible without login Plain text file opentag.php Test Unit test script
  Accessible without login Plain text file phpcf.php Test Unit test script
  Accessible without login Plain text file phpdoc.php Test Unit test script
  Accessible without login Plain text file several-times-apply.php Test Unit test script
  Accessible without login Plain text file short-array-ml.php Test Unit test script
  Accessible without login Plain text file short-array.php Test Unit test script
  Accessible without login Plain text file static.php Test Unit test script
  Accessible without login Plain text file switch-case.php Test Unit test script
  Accessible without login Plain text file ternary-ml.php Test Unit test script
  Accessible without login Plain text file ternary.php Test Unit test script
  Accessible without login Plain text file trait.php Test Unit test script
  Accessible without login Plain text file type-hint.php Test Unit test script
  Accessible without login Plain text file yield.php Test Unit test script

  Files folder image Files  /  phpcf-src  /  test  /  functional_dirty  
File Role Description
  Accessible without login Plain text file Test_after_commit.php Test Unit test script
  Accessible without login Plain text file Test_dirty.php Test Unit test script
  Accessible without login Plain text file Test_new_branch_formatted.php Test Unit test script
  Accessible without login Plain text file Test_new_commit.php Test Unit test script

  Files folder image Files  /  phpcf-src  /  test  /  original  
File Role Description
  Accessible without login Plain text file alignment.php Test Unit test script
  Accessible without login Plain text file anonymous.php Test Unit test script
  Accessible without login Plain text file binary-operators.php Test Unit test script
  Accessible without login Plain text file brace-after-comma.php Test Unit test script
  Accessible without login Plain text file broken-switch.php Test Unit test script
  Accessible without login Plain text file class-comm.php Test Unit test script
  Accessible without login Plain text file classref-function.php Test Unit test script
  Accessible without login Plain text file classref.php Test Unit test script
  Accessible without login Plain text file close-tag-safe1.php Test Unit test script
  Accessible without login Plain text file close-tag-safe2.php Test Unit test script
  Accessible without login Plain text file close-tag-safe3.php Test Unit test script
  Accessible without login Plain text file close-tag-unsafe1.php Test Unit test script
  Accessible without login Plain text file closure.php Test Unit test script
  Accessible without login Plain text file comments.php Test Unit test script
  Accessible without login Plain text file const-comment.php Test Unit test script
  Accessible without login Plain text file const-nl.php Test Unit test script
  Accessible without login Plain text file cyrillic.php Test Unit test script
  Accessible without login Plain text file declare.php Test Unit test script
  Accessible without login Plain text file deref.php Test Unit test script
  Accessible without login Plain text file empty-call.php Test Unit test script
  Accessible without login Plain text file empty-method.php Test Unit test script
  Accessible without login Plain text file empty-while-foreach.php Test Unit test script
  Accessible without login Plain text file end-space.php Test Unit test script
  Accessible without login Plain text file expression-static-call.php Test Unit test script
  Accessible without login Plain text file finally.php Test Unit test script
  Accessible without login Plain text file function-name.php Test Unit test script
  Accessible without login Plain text file heredoc.php Test Unit test script
  Accessible without login Plain text file if-comment.php Test Unit test script
  Accessible without login Plain text file if.php Test Unit test script
  Accessible without login Plain text file implements.php Test Unit test script
  Accessible without login Plain text file increment.php Test Unit test script
  Accessible without login Plain text file instanceof.php Test Unit test script
  Accessible without login Plain text file long-arr.php Test Unit test script
  Accessible without login Plain text file long-classdef.php Test Unit test script
  Accessible without login Plain text file long-expr.php Test Unit test script
  Accessible without login Plain text file long-params.php Test Unit test script
  Accessible without login Plain text file long-signature-array.php Test Unit test script
  Accessible without login Plain text file long-with-hint.php Test Unit test script
  Accessible without login Plain text file longdef.php Test Unit test script
  Accessible without login Plain text file ma-inst.php Test Unit test script
  Accessible without login Plain text file multiline-concat.php Test Unit test script
  Accessible without login Plain text file namespaces.php Test Unit test script
  Accessible without login Plain text file opentag.php Test Unit test script
  Accessible without login Plain text file phpcf.php Test Unit test script
  Accessible without login Plain text file phpdoc.php Test Unit test script
  Accessible without login Plain text file several-times-apply.php Test Unit test script
  Accessible without login Plain text file short-array-ml.php Test Unit test script
  Accessible without login Plain text file short-array.php Test Unit test script
  Accessible without login Plain text file static.php Test Unit test script
  Accessible without login Plain text file switch-case.php Test Unit test script
  Accessible without login Plain text file ternary-ml.php Test Unit test script
  Accessible without login Plain text file ternary.php Test Unit test script
  Accessible without login Plain text file trait.php Test Unit test script
  Accessible without login Plain text file type-hint.php Test Unit test script
  Accessible without login Plain text file yield.php Test Unit test script

 Version Control Unique User Downloads Download Rankings  
 100%
Total:283
This week:0
All time:7,560
This week:182Up