From c43d868eef5ee301990300f1ee2b1e63c2f56040 Mon Sep 17 00:00:00 2001 From: Denis Grinev Date: Wed, 20 Apr 2016 11:34:08 +0300 Subject: [PATCH] fix --- README.md | 96 +-- accepted/PSR-0.md | 77 +- accepted/PSR-1-basic-coding-standard.md | 153 ++-- accepted/PSR-2-coding-style-guide.md | 506 ++++++------- accepted/PSR-3-logger-interface.md | 304 -------- accepted/it/PSR-0.md | 76 -- accepted/it/PSR-1-basic-coding-standard.md | 177 ----- accepted/it/PSR-2-coding-style-guide.md | 812 --------------------- accepted/ru/PSR-0.md | 74 -- accepted/ru/PSR-1-basic-coding-standard.md | 175 ----- accepted/ru/PSR-2-coding-style-guide.md | 811 -------------------- bylaws/001-voting-protocol.md | 45 -- bylaws/002-psr-naming-conventions.md | 18 - proposed/.placeholder | 0 14 files changed, 379 insertions(+), 2945 deletions(-) delete mode 100644 accepted/PSR-3-logger-interface.md delete mode 100644 accepted/it/PSR-0.md delete mode 100644 accepted/it/PSR-1-basic-coding-standard.md delete mode 100644 accepted/it/PSR-2-coding-style-guide.md delete mode 100644 accepted/ru/PSR-0.md delete mode 100644 accepted/ru/PSR-1-basic-coding-standard.md delete mode 100644 accepted/ru/PSR-2-coding-style-guide.md delete mode 100644 bylaws/001-voting-protocol.md delete mode 100644 bylaws/002-psr-naming-conventions.md delete mode 100644 proposed/.placeholder diff --git a/README.md b/README.md index 112114fd7..55247bdaa 100644 --- a/README.md +++ b/README.md @@ -1,94 +1,8 @@ -PHP Framework Interoperability Group -==================================== - - Proposing a Standards Recommendation ------------------------------------- - -To propose a standards recommendation (PSR): - -- fork this repo, create a branch, checkout that branch, add the PSR in - `proposed/`, push the branch to Github, and send a pull request; or, - -- create a ticket to start a discussion on Github; or, - -- start a conversation on the [mailing list][]. - -[mailing list]: http://groups.google.com/group/php-fig/ - - -Requesting Membership ---------------------- - -You **do not** need to be a voting member to participate in discussion on -the [mailing list][]. - -To become a voting member, you must send an email to the [mailing list][]. - -- The subject line should read: `Membership Request: {$your_name} ({$project_name})` - -- The body should include your name, the name of (and link to) the project you - represent, and other details you feel are relevant. - -Current members will vote on your request. - -Do not combine separate membership requests in a single thread; one request -per thread, please. - - -Voting Members --------------- - -1. Nate Abele: Lithium - -1. Nils Adermann: phpBB - -1. Brett Bieber: PEAR, PEAR2 - -1. Guilherme Blanco: Doctrine, Doctrine2, et al. - -1. Jordi Boggiano: Composer, Packagist - -1. Karma Dordrak: Zikula - -1. Paul Dragoonis: PPI, PPI2 - -1. William Durand: Propel, Propel 2 - -1. Andrew Eddie: Joomla - -1. Cal Evans: the community at large - -1. Larry Garfield: Drupal - -1. Ivan Habunek: Apache log4php - -1. Paul M. Jones: Solar Framework, Aura Project - -1. Robert Lemke: TYPO3 Flow, TYPO3 Neos - -1. Larry Masters: CakePHP, CakePHP 2 - -1. John Mertic: SugarCRM - -1. Ryan Parman: Amazon Web Services SDK - -1. Evert Pot: SabreDAV - -1. Fabien Potencier: Symfony, Symfony2 - -1. Andre Romcke: eZ Publish - -1. Paul Scott: Chisimba, C4 - -1. Phil Sturgeon: PyroCMS - -1. Lukas Smith: Jackalope - -1. Kris Wallsmith: Assetic, Buzz - -1. Mike van Riel: phpDocumentor +==================================== -1. Matthew Weier O'Phinney: Zend Framework, Zend Framework 2 +PSR – это аббревиатура от Proposing a Standards Recommendation (предлагаемые рекомендации стандартов), которые были разработаны группой PHP Framework Interoperability Group, известная как PHP-FIG [http://www.php-fig.org/]. В число участников поддерживающих стандарты входят такие известные проекты как : phpBB, PEAR, Doctrine, Composer, Propel, CakePHP, Symfony, phpDocumentor, Zend и т.д. -1. David Zülke: Agavi + - PSR-0 Обязательные требования, которые должны соблюдаться в автозагрузчике. + - PSR-1 Основной стандарт написания кода. + - PSR-2 Руководство Оформления Кода. diff --git a/accepted/PSR-0.md b/accepted/PSR-0.md index 7d98c9472..76cb5874c 100644 --- a/accepted/PSR-0.md +++ b/accepted/PSR-0.md @@ -1,47 +1,48 @@ -The following describes the mandatory requirements that must be adhered -to for autoloader interoperability. - -Mandatory ---------- - -* A fully-qualified namespace and class must have the following - structure `\\(\)*` -* Each namespace must have a top-level namespace ("Vendor Name"). -* Each namespace can have as many sub-namespaces as it wishes. -* Each namespace separator is converted to a `DIRECTORY_SEPARATOR` when - loading from the file system. -* Each `_` character in the CLASS NAME is converted to a - `DIRECTORY_SEPARATOR`. The `_` character has no special meaning in the - namespace. -* The fully-qualified namespace and class is suffixed with `.php` when - loading from the file system. -* Alphabetic characters in vendor names, namespaces, and class names may - be of any combination of lower case and upper case. - -Examples --------- +Ниже описаны обязательные требования, которые должны соблюдаться в +автозагрузчике для взаимодействия. + +Обязательные +------------ + +* Полностью сформированное пространство имен и класс должны иметь следующую + структуру `\\(\)*` +* Каждое пространство имен должно иметь пространство имен верхнего уровня ("Vendor Name"). +* Каждое пространство имен может содержать столько вложенных пространств имен, + сколько ему необходимо. +* Каждый разделитель пространств имен преобразуется в `DIRECTORY_SEPARATOR` при + загрузке из файловой системы. +* Каждый символ `_` в ИМЕНИ КЛАССА преобразуется в `DIRECTORY_SEPARATOR`. + Символ `_` не имеет особого значения в пространстве имен. +* Полностью сформированное пространство имен и класс дополняются `.php` при + загрузке из файловой системы. +* Буквы в именах поставщиков, пространствах имен, и именах классов могут в любой комбинации + строчных и прописных букв. + +Примеры +------- * `\Doctrine\Common\IsolatedClassLoader` => `/path/to/project/lib/vendor/Doctrine/Common/IsolatedClassLoader.php` * `\Symfony\Core\Request` => `/path/to/project/lib/vendor/Symfony/Core/Request.php` * `\Zend\Acl` => `/path/to/project/lib/vendor/Zend/Acl.php` * `\Zend\Mail\Message` => `/path/to/project/lib/vendor/Zend/Mail/Message.php` -Underscores in Namespaces and Class Names ------------------------------------------ +Подчеркивания в Пространствах имен и Именах классов +--------------------------------------------------- * `\namespace\package\Class_Name` => `/path/to/project/lib/vendor/namespace/package/Class/Name.php` * `\namespace\package_name\Class_Name` => `/path/to/project/lib/vendor/namespace/package_name/Class/Name.php` -The standards we set here should be the lowest common denominator for -painless autoloader interoperability. You can test that you are -following these standards by utilizing this sample SplClassLoader -implementation which is able to load PHP 5.3 classes. +Стандарты установленные здесь должны быть наименьшим общим знаменателем для +безболезненного взаимодействия с автозагрузчиком. Вы можете проверить, что вы следуете +этим стандартам, используя предложенный пример SplClassLoader, реализующий возможность +загружать PHP 5.3 классы. + -Example Implementation ----------------------- +Пример реализации +----------------- -Below is an example function to simply demonstrate how the above -proposed standards are autoloaded. +Ниже приведен пример функции, чтобы просто показать, как выше +предложенные стандарты будут автоматически загружены. ```php ` tags or the short-echo `` tags; it -MUST NOT use the other tag variations. +PHP код ДОЛЖЕН использовать длинные `` теги или короткие-выводящие +`` теги; другие варианты тегов НЕ ДОЛЖНЫ использоваться. -### 2.2. Character Encoding +### 2.2. Кодировка символов -PHP code MUST use only UTF-8 without BOM. +PHP код ДОЛЖЕН использовать только UTF-8 без BOM. -### 2.3. Side Effects +### 2.3. Побочные эффекты -A file SHOULD declare new symbols (classes, functions, constants, -etc.) and cause no other side effects, or it SHOULD execute logic with side -effects, but SHOULD NOT do both. +Файлу СЛЕДУЕТ объявлять знаки (классы, функции, константы, и т.д.), +и не оказывать побочный эффект, или ему СЛЕДУЕТ выполнять логику с побочным +эффектом, но НЕ СЛЕДУЕТ делать и то и другое. -The phrase "side effects" means execution of logic not directly related to -declaring classes, functions, constants, etc., *merely from including the -file*. +Фраза "побочны эффекты" означает выполнение логики непосредственно не связанной с +объявлением классов, функций, констант и т.д., *просто от включения +файла*. -"Side effects" include but are not limited to: generating output, explicit -use of `require` or `include`, connecting to external services, modifying ini -settings, emitting errors or exceptions, modifying global or static variables, -reading from or writing to a file, and so on. +"Побочные эффекты" включают, но не ограничены: генерацией вывода, явным +использованием `require` или `include`, подключением к внешним сервисам, +изменениям настроек ini, испусканием ошибок или исключений, изменением глобальных +или статичных переменных, чтением или записью в файл, и так далее. -The following is an example of a file with both declarations and side effects; -i.e, an example of what to avoid: +Ниже приведен пример файла с одновременно объявляющий знаки и оказывающий +побочные эффекты; т.е., пример того, что следует избегать: ```php \n"; -// declaration +// описание function foo() { - // function body + // тело функции } ``` -The following example is of a file that contains declarations without side -effects; i.e., an example of what to emulate: +В следующем примере файл который содержит объявление без оказания побочных +эффектов; т.е., пример того, к чему следует стремится: ```php ` tag MUST be omitted from files containing only PHP. +Закрывающий `?>` тег ДОЛЖЕН быть исключен из файлов содержащих только PHP. -### 2.3. Lines +### 2.3. Строки -There MUST NOT be a hard limit on line length. +НЕ ДОЛЖНО быть жесткого ограничения на длину строки. -The soft limit on line length MUST be 120 characters; automated style checkers -MUST warn but MUST NOT error at the soft limit. +Мягкое ограничение на длину строки ДОЛЖНО быть 120 знаков; автоматические проверки +стиля ДОЛЖНЫ предупредить но НЕ ДОЛЖНЫ выдавать ошибку на мягкие ограничения. -Lines SHOULD NOT be longer than 80 characters; lines longer than that SHOULD -be split into multiple subsequent lines of no more than 80 characters each. +Строкам НЕ СЛЕДУЕТ быть длиннее 80 знаков; более длинные строки СЛЕДУЕТ +разбивать на несколько последующих строк не более чем 80 знаков в каждой. -There MUST NOT be trailing whitespace at the end of non-blank lines. +НЕ ДОЛЖНО быть замыкающий пробелов в конце строки на не пустых строках. -Blank lines MAY be added to improve readability and to indicate related -blocks of code. +Пустые строки МОГУТ быть добавлены для улучшения читабельности и указания +связанных блоков кода. -There MUST NOT be more than one statement per line. +НЕ ДОЛЖНО быть более одного оператора в строке. -### 2.4. Indenting +### 2.4. Отступы -Code MUST use an indent of 4 spaces, and MUST NOT use tabs for indenting. +Код ДОЛЖЕН использовать отступ в 4 пробела, и НЕ ДОЛЖЕН использовать табуляцию +для отступов. -> N.b.: Using only spaces, and not mixing spaces with tabs, helps to avoid -> problems with diffs, patches, history, and annotations. The use of spaces -> also makes it easy to insert fine-grained sub-indentation for inter-line -> alignment. +> Обратите особое внимание: Использование только пробелов, и не смешивание +> пробелов и табуляции, помогает избежать проблем с диффами, патчами, историей, +> и аннотациями. Использование пробелов также позволяет легко вставить +> тонко-настроенный суб-отступ для межстрочного выравнивания. -### 2.5. Keywords and True/False/Null +### 2.5. Ключевые слова и True/False/Null -PHP [keywords][] MUST be in lower case. +PHP [Ключевые слова][] ДОЛЖНЫ быть в нижнем регистре. -The PHP constants `true`, `false`, and `null` MUST be in lower case. +PHP константы `true`, `false`, и `null` ДОЛЖНЫ быть в нижнем регистре. -[keywords]: http://php.net/manual/en/reserved.keywords.php +[Ключевые слова]: http://php.net/manual/en/reserved.keywords.php -3. Namespace and Use Declarations ---------------------------------- +3. Объявление Пространства имен и Use +------------------------------------- -When present, there MUST be one blank line after the `namespace` declaration. +Если они присутствуют, то ДОЛЖНА быть одна пустая строка после объявления +`namespace`. -When present, all `use` declarations MUST go after the `namespace` -declaration. +Если они присутствуют, все объявления `use` ДОЛЖНЫ идти после объявления +`namespace`. -There MUST be one `use` keyword per declaration. +ДОЛЖНО быть ключевое слово `use` на каждое объявление. -There MUST be one blank line after the `use` block. +ДОЛЖНА быть одна пустая строка после блока `use`. -For example: +Например: ```php bar($arg1); Foo::bar($arg2, $arg3); ``` -Argument lists MAY be split across multiple lines, where each subsequent line -is indented once. When doing so, the first item in the list MUST be on the -next line, and there MUST be only one argument per line. +Списки аргументов МОГУТ быть разделены на несколько строк, где каждая +последующая строка с одним отступом. При этом первый элемент в списке ДОЛЖЕН +быть на следующей строке, и ДОЛЖЕН быть только один аргумент на строку. ```php bar( ); ``` -5. Control Structures ---------------------- +5. Управляющие конструкции +-------------------------- -The general style rules for control structures are as follows: +Общие правила стиля для управляющих конструкций следующие: -- There MUST be one space after the control structure keyword -- There MUST NOT be a space after the opening parenthesis -- There MUST NOT be a space before the closing parenthesis -- There MUST be one space between the closing parenthesis and the opening - brace -- The structure body MUST be indented once -- The closing brace MUST be on the next line after the body +- ДОЛЖЕН быть один пробел после ключевого слова управляющей конструкции +- НЕ ДОЛЖНО быть пробела после открывающих круглых скобок +- НЕ ДОЛЖНО быть пробела перед закрывающими круглыми скобками +- ДОЛЖЕН быть один пробел между закрывающей круглой скобкой и открывающей + фигурной скобкой +- Тело конструкции должно быть с одним отступом +- Закрывающая фигурная скобка ДОЛЖНА быть на следующей строке после тела + управляющей конструкции -The body of each structure MUST be enclosed by braces. This standardizes how -the structures look, and reduces the likelihood of introducing errors as new -lines get added to the body. +Тело каждой конструкции ДОЛЖНО быть заключено в фигурные скобки. Это +стандартизирует вид конструкций, и уменьшает вероятность внесения ошибок +при добавлении новых строк к телу управляющей конструкции. ### 5.1. `if`, `elseif`, `else` -An `if` structure looks like the following. Note the placement of parentheses, -spaces, and braces; and that `else` and `elseif` are on the same line as the -closing brace from the earlier body. +Оператор `if` выглядит следующим образом. Обратите внимание на размещение +круглых скобок, пробелов и фигурных скобок; и что `else` и `elseif` находятся +на одной линии, как и закрывающая фигурная скобка тела оператора. ```php $value) { - // foreach body + // тело оператора foreach } ``` ### 5.6. `try`, `catch` -A `try catch` block looks like the following. Note the placement of -parentheses, spaces, and braces. +Блок `try catch` выглядит следующим образом. Обратите внимание на размещение +круглых скобок, пробелов и фигурных скобок. ```php bar( $arg1, function ($arg2) use ($var1) { - // body + // тело функции }, $arg3 ); ``` -7. Conclusion --------------- +7. Заключение +------------- -There are many elements of style and practice intentionally omitted by this -guide. These include but are not limited to: +Есть много элементов оформления и практик умышленно опущенных в этом +руководстве. Они включают, но не ограничиваются: -- Declaration of global variables and global constants +- Объявление глобальных переменных и глобальных констант -- Declaration of functions +- Объявление функций -- Operators and assignment +- Операторы и присваивания -- Inter-line alignment +- Вписанное выравнивание -- Comments and documentation blocks +- Комментарии и блоки документации -- Class name prefixes and suffixes +- Приставки и окончания имен классов -- Best practices +- Практический опыт -Future recommendations MAY revise and extend this guide to address those or -other elements of style and practice. +Будущее рекомендации МОГУТ пересмотреть и расширить это руководство для решения +тех или иных элементов оформления и практик. -Appendix A. Survey ------------------- +Приложение A. Опрос +------------------- -In writing this style guide, the group took a survey of member projects to -determine common practices. The survey is retained herein for posterity. +При написании этого руководства оформления, группа провела опрос участвующих +проектов для определения общих практик. Опрос сохраняется в настоящем +документе для потомков. -### A.1. Survey Data +### A.1. Данные опроса url,http://www.horde.org/apps/horde/docs/CODING_STANDARDS,http://pear.php.net/manual/en/standards.php,http://solarphp.com/manual/appendix-standards.style,http://framework.zend.com/manual/en/coding-standard.html,http://symfony.com/doc/2.0/contributing/code/standards.html,http://www.ppi.io/docs/coding-standards.html,https://github.com/ezsystems/ezp-next/wiki/codingstandards,http://book.cakephp.org/2.0/en/contributing/cakephp-coding-conventions.html,https://github.com/UnionOfRAD/lithium/wiki/Spec%3A-Coding,http://drupal.org/coding-standards,http://code.google.com/p/sabredav/,http://area51.phpbb.com/docs/31x/coding-guidelines.html,https://docs.google.com/a/zikula.org/document/edit?authkey=CPCU0Us&hgd=1&id=1fcqb93Sn-hR9c0mkN6m_tyWnmEvoswKBtSc0tKkZmJA,http://www.chisimba.com,n/a,https://github.com/Respect/project-info/blob/master/coding-standards-sample.php,n/a,Object Calisthenics for PHP,http://doc.nette.org/en/coding-standard,http://flow3.typo3.org,https://github.com/propelorm/Propel2/wiki/Coding-Standards,http://developer.joomla.org/coding-standards.html voting,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,no,no,no,?,yes,no,yes @@ -654,72 +662,72 @@ determine common practices. The survey is retained herein for posterity. blank_line_after_php,no,no,no,no,yes,no,no,no,no,yes,yes,no,no,yes,?,yes,yes,no,yes,no,yes,no class_method_control_brace,next/next/same,next/next/same,next/next/same,next/next/same,next/next/same,same/same/same,next/next/next,same/same/same,same/same/same,same/same/same,same/same/same,next/next/next,next/next/same,next/same/same,next/next/next,next/next/same,next/next/same,next/next/same,next/next/same,same/same/same,next/next/same,next/next/next -### A.2. Survey Legend +### A.2. Условные обозначения опроса `indent_type`: -The type of indenting. `tab` = "Use a tab", `2` or `4` = "number of spaces" +Тип отступов. `tab` = "использование табуляции", `2` или `4` = "количество пробелов" `line_length_limit_soft`: -The "soft" line length limit, in characters. `?` = not discernible or no response, `no` means no limit. +"Мягкое" ограничение на длину строки, в знаках. `?` = не различимо или нет ответа, `no` значит нет лимита. `line_length_limit_hard`: -The "hard" line length limit, in characters. `?` = not discernible or no response, `no` means no limit. +"Жесткое" ограничение на длину строки, в знаках. `?` = не различимо или нет ответа, `no` значит нет лимита. `class_names`: -How classes are named. `lower` = lowercase only, `lower_under` = lowercase with underscore separators, `studly` = StudlyCase. +Как классы называются? `lower` = только строчные, `lower_under` = строчные с подчеркиванием разделителем, `studly` = StudlyCase. `class_brace_line`: -Does the opening brace for a class go on the `same` line as the class keyword, or on the `next` line after it? +Идет ли открывающая фигурная скобка класса на той же (`same`) линии что и ключевое слово класса, или на следующей (`next`) линии после нее? `constant_names`: How are class constants named? `upper` = Uppercase with underscore separators. `true_false_null`: -Are the `true`, `false`, and `null` keywords spelled as all `lower` case, or all `upper` case? +Ключевые слова `true`, `false`, и `null` написаны полностью строчными (`lower`), или полностью прописными (`upper`)? `method_names`: -How are methods named? `camel` = `camelCase`, `lower_under` = lowercase with underscore separators. +Как методы называются? `camel` = `camelCase`, `lower_under` = строчные с подчеркиванием разделителем. `method_brace_line`: -Does the opening brace for a method go on the `same` line as the method name, or on the `next` line? +Идет ли открывающая фигурная скобка метода на той же (`same`) линии что и ключевое слово метода, или на следующей (`next`) линии после нее? `control_brace_line`: -Does the opening brace for a control structure go on the `same` line, or on the `next` line? +Идет ли открывающая фигурная скобка управляющей конструкции на той же (`same`) линии, или на следующей (`next`)? `control_space_after`: -Is there a space after the control structure keyword? +Есть ли пробел после ключевого слова управляющей конструкции? `always_use_control_braces`: -Do control structures always use braces? +Всего использовать фигурные скобки для управляющих конструкций? `else_elseif_line`: -When using `else` or `elseif`, does it go on the `same` line as the previous closing brace, or does it go on the `next` line? +Когда используется `else` или `elseif`, идет ли оно на той же (`same`) линии, что и предыдущая закрывающая фигурная скобка, или оно идет на следующей (`next`) линии? `case_break_indent_from_switch`: -How many times are `case` and `break` indented from an opening `switch` statement? +На сколько отступов `case` и `break` от открывающего оператора `switch`? `function_space_after`: -Do function calls have a space after the function name and before the opening parenthesis? +При вызове функций есть ли пробел после имени функции и перед открывающими круглыми скобками? `closing_php_tag_required`: -In files containing only PHP, is the closing `?>` tag required? +В файлах содержащих только PHP необходим ли закрывающий `?>` тег? `line_endings`: -What type of line ending is used? +Какой тип окончания строки используется? `static_or_visibility_first`: -When declaring a method, does `static` come first, or does the visibility come first? +Когда объявляется метод, то `static` идет впереди, или область видимости идет впереди? `control_space_parens`: -In a control structure expression, is there a space after the opening parenthesis and a space before the closing parenthesis? `yes` = `if ( $expr )`, `no` = `if ($expr)`. +В выражении управляющей конструкции, есть ли пробел после открывающей круглой скобки, и пробел перед закрывающей круглой скобкой? `yes` = `if ( $expr )`, `no` = `if ($expr)`. `blank_line_after_php`: -Is there a blank line after the opening PHP tag? +Есть ли пустая строка после открытия PHP тега? `class_method_control_brace`: -A summary of what line the opening braces go on for classes, methods, and control structures. +Сводка на какой линии идет открывающая фигурная скобка после классов, методов, и управляющих конструкций. -### A.3. Survey Results +### A.3. Результаты опроса indent_type: tab: 7 diff --git a/accepted/PSR-3-logger-interface.md b/accepted/PSR-3-logger-interface.md deleted file mode 100644 index 24f968bc4..000000000 --- a/accepted/PSR-3-logger-interface.md +++ /dev/null @@ -1,304 +0,0 @@ -Logger Interface -================ - -This document describes a common interface for logging libraries. - -The main goal is to allow libraries to receive a `Psr\Log\LoggerInterface` -object and write logs to it in a simple and universal way. Frameworks -and CMSs that have custom needs MAY extend the interface for their own -purpose, but SHOULD remain compatible with this document. This ensures -that the third-party libraries an application uses can write to the -centralized application logs. - -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", -"SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be -interpreted as described in [RFC 2119][]. - -The word `implementor` in this document is to be interpreted as someone -implementing the `LoggerInterface` in a log-related library or framework. -Users of loggers are refered to as `user`. - -[RFC 2119]: http://tools.ietf.org/html/rfc2119 - -1. Specification ------------------ - -### 1.1 Basics - -- The `LoggerInterface` exposes eight methods to write logs to the eight - [RFC 5424][] levels (debug, info, notice, warning, error, critical, alert, - emergency). - -- A ninth method, `log`, accepts a log level as first argument. Calling this - method with one of the log level constants MUST have the same result as - calling the level-specific method. Calling this method with a level not - defined by this specification MUST throw a `Psr\Log\InvalidArgumentException` - if the implementation does not know about the level. Users SHOULD NOT use a - custom level without knowing for sure the current implementation supports it. - -[RFC 5424]: http://tools.ietf.org/html/rfc5424 - -### 1.2 Message - -- Every method accepts a string as the message, or an object with a - `__toString()` method. Implementors MAY have special handling for the passed - objects. If that is not the case, implementors MUST cast it to a string. - -- The message MAY contain placeholders which implementors MAY replace with - values from the context array. - - Placeholder names MUST correspond to keys in the context array. - - Placeholder names MUST be delimited with a single opening brace `{` and - a single closing brace `}`. There MUST NOT be any whitespace between the - delimiters and the placeholder name. - - Placeholder names SHOULD be composed only of the characters `A-Z`, `a-z`, - `0-9`, underscore `_`, and period `.`. The use of other characters is - reserved for future modifications of the placeholders specification. - - Implementors MAY use placeholders to implement various escaping strategies - and translate logs for display. Users SHOULD NOT pre-escape placeholder - values since they can not know in which context the data will be displayed. - - The following is an example implementation of placeholder interpolation - provided for reference purposes only: - - ```php - /** - * Interpolates context values into the message placeholders. - */ - function interpolate($message, array $context = array()) - { - // build a replacement array with braces around the context keys - $replace = array(); - foreach ($context as $key => $val) { - $replace['{' . $key . '}'] = $val; - } - - // interpolate replacement values into the message and return - return strtr($message, $replace); - } - - // a message with brace-delimited placeholder names - $message = "User {username} created"; - - // a context array of placeholder names => replacement values - $context = array('username' => 'bolivar'); - - // echoes "Username bolivar created" - echo interpolate($message, $context); - ``` - -### 1.3 Context - -- Every method accepts an array as context data. This is meant to hold any - extraneous information that does not fit well in a string. The array can - contain anything. Implementors MUST ensure they treat context data with - as much lenience as possible. A given value in the context MUST NOT throw - an exception nor raise any php error, warning or notice. - -- If an `Exception` object is passed in the context data, it MUST be in the - `'exception'` key. Logging exceptions is a common pattern and this allows - implementors to extract a stack trace from the exception when the log - backend supports it. Implementors MUST still verify that the `'exception'` - key is actually an `Exception` before using it as such, as it MAY contain - anything. - -### 1.4 Helper classes and interfaces - -- The `Psr\Log\AbstractLogger` class lets you implement the `LoggerInterface` - very easily by extending it and implementing the generic `log` method. - The other eight methods are forwarding the message and context to it. - -- Similarly, using the `Psr\Log\LoggerTrait` only requires you to - implement the generic `log` method. Note that since traits can not implement - interfaces, in this case you still have to `implement LoggerInterface`. - -- The `Psr\Log\NullLogger` is provided together with the interface. It MAY be - used by users of the interface to provide a fall-back "black hole" - implementation if no logger is given to them. However conditional logging - may be a better approach if context data creation is expensive. - -- The `Psr\Log\LoggerAwareInterface` only contains a - `setLogger(LoggerInterface $logger)` method and can be used by frameworks to - auto-wire arbitrary instances with a logger. - -- The `Psr\Log\LoggerAwareTrait` trait can be used to implement the equivalent - interface easily in any class. It gives you access to `$this->logger`. - -- The `Psr\Log\LogLevel` class holds constants for the eight log levels. - -2. Package ----------- - -The interfaces and classes described as well as relevant exception classes -and a test suite to verify your implementation is provided as part of the -[psr/log](https://packagist.org/packages/psr/log) package. - -3. `Psr\Log\LoggerInterface` ----------------------------- - -```php -\(\)*` -* Ogni namespace deve avere un namespace di primo livello ("Nome Vendor"). -* Ogni namespace può avere una quantità arbitraria di sotto-namespace. -* Ogni separatore di namespace deve essere convertito in un `DIRECTORY_SEPARATOR` al - caricamento da file system. -* Ogni carattere `_` nel NOME DELLA CLASSE deve essere convertito in un - `DIRECTORY_SEPARATOR`. Il carattere `_` non ha nessun significato particolare nel - namespace. -* Al fully-qualified namespace e alla classe viene apposto il suffisso `.php` al - caricamento da file system. -* I caratteri alfabetici nei nomi dei vendor, nei namespace, e nei nomi delle classi possono - formare una qualsiasi combinazione di caratteri minuscoli e caratteri maiuscoli. - -Esempi --------- - -* `\Doctrine\Common\IsolatedClassLoader` => `/percorso/del/mio/progetto/lib/vendor/Doctrine/Common/IsolatedClassLoader.php` -* `\Symfony\Core\Request` => `/percorso/del/mio/progetto/lib/vendor/Symfony/Core/Request.php` -* `\Zend\Acl` => `/percorso/del/mio/progetto/lib/vendor/Zend/Acl.php` -* `\Zend\Mail\Message` => `/percorso/del/mio/progetto/lib/vendor/Zend/Mail/Message.php` - -Underscore nei Namespace e nei Nomi delle Classi -------------------------------------------------- - -* `\namespace\package\Nome_Classe` => `/percorso/del/mio/progetto/lib/vendor/namespace/package/Nome/Classe.php` -* `\namespace\package_name\Nome_Classe` => `/percorso/del/mio/progetto/lib/vendor/namespace/package_name/Nome/Classe.php` - -Gli standard che abbiamo fissato dovrebbero essere il minimo comune -denominatore per l'interoperabilità indolore tra gli autoloader. Puoi -verificare l'aderenza del tuo codice agli standard utilizzando questa -implementazione esemplificativa dell'SplClassLoader, in grado di caricare -classi PHP 5.3. - -Esempio di implementazione ---------------------------- - -Di seguito una funzione per dimostrare im modo semplice come gli standard -proposti in precedenza permettano il caricamento automatico delle classi. - -```php -` o la versione -dei tag short-echo ``; NON DEVONO essere usate altre varianti dei tag. - -### 2.2. Codifica dei caratteri - -Per il codice PHP si DEVE usare soltanto UTF-8 senza BOM. - -### 2.3. Effetti collaterali - -Un file DOVREBBE dichiarare nuovi simboli (classi, funzioni, costanti, -etc.) senza causare altri effetti collaterali, oppure DOVREBBE eseguire logica -con effetti collaterali, ma NON DOVREBBE fare entrambe le cose. - -Con l'espressione "effetti collaterali" si intende l'esecuzione di logica non -direttamente correlata alla dichiarazione delle classi, delle funzioni, delle -costanti, etc., *al di fuori dell'inclusione del file*. - -Gli "effetti collaterali" includono, ma non sono limitati ai seguenti casi: -generazione di output, uso esplicito di `require` o `include`, connessione a -servizi esterni, modifica delle impostazioni ini, emissione di errori o eccezioni, -modifica di variabili globali o statiche, lettura o scrittura di file, e così via. - -Di seguito un esempio con un file in cui sono presenti sia dichiarazioni che effetti -collaterali; ecco un esempio di quello che va evitato: - -```php -\n"; - -// dichiarazione -function foo() -{ - // corpo della funzione -} -``` - -L'esempio che segue è un file che contiene dichiarazioni senza effetti -collaterali; ecco un esempio da imitare: - -```php - $b) { - $foo->bar($arg1); - } else { - BazClass::bar($arg2, $arg3); - } - } - - final public static function bar() - { - // corpo del metodo - } -} -``` - -2. Regole Generali -------------------- - -### 2.1 Standard elementare di scrittura codice - -Il codice DEVE seguire tutte le regole delineane nel [PSR-1][]. - -### 2.2 I file - -Tutti i file PHP DEVONO usare lo Unix LF (linefeed) per terminare la riga. - -Tutti i file PHP DEVONO finire con una singola riga vuota. - -Il tag `?>` di chiusura DEVE essere omesso dai file che contengono soltanto PHP. - -### 2.3. Le righe - -NON DEVE esserci un limite rigido nella lunghezza delle righe. - -Il limite debole sulla lunghezza delle righe DEVE essere di 120 caratteri; correttori -automatici di sile DEVONO avvertire ma NON DEVONO andare in errore al raggiungimento -del limite debole. - -Le righe NON DOVREBBERO essere più lunghe di 80 caratteri; righe più lunghe DOVREBBERO -essere divise in righe multiple successive, ognuna lunga non più di 80 caratteri. - -NON DEVONO esserci spazi alla fine di righe non vuote. - -Righe vuote POSSONO essere aggiunte per migliorare la leggibilità e per indicare -blocchi di codice correlati. - -NON PUO' esserci più di una dichiarazione per riga. - -### 2.4. Indentazione - -Il codice DEVE usare un'indentazione di 4 spazi, e NON DEVE usare tabulazioni per -l'indentazione. - -> N.b.: L'uso dei soli spazi, senza mischiare spazi e tabulazioni, aiuta -> ad evitare problemi con i diff, le patch, la cronologia e le annotazioni. L'uso di -> spazi rende peraltro facile l'inserimento di sotto-indentazione a grana fine -> per l'allineamento inter-riga. - -### 2.5. Keyword e True/False/Null - -Le [keywords][] PHP DEVONO essere minuscole. - -Le costanti PHP `true`, `false`, e `null` DEVONO essere minuscole. - -[keywords]: http://php.net/manual/en/reserved.keywords.php - - - -3. Namespace e dichiarazioni Use ---------------------------------- - -Quando presente, DEVE esserci una riga vuota dopo la dichiarazione `namespace`. - -Quando presenti, tutte le dichiarazioni `use` DEVONO andare dopo la dichiarazione -`namespace`. - -DEVE esserci una keyword `use` per dichiarazione. - -DEVE esserci una riga vuota dopo il blocco `use`. - -Per esempio: - -```php -bar($arg1); -Foo::bar($arg2, $arg3); -``` - -La lista di argomenti PUO' essere divisa su righe multiple, dove ogni riga seguente -è indentata una volta. In questo caso, il primo elemento nella lista DEVE essere -sulla riga seguente e DEVE esserci un solo argomento per riga. - -```php -bar( - $argomentoLungo, - $argomentoPiuLungo, - $argomentoAncoraPiuLungo -); -``` - -5. Strutture di controllo --------------------------- - -Le regole generali per le strutture di controllo sono le seguenti: - -- DEVE esserci uno spazio dopo la keyword della struttura di controllo -- NON DEVE esserci uno spazio dopo la parentesi di apertura -- NON DEVE esserci uno spazio prima della parentesi di chiusura -- DEVE esserci uno spazio tra la parentesi di chiusura le la graffa di - apertura -- Il corpo della struttura DEVE essere indentato una volta -- La graffa di chiusura DEVE essere sulla riga seguente, dopo il corpo - -Il corpo di ogni struttura DEVE essere racchiuso tra graffe. In questo modo -l'aspetto della struttura è standardizzato, e si riduce la probabilità di -introdurre errori quando si aggiungono nuove righe al corpo. - -### 5.1. `if`, `elseif`, `else` - -Una struttura `if` dovrebbe essere come la seguente. Da notare il posizionamento -delle parentesi, degli spazi e delle graffe; e il fatto che `else` e `elseif` - sono sulla stessa riga in cui si trova la graffa di chiusura del corpo precedente. - -```php - $value) { - // corpo del foreach -} -``` - -### 5.6. `try`, `catch` - -Una dichiarazione `try catch` dovrebbe essere come la seguente. Da notare -il posizionamento delle parentesi, degli spazi e delle graffe. - -```php -bar( - $arg1, - function ($arg2) use ($var1) { - // corpo - }, - $arg3 -); -``` - - -7. Conclusioni ----------------- - -Ci sono molti elementi di stile e pratiche tralasciate intenzionalmente da -questa guida. Questi includono, ma non sono limitati a: - -- Dichiarazioni di variabili globali e globali costanti - -- Dichiarazione di funzioni - -- Operatori e assegnazioni - -- Allineamento inter-riga - -- Commenti e blocchi di documentazione - -- Prefissi e suffissi dei nomi delle classi - -- Pratiche consigliate - -Raccomandazioni future POSSONO rivedere ed estendere questa guida per parlare di -questi o altri elementi di stile e pratiche. - - -Appendix A. Sondaggio ----------------------- - -Nello scrivere questa guida di sitle, il gruppo ha tenuto un sondaggio tra i -progetti-membro per determinare le pratiche comuni. Il sondaggio è riportato qui -di seguito a beneficio futuro. - -### A.1. Survey Data - - url,http://www.horde.org/apps/horde/docs/CODING_STANDARDS,http://pear.php.net/manual/en/standards.php,http://solarphp.com/manual/appendix-standards.style,http://framework.zend.com/manual/en/coding-standard.html,http://symfony.com/doc/2.0/contributing/code/standards.html,http://www.ppi.io/docs/coding-standards.html,https://github.com/ezsystems/ezp-next/wiki/codingstandards,http://book.cakephp.org/2.0/en/contributing/cakephp-coding-conventions.html,https://github.com/UnionOfRAD/lithium/wiki/Spec%3A-Coding,http://drupal.org/coding-standards,http://code.google.com/p/sabredav/,http://area51.phpbb.com/docs/31x/coding-guidelines.html,https://docs.google.com/a/zikula.org/document/edit?authkey=CPCU0Us&hgd=1&id=1fcqb93Sn-hR9c0mkN6m_tyWnmEvoswKBtSc0tKkZmJA,http://www.chisimba.com,n/a,https://github.com/Respect/project-info/blob/master/coding-standards-sample.php,n/a,Object Calisthenics for PHP,http://doc.nette.org/en/coding-standard,http://flow3.typo3.org,https://github.com/propelorm/Propel2/wiki/Coding-Standards,http://developer.joomla.org/coding-standards.html - voting,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,no,no,no,?,yes,no,yes - indent_type,4,4,4,4,4,tab,4,tab,tab,2,4,tab,4,4,4,4,4,4,tab,tab,4,tab - line_length_limit_soft,75,75,75,75,no,85,120,120,80,80,80,no,100,80,80,?,?,120,80,120,no,150 - line_length_limit_hard,85,85,85,85,no,no,no,no,100,?,no,no,no,100,100,?,120,120,no,no,no,no - class_names,studly,studly,studly,studly,studly,studly,studly,studly,studly,studly,studly,lower_under,studly,lower,studly,studly,studly,studly,?,studly,studly,studly - class_brace_line,next,next,next,next,next,same,next,same,same,same,same,next,next,next,next,next,next,next,next,same,next,next - constant_names,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper - true_false_null,lower,lower,lower,lower,lower,lower,lower,lower,lower,upper,lower,lower,lower,upper,lower,lower,lower,lower,lower,upper,lower,lower - method_names,camel,camel,camel,camel,camel,camel,camel,camel,camel,camel,camel,lower_under,camel,camel,camel,camel,camel,camel,camel,camel,camel,camel - method_brace_line,next,next,next,next,next,same,next,same,same,same,same,next,next,same,next,next,next,next,next,same,next,next - control_brace_line,same,same,same,same,same,same,next,same,same,same,same,next,same,same,next,same,same,same,same,same,same,next - control_space_after,yes,yes,yes,yes,yes,no,yes,yes,yes,yes,no,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes - always_use_control_braces,yes,yes,yes,yes,yes,yes,no,yes,yes,yes,no,yes,yes,yes,yes,no,yes,yes,yes,yes,yes,yes - else_elseif_line,same,same,same,same,same,same,next,same,same,next,same,next,same,next,next,same,same,same,same,same,same,next - case_break_indent_from_switch,0/1,0/1,0/1,1/2,1/2,1/2,1/2,1/1,1/1,1/2,1/2,1/1,1/2,1/2,1/2,1/2,1/2,1/2,0/1,1/1,1/2,1/2 - function_space_after,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no - closing_php_tag_required,no,no,no,no,no,no,no,no,yes,no,no,no,no,yes,no,no,no,no,no,yes,no,no - line_endings,LF,LF,LF,LF,LF,LF,LF,LF,?,LF,?,LF,LF,LF,LF,?,,LF,?,LF,LF,LF - static_or_visibility_first,static,?,static,either,either,either,visibility,visibility,visibility,either,static,either,?,visibility,?,?,either,either,visibility,visibility,static,? - control_space_parens,no,no,no,no,no,no,yes,no,no,no,no,no,no,yes,?,no,no,no,no,no,no,no - blank_line_after_php,no,no,no,no,yes,no,no,no,no,yes,yes,no,no,yes,?,yes,yes,no,yes,no,yes,no - class_method_control_brace,next/next/same,next/next/same,next/next/same,next/next/same,next/next/same,same/same/same,next/next/next,same/same/same,same/same/same,same/same/same,same/same/same,next/next/next,next/next/same,next/same/same,next/next/next,next/next/same,next/next/same,next/next/same,next/next/same,same/same/same,next/next/same,next/next/next - -### A.2. Survey Legend - -`indent_type`: -The type of indenting. `tab` = "Use a tab", `2` or `4` = "number of spaces" - -`line_length_limit_soft`: -The "soft" line length limit, in characters. `?` = not discernible or no response, `no` means no limit. - -`line_length_limit_hard`: -The "hard" line length limit, in characters. `?` = not discernible or no response, `no` means no limit. - -`class_names`: -How classes are named. `lower` = lowercase only, `lower_under` = lowercase with underscore separators, `studly` = StudlyCase. - -`class_brace_line`: -Does the opening brace for a class go on the `same` line as the class keyword, or on the `next` line after it? - -`constant_names`: -How are class constants named? `upper` = Uppercase with underscore separators. - -`true_false_null`: -Are the `true`, `false`, and `null` keywords spelled as all `lower` case, or all `upper` case? - -`method_names`: -How are methods named? `camel` = `camelCase`, `lower_under` = lowercase with underscore separators. - -`method_brace_line`: -Does the opening brace for a method go on the `same` line as the method name, or on the `next` line? - -`control_brace_line`: -Does the opening brace for a control structure go on the `same` line, or on the `next` line? - -`control_space_after`: -Is there a space after the control structure keyword? - -`always_use_control_braces`: -Do control structures always use braces? - -`else_elseif_line`: -When using `else` or `elseif`, does it go on the `same` line as the previous closing brace, or does it go on the `next` line? - -`case_break_indent_from_switch`: -How many times are `case` and `break` indented from an opening `switch` statement? - -`function_space_after`: -Do function calls have a space after the function name and before the opening parenthesis? - -`closing_php_tag_required`: -In files containing only PHP, is the closing `?>` tag required? - -`line_endings`: -What type of line ending is used? - -`static_or_visibility_first`: -When declaring a method, does `static` come first, or does the visibility come first? - -`control_space_parens`: -In a control structure expression, is there a space after the opening parenthesis and a space before the closing parenthesis? `yes` = `if ( $expr )`, `no` = `if ($expr)`. - -`blank_line_after_php`: -Is there a blank line after the opening PHP tag? - -`class_method_control_brace`: -A summary of what line the opening braces go on for classes, methods, and control structures. - -### A.3. Survey Results - - indent_type: - tab: 7 - 2: 1 - 4: 14 - line_length_limit_soft: - ?: 2 - no: 3 - 75: 4 - 80: 6 - 85: 1 - 100: 1 - 120: 4 - 150: 1 - line_length_limit_hard: - ?: 2 - no: 11 - 85: 4 - 100: 3 - 120: 2 - class_names: - ?: 1 - lower: 1 - lower_under: 1 - studly: 19 - class_brace_line: - next: 16 - same: 6 - constant_names: - upper: 22 - true_false_null: - lower: 19 - upper: 3 - method_names: - camel: 21 - lower_under: 1 - method_brace_line: - next: 15 - same: 7 - control_brace_line: - next: 4 - same: 18 - control_space_after: - no: 2 - yes: 20 - always_use_control_braces: - no: 3 - yes: 19 - else_elseif_line: - next: 6 - same: 16 - case_break_indent_from_switch: - 0/1: 4 - 1/1: 4 - 1/2: 14 - function_space_after: - no: 22 - closing_php_tag_required: - no: 19 - yes: 3 - line_endings: - ?: 5 - LF: 17 - static_or_visibility_first: - ?: 5 - either: 7 - static: 4 - visibility: 6 - control_space_parens: - ?: 1 - no: 19 - yes: 2 - blank_line_after_php: - ?: 1 - no: 13 - yes: 8 - class_method_control_brace: - next/next/next: 4 - next/next/same: 11 - next/same/same: 1 - same/same/same: 6 diff --git a/accepted/ru/PSR-0.md b/accepted/ru/PSR-0.md deleted file mode 100644 index 76cb5874c..000000000 --- a/accepted/ru/PSR-0.md +++ /dev/null @@ -1,74 +0,0 @@ -Ниже описаны обязательные требования, которые должны соблюдаться в -автозагрузчике для взаимодействия. - -Обязательные ------------- - -* Полностью сформированное пространство имен и класс должны иметь следующую - структуру `\\(\)*` -* Каждое пространство имен должно иметь пространство имен верхнего уровня ("Vendor Name"). -* Каждое пространство имен может содержать столько вложенных пространств имен, - сколько ему необходимо. -* Каждый разделитель пространств имен преобразуется в `DIRECTORY_SEPARATOR` при - загрузке из файловой системы. -* Каждый символ `_` в ИМЕНИ КЛАССА преобразуется в `DIRECTORY_SEPARATOR`. - Символ `_` не имеет особого значения в пространстве имен. -* Полностью сформированное пространство имен и класс дополняются `.php` при - загрузке из файловой системы. -* Буквы в именах поставщиков, пространствах имен, и именах классов могут в любой комбинации - строчных и прописных букв. - -Примеры -------- - -* `\Doctrine\Common\IsolatedClassLoader` => `/path/to/project/lib/vendor/Doctrine/Common/IsolatedClassLoader.php` -* `\Symfony\Core\Request` => `/path/to/project/lib/vendor/Symfony/Core/Request.php` -* `\Zend\Acl` => `/path/to/project/lib/vendor/Zend/Acl.php` -* `\Zend\Mail\Message` => `/path/to/project/lib/vendor/Zend/Mail/Message.php` - -Подчеркивания в Пространствах имен и Именах классов ---------------------------------------------------- - -* `\namespace\package\Class_Name` => `/path/to/project/lib/vendor/namespace/package/Class/Name.php` -* `\namespace\package_name\Class_Name` => `/path/to/project/lib/vendor/namespace/package_name/Class/Name.php` - -Стандарты установленные здесь должны быть наименьшим общим знаменателем для -безболезненного взаимодействия с автозагрузчиком. Вы можете проверить, что вы следуете -этим стандартам, используя предложенный пример SplClassLoader, реализующий возможность -загружать PHP 5.3 классы. - - -Пример реализации ------------------ - -Ниже приведен пример функции, чтобы просто показать, как выше -предложенные стандарты будут автоматически загружены. -```php -` теги или короткие-выводящие -`` теги; другие варианты тегов НЕ ДОЛЖНЫ использоваться. - -### 2.2. Кодировка символов - -PHP код ДОЛЖЕН использовать только UTF-8 без BOM. - -### 2.3. Побочные эффекты - -Файлу СЛЕДУЕТ объявлять знаки (классы, функции, константы, и т.д.), -и не оказывать побочный эффект, или ему СЛЕДУЕТ выполнять логику с побочным -эффектом, но НЕ СЛЕДУЕТ делать и то и другое. - -Фраза "побочны эффекты" означает выполнение логики непосредственно не связанной с -объявлением классов, функций, констант и т.д., *просто от включения -файла*. - -"Побочные эффекты" включают, но не ограничены: генерацией вывода, явным -использованием `require` или `include`, подключением к внешним сервисам, -изменениям настроек ini, испусканием ошибок или исключений, изменением глобальных -или статичных переменных, чтением или записью в файл, и так далее. - -Ниже приведен пример файла с одновременно объявляющий знаки и оказывающий -побочные эффекты; т.е., пример того, что следует избегать: - -```php -\n"; - -// описание -function foo() -{ - // тело функции -} -``` - -В следующем примере файл который содержит объявление без оказания побочных -эффектов; т.е., пример того, к чему следует стремится: - -```php - $b) { - $foo->bar($arg1); - } else { - BazClass::bar($arg2, $arg3); - } - } - - final public static function bar() - { - // тело метода - } -} -``` - -2. Общее --------- - -### 2.1 Основной стандарт написания кода - -Код ДОЛЖЕН следовать всем правилам изложенным в [PSR-1][]. - -### 2.2 Файлы - -Все PHP файлы ДОЛЖНЫ использовать переводы строк Unix LF (linefeed). - -Все PHP файлы ДОЛЖНЫ оканчиваться одной пустой строкой. - -Закрывающий `?>` тег ДОЛЖЕН быть исключен из файлов содержащих только PHP. - -### 2.3. Строки - -НЕ ДОЛЖНО быть жесткого ограничения на длину строки. - -Мягкое ограничение на длину строки ДОЛЖНО быть 120 знаков; автоматические проверки -стиля ДОЛЖНЫ предупредить но НЕ ДОЛЖНЫ выдавать ошибку на мягкие ограничения. - -Строкам НЕ СЛЕДУЕТ быть длиннее 80 знаков; более длинные строки СЛЕДУЕТ -разбивать на несколько последующих строк не более чем 80 знаков в каждой. - -НЕ ДОЛЖНО быть замыкающий пробелов в конце строки на не пустых строках. - -Пустые строки МОГУТ быть добавлены для улучшения читабельности и указания -связанных блоков кода. - -НЕ ДОЛЖНО быть более одного оператора в строке. - -### 2.4. Отступы - -Код ДОЛЖЕН использовать отступ в 4 пробела, и НЕ ДОЛЖЕН использовать табуляцию -для отступов. - -> Обратите особое внимание: Использование только пробелов, и не смешивание -> пробелов и табуляции, помогает избежать проблем с диффами, патчами, историей, -> и аннотациями. Использование пробелов также позволяет легко вставить -> тонко-настроенный суб-отступ для межстрочного выравнивания. - -### 2.5. Ключевые слова и True/False/Null - -PHP [Ключевые слова][] ДОЛЖНЫ быть в нижнем регистре. - -PHP константы `true`, `false`, и `null` ДОЛЖНЫ быть в нижнем регистре. - -[Ключевые слова]: http://php.net/manual/en/reserved.keywords.php - - - -3. Объявление Пространства имен и Use -------------------------------------- - -Если они присутствуют, то ДОЛЖНА быть одна пустая строка после объявления -`namespace`. - -Если они присутствуют, все объявления `use` ДОЛЖНЫ идти после объявления -`namespace`. - -ДОЛЖНО быть ключевое слово `use` на каждое объявление. - -ДОЛЖНА быть одна пустая строка после блока `use`. - -Например: - -```php -bar($arg1); -Foo::bar($arg2, $arg3); -``` - -Списки аргументов МОГУТ быть разделены на несколько строк, где каждая -последующая строка с одним отступом. При этом первый элемент в списке ДОЛЖЕН -быть на следующей строке, и ДОЛЖЕН быть только один аргумент на строку. - -```php -bar( - $longArgument, - $longerArgument, - $muchLongerArgument -); -``` - -5. Управляющие конструкции --------------------------- - -Общие правила стиля для управляющих конструкций следующие: - -- ДОЛЖЕН быть один пробел после ключевого слова управляющей конструкции -- НЕ ДОЛЖНО быть пробела после открывающих круглых скобок -- НЕ ДОЛЖНО быть пробела перед закрывающими круглыми скобками -- ДОЛЖЕН быть один пробел между закрывающей круглой скобкой и открывающей - фигурной скобкой -- Тело конструкции должно быть с одним отступом -- Закрывающая фигурная скобка ДОЛЖНА быть на следующей строке после тела - управляющей конструкции - -Тело каждой конструкции ДОЛЖНО быть заключено в фигурные скобки. Это -стандартизирует вид конструкций, и уменьшает вероятность внесения ошибок -при добавлении новых строк к телу управляющей конструкции. - - -### 5.1. `if`, `elseif`, `else` - -Оператор `if` выглядит следующим образом. Обратите внимание на размещение -круглых скобок, пробелов и фигурных скобок; и что `else` и `elseif` находятся -на одной линии, как и закрывающая фигурная скобка тела оператора. - -```php - $value) { - // тело оператора foreach -} -``` - -### 5.6. `try`, `catch` - -Блок `try catch` выглядит следующим образом. Обратите внимание на размещение -круглых скобок, пробелов и фигурных скобок. - -```php -bar( - $arg1, - function ($arg2) use ($var1) { - // тело функции - }, - $arg3 -); -``` - - -7. Заключение -------------- - -Есть много элементов оформления и практик умышленно опущенных в этом -руководстве. Они включают, но не ограничиваются: - -- Объявление глобальных переменных и глобальных констант - -- Объявление функций - -- Операторы и присваивания - -- Вписанное выравнивание - -- Комментарии и блоки документации - -- Приставки и окончания имен классов - -- Практический опыт - -Будущее рекомендации МОГУТ пересмотреть и расширить это руководство для решения -тех или иных элементов оформления и практик. - - -Приложение A. Опрос -------------------- - -При написании этого руководства оформления, группа провела опрос участвующих -проектов для определения общих практик. Опрос сохраняется в настоящем -документе для потомков. - -### A.1. Данные опроса - - url,http://www.horde.org/apps/horde/docs/CODING_STANDARDS,http://pear.php.net/manual/en/standards.php,http://solarphp.com/manual/appendix-standards.style,http://framework.zend.com/manual/en/coding-standard.html,http://symfony.com/doc/2.0/contributing/code/standards.html,http://www.ppi.io/docs/coding-standards.html,https://github.com/ezsystems/ezp-next/wiki/codingstandards,http://book.cakephp.org/2.0/en/contributing/cakephp-coding-conventions.html,https://github.com/UnionOfRAD/lithium/wiki/Spec%3A-Coding,http://drupal.org/coding-standards,http://code.google.com/p/sabredav/,http://area51.phpbb.com/docs/31x/coding-guidelines.html,https://docs.google.com/a/zikula.org/document/edit?authkey=CPCU0Us&hgd=1&id=1fcqb93Sn-hR9c0mkN6m_tyWnmEvoswKBtSc0tKkZmJA,http://www.chisimba.com,n/a,https://github.com/Respect/project-info/blob/master/coding-standards-sample.php,n/a,Object Calisthenics for PHP,http://doc.nette.org/en/coding-standard,http://flow3.typo3.org,https://github.com/propelorm/Propel2/wiki/Coding-Standards,http://developer.joomla.org/coding-standards.html - voting,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,no,no,no,?,yes,no,yes - indent_type,4,4,4,4,4,tab,4,tab,tab,2,4,tab,4,4,4,4,4,4,tab,tab,4,tab - line_length_limit_soft,75,75,75,75,no,85,120,120,80,80,80,no,100,80,80,?,?,120,80,120,no,150 - line_length_limit_hard,85,85,85,85,no,no,no,no,100,?,no,no,no,100,100,?,120,120,no,no,no,no - class_names,studly,studly,studly,studly,studly,studly,studly,studly,studly,studly,studly,lower_under,studly,lower,studly,studly,studly,studly,?,studly,studly,studly - class_brace_line,next,next,next,next,next,same,next,same,same,same,same,next,next,next,next,next,next,next,next,same,next,next - constant_names,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper,upper - true_false_null,lower,lower,lower,lower,lower,lower,lower,lower,lower,upper,lower,lower,lower,upper,lower,lower,lower,lower,lower,upper,lower,lower - method_names,camel,camel,camel,camel,camel,camel,camel,camel,camel,camel,camel,lower_under,camel,camel,camel,camel,camel,camel,camel,camel,camel,camel - method_brace_line,next,next,next,next,next,same,next,same,same,same,same,next,next,same,next,next,next,next,next,same,next,next - control_brace_line,same,same,same,same,same,same,next,same,same,same,same,next,same,same,next,same,same,same,same,same,same,next - control_space_after,yes,yes,yes,yes,yes,no,yes,yes,yes,yes,no,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes,yes - always_use_control_braces,yes,yes,yes,yes,yes,yes,no,yes,yes,yes,no,yes,yes,yes,yes,no,yes,yes,yes,yes,yes,yes - else_elseif_line,same,same,same,same,same,same,next,same,same,next,same,next,same,next,next,same,same,same,same,same,same,next - case_break_indent_from_switch,0/1,0/1,0/1,1/2,1/2,1/2,1/2,1/1,1/1,1/2,1/2,1/1,1/2,1/2,1/2,1/2,1/2,1/2,0/1,1/1,1/2,1/2 - function_space_after,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no,no - closing_php_tag_required,no,no,no,no,no,no,no,no,yes,no,no,no,no,yes,no,no,no,no,no,yes,no,no - line_endings,LF,LF,LF,LF,LF,LF,LF,LF,?,LF,?,LF,LF,LF,LF,?,,LF,?,LF,LF,LF - static_or_visibility_first,static,?,static,either,either,either,visibility,visibility,visibility,either,static,either,?,visibility,?,?,either,either,visibility,visibility,static,? - control_space_parens,no,no,no,no,no,no,yes,no,no,no,no,no,no,yes,?,no,no,no,no,no,no,no - blank_line_after_php,no,no,no,no,yes,no,no,no,no,yes,yes,no,no,yes,?,yes,yes,no,yes,no,yes,no - class_method_control_brace,next/next/same,next/next/same,next/next/same,next/next/same,next/next/same,same/same/same,next/next/next,same/same/same,same/same/same,same/same/same,same/same/same,next/next/next,next/next/same,next/same/same,next/next/next,next/next/same,next/next/same,next/next/same,next/next/same,same/same/same,next/next/same,next/next/next - -### A.2. Условные обозначения опроса - -`indent_type`: -Тип отступов. `tab` = "использование табуляции", `2` или `4` = "количество пробелов" - -`line_length_limit_soft`: -"Мягкое" ограничение на длину строки, в знаках. `?` = не различимо или нет ответа, `no` значит нет лимита. - -`line_length_limit_hard`: -"Жесткое" ограничение на длину строки, в знаках. `?` = не различимо или нет ответа, `no` значит нет лимита. - -`class_names`: -Как классы называются? `lower` = только строчные, `lower_under` = строчные с подчеркиванием разделителем, `studly` = StudlyCase. - -`class_brace_line`: -Идет ли открывающая фигурная скобка класса на той же (`same`) линии что и ключевое слово класса, или на следующей (`next`) линии после нее? - -`constant_names`: -How are class constants named? `upper` = Uppercase with underscore separators. - -`true_false_null`: -Ключевые слова `true`, `false`, и `null` написаны полностью строчными (`lower`), или полностью прописными (`upper`)? - -`method_names`: -Как методы называются? `camel` = `camelCase`, `lower_under` = строчные с подчеркиванием разделителем. - -`method_brace_line`: -Идет ли открывающая фигурная скобка метода на той же (`same`) линии что и ключевое слово метода, или на следующей (`next`) линии после нее? - -`control_brace_line`: -Идет ли открывающая фигурная скобка управляющей конструкции на той же (`same`) линии, или на следующей (`next`)? - -`control_space_after`: -Есть ли пробел после ключевого слова управляющей конструкции? - -`always_use_control_braces`: -Всего использовать фигурные скобки для управляющих конструкций? - -`else_elseif_line`: -Когда используется `else` или `elseif`, идет ли оно на той же (`same`) линии, что и предыдущая закрывающая фигурная скобка, или оно идет на следующей (`next`) линии? - -`case_break_indent_from_switch`: -На сколько отступов `case` и `break` от открывающего оператора `switch`? - -`function_space_after`: -При вызове функций есть ли пробел после имени функции и перед открывающими круглыми скобками? - -`closing_php_tag_required`: -В файлах содержащих только PHP необходим ли закрывающий `?>` тег? - -`line_endings`: -Какой тип окончания строки используется? - -`static_or_visibility_first`: -Когда объявляется метод, то `static` идет впереди, или область видимости идет впереди? - -`control_space_parens`: -В выражении управляющей конструкции, есть ли пробел после открывающей круглой скобки, и пробел перед закрывающей круглой скобкой? `yes` = `if ( $expr )`, `no` = `if ($expr)`. - -`blank_line_after_php`: -Есть ли пустая строка после открытия PHP тега? - -`class_method_control_brace`: -Сводка на какой линии идет открывающая фигурная скобка после классов, методов, и управляющих конструкций. - -### A.3. Результаты опроса - - indent_type: - tab: 7 - 2: 1 - 4: 14 - line_length_limit_soft: - ?: 2 - no: 3 - 75: 4 - 80: 6 - 85: 1 - 100: 1 - 120: 4 - 150: 1 - line_length_limit_hard: - ?: 2 - no: 11 - 85: 4 - 100: 3 - 120: 2 - class_names: - ?: 1 - lower: 1 - lower_under: 1 - studly: 19 - class_brace_line: - next: 16 - same: 6 - constant_names: - upper: 22 - true_false_null: - lower: 19 - upper: 3 - method_names: - camel: 21 - lower_under: 1 - method_brace_line: - next: 15 - same: 7 - control_brace_line: - next: 4 - same: 18 - control_space_after: - no: 2 - yes: 20 - always_use_control_braces: - no: 3 - yes: 19 - else_elseif_line: - next: 6 - same: 16 - case_break_indent_from_switch: - 0/1: 4 - 1/1: 4 - 1/2: 14 - function_space_after: - no: 22 - closing_php_tag_required: - no: 19 - yes: 3 - line_endings: - ?: 5 - LF: 17 - static_or_visibility_first: - ?: 5 - either: 7 - static: 4 - visibility: 6 - control_space_parens: - ?: 1 - no: 19 - yes: 2 - blank_line_after_php: - ?: 1 - no: 13 - yes: 8 - class_method_control_brace: - next/next/next: 4 - next/next/same: 11 - next/same/same: 1 - same/same/same: 6 diff --git a/bylaws/001-voting-protocol.md b/bylaws/001-voting-protocol.md deleted file mode 100644 index 34236b370..000000000 --- a/bylaws/001-voting-protocol.md +++ /dev/null @@ -1,45 +0,0 @@ -Voting Protocol -=============== - -1. Only voting members may initiate a call for votes on a measure. - -2. Only voting members may vote on a measure. - -3. The time limit on a vote is 14 days from the time of the call for votes, or -until all voting members have cast their vote, whichever comes first. Votes -cast after the time limit are not valid. - -4. Votes can be +1 ("in favor"), -1 ("against"), or 0 ("abstain"). - -5. One-third or more of the *voting members* must vote within the time limit -for the vote to be valid. This is the equivalent of establishing a quorum. For -example: - - - If there are 20, 21, or 22 members, then 7 or more must vote within the - time limit for the vote to be valid. - - - If there are 23, 24, or 25 members, then 8 or more must vote within the - time limit for the vote to be valid. - -6. The measure passes if a simple majority of the *votes cast* are "in favor". -The measure does not pass otherwise. For example: - - - If there are 10 or 11 votes cast, 6 or more must be "in favor". - - - If there are 12 or 13 votes cast, 7 or more must be "in favor". - -7. Measures passed are not binding. A vote "in favor" of a measure is an -indication that the measure is approved, but the voting member may not be able -to apply it immediately for reasons outside the purview of this group. - -8. Votes on membership requests represent a special case: - - - Regarding point 1, they may be initiated by non-members. - - - Regarding point 7, it is binding on all members. - -* * * - -N.b.: "Abstain" votes are counted only for quorum, and are not counted when -calculating majority. - diff --git a/bylaws/002-psr-naming-conventions.md b/bylaws/002-psr-naming-conventions.md deleted file mode 100644 index bae3a058d..000000000 --- a/bylaws/002-psr-naming-conventions.md +++ /dev/null @@ -1,18 +0,0 @@ -Naming conventions for code released by PHP-FIG ------------------------------------------------ - -1. Interfaces MUST be suffixed by `Interface`: e.g. `Psr\Foo\BarInterface`. -2. Abstract classes MUST be prefixed by `Abstract`: e.g. `Psr\Foo\AbstractBar`. -3. Traits MUST be suffixed by `Trait`: e.g. `Psr\Foo\BarTrait`. -4. PSR-0, 1 and 2 MUST be followed. -5. The vendor namespace MUST be `Psr`. -6. There MUST be a package/second-level namespace in relation with the PSR that - covers the code. -7. Composer package MUST be named `psr/` e.g. `psr/log`. If they - require an implementation as a virtual package it MUST be named - `psr/-implementation` and be required with a specific version like - `1.0.0`. Implementors of that PSR can then provide - `"psr/-implementation": "1.0.0"` in their package to satisfy that - requirement. Specification changes via further PSRs should only lead to a new - tag of the `psr/` package, and an equal version bump of the - implementation being required. diff --git a/proposed/.placeholder b/proposed/.placeholder deleted file mode 100644 index e69de29bb..000000000