Commit 83b80027 by Qiang Xue

Merge branch 'master' of git://github.com/yiisoft/yii2

parents a0d19e92 77368538
......@@ -9,6 +9,7 @@ namespace yii\build\controllers;
use Yii;
use yii\console\Controller;
use yii\helpers\Console;
use yii\helpers\VarDumper;
/**
......@@ -33,7 +34,10 @@ class MimeTypeController extends Controller
if ($outFile === null) {
$outFile = Yii::getAlias('@yii/helpers/mimeTypes.php');
}
$this->stdout('downloading mime-type file from apache httpd repository...');
if ($content = file_get_contents('http://svn.apache.org/viewvc/httpd/httpd/trunk/docs/conf/mime.types?view=co')) {
$this->stdout("done.\n", Console::FG_GREEN);
$this->stdout("generating file $outFile...");
$mimeMap = [];
foreach(explode("\n", $content) as $line) {
$line = trim($line);
......@@ -65,6 +69,7 @@ return $array;
EOD;
file_put_contents($outFile, $content);
$this->stdout("done.\n", Console::FG_GREEN);
} else {
$this->stderr("Failed to download mime.types file from apache SVN.\n");
}
......
......@@ -85,6 +85,7 @@ class PhpDocController extends Controller
$this->fixFileDoc($lines);
$this->fixDocBlockIndentation($lines);
$lines = array_values($this->fixLineSpacing($lines));
$newContent = implode("\n", $lines);
if ($sha !== sha1($newContent)) {
......@@ -163,6 +164,9 @@ class PhpDocController extends Controller
return FileHelper::findFiles($root, $options);
}
/**
* Fix file PHPdoc
*/
protected function fixFileDoc(&$lines)
{
// find namespace
......@@ -170,12 +174,15 @@ class PhpDocController extends Controller
$namespaceLine = '';
$contentAfterNamespace = false;
foreach($lines as $i => $line) {
if (substr_compare(trim($line), 'namespace', 0, 9) === 0) {
$namespace = $i;
$namespaceLine = trim($line);
} elseif ($namespace !== false && trim($line) !== '') {
$contentAfterNamespace = $i;
break;
$line = trim($line);
if (!empty($line)) {
if (strncmp($line, 'namespace', 9) === 0) {
$namespace = $i;
$namespaceLine = $line;
} elseif ($namespace !== false) {
$contentAfterNamespace = $i;
break;
}
}
}
......@@ -254,6 +261,116 @@ class PhpDocController extends Controller
}
}
/**
* Fixes line spacing code style for properties and constants
*/
protected function fixLineSpacing($lines)
{
$propertiesOnly = false;
// remove blank lines between properties
$skip = true;
foreach($lines as $i => $line) {
if (strpos($line, 'class ') !== false) {
$skip = false;
}
if ($skip) {
continue;
}
if (trim($line) === '') {
unset($lines[$i]);
} elseif (ltrim($line)[0] !== '*' && strpos($line, 'function ') !== false) {
break;
} elseif (trim($line) === '}') {
$propertiesOnly = true;
break;
}
}
$lines = array_values($lines);
// add back some
$endofUse = false;
$endofConst = false;
$endofPublic = false;
$endofProtected = false;
$endofPrivate = false;
$skip = true;
$level = 0; // track array properties
$property = '';
foreach($lines as $i => $line) {
if (strpos($line, 'class ') !== false) {
$skip = false;
}
if ($skip) {
continue;
}
// check for multi line array
if ($level > 0) {
${'endof'.$property} = $i;
}
$line = trim($line);
if (strncmp($line, 'public $', 8) === 0 || strncmp($line, 'public static $', 15) === 0) {
$endofPublic = $i;
$property = 'Public';
$level = 0;
} elseif (strncmp($line, 'protected $', 11) === 0 || strncmp($line, 'protected static $', 18) === 0) {
$endofProtected = $i;
$property = 'Protected';
$level = 0;
} elseif (strncmp($line, 'private $', 9) === 0 || strncmp($line, 'private static $', 16) === 0) {
$endofPrivate = $i;
$property = 'Private';
$level = 0;
} elseif (substr($line,0 , 6) === 'const ') {
$endofConst = $i;
$property = false;
} elseif (substr($line,0 , 4) === 'use ') {
$endofUse = $i;
$property = false;
} elseif (!empty($line) && $line[0] === '*') {
$property = false;
} elseif (!empty($line) && $line[0] !== '*' && strpos($line, 'function ') !== false || $line === '}') {
break;
}
// check for multi line array
if ($property !== false && strncmp($line, "'SQLSTATE[", 10) !== 0) {
$level += substr_count($line, '[') - substr_count($line, ']');
}
}
$endofAll = false;
foreach(['Private', 'Protected', 'Public', 'Const', 'Use'] as $var) {
if (${'endof'.$var} !== false) {
$endofAll = ${'endof'.$var};
break;
}
}
// $this->checkPropertyOrder($lineInfo);
$result = [];
foreach($lines as $i => $line) {
$result[] = $line;
if (!($propertiesOnly && $i === $endofAll)) {
if ($i === $endofUse || $i === $endofConst || $i === $endofPublic ||
$i === $endofProtected || $i === $endofPrivate) {
$result[] = '';
}
if ($i === $endofAll) {
$result[] = '';
}
}
}
return $result;
}
protected function checkPropertyOrder($lineInfo)
{
// TODO
}
protected function updateClassPropertyDocs($file, $className, $propertyDoc)
{
$ref = new \ReflectionClass($className);
......@@ -275,13 +392,15 @@ class PhpDocController extends Controller
// TODO move these checks to different action
$lines = explode("\n", $newDoc);
if (trim($lines[1]) == '*' || substr_compare(trim($lines[1]), '* @', 0, 3) === 0) {
$firstLine = trim($lines[1]);
if ($firstLine === '*' || strncmp($firstLine, '* @', 3) === 0) {
$this->stderr("[WARN] Class $className has no short description.\n", Console::FG_YELLOW, Console::BOLD);
}
foreach ($lines as $line) {
if (substr_compare(trim($line), '* @since ', 0, 9) === 0) {
$line = trim($line);
if (strncmp($line, '* @since ', 9) === 0) {
$seenSince = true;
} elseif (substr_compare(trim($line), '* @author ', 0, 10) === 0) {
} elseif (strncmp($line, '* @author ', 10) === 0) {
$seenAuthor = true;
}
}
......@@ -350,13 +469,14 @@ class PhpDocController extends Controller
$propertyPart = false;
$propertyPosition = false;
foreach ($lines as $i => $line) {
if (substr_compare(trim($line), '* @property ', 0, 12) === 0) {
$line = trim($line);
if (strncmp($line, '* @property ', 12) === 0) {
$propertyPart = true;
} elseif ($propertyPart && trim($line) == '*') {
} elseif ($propertyPart && $line == '*') {
$propertyPosition = $i;
$propertyPart = false;
}
if (substr_compare(trim($line), '* @author ', 0, 10) === 0 && $propertyPosition === false) {
if (strncmp($line, '* @author ', 10) === 0 && $propertyPosition === false) {
$propertyPosition = $i - 1;
$propertyPart = false;
}
......
......@@ -20,7 +20,7 @@ All Rights Reserved.
* [Встановлення Yii](start-installation.md)
* [Запуск додатка](start-workflow.md)
* [Говоримо «привіт»](start-hello.md)
* [Говоримо «Привіт»](start-hello.md)
* [Робота з формами](start-forms.md)
* [Робота з базами даних](start-databases.md)
* [Генерація коду за допомогою Gii](start-gii.md)
......
Говоримо «Привіт»
================
В даному розділі розглянемо як створити нову сторінку з надписом «Привіт». В процесі вирішеня задачі ви створите
[подію контролера](structure-controllers.md) і [представлення](structure-views.md):
* Додаток опрацює запит і передасть управління відповідній події;
* Подія, в свою чергу, відобразить представлення з надписом "Привіт" кінцевому користувачу.
З допомогою даного керівництва ви вивчите
* Як створити [подію](structure-controllers.md), яка буде відповідати на запити;
* Як створити [представлення](structure-views.md), щоб формувати зміст відповіді;
* Як додаток відправляє запити до [події](structure-controllers.md).
Створення Події <a name="creating-action"></a>
------------------------------------------------
Для нашої задачі знадобиться [подія](structure-controllers.md) `say`, котра читає параметр `message` із
запиту і відображає його значення користувачу. Якщо в запиті відсутній параметр `message`, то подія буде відображати «Привіт».
> Інформація: [Події](structure-controllers.md) можуть бути запущені безпосередньо користувачем і згруповані в
[контролери](structure-controllers.md). Результатом виконання події є відповідь, яку отримує користувач.
Події оголошуються в [контролерах](structure-controllers.md). Для зручності, ви можете оголосити подію
`say` в уже існуючому контролері `SiteController`, який оголошений у файлі класа `controllers/SiteController.php`:
```php
<?php
namespace app\controllers;
use yii\web\Controller;
class SiteController extends Controller
{
// ...існуючий код...
public function actionSay($message = 'Привіт')
{
return $this->render('say', ['message' => $message]);
}
}
```
В наведеному коді подія `say` оголошена як метод `actionSay` в класі `SiteController`.
Yii використовує префікс `action` для того, щоб відрізняти методи-події і звичайні методи. Назва після префікса `action`
вважається ідентифікатором відповідної події.
> Інформація: Ідентифікатори подій задаються в нижньому регістрі. Якщо ідентифікатор складається з декількох слів, вони
з’єднуються дефісами, тобто `create-comment`. Імена методів подій отримуються шляхом видалення дефісів з ідентифікатора, перетворення першої літери кожного слова у верхній регістр і добавлення префікса `action`.
Наприклад, ідентифікатор події `create-comment` відповідає методу `actionCreateComment`.
Метод події приймає параметр `$message`, який за замовчуванням дорівнює `"Привіт"`. Коли додаток отримує запит і визначає, що подія `say` відповідає за його опрацювання, параметр наповнюється одноіменним значенням із запиту.
Всередені метода події, для відображення [представлення](structure-views.md) з ім’ям `say`, використовується метод
[[yii\web\Controller::render()|render()]]. Для того, щоб вивести повідомлення, у представлення передається параметр `message`.
Результат відображення з допомогою `return` передається додатку, котрий віддає його користувачу.
Створення представлення <a name="creating-view"></a>
---------------------------------------------------
[Представлення](structure-views.md) є скриптами, які використовуються для формування тіла відповіді. Для нашого
додатку ви створите представлення `say`, яке буде виводити параметр `message`, отриманий із метода події:
```php
<?php
use yii\helpers\Html;
?>
<?= Html::encode($message) ?>
```
Представлення `say` мусить бути збережено у файлі `views/site/say.php`. Коли метод [[yii\web\Controller::render()|render()]]
викликається в події, він буде шукати PHP файл з ім’ям виду `views/ControllerID/ActionID/ViewName.php`.
Варто замітити, що в коді вище параметр `message` [[yii\helpers\Html::encode()|екранується для HTML]] перед відображенням.
Це обов’язково так як параметр приходить від користувача, котрий може спробувати провести
[XSS атаку](http://uk.wikipedia.org/wiki/%D0%9C%D1%96%D0%B6%D1%81%D0%B0%D0%B9%D1%82%D0%BE%D0%B2%D0%B8%D0%B9_%D1%81%D0%BA%D1%80%D0%B8%D0%BF%D1%82%D1%96%D0%BD%D0%B3)
шляхом вставки небезпечного JavaScript кода.
Ви можете доповнити представлення `say` HTML тегами, текстом або кодом PHP. Фактично, представлення `say` є
простим PHP скриптом, який виконується методом [[yii\web\Controller::render()|render()]]. Зміст, який відображається
скриптом представлення, буде передано додатком користувачу.
Спробуєм <a name="trying-it-out"></a>
--------------------------------------
Після створення події і представлення ви можете перейти на нову сторінку по наступному URL:
```
http://hostname/index.php?r=site/say&message=Привіт+світ
```
![Привіт, світ](../guide/images/start-hello-world.png)
Буде відображена сторінка з надписом Привіт світ. Вона використовує ту ж шапку і футер, що і решта сторінок додатка.
Якщо ви не вкажете параметр `message`, то побичите на сторінці лише «Привіт». Це відбувається тому, що `message` передається
в метод `actionSay()` і значення за замовчуванням — «Привіт».
> Інформація: Нова сторінка використовує ту ж шапку і футер, що і решта сторінок, тому що метод
[[yii\web\Controller::render()|render()]] автоматично підставляється в результат представлення `say` в, так називаємий,
[макет](structure-views.md) `views/layouts/main.php`.
Параметр `render` потребує додаткових пояснень. Він пов’язаний з [маршрутом (route)](runtime-routing.md), який являє собою унікальний ідентифікатор, який вказує на подію. Його формат `ControllerID/ActionID`. Коли додаток отримує запит, він перевіряє параметр `render` і, використовуючи `ControllerID`, визначає який контролер слід використовувати для опрацювання запиту. Потім, контролер використовує частину `ActionID`, щоб визначити яка подія виконує реальну роботу.
В нашому випадку маршрут `site/say` буде відповідати контролеру `SiteController` і його події `say`.
В результаті, для відпрацювання запиту буде визваний метод `SiteController::actionSay()`.
> Інформація: Як і події, контролери також мають ідентифікатори, котрі однозначно визначають їх в додатку.
Ідентифікатори контролерів використовують ті ж самі правила, що і ідентифікатори подій. Імена класів
контролерів отримуються шляхом видалення дефісів з ідентифікатора, перетворення першої літери кожного слова у верхній регістр і додавання в кінець `Controller`. Наприклад, ідентифікатор контролера `post-comment` відповідає
імені класа контролера `PostCommentController`.
Резюме <a name="summary"></a>
-----------------------------
В даному розділі ви затронули тему контролерів і представленнь в паттерні MVC. Ви створили подію як частину контролера,
який опрацьовує запити, і представлення, яке приймає участь у формувані відповіді. В цьому процесі ніяк не була задіяна
модель, так як в ролі даних виступає тільки простий параметр `message`.
Також ви ознайомились із концепцією маршрутизації, котра є сполучною ланкою між запитом користувача і подією контролера.
В наступному розділі ви дізнаєтесь як створювати моделі і добавляти нові сторінки з HTML формами.
Встановлення Yii
==============
Ви можете встановити Yii двома шляхами: використовуючи [Composer](http://getcomposer.org/) або завантаживши архів.
Перший варіант бажаніший тому, що дозволить встановити всі нові [розширення](structure-extensions.md)
або оновити Yii однією командою.
Встановлення за допомогою Composer <a name="installing-via-composer"></a>
-----------------------
Якщо Composer все ще не встановлено, то це можна зробити за допомогою інструкції на [getcomposer.org](https://getcomposer.org/download/), або одним із перерахованих способів:
* на Linux або Mac, використовуйте наступну команду:
```
curl -s http://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
```
* на Windows, завантажте і запустіть [Composer-Setup.exe](https://getcomposer.org/Composer-Setup.exe).
В разі наявності проблем або якщо вам необхідна додаткова інформація, зверніться до [документації Composer](https://getcomposer.org/doc/) .
Після встановлення Composer встановити Yii можна виконавши наступну команду з директорії, яка доступна через Web:
```
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
```
Composer встановить Yii (базовий додаток basic) в директорію `basic`.
> **Підказка**: Якщо хочете встановити останню нестабільну версію Yii, ви можете добавити ключ `stability`:
```
composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-basic basic
```
Варто замітити, що нестабільну версію Yii неможна використовувати на робочому сервері.
Встановлення з архіву <a name="installing-from-archive-file"></a>
-------------------------------
Встановлення Yii з архіву складається з двох кроків:
1. Завантажте архів за адресою [yiiframework.com](http://www.yiiframework.com/download/yii2-basic);
2. Розпакуйте архів в директорію, доступну через Web.
Інші параметри встановлення <a name="other-installation-options"></a>
--------------------------
Вище наведені інструкції по встановленню Yii у вигляді базового додатку готового до роботи.
Це відмінний варіант для невеликих проектів або для тих, хто тільки розпочинає вивчати Yii.
Є два основних варіанта данного встановлення:
* Якщо вам потрібен тільки один фреймворк і ви хотіли б створити додаток з нуля, використовуйте інструкцію, яка описана у розділі «[Створення додатка з нуля](tutorial-start-from-scratch.md)».
* Якщо хочете розпочати з більш насиченого додатка, який добре підходить для роботи в команді, використовуйте
[шаблон додатка advanced](tutorial-advanced-app.md).
Перевірка встановлення <a name="verifying-installation"></a>
----------------------
Якщо ви встановили додаток в теку `basic` базової директорії вашого веб сервера і ім’я сервера `hostname`,
запустити додаток можна відкривши наступний URL через браузер:
```
http://hostname/basic/web/index.php
```
![Успішно встановленний Yii](../guide/images/start-app-installed.png)
Ви повинні побачити сторінку привітання «Congratulations!». Якщо ні — провірте вимоги Yii одним із способів:
* Браузером перейдіть на адресу `http://hostname/basic/requirements.php`
* Або виконайте команду в консолі:
```
cd basic
php requirements.php
```
Для коректної роботи фреймворка вам необхідно мати PHP, який відповідає його мінімальним вимогам. Основна вимога — PHP версії 5.4 и вище. Якщо ваш додаток працює з базою даних, необхідно встановити
[розширення PHP PDO](http://www.php.net/manual/ru/pdo.installation.php) і відповідний драйвер
(наприклад, `pdo_mysql` для MySQL).
Налаштування веб сервера <a name="configuring-web-servers"></a>
-----------------------
> Інформація: можете пропустити даний підрозділ, якщо ви тільки розпочали знайомитися з фреймворком і не розгортаєте його на робочому сервері.
Додаток, встановлений за інструкціями, наведеними вище, буде працювати зразу як з [Apache](http://httpd.apache.org/),
так і з [Nginx](http://nginx.org/) під Windows і Linux.
На рабочому сервері вам напевно захочеться змінити URL додатку з `http://hostname/basic/web/index.php`
на `http://hostname/index.php`. Для цього необхідно змінити кореневу директорію в налаштуваннях веб сервера так, щоб ті
вказували на `basic/web`. Додатково можно сховати `index.php` відповідно описанню в розділі «[Розбір і генерація URL](runtime-url-handling.md)».
Далі буде показано як налаштувати Apache і Nginx.
> Інформація: Встанновлюючи `basic/web` кореневою директорією веб сервера ви захищаете від небажаного доступа код і дані, які знаходяться на одному рівні з `basic/web`. Це робить додаток більш захищенним.
> Інформація: Якщо додаток працює на хостингу, де немає доступу до налаштувань сервера, то можна змінити структуру додатка, як описано в розділі «[Робота на Shared хостингу](tutorial-shared-hosting.md)».
### Рекомендовані налаштування Apache <a name="recommended-apache-configuration"></a>
Добавте наступне в `httpd.conf` Apache або в конфігураційний файл віртуального хоста. Не забудьте замінити
`path/to/basic/web` на коректний шлях до `basic/web`.
```
# Встановлюємо кореневою директорією "basic/web"
DocumentRoot "path/to/basic/web"
<Directory "path/to/basic/web">
RewriteEngine on
# Якщо запитувана в URL директорія або файл відсутні звертаємось до них напряму
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Якщо ні - перенаправляємо запит на index.php
RewriteRule . index.php
# ...інші налаштування...
</Directory>
```
### Рекомендовані налаштування Nginx <a name="recommended-nginx-configuration"></a>
PHP повинен бути встановлений як [FPM SAPI](http://php.net/manual/ru/install.fpm.php) для [Nginx](http://wiki.nginx.org/).
Використовуйте наступні параметри Nginx і не забудьте замінити `path/to/basic/web` на коректний шлях до `basic/web`.
```
server {
charset utf-8;
client_max_body_size 128M;
listen 80; ## listen for ipv4
#listen [::]:80 default_server ipv6only=on; ## слухаєм ipv6
server_name mysite.local;
root /path/to/basic/web;
index index.php;
access_log /path/to/project/log/access.log main;
error_log /path/to/project/log/error.log;
location / {
# Перенаправляємо всі запити до неіснуючих директорій або файлів на index.php
try_files $uri $uri/ /index.php?$args;
}
# розкоментуйте строки нище для запобігання обробки Yii звернень до неіснуючих статичних файлів
#location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
# try_files $uri =404;
#}
#error_page 404 /404.html;
location ~ \.php$ {
include fastcgi.conf;
fastcgi_pass 127.0.0.1:9000;
#fastcgi_pass unix:/var/run/php5-fpm.sock;
}
location ~ /\.(ht|svn|git) {
deny all;
}
}
```
Використовуючи дану конфігурацію встановіть `cgi.fix_pathinfo=0` в `php.ini` щоб запобігти зайвим системним визовам `stat()`.
Врахуйте також, що при використанні HTTPS необхідно задавати `fastcgi_param HTTPS on;` щоб Yii міг корректно оприділяти захищене
з’єднання.
Запуск додатка
====================
Після встановлення Yii, базовий додаток буде доступний або по URL `http://hostname/basic/web/index.php`, або по `http://hostname/index.php`, в залежності від налаштування Web сервера. Даний розділ - загальне введення в організацію коду, вбудований функціонал і опрацювання звернень додатком Yii.
> Інформація: Далі, в даному посібнику передбачається що Yii встановлений в теку `basic/web`, яка, в свою чергу, встановлена як коренева директорія в налаштуваннях Web сервера. В результаті, звернувшись по URL `http://hostname/index.php` ви отримаєте доступ до додатку, розміщенному в `basic/web`. Детальніше з процесом початкового налаштування можна ознайомитись в розділі [Встановлення Yii](start-installation.md).
Функціонал <a name="functionality"></a>
---------------
Вбудований шаблон простого додатку складається з чотирьох сторінок:
* домашня сторінка, відображається при переході по URL `http://hostname/index.php`
* "About" ("Про нас")
* на сторінці "Contact" знаходиться форма зворотнього зв’язку, на якій користувач може звернутися до розробника по e-mail
* на сторінці "Login" відображається форма авторизації. Спробуйте авторизуватись з логіном/паролем "admin/admin". Зверніть увагу на зміну розділу "Login" в головному меню на "Logout".
Ці сторінки використовують суміжний хедер (шапка сайта) і футер (підвал). В "шапці" знаходиться головне меню, за допомогою якого користувач переміщається по сайту. В "підвалі" - копірайт і загальна інформація.
В самій верхній частині вікна ви будете бачити системні повідомлення Yii - журнал, відлагоджувальну інформацію, повідомлення про помилки, запити до бази даних і т.п. Відображенням данної інформацію керує [вбудований відладчик](tool-debugger.md), він записує і відображає інформацію про хід виконання додатку.
Структура додатка Yii <a name="application-structure"></a>
---------------------
Нижще наведений перелік основних директорій і файлів вашого додатку (вважаєм, що додаток встановлений в директорію `basic`):
```
basic/ кореневий каталог додатка
composer.json використовується Composer'ом, містить опис додатку
config/ конфігураційні файли
console.php конфігурація консольного додатка
web.php конфігурація Web додатка
commands/ містить класи консольних команд
controllers/ контролери
models/ моделі
runtime/ файли, які генерує Yii під час виконання додатку (логи, кеш і т.п.)
vendor/ містить пакунки Composer'а і, власне, сам фреймворк Yii
views/ представлення додатку
web/ коренева директорія Web додатку. Містить файли, доступні через Web
assets/ скрипти, які використовуються додатком (js, css)
index.php місце входження в додаток Yii. З нього розпочинається виконання додатку
yii скрипт виконання консольного додатку Yii
```
В цілому, додаток Yii можна розділити на дві категорії файлів: розміщенні в `basic/web` і розміщенні в інших директоріях. Перша категорія доступна через Web (наприклад, браузером), друга недоступна зовні та і не повинна бути так як містить службову інформацію.
В Yii реалізована схема проектування [модель-представлення-контролер (MVC)](http://http://uk.wikipedia.org/wiki/Model-View-Controller),
яка відповідає структурі директорій додатка. В директорії `models` знаходяться [Моделі](structure-models.md),
в `views` розміщені [Представлення](structure-views.md), а в каталозі `controllers` всі [Контролери](structure-controllers.md) додатка.
Діаграма нижче демонструє внутрішню будову додатка.
![внутрішня будова додатка](../guide/images/application-structure.png)
В кожному додатку Yii є місце входження в додаток, `web/index.php` це єдиний PHP-скрипт доступний для виконання через Web. Він отримує вхідний запит і створює екземпляр [додатку](structure-applications.md).
[Додаток](structure-applications.md) опрацьовує вхідні запити з допомогою [компонентів](concept-components.md) і відправляє запит контролеру. [Віджети](structure-widgets.md) використовуються у [Представленнях](structure-views.md) для побудови динамічних інтерфейсів сайта.
Життєвий цикл запиту користувача <a name="request-lifecycle"></a>
-----------------
На діаграмі показано як додаток опрацьовує запит.
![Життєвий цикл запиту](../guide/images/application-lifecycle.png)
1. Користувач звертається до [місця входження](structure-entry-scripts.md) `web/index.php`.
2. Скрипт завантажує конфігурацію [configuration](concept-configurations.md) і створює екземпляр [додатку](structure-applications.md) для наступного опрацювання запиту.
3. Додаток визначає [маршрут](runtime-routing.md) запиту за допомогою компонента додатка [запит](runtime-requests.md).
4. Додаток створює екземпляр [контролера](structure-controllers.md) для виконання запиту.
5. Контролер, в свою чергу, створює [подію](structure-controllers.md) і накладає на неї фільтри.
6. Якщо хоч один фільтр поверне помилку - виконання додатку зупиняється.
7. Якщо всі фільтри пройдені - додаток виконується.
8. Подія завантажує модель даних. Скоріше за все із бази даних.
9. Подія генерує представлення, відображаючи в ньому дані (в т.ч. і отримані із моделі).
10. Згенерований вид додатку передається як компонент [відповідь](runtime-responses.md).
11. Компонент "відповідь" відправляє готовий результат роботи додатку браузеру користувача.
......@@ -151,7 +151,7 @@ For example,
During the bootstrapping process, each component will be instantiated. If the component class
implements [[yii\base\BootstrapInterface]], its [[yii\base\BootstrapInterface::bootstrap()|bootstrap()]] method
will be also be called.
will also be called.
Another practical example is in the application configuration for the [Basic Application Template](start-installation.md),
where the `debug` and `gii` modules are configured as bootstrapping components when the application is running
......@@ -391,11 +391,11 @@ does not specify one. The route may consist of child module ID, controller ID, a
For example, `help`, `post/create`, `admin/post/create`. If action ID is not given, it will take the default
value as specified in [[yii\base\Controller::defaultAction]].
For [yii\web\Application|Web applications], the default value of this property is `'site'`, which means
For [[yii\web\Application|Web applications]], the default value of this property is `'site'`, which means
the `SiteController` controller and its default action should be used. As a result, if you access
the application without specifying a route, it will show the result of `app\controllers\SiteController::actionIndex()`.
For [yii\console\Application|console applications], the default value is `'help'`, which means the core command
For [[yii\console\Application|console applications]], the default value is `'help'`, which means the core command
[[yii\console\controllers\HelpController::actionIndex()]] should be used. As a result, if you run the command `yii`
without providing any arguments, it will display the help information.
......@@ -556,7 +556,7 @@ For example,
```
Note that the same `beforeAction` event is also triggered by [modules](structure-modules.md)
and [controllers)(structure-controllers.md). Application objects are the first ones
and [controllers](structure-controllers.md). Application objects are the first ones
triggering this event, followed by modules (if any), and finally controllers. If an event handler
sets [[yii\base\ActionEvent::isValid]] to be `false`, all the following events will NOT be triggered.
......@@ -582,7 +582,7 @@ For example,
```
Note that the same `afterAction` event is also triggered by [modules](structure-modules.md)
and [controllers)(structure-controllers.md). These objects trigger this event in the reverse order
and [controllers](structure-controllers.md). These objects trigger this event in the reverse order
as for that of `beforeAction`. That is, controllers are the first objects triggering this event,
followed by modules (if any), and finally applications.
......
......@@ -28,8 +28,8 @@ class ApiController extends BaseController
*/
public $guide;
// TODO add force update option
// TODO add force update option
/**
* Renders API documentation files
* @param array $sourceDirs
......
......@@ -28,6 +28,7 @@ class GuideController extends BaseController
*/
public $apiDocs;
/**
* Renders API documentation files
* @param array $sourceDirs
......
......@@ -30,6 +30,7 @@ abstract class BaseController extends Controller
*/
public $exclude;
protected function normalizeTargetDir($target)
{
$target = rtrim(Yii::getAlias($target), '\\/');
......
<?php
/**
*
*
* @author Carsten Brandt <mail@cebe.cc>
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\apidoc\helpers;
use cebe\jssearch\Indexer;
use cebe\jssearch\tokenizer\StandardTokenizer;
use cebe\jssearch\TokenizerInterface;
......
......@@ -31,6 +31,7 @@ class ApiMarkdown extends GithubMarkdown
protected $renderingContext;
/**
* Renders a code block
*/
......
......@@ -29,6 +29,7 @@ class ApiMarkdownLaTeX extends GithubMarkdown
protected $renderingContext;
protected function inlineMarkers()
{
return array_merge(parent::inlineMarkers(), [
......
......@@ -17,6 +17,7 @@ class IndexFileAnalyzer extends Markdown
private $_chapter = 0;
private $_chapters = [];
public function analyze($text)
{
$this->parse($text);
......
......@@ -24,24 +24,21 @@ class BaseDoc extends Object
* @var \phpDocumentor\Reflection\DocBlock\Context
*/
public $phpDocContext;
public $name;
public $sourceFile;
public $startLine;
public $endLine;
public $shortDescription;
public $description;
public $since;
public $deprecatedSince;
public $deprecatedReason;
/**
* @var \phpDocumentor\Reflection\DocBlock\Tag[]
*/
public $tags = [];
public function hasTag($name)
{
foreach ($this->tags as $tag) {
......
......@@ -18,10 +18,8 @@ namespace yii\apidoc\models;
class ClassDoc extends TypeDoc
{
public $parentClass;
public $isAbstract;
public $isFinal;
/**
* @var string[]
*/
......@@ -29,7 +27,6 @@ class ClassDoc extends TypeDoc
public $traits = [];
// will be set by Context::updateReferences()
public $subclasses = [];
/**
* @var EventDoc[]
*/
......@@ -39,6 +36,7 @@ class ClassDoc extends TypeDoc
*/
public $constants = [];
public function findSubject($subjectName)
{
if (($subject = parent::findSubject($subjectName)) !== null) {
......
......@@ -18,6 +18,7 @@ class ConstDoc extends BaseDoc
public $definedBy;
public $value;
/**
* @param \phpDocumentor\Reflection\ClassReflector\ConstantReflector $reflector
* @param Context $context
......
......@@ -33,9 +33,9 @@ class Context extends Component
* @var TraitDoc[]
*/
public $traits = [];
public $errors = [];
public function getType($type)
{
$type = ltrim($type, '\\');
......
......@@ -20,6 +20,7 @@ class EventDoc extends ConstDoc
public $type;
public $types;
/**
* @param \phpDocumentor\Reflection\ClassReflector\ConstantReflector $reflector
* @param Context $context
......
......@@ -30,6 +30,7 @@ class FunctionDoc extends BaseDoc
public $returnTypes;
public $isReturnByReference;
/**
* @param \phpDocumentor\Reflection\FunctionReflector $reflector
* @param Context $context
......
......@@ -16,10 +16,10 @@ namespace yii\apidoc\models;
class InterfaceDoc extends TypeDoc
{
public $parentInterfaces = [];
// will be set by Context::updateReferences()
public $implementedBy = [];
/**
* @param \phpDocumentor\Reflection\InterfaceReflector $reflector
* @param Context $context
......
......@@ -17,14 +17,12 @@ class MethodDoc extends FunctionDoc
{
public $isAbstract;
public $isFinal;
public $isStatic;
public $visibility;
// will be set by creating class
public $definedBy;
/**
* @param \phpDocumentor\Reflection\ClassReflector\MethodReflector $reflector
* @param Context $context
......
......@@ -23,13 +23,13 @@ class ParamDoc extends Object
public $isOptional;
public $defaultValue;
public $isPassedByReference;
// will be set by creating class
public $description;
public $type;
public $types;
public $sourceFile;
/**
* @param \phpDocumentor\Reflection\FunctionReflector\ArgumentReflector $reflector
* @param Context $context
......
......@@ -20,18 +20,16 @@ class PropertyDoc extends BaseDoc
{
public $visibility;
public $isStatic;
public $type;
public $types;
public $defaultValue;
// will be set by creating class
public $getter;
public $setter;
// will be set by creating class
public $definedBy;
public function getIsReadOnly()
{
return $this->getter !== null && $this->setter === null;
......
......@@ -18,9 +18,9 @@ class TraitDoc extends TypeDoc
// classes using the trait
// will be set by Context::updateReferences()
public $usedBy = [];
public $traits = [];
/**
* @param \phpDocumentor\Reflection\TraitReflector $reflector
* @param Context $context
......
......@@ -34,9 +34,9 @@ class TypeDoc extends BaseDoc
* @var PropertyDoc[]
*/
public $properties = [];
public $namespace;
public function findSubject($subjectName)
{
if ($subjectName[0] != '$') {
......@@ -46,7 +46,7 @@ class TypeDoc extends BaseDoc
}
}
}
if (substr_compare($subjectName, '()', -2, 2) === 0) {
if (!empty($subjectName) && substr_compare($subjectName, '()', -2, 2) === 0) {
return null;
}
if ($this->properties === null) {
......
......@@ -42,10 +42,10 @@ abstract class BaseRenderer extends Component
* @var Controller the apidoc controller instance. Can be used to control output.
*/
public $controller;
public $guideUrl;
public $guideReferences = [];
public function init()
{
ApiMarkdown::$renderer = $this;
......@@ -72,7 +72,7 @@ abstract class BaseRenderer extends Component
foreach ($types as $type) {
$postfix = '';
if (is_string($type)) {
if (substr_compare($type, '[]', -2, 2) === 0) {
if (!empty($type) && substr_compare($type, '[]', -2, 2) === 0) {
$postfix = '[]';
$type = substr($type, 0, -2);
}
......
......@@ -24,6 +24,7 @@ class ApiRenderer extends \yii\apidoc\templates\html\ApiRenderer
public $layout = '@yii/apidoc/templates/bootstrap/layouts/api.php';
public $indexView = '@yii/apidoc/templates/bootstrap/views/index.php';
/**
* @inheritdoc
*/
......
......@@ -23,6 +23,7 @@ class GuideRenderer extends \yii\apidoc\templates\html\GuideRenderer
public $layout = '@yii/apidoc/templates/bootstrap/layouts/guide.php';
/**
* @inheritDoc
*/
......
......@@ -78,6 +78,7 @@ class SideNavWidget extends \yii\bootstrap\Widget
*/
public $activeUrl;
/**
* Initializes the widget.
*/
......
......@@ -46,12 +46,14 @@ class ApiRenderer extends BaseApiRenderer implements ViewContextInterface
* @var string path or alias of the view file to use for rendering the index page.
*/
public $indexView = '@yii/apidoc/templates/html/views/index.php';
/**
* @var View
*/
private $_view;
private $_targetDir;
public function init()
{
parent::init();
......
......@@ -34,6 +34,7 @@ abstract class GuideRenderer extends BaseGuideRenderer
private $_view;
private $_targetDir;
public function init()
{
parent::init();
......
......@@ -23,10 +23,12 @@ if (empty($see)) {
} else {
echo '<p>See also:</p><ul>';
foreach ($see as $ref) {
if (substr_compare($ref, '>', -1, 1)) {
$ref .= '.';
if (!empty($ref)) {
if (substr_compare($ref, '>', -1, 1)) {
$ref .= '.';
}
echo "<li>$ref</li>";
}
echo "<li>$ref</li>";
}
echo '</ul>';
}
......@@ -20,9 +20,9 @@ class ApiRenderer extends \yii\apidoc\templates\html\ApiRenderer
{
public $layout = false;
public $indexView = '@yii/apidoc/templates/online/views/index.php';
public $pageTitle = 'Yii Framework 2.0 API Documentation';
/**
* @inheritdoc
*/
......
......@@ -93,6 +93,8 @@ class AuthAction extends Action
* @var string the redirect url after unsuccessful authorization (e.g. user canceled).
*/
private $_cancelUrl = '';
/**
* @var string name or alias of the view file, which should be rendered in order to perform redirection.
* If not set default one will be used.
......
......@@ -58,6 +58,7 @@ abstract class BaseClient extends Component implements ClientInterface
*/
private $_viewOptions;
/**
* @param string $id service id.
*/
......
......@@ -39,12 +39,6 @@ abstract class BaseOAuth extends BaseClient implements ClientInterface
*/
public $version = '1.0';
/**
* @var string URL, which user will be redirected after authentication at the OAuth provider web site.
* Note: this should be absolute URL (with http:// or https:// leading).
* By default current URL will be used.
*/
private $_returnUrl;
/**
* @var string API base URL.
*/
public $apiBaseUrl;
......@@ -56,6 +50,13 @@ abstract class BaseOAuth extends BaseClient implements ClientInterface
* @var string auth request scope.
*/
public $scope;
/**
* @var string URL, which user will be redirected after authentication at the OAuth provider web site.
* Note: this should be absolute URL (with http:// or https:// leading).
* By default current URL will be used.
*/
private $_returnUrl;
/**
* @var array cURL request options. Option values from this field will overwrite corresponding
* values from [[defaultCurlOptions()]].
......@@ -70,6 +71,7 @@ abstract class BaseOAuth extends BaseClient implements ClientInterface
*/
private $_signatureMethod = [];
/**
* @param string $returnUrl return URL
*/
......
......@@ -47,6 +47,7 @@ class Collection extends Component
*/
private $_clients = [];
/**
* @param array $clients list of auth clients
*/
......
......@@ -26,6 +26,7 @@ class InvalidResponseException extends Exception
*/
public $responseBody = '';
/**
* Constructor.
* @param array $responseHeaders response headers
......
......@@ -62,6 +62,7 @@ class OAuth1 extends BaseOAuth
*/
public $accessTokenMethod = 'GET';
/**
* Fetches the OAuth request token.
* @param array $params additional request params.
......
......@@ -50,6 +50,7 @@ class OAuth2 extends BaseOAuth
*/
public $tokenUrl;
/**
* Composes user authorization URL.
* @param array $params additional auth GET params.
......
......@@ -43,6 +43,8 @@ class OAuthToken extends Object
* @var array token parameters.
*/
private $_params = [];
/**
* @var integer object creation timestamp.
*/
......
......@@ -68,7 +68,6 @@ class OpenId extends BaseClient implements ClientInterface
* ~~~
*/
public $optionalAttributes = [];
/**
* @var boolean whether to verify the peer's certificate.
*/
......@@ -83,7 +82,6 @@ class OpenId extends BaseClient implements ClientInterface
* This value will take effect only if [[verifyPeer]] is set.
*/
public $cainfo;
/**
* @var string authentication return URL.
*/
......@@ -96,6 +94,8 @@ class OpenId extends BaseClient implements ClientInterface
* @var string client trust root (realm), by default [[\yii\web\Request::hostInfo]] value will be used.
*/
private $_trustRoot;
/**
* @var array data, which should be used to retrieve the OpenID response.
* If not set combination of GET and POST will be used.
......@@ -761,7 +761,7 @@ class OpenId extends BaseClient implements ClientInterface
} else {
// 'ax' prefix is either undefined, or points to another extension, so we search for another prefix
foreach ($this->data as $key => $value) {
if (substr_compare($key, 'openid_ns_', 0, 10) === 0 && $value == 'http://openid.net/srv/ax/1.0') {
if (strncmp($key, 'openid_ns_', 10) === 0 && $value == 'http://openid.net/srv/ax/1.0') {
$alias = substr($key, strlen('openid_ns_'));
break;
}
......@@ -775,7 +775,7 @@ class OpenId extends BaseClient implements ClientInterface
$attributes = [];
foreach ($this->data as $key => $value) {
$keyMatch = 'openid_' . $alias . '_value_';
if (substr_compare($key, $keyMatch, 0, strlen($keyMatch))) {
if (strncmp($key, $keyMatch, strlen($keyMatch))) {
continue;
}
$key = substr($key, strlen($keyMatch));
......@@ -802,7 +802,7 @@ class OpenId extends BaseClient implements ClientInterface
$sregToAx = array_flip($this->axToSregMap);
foreach ($this->data as $key => $value) {
$keyMatch = 'openid_sreg_';
if (substr_compare($key, $keyMatch, 0, strlen($keyMatch))) {
if (strncmp($key, $keyMatch, strlen($keyMatch))) {
continue;
}
$key = substr($key, strlen($keyMatch));
......
......@@ -57,6 +57,7 @@ class Facebook extends OAuth2
*/
public $scope = 'email';
/**
* @inheritdoc
*/
......
......@@ -53,6 +53,7 @@ class GitHub extends OAuth2
*/
public $apiBaseUrl = 'https://api.github.com';
/**
* @inheritdoc
*/
......
......@@ -55,6 +55,7 @@ class GoogleOAuth extends OAuth2
*/
public $apiBaseUrl = 'https://www.googleapis.com/plus/v1';
/**
* @inheritdoc
*/
......
......@@ -48,6 +48,7 @@ class GoogleOpenId extends OpenId
'pref/language',
];
/**
* @inheritdoc
*/
......
......@@ -56,6 +56,7 @@ class LinkedIn extends OAuth2
*/
public $apiBaseUrl = 'https://api.linkedin.com/v1';
/**
* @inheritdoc
*/
......
......@@ -53,6 +53,7 @@ class Live extends OAuth2
*/
public $apiBaseUrl = 'https://apis.live.net/v5.0';
/**
* @inheritdoc
*/
......
......@@ -65,6 +65,7 @@ class Twitter extends OAuth1
*/
public $apiBaseUrl = 'https://api.twitter.com/1.1';
/**
* @inheritdoc
*/
......
......@@ -14,7 +14,6 @@ use yii\authclient\OAuth2;
*
* In order to use VKontakte OAuth you must register your application at <http://vk.com/editapp?act=create>.
*
*
* Example application configuration:
*
* ~~~
......@@ -54,6 +53,7 @@ class VKontakte extends OAuth2
*/
public $apiBaseUrl = 'https://api.vk.com/method';
/**
* @inheritdoc
*/
......
......@@ -53,6 +53,7 @@ class YandexOAuth extends OAuth2
*/
public $apiBaseUrl = 'https://login.yandex.ru';
/**
* @inheritdoc
*/
......
......@@ -46,6 +46,7 @@ class YandexOpenId extends OpenId
'contact/email',
];
/**
* @inheritdoc
*/
......
......@@ -33,6 +33,8 @@ class RsaSha1 extends BaseMethod
* This value can be fetched from file specified by [[publicCertificateFile]].
*/
protected $_publicCertificate;
/**
* @var string path to the file, which holds private key certificate.
*/
......
......@@ -96,6 +96,7 @@ class AuthChoice extends Widget
*/
private $_clients;
/**
* @param ClientInterface[] $clients auth providers
*/
......
......@@ -95,17 +95,14 @@ class ActiveField extends \yii\widgets\ActiveField
* @var bool whether to render [[checkboxList()]] and [[radioList()]] inline.
*/
public $inline = false;
/**
* @var string|null optional template to render the `{input}` placeholder content
*/
public $inputTemplate;
/**
* @var array options for the wrapper tag, used in the `{beginWrapper}` placeholder
*/
public $wrapperOptions = [];
/**
* @var null|array CSS grid classes for horizontal layout. This must be an array with these keys:
* - 'offset' the offset grid class to append to the wrapper if no label is rendered
......@@ -115,47 +112,40 @@ class ActiveField extends \yii\widgets\ActiveField
* - 'hint' the hint grid class
*/
public $horizontalCssClasses;
/**
* @var string the template for checkboxes in default layout
*/
public $checkboxTemplate = "<div class=\"checkbox\">\n{beginLabel}\n{input}\n{labelTitle}\n{endLabel}\n{error}\n{hint}\n</div>";
/**
* @var string the template for radios in default layout
*/
public $radioTemplate = "<div class=\"radio\">\n{beginLabel}\n{input}\n{labelTitle}\n{endLabel}\n{error}\n{hint}\n</div>";
/**
* @var string the template for checkboxes in horizontal layout
*/
public $horizontalCheckboxTemplate = "{beginWrapper}\n<div class=\"checkbox\">\n{beginLabel}\n{input}\n{labelTitle}\n{endLabel}\n</div>\n{error}\n{endWrapper}\n{hint}";
/**
* @var string the template for radio buttons in horizontal layout
*/
public $horizontalRadioTemplate = "{beginWrapper}\n<div class=\"radio\">\n{beginLabel}\n{input}\n{labelTitle}\n{endLabel}\n</div>\n{error}\n{endWrapper}\n{hint}";
/**
* @var string the template for inline checkboxLists
*/
public $inlineCheckboxListTemplate = "{label}\n{beginWrapper}\n{input}\n{error}\n{endWrapper}\n{hint}";
/**
* @var string the template for inline radioLists
*/
public $inlineRadioListTemplate = "{label}\n{beginWrapper}\n{input}\n{error}\n{endWrapper}\n{hint}";
/**
* @var bool whether to render the error. Default is `true` except for layout `inline`.
*/
public $enableError = true;
/**
* @var bool whether to render the label. Default is `true`.
*/
public $enableLabel = true;
/**
* @inheritdoc
*/
......
......@@ -69,7 +69,6 @@ class ActiveForm extends \yii\widgets\ActiveForm
* @var array HTML attributes for the form tag. Default is `['role' => 'form']`.
*/
public $options = ['role' => 'form'];
/**
* @var string the form layout. Either 'default', 'horizontal' or 'inline'.
* By choosing a layout, an appropriate default field configuration is applied. This will
......@@ -79,6 +78,7 @@ class ActiveForm extends \yii\widgets\ActiveForm
*/
public $layout = 'default';
/**
* @inheritdoc
*/
......
......@@ -68,6 +68,7 @@ class Alert extends Widget
*/
public $closeButton = [];
/**
* Initializes the widget.
*/
......
......@@ -39,6 +39,7 @@ class Button extends Widget
*/
public $encodeLabel = true;
/**
* Initializes the widget.
* If you override this method, make sure you call the parent implementation first.
......
......@@ -59,6 +59,7 @@ class ButtonDropdown extends Widget
*/
public $encodeLabel = true;
/**
* Renders the widget.
*/
......
......@@ -52,6 +52,7 @@ class ButtonGroup extends Widget
*/
public $encodeLabels = true;
/**
* Initializes the widget.
* If you override this method, make sure you call the parent implementation first.
......
......@@ -66,6 +66,7 @@ class Carousel extends Widget
*/
public $items = [];
/**
* Initializes the widget.
*/
......
......@@ -59,6 +59,7 @@ class Collapse extends Widget
*/
public $items = [];
/**
* Initializes the widget.
*/
......
......@@ -45,7 +45,8 @@ class Dropdown extends Widget
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
protected $_containerOptions = [];
/**
* Initializes the widget.
* If you override this method, make sure you call the parent implementation first.
......
......@@ -82,6 +82,7 @@ class Modal extends Widget
*/
public $toggleButton;
/**
* Initializes the widget.
*/
......
......@@ -93,6 +93,7 @@ class Nav extends Widget
*/
public $params;
/**
* Initializes the widget.
*/
......
......@@ -85,6 +85,7 @@ class NavBar extends Widget
*/
public $innerContainerOptions = [];
/**
* Initializes the widget.
*/
......
......@@ -89,6 +89,7 @@ class Progress extends Widget
*/
public $bars;
/**
* Initializes the widget.
* If you override this method, make sure you call the parent implementation first.
......
......@@ -102,6 +102,7 @@ class Tabs extends Widget
*/
public $navType = 'nav-tabs';
/**
* Initializes the widget.
*/
......
......@@ -39,6 +39,7 @@ class Widget extends \yii\base\Widget
*/
public $clientEvents = [];
/**
* Initializes the widget.
* This method will register the bootstrap asset bundle. If you override this method,
......
......@@ -27,11 +27,13 @@ abstract class BasePage extends Component
* the route and the rest of the name-value pairs are treated as GET parameters, e.g. `array('site/page', 'name' => 'about')`.
*/
public $route;
/**
* @var \Codeception\AbstractGuy the testing guy object
*/
protected $guy;
/**
* Constructor.
*
......
......@@ -33,6 +33,7 @@ class TestCase extends Test
*/
public $appConfig = '@tests/unit/_config.php';
/**
* Returns the value of an object property.
*
......
......@@ -23,9 +23,9 @@ class Installer extends LibraryInstaller
const EXTRA_WRITABLE = 'writable';
const EXTRA_EXECUTABLE = 'executable';
const EXTRA_CONFIG = 'config';
const EXTENSION_FILE = 'yiisoft/extensions.php';
/**
* @inheritdoc
*/
......
......@@ -25,6 +25,7 @@ class LogTarget extends Target
public $module;
public $tag;
/**
* @param \yii\debug\Module $module
* @param array $config
......
......@@ -194,8 +194,7 @@ class Module extends \yii\base\Module implements BootstrapInterface
return true;
}
}
Yii::warning('Access to debugger is denied due to IP address restriction. The requested IP is ' . $ip, __METHOD__);
Yii::warning('Access to debugger is denied due to IP address restriction. The requesting IP address is ' . $ip, __METHOD__);
return false;
}
......
......@@ -49,6 +49,7 @@ class Panel extends Component
*/
public $actions = [];
/**
* @return string name of the panel
*/
......
......@@ -23,6 +23,7 @@ class Filter extends Component
*/
protected $rules = [];
/**
* Adds data filtering rule.
*
......
......@@ -22,6 +22,7 @@ abstract class Base extends Component implements MatcherInterface
*/
protected $baseValue;
/**
* @inheritdoc
*/
......
......@@ -20,6 +20,7 @@ class SameAs extends Base
*/
public $partial = false;
/**
* @inheritdoc
*/
......
......@@ -33,6 +33,7 @@ class DefaultController extends Controller
*/
public $summary;
/**
* @inheritdoc
*/
......
......@@ -23,12 +23,12 @@ class Db extends Base
* @var string type of the input search value
*/
public $type;
/**
* @var integer query attribute input search value
*/
public $query;
/**
* @inheritdoc
*/
......
......@@ -23,47 +23,40 @@ class Debug extends Base
* @var string tag attribute input search value
*/
public $tag;
/**
* @var string ip attribute input search value
*/
public $ip;
/**
* @var string method attribute input search value
*/
public $method;
/**
* @var integer ajax attribute input search value
*/
public $ajax;
/**
* @var string url attribute input search value
*/
public $url;
/**
* @var string status code attribute input search value
*/
public $statusCode;
/**
* @var integer sql count attribute input search value
*/
public $sqlCount;
/**
* @var integer total mail count attribute input search value
*/
public $mailCount;
/**
* @var array critical codes, used to determine grid row options.
*/
public $criticalCodes = [400, 404, 500];
/**
* @inheritdoc
*/
......
......@@ -23,17 +23,16 @@ class Log extends Base
* @var string ip attribute input search value
*/
public $level;
/**
* @var string method attribute input search value
*/
public $category;
/**
* @var integer message attribute input search value
*/
public $message;
/**
* @inheritdoc
*/
......
......@@ -22,52 +22,44 @@ class Mail extends Base
* @var string from attribute input search value
*/
public $from;
/**
* @var string to attribute input search value
*/
public $to;
/**
* @var string reply attribute input search value
*/
public $reply;
/**
* @var string cc attribute input search value
*/
public $cc;
/**
* @var string bcc attribute input search value
*/
public $bcc;
/**
* @var string subject attribute input search value
*/
public $subject;
/**
* @var string body attribute input search value
*/
public $body;
/**
* @var string charset attribute input search value
*/
public $charset;
/**
* @var string headers attribute input search value
*/
public $headers;
/**
* @var string file attribute input search value
*/
public $file;
public function rules()
{
return [
......
......@@ -23,12 +23,12 @@ class Profile extends Base
* @var string method attribute input search value
*/
public $category;
/**
* @var integer info attribute input search value
*/
public $info;
/**
* @inheritdoc
*/
......
......@@ -28,16 +28,17 @@ class DbPanel extends Panel
* the execution is considered taking critical number of DB queries.
*/
public $criticalQueryThreshold;
/**
* @var array db queries info extracted to array as models, to use with data provider.
*/
private $_models;
/**
* @var array current database request timings
*/
private $_timings;
/**
* @inheritdoc
*/
......
......@@ -25,6 +25,7 @@ class LogPanel extends Panel
*/
private $_models;
/**
* @inheritdoc
*/
......
......@@ -29,11 +29,13 @@ class MailPanel extends Panel
* @var string path where all emails will be saved. should be an alias.
*/
public $mailPath = '@runtime/debug/mail';
/**
* @var array current request sent messages
*/
private $_messages = [];
/**
* @inheritdoc
*/
......
......@@ -25,6 +25,7 @@ class ProfilingPanel extends Panel
*/
private $_models;
/**
* @inheritdoc
*/
......
......@@ -56,6 +56,7 @@ class ActiveRecord extends BaseActiveRecord
private $_version;
private $_highlight;
/**
* Returns the database connection used by this AR class.
* By default, the "elasticsearch" application component is used as the database connection.
......
......@@ -43,9 +43,9 @@ class Command extends Component
* @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-highlighting.html
*/
public $highlight;
public $options = [];
/**
* @param array $options
* @return mixed
......
......@@ -46,7 +46,6 @@ class Connection extends Component
* @var array the active node. key of [[nodes]]. Will be randomly selected on [[open()]].
*/
public $activeNode;
// TODO http://www.elasticsearch.org/guide/en/elasticsearch/client/php-api/current/_configuration.html#_example_configuring_http_basic_auth
public $auth = [];
/**
......@@ -62,6 +61,7 @@ class Connection extends Component
*/
public $dataTimeout = null;
public function init()
{
foreach ($this->nodes as $node) {
......
......@@ -36,6 +36,7 @@ class DebugAction extends Action
*/
public $controller;
public function run($logId, $tag)
{
$this->controller->loadData($tag);
......
......@@ -24,6 +24,7 @@ class DebugPanel extends Panel
{
public $db = 'elasticsearch';
public function init()
{
$this->actions['elasticsearch-query'] = [
......
......@@ -137,7 +137,6 @@ class Query extends Component implements QueryInterface
* on one or more fields.
*/
public $highlight;
public $facets = [];
......
......@@ -24,6 +24,7 @@ class QueryBuilder extends \yii\base\Object
*/
public $db;
/**
* Constructor.
* @param Connection $connection the database connection.
......
......@@ -164,6 +164,7 @@ class FixtureController extends \yii\console\controllers\FixtureController
* More info in [Faker](https://github.com/fzaninotto/Faker.) library docs.
*/
public $providers = [];
/**
* @var \Faker\Generator Faker generator instance
*/
......
......@@ -54,6 +54,7 @@ class CodeFile extends Object
*/
public $operation;
/**
* Constructor.
* @param string $path the file path that the new code should be saved to.
......
......@@ -58,6 +58,7 @@ abstract class Generator extends Model
*/
public $messageCategory = 'app';
/**
* @return string name of the code generator
*/
......
......@@ -21,6 +21,7 @@ class ActiveField extends \yii\widgets\ActiveField
*/
public $model;
/**
* @inheritdoc
*/
......
......@@ -27,6 +27,7 @@ class DefaultController extends Controller
*/
public $generator;
public function actionIndex()
{
$this->layout = 'main';
......
......@@ -46,6 +46,7 @@ class Generator extends \yii\gii\Generator
*/
public $actions = 'index';
/**
* @inheritdoc
*/
......
......@@ -38,6 +38,7 @@ class Generator extends \yii\gii\Generator
public $indexWidgetType = 'grid';
public $searchModelClass = '';
/**
* @inheritdoc
*/
......@@ -373,7 +374,7 @@ class Generator extends \yii\gii\Generator
$labels[$name] = 'ID';
} else {
$label = Inflector::camel2words($name);
if (strcasecmp(substr($label, -3), ' id') === 0) {
if (!empty($label) && substr_compare($label, ' id', -3, null, true) === 0) {
$label = substr($label, 0, -3) . ' ID';
}
$labels[$name] = $label;
......
......@@ -34,6 +34,7 @@ class Generator extends \yii\gii\Generator
public $authorName;
public $authorEmail;
/**
* @inheritdoc
*/
......
<?php
/**
* This is just an example.
*/
echo "<?php\n";
?>
<?= "<?php\n" ?>
namespace <?= substr($generator->namespace, 0, -1) ?>;
/**
* This is just an example.
*/
class AutoloadExample extends \yii\base\Widget
{
public function run()
......
......@@ -26,6 +26,7 @@ class Generator extends \yii\gii\Generator
public $viewName;
public $scenarioName;
/**
* @inheritdoc
*/
......
......@@ -32,6 +32,7 @@ class Generator extends \yii\gii\Generator
public $generateLabelsFromComments = false;
public $useTablePrefix = false;
/**
* @inheritdoc
*/
......@@ -196,7 +197,7 @@ class Generator extends \yii\gii\Generator
$labels[$column->name] = 'ID';
} else {
$label = Inflector::camel2words($column->name);
if (strcasecmp(substr($label, -3), ' id') === 0) {
if (!empty($label) && substr_compare($label, ' id', -3, null, true)) {
$label = substr($label, 0, -3) . ' ID';
}
$labels[$column->name] = $label;
......@@ -428,7 +429,7 @@ class Generator extends \yii\gii\Generator
*/
protected function generateRelationName($relations, $className, $table, $key, $multiple)
{
if (strcasecmp(substr($key, -2), 'id') === 0 && strcasecmp($key, 'id')) {
if (!empty($key) && substr_compare($key, 'id', -2, null, true) === 0 && strcasecmp($key, 'id')) {
$key = rtrim(substr($key, 0, -2), '_');
}
if ($multiple) {
......@@ -478,7 +479,7 @@ class Generator extends \yii\gii\Generator
if ($this->isReservedKeyword($this->modelClass)) {
$this->addError('modelClass', 'Class name cannot be a reserved PHP keyword.');
}
if (substr_compare($this->tableName, '*', -1) && $this->modelClass == '') {
if ((empty($this->tableName) || substr_compare($this->tableName, '*', -1)) && $this->modelClass == '') {
$this->addError('modelClass', 'Model Class cannot be blank if table name does not end with asterisk.');
}
}
......@@ -488,7 +489,7 @@ class Generator extends \yii\gii\Generator
*/
public function validateTableName()
{
if (strpos($this->tableName, '*') !== false && substr($this->tableName, -1) !== '*') {
if (strpos($this->tableName, '*') !== false && substr_compare($this->tableName, '*', -1)) {
$this->addError('tableName', 'Asterisk is only allowed as the last character.');
return;
......
......@@ -26,6 +26,7 @@ class Generator extends \yii\gii\Generator
public $moduleClass;
public $moduleID;
/**
* @inheritdoc
*/
......@@ -146,7 +147,7 @@ EOD;
if (strpos($this->moduleClass, '\\') === false || Yii::getAlias('@' . str_replace('\\', '/', $this->moduleClass), false) === false) {
$this->addError('moduleClass', 'Module class must be properly namespaced.');
}
if (substr_compare($this->moduleClass, '\\', -1, 1) === 0) {
if (empty($this->moduleClass) || substr_compare($this->moduleClass, '\\', -1, 1) === 0) {
$this->addError('moduleClass', 'Module class name must not be empty. Please enter a fully qualified class name. e.g. "app\\modules\\admin\\Module".');
}
}
......
......@@ -41,6 +41,7 @@ class BaseImage
* gmagick driver definition.
*/
const DRIVER_GMAGICK = 'gmagick';
/**
* @var array|string the driver to use. This can be either a single driver name or an array of driver names.
* If the latter, the first available driver will be used.
......@@ -52,6 +53,7 @@ class BaseImage
*/
private static $_imagine;
/**
* Returns the `Imagine` object that supports various image manipulations.
* @return ImagineInterface the `Imagine` object
......
......@@ -85,6 +85,7 @@ class Accordion extends Widget
*/
public $headerOptions = [];
/**
* Renders the widget.
*/
......
......@@ -60,6 +60,7 @@ class DatePicker extends InputWidget
*/
public $containerOptions = [];
/**
* @inheritdoc
*/
......
......@@ -36,6 +36,7 @@ class InputWidget extends Widget
*/
public $value;
/**
* Initializes the widget.
* If you override this method, make sure you call the parent implementation first.
......
......@@ -33,6 +33,7 @@ class Menu extends \yii\widgets\Menu
*/
public $clientEvents = [];
/**
* Initializes the widget.
* If you override this method, make sure you call the parent implementation first.
......
......@@ -79,6 +79,7 @@ class Selectable extends Widget
*/
public $itemOptions = [];
/**
* Renders the widget.
*/
......
......@@ -37,6 +37,7 @@ class Slider extends Widget
'stop' => 'slidestop',
];
/**
* Executes the widget.
*/
......
......@@ -44,6 +44,12 @@ use yii\helpers\Html;
class SliderInput extends InputWidget
{
/**
* @var array the HTML attributes for the container tag.
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $containerOptions = [];
/**
* @inheritDoc
*/
protected $clientEventMap = [
......@@ -53,11 +59,7 @@ class SliderInput extends InputWidget
'start' => 'slidestart',
'stop' => 'slidestop',
];
/**
* @var array the HTML attributes for the container tag.
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $containerOptions = [];
/**
* @inheritdoc
......
......@@ -88,6 +88,7 @@ class Sortable extends Widget
'update' => 'sortupdate',
];
/**
* Renders the widget.
*/
......
......@@ -44,6 +44,7 @@ class Spinner extends InputWidget
'spin' => 'spin',
];
/**
* Renders the widget.
*/
......
......@@ -98,6 +98,7 @@ class Tabs extends Widget
*/
public $encodeLabels = true;
/**
* Renders the widget.
*/
......
......@@ -58,6 +58,7 @@ class Widget extends \yii\base\Widget
*/
protected $clientEventMap = [];
/**
* Initializes the widget.
* If you override this method, make sure you call the parent implementation first.
......
......@@ -39,6 +39,7 @@ class ActiveFixture extends BaseActiveFixture
*/
public $collectionName;
/**
* @inheritdoc
*/
......
......@@ -54,6 +54,7 @@ class Cache extends \yii\caching\Cache
*/
public $gcProbability = 100;
/**
* Initializes the Cache component.
* This method will initialize the [[db]] property to make sure it refers to a valid MongoDB connection.
......
......@@ -72,6 +72,7 @@ class Collection extends Object
*/
public $mongoCollection;
/**
* @return string name of this collection.
*/
......
......@@ -112,11 +112,13 @@ class Connection extends Component
* @var \MongoClient Mongo client instance.
*/
public $mongoClient;
/**
* @var Database[] list of Mongo databases
*/
private $_databases = [];
/**
* Returns the Mongo collection with the given name.
* @param string|null $name collection name, if null default one will be used.
......
......@@ -26,6 +26,7 @@ class Database extends Object
* @var \MongoDB Mongo database instance.
*/
public $mongoDb;
/**
* @var Collection[] list of collections.
*/
......@@ -35,6 +36,7 @@ class Database extends Object
*/
private $_fileCollections = [];
/**
* @return string name of this database.
*/
......
......@@ -39,6 +39,7 @@ abstract class Migration extends Component implements MigrationInterface
*/
public $db = 'mongodb';
/**
* Initializes the migration.
* This method will set [[db]] to be the 'db' application component, if it is null.
......
......@@ -54,6 +54,7 @@ class Query extends Component implements QueryInterface
*/
public $from;
/**
* Returns the Mongo collection for this query.
* @param Connection $db Mongo connection.
......
......@@ -69,6 +69,7 @@ class MigrateController extends BaseMigrateController
*/
public $db = 'mongodb';
/**
* @inheritdoc
*/
......
......@@ -28,11 +28,13 @@ class Collection extends \yii\mongodb\Collection
* @var \MongoGridFS Mongo GridFS collection instance.
*/
public $mongoCollection;
/**
* @var \yii\mongodb\Collection file chunks Mongo collection.
*/
private $_chunkCollection;
/**
* Returns the Mongo collection for the file chunks.
* @param boolean $refresh whether to reload the collection instance even if it is found in the cache.
......
......@@ -29,6 +29,7 @@ class Generator extends \yii\gii\Generator
public $modelClass;
public $baseClass = 'yii\mongodb\ActiveRecord';
/**
* @inheritdoc
*/
......@@ -182,7 +183,7 @@ class Generator extends \yii\gii\Generator
$label = 'ID';
} else {
$label = Inflector::camel2words($attribute);
if (strcasecmp(substr($label, -3), ' id') === 0) {
if (substr_compare($label, ' id', -3, null, true) === 0) {
$label = substr($label, 0, -3) . ' ID';
}
}
......
......@@ -37,6 +37,7 @@ class MongoDbTarget extends Target
*/
public $logCollection = 'log';
/**
* Initializes the MongoDbTarget component.
* This method will initialize the [[db]] property to make sure it refers to a valid MongoDB connection.
......
......@@ -82,6 +82,7 @@ class ActiveQuery extends Component implements ActiveQueryInterface
*/
const EVENT_INIT = 'init';
/**
* Constructor.
* @param array $modelClass the model class associated with this query
......
......@@ -67,6 +67,7 @@ class Cache extends \yii\caching\Cache
*/
public $redis = 'redis';
/**
* Initializes the redis Cache component.
* This method will initialize the [[redis]] property to make sure it refers to a valid redis connection.
......
......@@ -209,6 +209,7 @@ class Connection extends Component
'ZSCORE', // key member Get the score associated with the given member in a sorted set
'ZUNIONSTORE', // destination numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX] Add multiple sorted sets and store the resulting sorted set in a new key
];
/**
* @var resource redis socket connection
*/
......
......@@ -25,17 +25,16 @@ class ViewRenderer extends BaseViewRenderer
* @var string the directory or path alias pointing to where Smarty cache will be stored.
*/
public $cachePath = '@runtime/Smarty/cache';
/**
* @var string the directory or path alias pointing to where Smarty compiled templates will be stored.
*/
public $compilePath = '@runtime/Smarty/compile';
/**
* @var Smarty
*/
public $smarty;
public function init()
{
$this->smarty = new Smarty();
......
......@@ -54,6 +54,7 @@ abstract class ActiveRecord extends BaseActiveRecord
*/
private $_snippet;
/**
* Returns the Sphinx connection used by this AR class.
* By default, the "sphinx" application component is used as the Sphinx connection.
......
......@@ -54,6 +54,7 @@ class ColumnSchema extends Object
*/
public $isMva;
/**
* Converts the input value according to [[phpType]] after retrieval from the database.
* If the value is null or an [[Expression]], it will not be converted.
......
......@@ -49,6 +49,7 @@ class Command extends \yii\db\Command
*/
public $db;
/**
* Creates a batch INSERT command.
* For example,
......
......@@ -67,6 +67,7 @@ class Connection extends \yii\db\Connection
'mysql' => 'yii\sphinx\Schema', // MySQL
];
/**
* Obtains the schema information for the named index.
* @param string $name index name.
......
......@@ -40,6 +40,7 @@ class IndexSchema extends Object
*/
public $columns = [];
/**
* Gets the named column metadata.
* This is a convenient method for retrieving a named column even if it does not exist.
......
......@@ -125,11 +125,13 @@ class Query extends Component implements QueryInterface
* @var array query options for the call snippet.
*/
public $snippetOptions;
/**
* @var Connection the Sphinx connection used to generate the SQL statements.
*/
private $_connection;
/**
* @param Connection $connection Sphinx connection instance
* @return static the query object itself
......
......@@ -38,6 +38,7 @@ class QueryBuilder extends Object
*/
public $separator = " ";
/**
* Constructor.
* @param Connection $connection the Sphinx connection.
......
......@@ -60,6 +60,7 @@ class Schema extends Object
*/
private $_builder;
/**
* @var array mapping from physical column types (keys) to abstract column types (values)
*/
......
......@@ -29,6 +29,7 @@ class Generator extends \yii\gii\Generator
public $baseClass = 'yii\sphinx\ActiveRecord';
public $useIndexPrefix = false;
/**
* @inheritdoc
*/
......@@ -180,7 +181,7 @@ class Generator extends \yii\gii\Generator
$labels[$column->name] = 'ID';
} else {
$label = Inflector::camel2words($column->name);
if (strcasecmp(substr($label, -3), ' id') === 0) {
if (substr_compare($label, ' id', -3, null, true) === 0) {
$label = substr($label, 0, -3) . ' ID';
}
$labels[$column->name] = $label;
......@@ -266,7 +267,7 @@ class Generator extends \yii\gii\Generator
if ($this->isReservedKeyword($this->modelClass)) {
$this->addError('modelClass', 'Class name cannot be a reserved PHP keyword.');
}
if (substr_compare($this->indexName, '*', -1) && $this->modelClass == '') {
if ((empty($this->indexName) || substr_compare($this->indexName, '*', -1)) && $this->modelClass == '') {
$this->addError('modelClass', 'Model Class cannot be blank if table name does not end with asterisk.');
}
}
......@@ -276,7 +277,7 @@ class Generator extends \yii\gii\Generator
*/
public function validateIndexName()
{
if (strpos($this->indexName, '*') !== false && substr($this->indexName, -1) !== '*') {
if (strpos($this->indexName, '*') !== false && substr_compare($this->indexName, '*', -1)) {
$this->addError('indexName', 'Asterisk is only allowed as the last character.');
return;
......
......@@ -79,6 +79,7 @@ class Mailer extends BaseMailer
* @var string message default class name.
*/
public $messageClass = 'yii\swiftmailer\Message';
/**
* @var \Swift_Mailer Swift mailer instance.
*/
......@@ -88,6 +89,7 @@ class Mailer extends BaseMailer
*/
private $_transport = [];
/**
* @return array|\Swift_Mailer Swift mailer instance or array configuration.
*/
......
......@@ -29,6 +29,7 @@ class Message extends BaseMessage
*/
private $_swiftMessage;
/**
* @return \Swift_Message Swift message instance.
*/
......
......@@ -24,17 +24,16 @@ class Extension extends \Twig_Extension
* @var array used namespaces
*/
protected $namespaces = [];
/**
* @var array used class aliases
*/
protected $aliases = [];
/**
* @var array used widgets
*/
protected $widgets = [];
/**
* Creates new instance
*
......
......@@ -19,6 +19,7 @@ class FileLoader implements \Twig_LoaderInterface
*/
private $_dir;
/**
* @param string $dir path to directory
*/
......
......@@ -26,13 +26,11 @@ class ViewRenderer extends BaseViewRenderer
* templates cache.
*/
public $cachePath = '@runtime/Twig/cache';
/**
* @var array Twig options.
* @see http://twig.sensiolabs.org/doc/api.html#environment-options
*/
public $options = [];
/**
* @var array Objects or static classes.
* Keys of the array are names to call in template, values are objects or names of static classes.
......@@ -40,7 +38,6 @@ class ViewRenderer extends BaseViewRenderer
* In the template you can use it like this: `{{ html.a('Login', 'site/login') | raw }}`.
*/
public $globals = [];
/**
* @var array Custom functions.
* Keys of the array are names to call in template, values are names of functions or static methods of some class.
......@@ -48,7 +45,6 @@ class ViewRenderer extends BaseViewRenderer
* In the template you can use it like this: `{{ rot13('test') }}` or `{{ a('Login', 'site/login') | raw }}`.
*/
public $functions = [];
/**
* @var array Custom filters.
* Keys of the array are names to call in template, values are names of functions or static methods of some class.
......@@ -56,13 +52,11 @@ class ViewRenderer extends BaseViewRenderer
* In the template you can use it like this: `{{ 'test'|rot13 }}` or `{{ model|jsonEncode }}`.
*/
public $filters = [];
/**
* @var array Custom extensions.
* Example: `['Twig_Extension_Sandbox', new \Twig_Extension_Text()]`
*/
public $extensions = [];
/**
* @var array Twig lexer options.
*
......@@ -77,7 +71,6 @@ class ViewRenderer extends BaseViewRenderer
* @see http://twig.sensiolabs.org/doc/recipes.html#customizing-the-syntax
*/
public $lexerOptions = [];
/**
* @var array namespaces and classes to import.
*
......@@ -92,12 +85,12 @@ class ViewRenderer extends BaseViewRenderer
* ```
*/
public $uses = [];
/**
* @var \Twig_Environment twig environment object that renders twig templates
*/
public $twig;
public function init()
{
$this->twig = new \Twig_Environment(null, array_merge([
......
......@@ -17,6 +17,7 @@ class ViewRendererStaticClassProxy
{
private $_staticClassName;
public function __construct($staticClassName)
{
$this->_staticClassName = $staticClassName;
......
......@@ -75,6 +75,7 @@ Yii Framework 2 Change Log
- Bug #4453: `yii message/extract` wasn't properly writing to po files in case of multiple categories (samdark)
- Bug #4469: Make `Security::compareString()` timing depend only on length of `$actual` input and add unit test. (tom--)
- Bug #4470: Avoid endless loop when exporting logs with low values of flushInterval and eportInterval (cebe)
- Bug #4514: Fixed Request class crashing when empty CSRF token value is sent in cookie (cebe)
- Bug: Fixed inconsistent return of `\yii\console\Application::runAction()` (samdark)
- Bug: URL encoding for the route parameter added to `\yii\web\UrlManager` (klimov-paul)
- Bug: Fixed the bug that requesting protected or private action methods would cause 500 error instead of 404 (qiangxue)
......
......@@ -45,6 +45,7 @@ class Action extends Component
*/
public $controller;
/**
* Constructor.
*
......
......@@ -32,6 +32,7 @@ class ActionEvent extends Event
*/
public $isValid = true;
/**
* Constructor.
* @param Action $action the action associated with this action event.
......
......@@ -12,8 +12,9 @@ use Yii;
/**
* Application is the base class for all application classes.
*
* @property \yii\web\AssetManager $assetManager The asset manager component. This property is read-only.
* @property \yii\rbac\ManagerInterface $authManager The auth manager for this application. Null is returned
* @property \yii\web\AssetManager $assetManager The asset manager application component. This property is
* read-only.
* @property \yii\rbac\ManagerInterface $authManager The auth manager application component. Null is returned
* if auth manager is not configured. This property is read-only.
* @property string $basePath The root directory of the application.
* @property \yii\caching\Cache $cache The cache application component. Null if the component is not enabled.
......@@ -21,23 +22,23 @@ use Yii;
* @property \yii\db\Connection $db The database connection. This property is read-only.
* @property \yii\web\ErrorHandler|\yii\console\ErrorHandler $errorHandler The error handler application
* component. This property is read-only.
* @property \yii\base\Formatter|\yii\i18n\Formatter $formatter The formatter application component. This property is read-only.
* @property \yii\i18n\I18N $i18n The internationalization component. This property is read-only.
* @property \yii\log\Dispatcher $log The log dispatcher component. This property is read-only.
* @property \yii\mail\MailerInterface $mailer The mailer interface. This property is read-only.
* @property \yii\base\Formatter $formatter The formatter application component. This property is read-only.
* @property \yii\i18n\I18N $i18n The internationalization application component. This property is read-only.
* @property \yii\log\Dispatcher $log The log dispatcher application component. This property is read-only.
* @property \yii\mail\MailerInterface $mailer The mailer application component. This property is read-only.
* @property \yii\web\Request|\yii\console\Request $request The request component. This property is read-only.
* @property \yii\web\Response|\yii\console\Response $response The response component. This property is
* read-only.
* @property string $runtimePath The directory that stores runtime files. Defaults to the "runtime"
* subdirectory under [[basePath]].
* @property \yii\base\Security $security The security application component.
* @property \yii\base\Security $security The security application component. This property is read-only.
* @property string $timeZone The time zone used by this application.
* @property string $uniqueId The unique ID of the module. This property is read-only.
* @property \yii\web\UrlManager $urlManager The URL manager for this application. This property is read-only.
* @property string $vendorPath The directory that stores vendor files. Defaults to "vendor" directory under
* [[basePath]].
* @property View|\yii\web\View $view The view object that is used to render various view files. This property
* is read-only.
* @property View|\yii\web\View $view The view application component that is used to render various view
* files. This property is read-only.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
......@@ -477,7 +478,7 @@ abstract class Application extends Module
/**
* Returns the database connection component.
* @return \yii\db\Connection the database connection
* @return \yii\db\Connection the database connection.
*/
public function getDb()
{
......@@ -486,7 +487,7 @@ abstract class Application extends Module
/**
* Returns the log dispatcher component.
* @return \yii\log\Dispatcher the log dispatcher component
* @return \yii\log\Dispatcher the log dispatcher application component.
*/
public function getLog()
{
......@@ -522,7 +523,7 @@ abstract class Application extends Module
/**
* Returns the request component.
* @return \yii\web\Request|\yii\console\Request the request component
* @return \yii\web\Request|\yii\console\Request the request component.
*/
public function getRequest()
{
......@@ -531,7 +532,7 @@ abstract class Application extends Module
/**
* Returns the response component.
* @return \yii\web\Response|\yii\console\Response the response component
* @return \yii\web\Response|\yii\console\Response the response component.
*/
public function getResponse()
{
......@@ -540,7 +541,7 @@ abstract class Application extends Module
/**
* Returns the view object.
* @return View|\yii\web\View the view object that is used to render various view files.
* @return View|\yii\web\View the view application component that is used to render various view files.
*/
public function getView()
{
......@@ -558,7 +559,7 @@ abstract class Application extends Module
/**
* Returns the internationalization (i18n) component
* @return \yii\i18n\I18N the internationalization component
* @return \yii\i18n\I18N the internationalization application component.
*/
public function getI18n()
{
......@@ -567,7 +568,7 @@ abstract class Application extends Module
/**
* Returns the mailer component.
* @return \yii\mail\MailerInterface the mailer interface
* @return \yii\mail\MailerInterface the mailer application component.
*/
public function getMailer()
{
......@@ -576,7 +577,7 @@ abstract class Application extends Module
/**
* Returns the auth manager for this application.
* @return \yii\rbac\ManagerInterface the auth manager for this application.
* @return \yii\rbac\ManagerInterface the auth manager application component.
* Null is returned if auth manager is not configured.
*/
public function getAuthManager()
......@@ -586,7 +587,7 @@ abstract class Application extends Module
/**
* Returns the asset manager.
* @return \yii\web\AssetManager the asset manager component
* @return \yii\web\AssetManager the asset manager application component.
*/
public function getAssetManager()
{
......@@ -595,7 +596,7 @@ abstract class Application extends Module
/**
* Returns the security component.
* @return \yii\base\Security security component
* @return \yii\base\Security the security application component.
*/
public function getSecurity()
{
......@@ -603,8 +604,8 @@ abstract class Application extends Module
}
/**
* Returns the core application components.
* @see set
* Returns the configuration of core application components.
* @see set()
*/
public function coreComponents()
{
......
......@@ -25,6 +25,7 @@ class Behavior extends Object
*/
public $owner;
/**
* Declares event handlers for the [[owner]]'s events.
*
......
......@@ -102,10 +102,11 @@ class Component extends Object
*/
private $_events = [];
/**
* @var Behavior[] the attached behaviors (behavior name => behavior)
* @var Behavior[]|null the attached behaviors (behavior name => behavior). This is `null` when not initialized.
*/
private $_behaviors;
/**
* Returns the value of a component property.
* This method will check in the following order and act accordingly:
......@@ -223,7 +224,6 @@ class Component extends Object
}
}
}
return false;
}
......@@ -244,7 +244,6 @@ class Component extends Object
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
} else {
// behavior property
......@@ -252,7 +251,6 @@ class Component extends Object
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = null;
return;
}
}
......@@ -281,7 +279,6 @@ class Component extends Object
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
......@@ -343,7 +340,6 @@ class Component extends Object
}
}
}
return false;
}
......@@ -374,7 +370,6 @@ class Component extends Object
}
}
}
return false;
}
......@@ -401,7 +396,6 @@ class Component extends Object
}
}
}
return false;
}
......@@ -444,7 +438,6 @@ class Component extends Object
public function hasEventHandlers($name)
{
$this->ensureBehaviors();
return !empty($this->_events[$name]) || Event::hasHandlers($this, $name);
}
......@@ -517,7 +510,6 @@ class Component extends Object
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
}
return $removed;
}
}
......@@ -562,7 +554,6 @@ class Component extends Object
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
......@@ -573,7 +564,6 @@ class Component extends Object
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
......@@ -595,7 +585,6 @@ class Component extends Object
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
......@@ -627,7 +616,6 @@ class Component extends Object
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
$behavior->detach();
return $behavior;
} else {
return null;
......@@ -681,7 +669,6 @@ class Component extends Object
$behavior->attach($this);
$this->_behaviors[$name] = $behavior;
}
return $behavior;
}
}
......@@ -36,6 +36,7 @@ class Controller extends Component implements ViewContextInterface
* @event ActionEvent an event raised right after executing a controller action.
*/
const EVENT_AFTER_ACTION = 'afterAction';
/**
* @var string the ID of this controller.
*/
......@@ -61,11 +62,13 @@ class Controller extends Component implements ViewContextInterface
* by [[run()]] when it is called by [[Application]] to run an action.
*/
public $action;
/**
* @var View the view object that can be used to render views or view files.
*/
private $_view;
/**
* @param string $id the ID of this controller.
* @param Module $module the module that this controller belongs to.
......
......@@ -57,6 +57,7 @@ class DynamicModel extends Model
{
private $_attributes = [];
/**
* Constructors.
* @param array $attributes the dynamic attributes (name-value pairs, or names) being defined
......
......@@ -50,6 +50,7 @@ class Event extends Object
private static $_events = [];
/**
* Attaches an event handler to a class-level event.
*
......
......@@ -77,6 +77,7 @@ class Formatter extends Component
'decimalSeparator' => null,
];
/**
* Initializes the component.
*/
......
......@@ -25,6 +25,7 @@ class InlineAction extends Action
*/
public $actionMethod;
/**
* @param string $id the ID of this action
* @param Controller $controller the controller that owns this action
......
......@@ -83,6 +83,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab
*/
private $_scenario = self::SCENARIO_DEFAULT;
/**
* Returns the validation rules for attributes.
*
......
......@@ -106,6 +106,7 @@ class Module extends ServiceLocator
* [[Controller::defaultAction]].
*/
public $defaultRoute = 'default';
/**
* @var string the root directory of the module.
*/
......@@ -127,6 +128,7 @@ class Module extends ServiceLocator
*/
private static $_instances = [];
/**
* Constructor.
* @param string $id the ID of this module
......
......@@ -23,6 +23,7 @@ abstract class Request extends Component
private $_scriptFile;
private $_isConsoleRequest;
/**
* Resolves the current request into a route and the associated parameters.
* @return array the first element is the route, and the second is the associated parameters.
......
......@@ -21,6 +21,7 @@ class Response extends Component
*/
public $exitStatus = 0;
/**
* Sends the response to client.
*/
......
......@@ -30,20 +30,6 @@ use Yii;
class Security extends Component
{
/**
* @var integer derivation iterations count.
* Set as high as possible to hinder dictionary password attacks.
*/
public $derivationIterations = 100000;
/**
* @var string strategy, which should be used to generate password hash.
* Available strategies:
* - 'password_hash' - use of PHP `password_hash()` function with PASSWORD_DEFAULT algorithm.
* This option is recommended, but it requires PHP version >= 5.5.0
* - 'crypt' - use PHP `crypt()` function.
*/
public $passwordHashStrategy = 'crypt';
/**
* Cipher algorithm for mcrypt module.
* AES has 128-bit block size and three key sizes: 128, 192 and 256 bits.
* mcrypt offers the Rijndael cipher with block sizes of 128, 192 and 256
......@@ -73,8 +59,23 @@ class Security extends Component
*/
const AUTH_KEY_INFO = 'AuthorizationKey';
/**
* @var integer derivation iterations count.
* Set as high as possible to hinder dictionary password attacks.
*/
public $derivationIterations = 100000;
/**
* @var string strategy, which should be used to generate password hash.
* Available strategies:
* - 'password_hash' - use of PHP `password_hash()` function with PASSWORD_DEFAULT algorithm.
* This option is recommended, but it requires PHP version >= 5.5.0
* - 'crypt' - use PHP `crypt()` function.
*/
public $passwordHashStrategy = 'crypt';
private $_cryptModule;
/**
* Encrypts data using a password.
* Derives keys for encryption and authentication from the password using PBKDF2 and a random salt,
......@@ -178,7 +179,7 @@ class Security extends Component
* @param bool $passwordBased set true to use password-based key derivation
* @param string $secret the encryption password or key
* @param string $info context/application specific information, e.g. a user ID
* See RFC 5869 Section 3.2 @link https://tools.ietf.org/html/rfc5869
* See [RFC 5869 Section 3.2](https://tools.ietf.org/html/rfc5869#section-3.2) for more details.
* @return string the encrypted data
* @throws Exception if PHP Mcrypt extension is not loaded or failed to be initialized
* @see decrypt()
......
......@@ -79,6 +79,7 @@ class Theme extends Component
*/
public $pathMap;
/**
* Initializes the theme.
* @throws InvalidConfigException if [[basePath]] is not set.
......
......@@ -34,7 +34,6 @@ class Widget extends Component implements ViewContextInterface
* @see getId()
*/
public static $autoIdPrefix = 'w';
/**
* @var Widget[] the widgets that are currently being rendered (not ended). This property
* is maintained by [[begin()]] and [[end()]] methods.
......@@ -42,6 +41,7 @@ class Widget extends Component implements ViewContextInterface
*/
public static $stack = [];
/**
* Begins a widget.
* This method creates an instance of the calling class. It will apply the configuration
......
......@@ -74,6 +74,7 @@ class AttributeBehavior extends Behavior
*/
public $value;
/**
* @inheritdoc
*/
......
......@@ -75,6 +75,7 @@ class BlameableBehavior extends AttributeBehavior
*/
public $value;
/**
* @inheritdoc
*/
......
......@@ -73,6 +73,7 @@ class SluggableBehavior extends AttributeBehavior
*/
public $value;
/**
* @inheritdoc
*/
......
......@@ -78,6 +78,7 @@ class TimestampBehavior extends AttributeBehavior
*/
public $value;
/**
* @inheritdoc
*/
......
......@@ -32,6 +32,7 @@ class ChainedDependency extends Dependency
*/
public $dependOnAll = true;
/**
* Evaluates the dependency by generating and saving the data related with dependency.
* @param Cache $cache the cache component that is currently evaluating this dependency
......
......@@ -72,6 +72,7 @@ class DbCache extends Cache
*/
public $gcProbability = 100;
/**
* Initializes the DbCache component.
* This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
......
......@@ -37,6 +37,7 @@ class DbDependency extends Dependency
*/
public $params = [];
/**
* Generates the data needed to determine if dependency has been changed.
* This method returns the value of the global state.
......
......@@ -36,6 +36,7 @@ abstract class Dependency extends \yii\base\Object
*/
private static $_reusableData = [];
/**
* Evaluates the dependency by generating and saving the data related with dependency.
* This method is invoked by cache before writing data into it.
......
......@@ -34,6 +34,7 @@ class ExpressionDependency extends Dependency
*/
public $params;
/**
* Generates the data needed to determine if dependency has been changed.
* This method returns the result of the PHP expression.
......
......@@ -68,6 +68,7 @@ class FileCache extends Cache
*/
public $dirMode = 0775;
/**
* Initializes this component by ensuring the existence of the cache path.
*/
......
......@@ -27,6 +27,7 @@ class FileDependency extends Dependency
*/
public $fileName;
/**
* Generates the data needed to determine if dependency has been changed.
* This method returns the file's last modification time.
......
......@@ -82,6 +82,7 @@ class MemCache extends Cache
* @see http://ca2.php.net/manual/en/memcached.setoptions.php
*/
public $options;
/**
* @var \Memcache|\Memcached the Memcache instance
*/
......
......@@ -7,7 +7,6 @@
namespace yii\caching;
/**
* TagDependency associates a cached data item with one or multiple [[tags]].
*
......@@ -23,6 +22,7 @@ class TagDependency extends Dependency
*/
public $tags = [];
/**
* Generates the data needed to determine if dependency has been changed.
* This method does nothing in this class.
......
......@@ -57,6 +57,7 @@ class Captcha extends InputWidget
*/
public $options = ['class' => 'form-control'];
/**
* Initializes the widget.
*/
......
......@@ -42,6 +42,7 @@ class CaptchaAction extends Action
* The name of the GET parameter indicating whether the CAPTCHA image should be regenerated.
*/
const REFRESH_GET_VAR = 'refresh';
/**
* @var integer how many times should the same CAPTCHA be displayed. Defaults to 3.
* A value less than or equal to 0 means the test is unlimited (available since version 1.1.2).
......@@ -98,6 +99,7 @@ class CaptchaAction extends Action
*/
public $fixedVerifyCode;
/**
* Initializes the action.
* @throws InvalidConfigException if the font file does not exist.
......
......@@ -39,6 +39,7 @@ class CaptchaValidator extends Validator
*/
public $captchaAction = 'site/captcha';
/**
* @inheritdoc
*/
......
......@@ -66,9 +66,9 @@ return [
'yii\caching\ExpressionDependency' => YII_PATH . '/caching/ExpressionDependency.php',
'yii\caching\FileCache' => YII_PATH . '/caching/FileCache.php',
'yii\caching\FileDependency' => YII_PATH . '/caching/FileDependency.php',
'yii\caching\TagDependency' => YII_PATH . '/caching/TagDependency.php',
'yii\caching\MemCache' => YII_PATH . '/caching/MemCache.php',
'yii\caching\MemCacheServer' => YII_PATH . '/caching/MemCacheServer.php',
'yii\caching\TagDependency' => YII_PATH . '/caching/TagDependency.php',
'yii\caching\WinCache' => YII_PATH . '/caching/WinCache.php',
'yii\caching\XCache' => YII_PATH . '/caching/XCache.php',
'yii\caching\ZendDataCache' => YII_PATH . '/caching/ZendDataCache.php',
......@@ -130,6 +130,7 @@ return [
'yii\filters\AccessControl' => YII_PATH . '/filters/AccessControl.php',
'yii\filters\AccessRule' => YII_PATH . '/filters/AccessRule.php',
'yii\filters\ContentNegotiator' => YII_PATH . '/filters/ContentNegotiator.php',
'yii\filters\Cors' => YII_PATH . '/filters/Cors.php',
'yii\filters\HttpCache' => YII_PATH . '/filters/HttpCache.php',
'yii\filters\PageCache' => YII_PATH . '/filters/PageCache.php',
'yii\filters\RateLimitInterface' => YII_PATH . '/filters/RateLimitInterface.php',
......@@ -157,7 +158,6 @@ return [
'yii\helpers\BaseInflector' => YII_PATH . '/helpers/BaseInflector.php',
'yii\helpers\BaseJson' => YII_PATH . '/helpers/BaseJson.php',
'yii\helpers\BaseMarkdown' => YII_PATH . '/helpers/BaseMarkdown.php',
'yii\helpers\BaseSecurity' => YII_PATH . '/helpers/BaseSecurity.php',
'yii\helpers\BaseStringHelper' => YII_PATH . '/helpers/BaseStringHelper.php',
'yii\helpers\BaseUrl' => YII_PATH . '/helpers/BaseUrl.php',
'yii\helpers\BaseVarDumper' => YII_PATH . '/helpers/BaseVarDumper.php',
......
......@@ -69,6 +69,7 @@ class Application extends \yii\base\Application
*/
public $controller;
/**
* @inheritdoc
*/
......
......@@ -36,13 +36,13 @@ class Controller extends \yii\base\Controller
* @var boolean whether to run the command interactively.
*/
public $interactive = true;
/**
* @var boolean whether to enable ANSI color in the output.
* If not set, ANSI color will only be enabled for terminals that support it.
*/
public $color;
/**
* Returns a value indicating whether ANSI color is enabled.
*
......
......@@ -31,6 +31,7 @@ class Markdown extends \cebe\markdown\Parser
'_', // underscore
];
/**
* @inheritDoc
*/
......
......@@ -22,6 +22,7 @@ class Request extends \yii\base\Request
{
private $_params;
/**
* Returns the command line arguments.
* @return array the command line arguments. It does not include the entry script name.
......
......@@ -92,6 +92,7 @@ class AssetController extends Controller
*/
private $_assetManager = [];
/**
* Returns the asset manager instance.
* @throws \yii\console\Exception on invalid configuration.
......
......@@ -41,6 +41,7 @@ abstract class BaseMigrateController extends Controller
*/
public $templateFile;
/**
* @inheritdoc
*/
......
......@@ -156,7 +156,7 @@ class HelpController extends Controller
if (is_dir($controllerPath)) {
$files = scandir($controllerPath);
foreach ($files as $file) {
if (strcmp(substr($file, -14), 'Controller.php') === 0) {
if (!empty($file) && substr_compare($file, 'Controller.php', -14) === 0) {
$controllerClass = $module->controllerNamespace . '\\' . substr(basename($file), 0, -4);
if ($this->validateControllerClass($controllerClass)) {
$commands[] = $prefix . Inflector::camel2id(substr(basename($file), 0, -14));
......
......@@ -41,6 +41,7 @@ class MessageController extends Controller
*/
public $defaultAction = 'extract';
/**
* Creates a configuration file for the "extract" command.
*
......@@ -331,7 +332,7 @@ class MessageController extends Controller
ksort($existingMessages);
foreach ($existingMessages as $message => $translation) {
if (!isset($merged[$message]) && !isset($todo[$message]) && !$removeUnused) {
if (mb_strlen($translation, Yii::$app->charset) >= 2 && substr_compare($translation, '@@', 0, 2) === 0 && substr_compare($translation, '@@', -2) === 0) {
if (!empty($translation) && strncmp($translation, '@@', 2) === 0 && substr_compare($translation, '@@', -2) === 0) {
$todo[$message] = $translation;
} else {
$todo[$message] = '@@' . $translation . '@@';
......@@ -445,7 +446,7 @@ EOD;
// add obsolete unused messages
foreach ($existingMessages as $message => $translation) {
if (!isset($merged[$category . chr(4) . $message]) && !isset($todos[$category . chr(4) . $message]) && !$removeUnused) {
if (mb_strlen($translation, Yii::$app->charset) >= 2 && substr($translation, 0, 2) === '@@' && substr($translation, -2) === '@@') {
if (!empty($translation) && substr($translation, 0, 2) === '@@' && substr($translation, -2) === '@@') {
$todos[$category . chr(4) . $message] = $translation;
} else {
$todos[$category . chr(4) . $message] = '@@' . $translation . '@@';
......
......@@ -68,6 +68,7 @@ class MigrateController extends BaseMigrateController
*/
public $db = 'db';
/**
* @inheritdoc
*/
......
......@@ -43,6 +43,7 @@ abstract class BaseDataProvider extends Component implements DataProviderInterfa
private $_models;
private $_totalCount;
/**
* Prepares the data models that will be made available in the current page.
* @return array the available data models
......
......@@ -134,12 +134,14 @@ class Pagination extends Object implements Linkable
* the maximal page size. If this is false, it means [[pageSize]] should always return the value of [[defaultPageSize]].
*/
public $pageSizeLimit = [1, 50];
/**
* @var integer number of items on each page.
* If it is less than 1, it means the page size is infinite, and thus a single page contains all items.
*/
private $_pageSize;
/**
* @return integer number of pages
*/
......
......@@ -81,7 +81,6 @@ class Sort extends Object
* Defaults to false, which means each time the data can only be sorted by one attribute.
*/
public $enableMultiSort = false;
/**
* @var array list of attributes that are allowed to be sorted. Its syntax can be
* described using the following example:
......
......@@ -82,6 +82,7 @@ class SqlDataProvider extends BaseDataProvider
*/
public $key;
/**
* Initializes the DB connection component.
* This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
......
......@@ -96,6 +96,7 @@ class ActiveRecord extends BaseActiveRecord
*/
const OP_ALL = 0x07;
/**
* Loads default values from database table schema
*
......
......@@ -49,6 +49,7 @@ class BatchQueryResult extends Object implements \Iterator
* If false, a whole batch of rows will be returned in each iteration.
*/
public $each = false;
/**
* @var DataReader the data reader associated with this batch query.
*/
......@@ -66,6 +67,7 @@ class BatchQueryResult extends Object implements \Iterator
*/
private $_key;
/**
* Destructor.
*/
......
......@@ -78,6 +78,7 @@ class ColumnSchema extends Object
*/
public $comment;
/**
* Converts the input value according to [[phpType]] after retrieval from the database.
* If the value is null or an [[Expression]], it will not be converted.
......
......@@ -110,15 +110,22 @@ use yii\caching\Cache;
* ],
* ~~~
*
*
* @property string $driverName Name of the DB driver.
* @property boolean $isActive Whether the DB connection is established. This property is read-only.
* @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the
* sequence object. This property is read-only.
* @property PDO $masterPdo The PDO instance for the currently active master connection. This property is
* read-only.
* @property QueryBuilder $queryBuilder The query builder for the current DB connection. This property is
* read-only.
* @property array $queryCacheInfo The current query cache information, or null if query cache is not enabled.
* This property is read-only.
* @property Schema $schema The schema information for the database opened by this connection. This property
* is read-only.
* @property Connection $slave The currently active slave connection. Null is returned if there is slave
* available and `$fallbackToMaster` is false. This property is read-only.
* @property PDO $slavePdo The PDO instance for the currently active slave connection. Null is returned if no
* slave connection is available and `$fallbackToMaster` is false. This property is read-only.
* @property Transaction $transaction The currently active transaction. Null if no active transaction. This
* property is read-only.
*
......
......@@ -58,6 +58,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable
private $_row;
private $_index = -1;
/**
* Constructor.
* @param Command $command the command generating the query result
......
......@@ -21,6 +21,7 @@ class Exception extends \yii\base\Exception
*/
public $errorInfo = [];
/**
* Constructor.
* @param string $message PDO error message
......
......@@ -36,6 +36,7 @@ class Expression extends \yii\base\Object
*/
public $params = [];
/**
* Constructor.
* @param string $expression the DB expression
......
......@@ -44,6 +44,7 @@ class Migration extends Component implements MigrationInterface
*/
public $db = 'db';
/**
* Initializes the migration.
* This method will set [[db]] to be the 'db' application component, if it is null.
......
......@@ -41,6 +41,7 @@ class QueryBuilder extends \yii\base\Object
* Child classes should override this property to declare supported type mappings.
*/
public $typeMap = [];
/**
* @var array map of query condition to builder methods.
* These methods are used by [[buildCondition]] to build SQL conditions from array syntax.
......
......@@ -64,6 +64,14 @@ abstract class Schema extends Object
*/
public $defaultSchema;
/**
* @var array map of DB errors and corresponding exceptions
* If left part is found in DB error message exception class from the right part is used.
*/
public $exceptionMap = [
'SQLSTATE[23' => 'yii\db\IntegrityException',
];
/**
* @var array list of ALL table names in the database
*/
private $_tableNames = [];
......@@ -76,13 +84,6 @@ abstract class Schema extends Object
*/
private $_builder;
/**
* @var array map of DB errors and corresponding exceptions
* If left part is found in DB error message exception class from the right part is used.
*/
public $exceptionMap = [
'SQLSTATE[23' => 'yii\db\IntegrityException',
];
/**
* Loads the metadata for the specified table.
......
......@@ -59,6 +59,7 @@ class TableSchema extends Object
*/
public $columns = [];
/**
* Gets the named column metadata.
* This is a convenient method for retrieving a named column even if it does not exist.
......
......@@ -67,6 +67,7 @@ class Transaction extends \yii\base\Object
* @var Connection the database connection that this transaction is associated with.
*/
public $db;
/**
* @var integer the nesting level of the transaction. 0 means the outermost level.
*/
......
......@@ -39,6 +39,7 @@ class QueryBuilder extends \yii\db\QueryBuilder
Schema::TYPE_MONEY => 'decimal(19,4)',
];
/**
* Creates a SQL statement for resetting the sequence value of a table's primary key.
* The sequence will be reset such that the primary key of the next new row inserted
......
......@@ -64,7 +64,6 @@ class Schema extends \yii\db\Schema
'sequence' => self::TYPE_STRING,
'enum' => self::TYPE_STRING,
];
/**
* @var array map of DB errors and corresponding exceptions
* If left part is found in DB error message exception class from the right part is used.
......@@ -73,6 +72,7 @@ class Schema extends \yii\db\Schema
'Operation would have caused one or more unique constraint violations' => 'yii\db\IntegrityException',
];
/**
* @inheritdoc
*/
......
......@@ -17,8 +17,6 @@ use yii\base\InvalidParamException;
*/
class QueryBuilder extends \yii\db\QueryBuilder
{
protected $_oldMssql;
/**
* @var array mapping from abstract column types (keys) to physical column types (values).
*/
......@@ -233,7 +231,12 @@ class QueryBuilder extends \yii\db\QueryBuilder
}
/**
* @return boolean if MSSQL used is old
* @var boolean whether MSSQL used is old.
*/
private $_oldMssql;
/**
* @return boolean whether MSSQL used is old.
* @throws \yii\base\InvalidConfigException
* @throws \yii\db\Exception
*/
......
......@@ -35,11 +35,9 @@ class Schema extends \yii\db\Schema
'int' => self::TYPE_INTEGER,
'tinyint' => self::TYPE_SMALLINT,
'money' => self::TYPE_MONEY,
// approximate numbers
'float' => self::TYPE_FLOAT,
'real' => self::TYPE_FLOAT,
// date and time
'date' => self::TYPE_DATE,
'datetimeoffset' => self::TYPE_DATETIME,
......@@ -47,22 +45,18 @@ class Schema extends \yii\db\Schema
'smalldatetime' => self::TYPE_DATETIME,
'datetime' => self::TYPE_DATETIME,
'time' => self::TYPE_TIME,
// character strings
'char' => self::TYPE_STRING,
'varchar' => self::TYPE_STRING,
'text' => self::TYPE_TEXT,
// unicode character strings
'nchar' => self::TYPE_STRING,
'nvarchar' => self::TYPE_STRING,
'ntext' => self::TYPE_TEXT,
// binary strings
'binary' => self::TYPE_BINARY,
'varbinary' => self::TYPE_BINARY,
'image' => self::TYPE_BINARY,
// other data types
// 'cursor' type cannot be used with tables
'timestamp' => self::TYPE_TIMESTAMP,
......@@ -73,6 +67,7 @@ class Schema extends \yii\db\Schema
'table' => self::TYPE_STRING,
];
/**
* @inheritdoc
*/
......
......@@ -40,6 +40,7 @@ class QueryBuilder extends \yii\db\QueryBuilder
Schema::TYPE_MONEY => 'decimal(19,4)',
];
/**
* Builds a SQL statement for renaming a column.
* @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
......
......@@ -52,6 +52,7 @@ class Schema extends \yii\db\Schema
'enum' => self::TYPE_STRING,
];
/**
* Quotes a table name for use in a query.
* A simple table name has no schema prefix.
......
......@@ -42,6 +42,7 @@ class QueryBuilder extends \yii\db\QueryBuilder
private $_sql;
/**
* @inheritdoc
*/
......
......@@ -15,6 +15,9 @@ use yii\db\ColumnSchema;
/**
* Schema is the class for retrieving metadata from an Oracle database
*
* @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the
* sequence object. This property is read-only.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
......
......@@ -38,6 +38,7 @@ class QueryBuilder extends \yii\db\QueryBuilder
Schema::TYPE_BOOLEAN => 'boolean',
Schema::TYPE_MONEY => 'numeric(19,4)',
];
/**
* @var array map of query condition to builder methods.
* These methods are used by [[buildCondition]] to build SQL conditions from array syntax.
......
......@@ -107,6 +107,7 @@ class Schema extends \yii\db\Schema
'xml' => self::TYPE_STRING
];
/**
* Creates a query builder for the PostgreSQL database.
* @return QueryBuilder query builder instance
......
......@@ -58,6 +58,7 @@ class Schema extends \yii\db\Schema
'enum' => self::TYPE_STRING,
];
/**
* Quotes a table name for use in a query.
* A simple table name has no schema prefix.
......
......@@ -57,6 +57,7 @@ class Instance
*/
public $id;
/**
* Constructor.
* @param string $id the component ID
......
......@@ -58,6 +58,7 @@ class ServiceLocator extends Component
*/
private $_definitions = [];
/**
* Getter magic method.
* This method is overridden to support accessing components like reading properties.
......
......@@ -90,6 +90,7 @@ class AccessRule extends Component
*/
public $denyCallback;
/**
* Checks whether the Web user is allowed to perform the specified action.
* @param Action $action the action to be performed
......
......@@ -54,7 +54,6 @@ use yii\web\Response;
* }
* ```
*
*
* @author Philippe Gaultier <pgaultier@gmail.com>
* @since 2.0
*/
......@@ -83,6 +82,7 @@ class Cors extends ActionFilter
'Access-Control-Max-Age' => 86400,
];
/**
* @inheritdoc
*/
......
......@@ -70,6 +70,7 @@ class VerbFilter extends Behavior
*/
public $actions = [];
/**
* Declares event handlers for the [[owner]]'s events.
* @return array events (array keys) and the corresponding event handler methods (array values).
......
......@@ -36,6 +36,7 @@ class HttpBearerAuth extends AuthMethod
*/
public $realm = 'api';
/**
* @inheritdoc
*/
......
......@@ -23,6 +23,7 @@ class QueryParamAuth extends AuthMethod
*/
public $tokenParam = 'access-token';
/**
* @inheritdoc
*/
......
......@@ -53,6 +53,7 @@ class CheckboxColumn extends Column
*/
public $multiple = true;
/**
* @inheritdoc
* @throws \yii\base\InvalidConfigException if [[name]] is not set.
......
......@@ -191,7 +191,6 @@ class GridView extends BaseListView
* This is mainly used by [[Html::error()]] when rendering an error message next to every filter input field.
*/
public $filterErrorOptions = ['class' => 'help-block'];
/**
* @var string the layout that determines how different sections of the list view should be organized.
* The following tokens will be replaced with the corresponding section contents:
......@@ -204,6 +203,7 @@ class GridView extends BaseListView
*/
public $layout = "{summary}\n{items}\n{pager}";
/**
* Initializes the grid view.
* This method will initialize required property values and instantiate [[columns]] objects.
......
......@@ -29,6 +29,7 @@ class SerialColumn extends Column
{
public $header = '#';
/**
* @inheritdoc
*/
......
......@@ -27,6 +27,7 @@ class BaseFileHelper
const PATTERN_MUSTBEDIR = 8;
const PATTERN_NEGATIVE = 16;
/**
* Normalizes a file/directory path.
* The normalization does the following work:
......
......@@ -80,6 +80,7 @@ class BaseHtml
'media',
];
/**
* Encodes special characters into HTML entities.
* The [[\yii\base\Application::charset|application charset]] will be used for encoding.
......@@ -797,13 +798,13 @@ class BaseHtml
if (!array_key_exists('size', $options)) {
$options['size'] = 4;
}
if (!empty($options['multiple']) && substr($name, -2) !== '[]') {
if (!empty($options['multiple']) && !empty($name) && substr_compare($name, '[]', -2)) {
$name .= '[]';
}
$options['name'] = $name;
if (isset($options['unselect'])) {
// add a hidden field so that if the list box has no option being selected, it still submits a value
if (substr_compare($name, '[]', -2) === 0) {
if (!empty($name) && substr_compare($name, '[]', -2) === 0) {
$name = substr($name, 0, -2);
}
$hidden = static::hiddenInput($name, $options['unselect']);
......
......@@ -216,7 +216,6 @@ class BaseInflector
'wildebeest' => 'wildebeest',
'Yengeese' => 'Yengeese',
];
/**
* @var array fallback map for transliteration used by [[slug()]] when intl isn't available.
*/
......@@ -233,6 +232,7 @@ class BaseInflector
'ÿ' => 'y',
];
/**
* Converts a word to its plural form.
* Note that this is for English only!
......
......@@ -45,6 +45,7 @@ class BaseMarkdown
*/
public static $defaultFlavor = 'original';
/**
* Converts markdown into HTML.
*
......
......@@ -21,6 +21,7 @@ class BaseVarDumper
private static $_output;
private static $_depth;
/**
* Displays a variable.
* This method achieves the similar functionality as var_dump and print_r
......
......@@ -85,6 +85,7 @@ class DbMessageSource extends MessageSource
*/
public $enableCaching = false;
/**
* Initializes the DbMessageSource component.
* This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
......
......@@ -79,6 +79,7 @@ class Formatter extends \yii\base\Formatter
*/
public $currencyCode;
/**
* Initializes the component.
* This method will check if the "intl" PHP extension is installed and set the
......
......@@ -48,6 +48,7 @@ class GettextMessageSource extends MessageSource
*/
public $useBigEndian = false;
/**
* Loads the message translation for the specified language and category.
* If translation for specific locale code such as `en-US` isn't found it
......
......@@ -48,6 +48,7 @@ class GettextMoFile extends GettextFile
*/
public $useBigEndian = false;
/**
* Loads messages from an MO file.
* @param string $filePath file path
......@@ -107,7 +108,8 @@ class GettextMoFile extends GettextFile
$id = $this->readString($fileHandle, $sourceLengths[$i], $sourceOffsets[$i]);
$separatorPosition = strpos($id, chr(4));
if (($context && $separatorPosition !== false && substr($id, 0, $separatorPosition) === $context) ||
if (($context && $separatorPosition !== false && strncmp($id, $context, $separatorPosition) === 0) ||
(!$context && $separatorPosition === false)) {
if ($separatorPosition !== false) {
$id = substr($id, $separatorPosition+1);
......
......@@ -48,6 +48,7 @@ class I18N extends Component
*/
public $translations;
/**
* Initializes the component by configuring the default message categories.
*/
......
......@@ -47,6 +47,7 @@ class MessageFormatter extends Component
private $_errorCode = 0;
private $_errorMessage = '';
/**
* Get the error code from the last operation
* @link http://php.net/manual/en/messageformatter.geterrorcode.php
......@@ -390,7 +391,8 @@ class MessageFormatter extends Component
return false;
}
$selector = trim($plural[$i++]);
if ($i == 1 && substr($selector, 0, 7) == 'offset:') {
if ($i == 1 && strncmp($selector, 'offset:', 7) === 0) {
$offset = (int) trim(mb_substr($selector, 7, ($pos = mb_strpos(str_replace(["\n", "\r", "\t"], ' ', $selector), ' ', 7)) - 7));
$selector = trim(mb_substr($selector, $pos + 1));
}
......
......@@ -40,6 +40,7 @@ class MessageSource extends Component
private $_messages = [];
/**
* Initializes this component.
*/
......
......@@ -51,6 +51,7 @@ class PhpMessageSource extends MessageSource
*/
public $fileMap;
/**
* Loads the message translation for the specified language and category.
* If translation for specific locale code such as `en-US` isn't found it
......
......@@ -74,7 +74,6 @@ class Logger extends Component
*/
const LEVEL_PROFILE_END = 0x60;
/**
* @var array logged messages. This property is managed by [[log()]] and [[flush()]].
* Each log message is of the following structure:
......
......@@ -22,7 +22,6 @@ class SyslogTarget extends Target
* @var string syslog identity
*/
public $identity;
/**
* @var integer syslog facility.
*/
......
......@@ -204,7 +204,7 @@ abstract class Target extends Component
$matched = empty($categories);
foreach ($categories as $category) {
if ($message[2] === $category || substr($category, -1) === '*' && strpos($message[2], rtrim($category, '*')) === 0) {
if ($message[2] === $category || !empty($category) && substr_compare($category, '*', -1) === 0 && strpos($message[2], rtrim($category, '*')) === 0) {
$matched = true;
break;
}
......
......@@ -39,6 +39,7 @@ abstract class BaseMailer extends Component implements MailerInterface, ViewCont
* @event MailEvent an event raised right after send.
*/
const EVENT_AFTER_SEND = 'afterSend';
/**
* @var string|boolean HTML layout view name. This is the layout used to render HTML mail body.
* The property can take the following values:
......@@ -105,6 +106,7 @@ abstract class BaseMailer extends Component implements MailerInterface, ViewCont
*/
private $_viewPath;
/**
* @param array|View $view view instance or its array configuration that will be used to
* render message bodies.
......
......@@ -29,6 +29,7 @@ abstract class DbMutex extends Mutex
*/
public $db = 'db';
/**
* Initializes generic database table based mutex implementation.
* @throws InvalidConfigException if [[db]] is invalid.
......
......@@ -58,11 +58,13 @@ class FileMutex extends Mutex
* but read-only for other users.
*/
public $dirMode = 0775;
/**
* @var resource[] stores all opened lock files. Keys are lock names and values are file handles.
*/
private $_files = [];
/**
* Initializes mutex component implementation dedicated for UNIX, GNU/Linux, Mac OS X, and other UNIX-like
* operating systems.
......
......@@ -38,11 +38,13 @@ abstract class Mutex extends Component
* acquire in this process must be released in any case (regardless any kind of errors or exceptions).
*/
public $autoRelease = true;
/**
* @var string[] names of the locks acquired in the current PHP process.
*/
private $_locks = [];
/**
* Initializes the mutex component.
*/
......
......@@ -24,6 +24,7 @@ abstract class BaseManager extends Component implements ManagerInterface
*/
public $defaultRoles = [];
/**
* Returns the named auth item.
* @param string $name the auth item name.
......
......@@ -345,7 +345,7 @@ class DbManager extends BaseManager
$query = (new Query)->select('b.*')
->from(['a' => $this->assignmentTable, 'b' => $this->itemTable])
->where('a.item_name=b.name')
->andWhere(['a.user_id' => $userId]);
->andWhere(['a.user_id' => (string)$userId]);
$roles = [];
foreach ($query->all($this->db) as $row) {
......@@ -383,7 +383,7 @@ class DbManager extends BaseManager
{
$query = (new Query)->select('item_name')
->from($this->assignmentTable)
->where(['user_id' => $userId]);
->where(['user_id' => (string)$userId]);
$childrenList = $this->getChildrenList();
$result = [];
......@@ -470,7 +470,7 @@ class DbManager extends BaseManager
public function getAssignment($roleName, $userId)
{
$row = (new Query)->from($this->assignmentTable)
->where(['user_id' => $userId, 'item_name' => $roleName])
->where(['user_id' => (string)$userId, 'item_name' => $roleName])
->one($this->db);
if ($row === false) {
......@@ -491,7 +491,7 @@ class DbManager extends BaseManager
{
$query = (new Query)
->from($this->assignmentTable)
->where(['user_id' => $userId]);
->where(['user_id' => (string)$userId]);
$assignments = [];
foreach ($query->all($this->db) as $row) {
......@@ -614,7 +614,7 @@ class DbManager extends BaseManager
public function revoke($role, $userId)
{
return $this->db->createCommand()
->delete($this->assignmentTable, ['user_id' => $userId, 'item_name' => $role->name])
->delete($this->assignmentTable, ['user_id' => (string)$userId, 'item_name' => $role->name])
->execute() > 0;
}
......@@ -624,7 +624,7 @@ class DbManager extends BaseManager
public function revokeAll($userId)
{
return $this->db->createCommand()
->delete($this->assignmentTable, ['user_id' => $userId])
->delete($this->assignmentTable, ['user_id' => (string)$userId])
->execute() > 0;
}
......
......@@ -30,6 +30,7 @@ abstract class Rule extends Object
*/
public $updatedAt;
/**
* Executes the rule.
*
......
......@@ -56,6 +56,7 @@ class Action extends \yii\base\Action
*/
public $checkAccess;
/**
* @inheritdoc
*/
......
......@@ -52,6 +52,7 @@ class ActiveController extends Controller
*/
public $createScenario = Model::SCENARIO_DEFAULT;
/**
* @inheritdoc
*/
......
......@@ -28,6 +28,7 @@ class CreateAction extends Action
*/
public $viewAction = 'view';
/**
* Creates a new model.
* @return \yii\db\ActiveRecordInterface the model newly created
......
......@@ -31,6 +31,7 @@ class IndexAction extends Action
*/
public $prepareDataProvider;
/**
* @return ActiveDataProvider
*/
......
......@@ -26,6 +26,7 @@ class OptionsAction extends \yii\base\Action
*/
public $resourceOptions = ['GET', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
/**
* Responds to the OPTIONS request.
* @param string $id
......
......@@ -98,6 +98,7 @@ class Serializer extends Component
*/
public $response;
/**
* @inheritdoc
*/
......
......@@ -24,6 +24,7 @@ class UpdateAction extends Action
*/
public $scenario = Model::SCENARIO_DEFAULT;
/**
* Updates an existing model.
* @param string $id the primary key of the model.
......
......@@ -135,6 +135,7 @@ class UrlRule extends CompositeUrlRule
*/
public $pluralize = true;
/**
* @inheritdoc
*/
......
......@@ -44,11 +44,13 @@ class ActiveFixture extends BaseActiveFixture
* name of the table associated with this fixture. You can set this property to be false to prevent loading any data.
*/
public $dataFile;
/**
* @var TableSchema the table schema for the table associated with this fixture
*/
private $_table;
/**
* @inheritdoc
*/
......
......@@ -34,11 +34,13 @@ abstract class BaseActiveFixture extends DbFixture implements \IteratorAggregate
* to be returned by [[getData()]]. You can set this property to be false to prevent loading any data.
*/
public $dataFile;
/**
* @var \yii\db\ActiveRecord[] the loaded AR models
*/
private $_models = [];
/**
* Returns the AR model by the specified model name.
* A model name is the key of the corresponding data row in [[data]].
......
......@@ -29,6 +29,7 @@ abstract class DbFixture extends Fixture
*/
public $db = 'db';
/**
* @inheritdoc
*/
......
......@@ -35,6 +35,7 @@ class Fixture extends Component
*/
public $depends = [];
/**
* Loads the fixture.
* This method is called before performing every test method.
......
......@@ -32,6 +32,7 @@ trait FixtureTrait
*/
private $_fixtures;
/**
* Declares the fixtures that are needed by the current test case.
* The return value of this method must be an array of fixture configurations. For example,
......
......@@ -40,6 +40,7 @@ class InitDbFixture extends DbFixture
*/
public $schemas = [''];
/**
* @inheritdoc
*/
......
......@@ -35,6 +35,7 @@ class BooleanValidator extends Validator
*/
public $strict = false;
/**
* @inheritdoc
*/
......
......@@ -68,6 +68,7 @@ class CompareValidator extends Validator
*/
public $message;
/**
* @inheritdoc
*/
......
......@@ -31,6 +31,7 @@ class DateValidator extends Validator
*/
public $timestampAttribute;
/**
* @inheritdoc
*/
......
......@@ -37,6 +37,7 @@ class DefaultValueValidator extends Validator
*/
public $skipOnEmpty = false;
/**
* @inheritdoc
*/
......
......@@ -50,6 +50,7 @@ class EmailValidator extends Validator
*/
public $enableIDN = false;
/**
* @inheritdoc
*/
......
......@@ -66,6 +66,7 @@ class ExistValidator extends Validator
*/
public $allowArray = false;
/**
* @inheritdoc
*/
......
......@@ -50,6 +50,7 @@ class FilterValidator extends Validator
*/
public $skipOnEmpty = false;
/**
* @inheritdoc
*/
......
......@@ -54,6 +54,7 @@ class InlineValidator extends Validator
*/
public $clientValidate;
/**
* @inheritdoc
*/
......
......@@ -53,6 +53,7 @@ class NumberValidator extends Validator
*/
public $numberPattern = '/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/';
/**
* @inheritdoc
*/
......
......@@ -40,6 +40,7 @@ class RangeValidator extends Validator
*/
public $allowArray = false;
/**
* @inheritdoc
*/
......
......@@ -32,6 +32,7 @@ class RegularExpressionValidator extends Validator
*/
public $not = false;
/**
* @inheritdoc
*/
......
......@@ -49,6 +49,7 @@ class RequiredValidator extends Validator
*/
public $message;
/**
* @inheritdoc
*/
......
......@@ -60,6 +60,7 @@ class StringValidator extends Validator
*/
public $encoding;
/**
* @inheritdoc
*/
......
......@@ -59,6 +59,7 @@ class UniqueValidator extends Validator
*/
public $filter;
/**
* @inheritdoc
*/
......
......@@ -81,7 +81,6 @@ class Validator extends Component
'unique' => 'yii\validators\UniqueValidator',
'url' => 'yii\validators\UrlValidator',
];
/**
* @var array|string attributes to be validated by this validator. For multiple attributes,
* please specify them as an array; for single attribute, you may use either a string or an array.
......@@ -173,6 +172,7 @@ class Validator extends Component
*/
public $whenClient;
/**
* Creates a validator object.
* @param mixed $type the validator type. This can be a built-in validator name,
......
......@@ -50,6 +50,7 @@ class Application extends \yii\base\Application
*/
public $controller;
/**
* @inheritdoc
*/
......@@ -123,7 +124,7 @@ class Application extends \yii\base\Application
/**
* Returns the session component.
* @return Session the session component
* @return Session the session component.
*/
public function getSession()
{
......@@ -132,7 +133,7 @@ class Application extends \yii\base\Application
/**
* Returns the user component.
* @return User the user component
* @return User the user component.
*/
public function getUser()
{
......
......@@ -35,6 +35,7 @@ class AssetConverter extends Component implements AssetConverterInterface
'ts' => ['js', 'tsc --out {to} {from}'],
];
/**
* Converts a given asset file into a CSS or JS file.
* @param string $asset the asset file path, relative to $basePath
......
......@@ -47,6 +47,7 @@ class CacheSession extends Session
*/
public $cache = 'cache';
/**
* Initializes the application component.
*/
......
......@@ -24,6 +24,7 @@ abstract class CompositeUrlRule extends Object implements UrlRuleInterface
*/
protected $rules = [];
/**
* Creates the URL rules that should be contained within this composite rule.
* @return UrlRuleInterface[] the URL rules
......
......@@ -29,6 +29,7 @@ class Controller extends \yii\base\Controller
*/
public $actionParams = [];
/**
* Renders a view in response to an AJAX request.
*
......
......@@ -47,6 +47,7 @@ class Cookie extends \yii\base\Object
*/
public $httpOnly = true;
/**
* Magic method to turn a cookie object into a string without having to explicitly access [[value]].
*
......
......@@ -34,6 +34,7 @@ class CookieCollection extends Object implements \IteratorAggregate, \ArrayAcces
*/
private $_cookies = [];
/**
* Constructor.
* @param array $cookies the cookies that this collection initially contains. This should be
......
......@@ -68,6 +68,7 @@ class DbSession extends Session
*/
public $sessionTable = '{{%session}}';
/**
* Initializes the DbSession component.
* This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
......
......@@ -66,6 +66,7 @@ class ErrorAction extends Action
*/
public $defaultMessage;
/**
* Runs the action
*
......
......@@ -24,6 +24,7 @@ class HtmlResponseFormatter extends Component implements ResponseFormatterInterf
*/
public $contentType = 'text/html';
/**
* Formats the specified response.
* @param Response $response the response to be formatted.
......
......@@ -34,6 +34,7 @@ class HttpException extends UserException
*/
public $statusCode;
/**
* Constructor.
* @param integer $status HTTP status code, such as 404, 500, etc.
......
......@@ -25,6 +25,7 @@ class JsExpression extends Object
*/
public $expression;
/**
* Constructor.
* @param string $expression the JavaScript expression represented by this object
......
......@@ -37,6 +37,7 @@ class JsonParser implements RequestParserInterface
*/
public $throwException = true;
/**
* Parses a HTTP request body.
* @param string $rawBody the raw HTTP request body.
......
......@@ -28,6 +28,7 @@ class JsonResponseFormatter extends Component implements ResponseFormatterInterf
*/
public $useJsonp = false;
/**
* Formats the specified response.
* @param Response $response the response to be formatted.
......
......@@ -52,6 +52,7 @@ class Link extends Object
*/
public $hreflang;
/**
* Serializes a list of links into proper array format.
* @param array $links the links to be serialized
......
......@@ -75,7 +75,8 @@ use yii\helpers\StringHelper;
* @property string $url The currently requested relative URL. Note that the URI returned is URL-encoded.
* @property string $userAgent User agent, null if not present. This property is read-only.
* @property string $userHost User host name, null if cannot be determined. This property is read-only.
* @property string $userIP User IP address. This property is read-only.
* @property string $userIP User IP address. Null is returned if the user IP address cannot be detected. This
* property is read-only.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
......@@ -163,6 +164,7 @@ class Request extends \yii\base\Request
*/
private $_headers;
/**
* Resolves the current request into a route and the associated parameters.
* @return array the first element is the route, and the second is the associated parameters.
......@@ -1228,12 +1230,11 @@ class Request extends \yii\base\Request
{
if ($this->_csrfCookie === null) {
$this->_csrfCookie = $this->getCookies()->get($this->csrfParam);
if ($this->_csrfCookie === null) {
if ($this->_csrfCookie === null || empty($this->_csrfCookie->value)) {
$this->_csrfCookie = $this->createCsrfCookie();
Yii::$app->getResponse()->getCookies()->add($this->_csrfCookie);
}
}
return $this->_csrfCookie->value;
}
......@@ -1277,7 +1278,7 @@ class Request extends \yii\base\Request
if ($n1 > $n2) {
$token2 = str_pad($token2, $n1, $token2);
} elseif ($n1 < $n2) {
$token1 = str_pad($token1, $n2, $token1);
$token1 = str_pad($token1, $n2, $n1 === 0 ? ' ' : $token1);
}
return $token1 ^ $token2;
......@@ -1289,7 +1290,6 @@ class Request extends \yii\base\Request
public function getCsrfTokenFromHeader()
{
$key = 'HTTP_' . str_replace('-', '_', strtoupper(self::CSRF_HEADER));
return isset($_SERVER[$key]) ? $_SERVER[$key] : null;
}
......@@ -1304,7 +1304,6 @@ class Request extends \yii\base\Request
$options = $this->csrfCookie;
$options['name'] = $this->csrfParam;
$options['value'] = Yii::$app->getSecurity()->generateRandomString();
return new Cookie($options);
}
......
......@@ -235,6 +235,7 @@ class Response extends \yii\base\Response
*/
private $_headers;
/**
* Initializes this component.
*/
......
......@@ -79,6 +79,7 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co
* @var \SessionHandlerInterface|array an object implementing the SessionHandlerInterface or a configuration array. If set, will be used to provide persistency instead of build-in methods.
*/
public $handler;
/**
* @var array parameter-value pairs to override default session cookie parameters that are used for session_set_cookie_params() function
* Array may have the following possible keys: 'lifetime', 'path', 'domain', 'secure', 'httponly'
......@@ -86,6 +87,7 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co
*/
private $_cookieParams = ['httponly' => true];
/**
* Initializes the application component.
* This method is required by IApplicationComponent and is invoked by application.
......
......@@ -24,6 +24,7 @@ class SessionIterator implements \Iterator
*/
private $_key;
/**
* Constructor.
*/
......
......@@ -28,8 +28,6 @@ use yii\helpers\Html;
*/
class UploadedFile extends Object
{
private static $_files;
/**
* @var string the original name of the file being uploaded
*/
......@@ -56,6 +54,8 @@ class UploadedFile extends Object
*/
public $error;
private static $_files;
/**
* String output.
......
......@@ -31,9 +31,11 @@ use yii\caching\Cache;
* ]
* ~~~
*
* @property string $baseUrl The base URL that is used by [[createUrl()]] to prepend URLs it creates.
* @property string $baseUrl The base URL that is used by [[createUrl()]] to prepend to created URLs.
* @property string $hostInfo The host info (e.g. "http://www.example.com") that is used by
* [[createAbsoluteUrl()]] to prepend URLs it creates.
* [[createAbsoluteUrl()]] to prepend to created URLs.
* @property string $scriptUrl The entry script URL that is used by [[createUrl()]] to prepend to created
* URLs.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
......@@ -128,6 +130,7 @@ class UrlManager extends Component
private $_scriptUrl;
private $_hostInfo;
/**
* Initializes UrlManager.
*/
......@@ -366,10 +369,10 @@ class UrlManager extends Component
}
/**
* Returns the base URL that is used by [[createUrl()]] to prepend to the URLs it creates.
* Returns the base URL that is used by [[createUrl()]] to prepend to created URLs.
* It defaults to [[Request::baseUrl]].
* This is mainly used when [[enablePrettyUrl]] is true and [[showScriptName]] is false.
* @return string the base URL that is used by [[createUrl()]] to prepend to the URLs it creates.
* @return string the base URL that is used by [[createUrl()]] to prepend to created URLs.
* @throws InvalidConfigException if running in console application and [[baseUrl]] is not configured.
*/
public function getBaseUrl()
......@@ -387,9 +390,9 @@ class UrlManager extends Component
}
/**
* Sets the base URL that is used by [[createUrl()]] to prepend to the URLs it creates.
* Sets the base URL that is used by [[createUrl()]] to prepend to created URLs.
* This is mainly used when [[enablePrettyUrl]] is true and [[showScriptName]] is false.
* @param string $value the base URL that is used by [[createUrl()]] to prepend URLs it creates.
* @param string $value the base URL that is used by [[createUrl()]] to prepend to created URLs.
*/
public function setBaseUrl($value)
{
......@@ -397,10 +400,10 @@ class UrlManager extends Component
}
/**
* Returns the entry script URL that is used by [[createUrl()]] to prepend to the URLs it creates.
* Returns the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
* It defaults to [[Request::scriptUrl]].
* This is mainly used when [[enablePrettyUrl]] is false or [[showScriptName]] is true.
* @return string the entry script URL that is used by [[createUrl()]] to prepend to the URLs it creates.
* @return string the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
* @throws InvalidConfigException if running in console application and [[scriptUrl]] is not configured.
*/
public function getScriptUrl()
......@@ -418,9 +421,9 @@ class UrlManager extends Component
}
/**
* Sets the entry script URL that is used by [[createUrl()]] to prepend to the URLs it creates.
* Sets the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
* This is mainly used when [[enablePrettyUrl]] is false or [[showScriptName]] is true.
* @param string $value the entry script URL that is used by [[createUrl()]] to prepend URLs it creates.
* @param string $value the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
*/
public function setScriptUrl($value)
{
......@@ -428,8 +431,8 @@ class UrlManager extends Component
}
/**
* Returns the host info that is used by [[createAbsoluteUrl()]] to prepend URLs it creates.
* @return string the host info (e.g. "http://www.example.com") that is used by [[createAbsoluteUrl()]] to prepend URLs it creates.
* Returns the host info that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
* @return string the host info (e.g. "http://www.example.com") that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
* @throws InvalidConfigException if running in console application and [[hostInfo]] is not configured.
*/
public function getHostInfo()
......@@ -447,8 +450,8 @@ class UrlManager extends Component
}
/**
* Sets the host info that is used by [[createAbsoluteUrl()]] to prepend URLs it creates.
* @param string $value the host info (e.g. "http://www.example.com") that is used by [[createAbsoluteUrl()]] to prepend URLs it creates.
* Sets the host info that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
* @param string $value the host info (e.g. "http://www.example.com") that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
*/
public function setHostInfo($value)
{
......
......@@ -138,6 +138,7 @@ class User extends Component
private $_access = [];
/**
* Initializes the application component.
*/
......
......@@ -49,7 +49,6 @@ class View extends \yii\base\View
* @event Event an event that is triggered by [[endBody()]].
*/
const EVENT_END_BODY = 'endBody';
/**
* The location of registered JavaScript code block or files.
* This means the location is in the head section.
......@@ -131,6 +130,7 @@ class View extends \yii\base\View
private $_assetManager;
/**
* Marks the position of an HTML head section.
*/
......
......@@ -34,7 +34,6 @@ class ViewAction extends Action
* @var string the name of the GET parameter that contains the requested view name.
*/
public $viewParam = 'view';
/**
* @var string the name of the default view when [[\yii\web\ViewAction::$viewParam]] GET parameter is not provided
* by user. Defaults to 'index'. This should be in the format of 'path/to/view', similar to that given in the
......@@ -42,7 +41,6 @@ class ViewAction extends Action
* @see \yii\web\ViewAction::$viewPrefix
*/
public $defaultView = 'index';
/**
* @var string a string to be prefixed to the user-specified view name to form a complete view name.
* For example, if a user requests for `tutorial/chap1`, the corresponding view name will
......@@ -51,7 +49,6 @@ class ViewAction extends Action
* @see \yii\base\View::findViewFile()
*/
public $viewPrefix = 'pages';
/**
* @var mixed the name of the layout to be applied to the requested view.
* This will be assigned to [[\yii\base\Controller::$layout]] before the view is rendered.
......@@ -60,6 +57,7 @@ class ViewAction extends Action
*/
public $layout;
/**
* Runs the action.
* This method displays the view requested by the user.
......
......@@ -45,6 +45,7 @@ class XmlResponseFormatter extends Component implements ResponseFormatterInterfa
*/
public $itemTag = 'item';
/**
* Formats the specified response.
* @param Response $response the response to be formatted.
......
......@@ -178,6 +178,7 @@ class ActiveForm extends Widget
*/
public $attributes = [];
/**
* Initializes the widget.
* This renders the form open tag.
......
......@@ -84,6 +84,7 @@ abstract class BaseListView extends Widget
*/
public $layout = "{summary}\n{items}\n{pager}";
/**
* Renders the data models.
* @return string the rendering result.
......
......@@ -21,6 +21,7 @@ class Block extends Widget
*/
public $renderInPlace = false;
/**
* Starts recording a block.
*/
......
......@@ -101,6 +101,7 @@ class Breadcrumbs extends Widget
*/
public $activeItemTemplate = "<li class=\"active\">{link}</li>\n";
/**
* Renders the widget.
*/
......
......@@ -26,6 +26,7 @@ class ContentDecorator extends Widget
*/
public $params = [];
/**
* Starts recording a clip.
*/
......
......@@ -101,6 +101,7 @@ class DetailView extends Widget
*/
public $formatter;
/**
* Initializes the detail view.
* This method will initialize required property values.
......
......@@ -73,6 +73,7 @@ class FragmentCache extends Widget
*/
public $dynamicPlaceholders;
/**
* Initializes the FragmentCache object.
*/
......
......@@ -47,6 +47,7 @@ class InputWidget extends Widget
*/
public $options = [];
/**
* Initializes the widget.
* If you override this method, make sure you call the parent implementation first.
......
......@@ -103,6 +103,7 @@ class LinkPager extends Widget
*/
public $hideOnSinglePage = true;
/**
* Initializes the pager.
*/
......
......@@ -39,6 +39,7 @@ class LinkSorter extends Widget
*/
public $options = ['class' => 'sorter'];
/**
* Initializes the sorter.
*/
......
......@@ -60,6 +60,7 @@ class ListView extends BaseListView
*/
public $options = ['class' => 'list-view'];
/**
* Renders all data models.
* @return string the rendering result
......
......@@ -85,6 +85,7 @@ class Pjax extends Widget
*/
public $clientOptions;
/**
* @inheritdoc
*/
......
......@@ -279,9 +279,6 @@ abstract class ManagerTestCase extends TestCase
$this->auth->assign($reader, 42);
$this->auth->assign($author, 1337);
$this->auth->assign($reader, 1337);
if ($this->auth instanceof PhpManager) {
$this->auth->save();
}
$this->auth = $this->createManager();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment