Merge branch 'master' of git://github.com/yiisoft/yii2 into guide-pl

This commit is contained in:
Bizley
2015-07-21 18:17:29 +02:00
17 changed files with 108 additions and 31 deletions

View File

@ -3,7 +3,7 @@
Yii предоставляет набор [виджетов](structure-widgets.md), которые могут быть использованы для отображения данных. Yii предоставляет набор [виджетов](structure-widgets.md), которые могут быть использованы для отображения данных.
В то время как виджет [DetailView](#detail-view) может быть использован для отображения данных по одной записи, то В то время как виджет [DetailView](#detail-view) может быть использован для отображения данных по одной записи, то
виджеты [ListView](#list-view) и [GridView](#grid-view) могут быть использованы для показа данных в виде списка иил виджеты [ListView](#list-view) и [GridView](#grid-view) могут быть использованы для показа данных в виде списка или
таблицы с возможностью сортировки, фильтрации и разбивки данных постранично. таблицы с возможностью сортировки, фильтрации и разбивки данных постранично.
@ -40,7 +40,7 @@ echo DetailView::widget([
ListView <a name="list-view"></a> ListView <a name="list-view"></a>
-------- --------
Виджет [[yii\widgets\ListView|ListView]] использует для отображения информации [провайдер данных](output-data-providers.md). Виджет [[yii\widgets\ListView|ListView]] использует для отображения информации [провайдера данных](output-data-providers.md).
Каждая модель отображается, используя определённый [[yii\widgets\ListView::$itemView|вид]]. Поскольку провайдер включает Каждая модель отображается, используя определённый [[yii\widgets\ListView::$itemView|вид]]. Поскольку провайдер включает
в себя разбивку на страницы, сортировку и фильтрацию, то его использование удобно для отображения информации конечному в себя разбивку на страницы, сортировку и фильтрацию, то его использование удобно для отображения информации конечному
пользователю и создания интерфейса управления данными. пользователю и создания интерфейса управления данными.
@ -459,10 +459,9 @@ $query->andFilterWhere(['LIKE', 'author.name', $this->getAttribute('author.name'
``` ```
> Информация: В коде, что выше, использует такая же строка, как и имя зависимости и псевдонима таблицы. > Информация: В коде, что выше, использует такая же строка, как и имя зависимости и псевдонима таблицы.
> however, when your alias and relation name > Однако, когда ваш псевдоним и имя связи различаются, вы должны обратить внимание, где вы используете псевдоним,
> differ, you have to pay attention to where you use the alias and where you use the relation name. > а где имя связи. Простым правилом для этого является использование псевдонима в каждом месте, которое используется
> A simple rule for this is to use the alias in every place that is used to build the database query and the > для построения запроса к базе данных, и имя связи во всех других определениях, таких как `attributes()`, `rules()` и т.д.
> relation name in all other definitions such as `attributes()` and `rules()` etc.
> >
> Например, если вы используете псевдоним `au` для связи с таблицей автора, то joinWith будет выглядеть так: > Например, если вы используете псевдоним `au` для связи с таблицей автора, то joinWith будет выглядеть так:
> >

View File

@ -244,7 +244,7 @@ public function rules()
Если не указать свойство `on`, то правило применяется во всех сценариях. Правило называется *активным правилом* если оно может быть применено в текущем сценарии [[yii\base\Model::scenario|scenario]]. Если не указать свойство `on`, то правило применяется во всех сценариях. Правило называется *активным правилом* если оно может быть применено в текущем сценарии [[yii\base\Model::scenario|scenario]].
Атрибут будет проверяться тогда и только тогда если он является активным атрибутом объявленным в `scenarios()` и Атрибут будет проверяться тогда и только тогда если он является активным атрибутом объявленным в `scenarios()` и
связаным с одним или несколькими активными правилами, объявленными в `rules()`. связанным с одним или несколькими активными правилами, объявленными в `rules()`.
## Массовое Присвоение <span id="massive-assignment"></span> ## Массовое Присвоение <span id="massive-assignment"></span>

View File

@ -294,7 +294,7 @@ use yii\helpers\Html;
Как видите, шаблон генерирует HTML тэги, которые присутствуют на всех страницах. Внутри секции `<body>`, шаблон выводит переменную `$content`, которая содержит результат рендеринга видов контента, который передается в шаблон, при работе метода [[yii\base\Controller::render()]]. Как видите, шаблон генерирует HTML тэги, которые присутствуют на всех страницах. Внутри секции `<body>`, шаблон выводит переменную `$content`, которая содержит результат рендеринга видов контента, который передается в шаблон, при работе метода [[yii\base\Controller::render()]].
Большинство шаблонов вызывают методы, аналогично тому, как это сделано в примере выше, чтобы скрипты и тэги, зарегистированные в других местах приложения могли быть правильно отображены в местах вызова (например, в шаблоне). Большинство шаблонов вызывают методы, аналогично тому, как это сделано в примере выше, чтобы скрипты и тэги, зарегистрированные в других местах приложения могли быть правильно отображены в местах вызова (например, в шаблоне).
- [[yii\base\View::beginPage()|beginPage()]]: Этот метод нужно вызывать в самом начале шаблона. - [[yii\base\View::beginPage()|beginPage()]]: Этот метод нужно вызывать в самом начале шаблона.
Он вызывает событие [[yii\base\View::EVENT_BEGIN_PAGE|EVENT_BEGIN_PAGE]], которое происходит при начале обработки страницы. Он вызывает событие [[yii\base\View::EVENT_BEGIN_PAGE|EVENT_BEGIN_PAGE]], которое происходит при начале обработки страницы.
@ -516,7 +516,7 @@ $this->registerMetaTag(['name' => 'keywords', 'content' => 'yii, framework, php'
<meta name="keywords" content="yii, framework, php"> <meta name="keywords" content="yii, framework, php">
``` ```
Обратите внимание, что при вызове метода [[yii\web\View::registerMetaTag()]] несколько раз мета тэги будут регистироваться Обратите внимание, что при вызове метода [[yii\web\View::registerMetaTag()]] несколько раз мета тэги будут регистрироваться
каждый раз без проверки на уникальность. каждый раз без проверки на уникальность.
Чтобы убедиться, что зарегистрирован только один экземпляр одного типа мета тэгов, вы можете указать ключ мета тэга в качестве второго Чтобы убедиться, что зарегистрирован только один экземпляр одного типа мета тэгов, вы можете указать ключ мета тэга в качестве второго

View File

@ -13,7 +13,7 @@ Yii располагает несколькими средствами, приз
Локализация и языки Локализация и языки
------------------- -------------------
В Yii приложении определены два языка: [[yii\base\Application::$sourceLanguage|исходный язык]] н [[yii\base\ В Yii приложении определены два языка: [[yii\base\Application::$sourceLanguage|исходный язык]] и [[yii\base\
Application::$language|язык перевода]]. Application::$language|язык перевода]].
На "исходном языке" написаны сообщения в коде приложения. Если мы определяем исходным языком английский, то На "исходном языке" написаны сообщения в коде приложения. Если мы определяем исходным языком английский, то

View File

@ -207,8 +207,8 @@ For example,
// "db" is a previously registered alias name // "db" is a previously registered alias name
$db = $container->get('db'); $db = $container->get('db');
// equivalent to: $engine = new \app\components\SearchEngine($apiKey, ['type' => 1]); // equivalent to: $engine = new \app\components\SearchEngine($apiKey, $apiSecret, ['type' => 1]);
$engine = $container->get('app\components\SearchEngine', [$apiKey], ['type' => 1]); $engine = $container->get('app\components\SearchEngine', [$apiKey, $apiSecret], ['type' => 1]);
``` ```
Behind the scene, the DI container does much more work than just creating a new object. Behind the scene, the DI container does much more work than just creating a new object.

View File

@ -23,7 +23,9 @@ $config = [ ... ];
if (YII_ENV_DEV) { if (YII_ENV_DEV) {
$config['bootstrap'][] = 'gii'; $config['bootstrap'][] = 'gii';
$config['modules']['gii'] = 'yii\gii\Module'; $config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
} }
``` ```

View File

@ -575,9 +575,8 @@ language is `ru-RU`, you may translate the view and save it as the file `views/
whenever you call [[yii\base\View::renderFile()]] or any method that invoke this method (e.g. [[yii\base\Controller::render()]]) whenever you call [[yii\base\View::renderFile()]] or any method that invoke this method (e.g. [[yii\base\Controller::render()]])
to render the view `views/site/index.php`, it will end up rendering the translated view `views/site/ru-RU/index.php`, instead. to render the view `views/site/index.php`, it will end up rendering the translated view `views/site/ru-RU/index.php`, instead.
> Note: If the [[yii\base\Application::$language|target language]] is the same as [[yii\base\Application::$sourceLanguage|source language]], > Note: If the [[yii\base\Application::$language|target language]] is the same as [[yii\base\Application::$sourceLanguage|source language]]
> view translation may still work as long as you provide a translated view. For example, if both languages are `en-US` > original view will be rendered regardless of presence of translated view.
> and you have both `views/site/index.php` and `views/site/en-US/index.php`, then the latter will be rendered.
## Formatting Date and Number Values <span id="date-number"></span> ## Formatting Date and Number Values <span id="date-number"></span>

View File

@ -24,6 +24,9 @@ Yii Framework 2 Change Log
- Bug #8772: ActiveQuery failed removing duplicate records after join when the resultset did not contain the pk values e.g. after grouping (cebe) - Bug #8772: ActiveQuery failed removing duplicate records after join when the resultset did not contain the pk values e.g. after grouping (cebe)
- Bug #8900: Fixed determine active menu item with url-alias in route `\yii\widgets\Menu::isItemActive()` (demi) - Bug #8900: Fixed determine active menu item with url-alias in route `\yii\widgets\Menu::isItemActive()` (demi)
- Bug #9046: Fixed problem with endless error loop when an error occurred after sending a stream or file download response to the user (cebe) - Bug #9046: Fixed problem with endless error loop when an error occurred after sending a stream or file download response to the user (cebe)
- Bug #9063: Workaround for MySQL losing table case when adding index (sebathi)
- Bug #9127, #9128: Fixed MSSQL `QueryBuilder::renameColumn()` and `QueryBuilder::renameTable()` escaping (sitawit)
- Bug #9161: Fixed `yii\web\Request` ignore `queryParams` when resolve request (zetamen)
- Bug: Fixed string comparison in `BaseActiveRecord::unlink()` which may result in wrong comparison result for hash valued primary keys starting with `0e` (cebe) - Bug: Fixed string comparison in `BaseActiveRecord::unlink()` which may result in wrong comparison result for hash valued primary keys starting with `0e` (cebe)
- Bug: Pass correct action name to `yii\console\Controller::options()` when default action was requested (cebe) - Bug: Pass correct action name to `yii\console\Controller::options()` when default action was requested (cebe)
- Bug: Automatic garbage collection in `yii\caching\FileCache` was not triggered (kidol) - Bug: Automatic garbage collection in `yii\caching\FileCache` was not triggered (kidol)
@ -43,6 +46,7 @@ Yii Framework 2 Change Log
- Enh #8903: PostgreSQL `QueryBuilder::createIndex()` can now specify the index method to use (LAV45) - Enh #8903: PostgreSQL `QueryBuilder::createIndex()` can now specify the index method to use (LAV45)
- Enh #9011: Allow `yii\widgets\MaskedInput` to produce an input tag of a custom type (TriAnMan) - Enh #9011: Allow `yii\widgets\MaskedInput` to produce an input tag of a custom type (TriAnMan)
- Enh #9038: Write warning to log in case `FileCache` fails to write into file (foccy) - Enh #9038: Write warning to log in case `FileCache` fails to write into file (foccy)
- Enh #9149: Print directory migrationPath in a `yii migrate` command error. (RusAlex)
- Chg #6354: `ErrorHandler::logException()` will now log the whole exception object instead of only its string representation (cebe) - Chg #6354: `ErrorHandler::logException()` will now log the whole exception object instead of only its string representation (cebe)
- Chg #8556: Extracted `yii\web\User::getAuthManager()` method (samdark) - Chg #8556: Extracted `yii\web\User::getAuthManager()` method (samdark)

View File

@ -13,7 +13,7 @@ use yii\base\InvalidConfigException;
/** /**
* FileDependency represents a dependency based on a file's last modification time. * FileDependency represents a dependency based on a file's last modification time.
* *
* If th last modification time of the file specified via [[fileName]] is changed, * If the last modification time of the file specified via [[fileName]] is changed,
* the dependency is considered as changed. * the dependency is considered as changed.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>

View File

@ -75,7 +75,6 @@ class Application extends \yii\base\Application
*/ */
public $controller; public $controller;
/** /**
* @inheritdoc * @inheritdoc
*/ */

View File

@ -68,7 +68,7 @@ abstract class BaseMigrateController extends Controller
$path = Yii::getAlias($this->migrationPath); $path = Yii::getAlias($this->migrationPath);
if (!is_dir($path)) { if (!is_dir($path)) {
if ($action->id !== 'create') { if ($action->id !== 'create') {
throw new Exception('Migration failed. Directory specified in migrationPath doesn\'t exist.'); throw new Exception("Migration failed. Directory specified in migrationPath doesn't exist: {$this->migrationPath}");
} }
FileHelper::createDirectory($path); FileHelper::createDirectory($path);
} }
@ -367,7 +367,7 @@ abstract class BaseMigrateController extends Controller
* ~~~ * ~~~
* *
* @param integer $limit the maximum number of migrations to be displayed. * @param integer $limit the maximum number of migrations to be displayed.
* If it is 0, the whole migration history will be displayed. * If it is "all", the whole migration history will be displayed.
* @throws \yii\console\Exception if invalid limit value passed * @throws \yii\console\Exception if invalid limit value passed
*/ */
public function actionHistory($limit = 10) public function actionHistory($limit = 10)

View File

@ -119,25 +119,28 @@ class QueryBuilder extends \yii\db\QueryBuilder
/** /**
* Builds a SQL statement for renaming a DB table. * Builds a SQL statement for renaming a DB table.
* @param string $table the table to be renamed. The name will be properly quoted by the method. * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
* @param string $newName the new table name. The name will be properly quoted by the method. * @param string $newName the new table name. The name will be properly quoted by the method.
* @return string the SQL statement for renaming a DB table. * @return string the SQL statement for renaming a DB table.
*/ */
public function renameTable($table, $newName) public function renameTable($oldName, $newName)
{ {
return "sp_rename '$table', '$newName'"; return 'sp_rename ' . $this->db->quoteTableName($oldName) . ', ' . $this->db->quoteTableName($newName);
} }
/** /**
* Builds a SQL statement for renaming a column. * 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. * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
* @param string $name the old name of the column. The name will be properly quoted by the method. * @param string $oldName the old name of the column. The name will be properly quoted by the method.
* @param string $newName the new name of the column. The name will be properly quoted by the method. * @param string $newName the new name of the column. The name will be properly quoted by the method.
* @return string the SQL statement for renaming a DB column. * @return string the SQL statement for renaming a DB column.
*/ */
public function renameColumn($table, $name, $newName) public function renameColumn($table, $oldName, $newName)
{ {
return "sp_rename '$table.$name', '$newName', 'COLUMN'"; $table = $this->db->quoteTableName($table);
$oldName = $this->db->quoteColumnName($oldName);
$newName = $this->db->quoteColumnName($newName);
return "sp_rename '{$table}.{$oldName}', {$newName}, 'COLUMN'";
} }
/** /**

View File

@ -80,6 +80,19 @@ class QueryBuilder extends \yii\db\QueryBuilder
. $this->db->quoteColumnName($newName); . $this->db->quoteColumnName($newName);
} }
/**
* @inheritdoc
* @see https://bugs.mysql.com/bug.php?id=48875
*/
public function createIndex($name, $table, $columns, $unique = false)
{
return 'ALTER TABLE '
. $this->db->quoteTableName($table)
. ($unique ? ' ADD UNIQUE INDEX ' : ' ADD INDEX ')
. $this->db->quoteTableName($name)
. ' (' . $this->buildColumns($columns) . ')';
}
/** /**
* Builds a SQL statement for dropping a foreign key constraint. * Builds a SQL statement for dropping a foreign key constraint.
* @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method. * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.

View File

@ -98,5 +98,5 @@ return [
'{nFormatted} {n, plural, =1{pebibyte} other{pebibytes}}' => '{nFormatted} بيبيبايت', '{nFormatted} {n, plural, =1{pebibyte} other{pebibytes}}' => '{nFormatted} بيبيبايت',
'{nFormatted} {n, plural, =1{petabyte} other{petabytes}}' => '{nFormatted} بيتابايت', '{nFormatted} {n, plural, =1{petabyte} other{petabytes}}' => '{nFormatted} بيتابايت',
'{nFormatted} {n, plural, =1{tebibyte} other{tebibytes}}' => '{nFormatted} تيبيبايت', '{nFormatted} {n, plural, =1{tebibyte} other{tebibytes}}' => '{nFormatted} تيبيبايت',
'{nFormatted} {n, plural, =1{terabyte} other{terabytes}}' => '{nFormatted} تيرابايت', '{nFormatted} {n, plural, =1{terabyte} other{terabytes}}' => '{nFormatted} تيرابايت',
]; ];

View File

@ -50,7 +50,6 @@ class Application extends \yii\base\Application
*/ */
public $controller; public $controller;
/** /**
* @inheritdoc * @inheritdoc
*/ */

View File

@ -180,9 +180,12 @@ class Request extends \yii\base\Request
$result = Yii::$app->getUrlManager()->parseRequest($this); $result = Yii::$app->getUrlManager()->parseRequest($this);
if ($result !== false) { if ($result !== false) {
list ($route, $params) = $result; list ($route, $params) = $result;
if ($this->_queryParams === null) {
$_GET = $params + $_GET; // preserve numeric keys $_GET = $params + $_GET; // preserve numeric keys
} else {
return [$route, $_GET]; $this->_queryParams = $params + $this->_queryParams;
}
return [$route, $this->getQueryParams()];
} else { } else {
throw new NotFoundHttpException(Yii::t('yii', 'Page not found.')); throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
} }

View File

@ -90,4 +90,60 @@ class RequestTest extends TestCase
$this->assertTrue($request->validateCsrfToken($token)); $this->assertTrue($request->validateCsrfToken($token));
} }
public function testResolve()
{
$this->mockWebApplication([
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'cache' => null,
'rules' => [
'posts' => 'post/list',
'post/<id>' => 'post/view',
],
]
]
]);
$request = new Request();
$request->pathInfo = 'posts';
$_GET['page'] = 1;
$result = $request->resolve();
$this->assertEquals(['post/list', ['page' => 1]], $result);
$this->assertEquals($_GET, ['page' => 1]);
$request->setQueryParams(['page' => 5]);
$result = $request->resolve();
$this->assertEquals(['post/list', ['page' => 5]], $result);
$this->assertEquals($_GET, ['page' => 1]);
$request->setQueryParams(['custom-page' => 5]);
$result = $request->resolve();
$this->assertEquals(['post/list', ['custom-page' => 5]], $result);
$this->assertEquals($_GET, ['page' => 1]);
unset($_GET['page']);
$request = new Request();
$request->pathInfo = 'post/21';
$this->assertEquals($_GET, []);
$result = $request->resolve();
$this->assertEquals(['post/view', ['id' => 21]], $result);
$this->assertEquals($_GET, ['id' => 21]);
$_GET['id'] = 42;
$result = $request->resolve();
$this->assertEquals(['post/view', ['id' => 21]], $result);
$this->assertEquals($_GET, ['id' => 21]);
$_GET['id'] = 63;
$request->setQueryParams(['token' => 'secret']);
$result = $request->resolve();
$this->assertEquals(['post/view', ['id' => 21, 'token' => 'secret']], $result);
$this->assertEquals($_GET, ['id' => 63]);
}
} }