Commit 56139369 by funson86
parents 3aa6d45e 033d5e73
......@@ -38,21 +38,21 @@ addons:
postgresql: "9.3"
before_install:
- wget https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.3.4.deb && sudo dpkg -i --force-confnew elasticsearch-1.3.4.deb
- travis_retry wget https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.3.4.deb && sudo dpkg -i --force-confnew elasticsearch-1.3.4.deb
- sudo service elasticsearch start
install:
- composer self-update && composer --version
- composer global require "fxp/composer-asset-plugin:1.0.0-beta3"
- travis_retry composer self-update && composer --version
- travis_retry composer global require "fxp/composer-asset-plugin:1.0.0-beta3"
- export PATH="$HOME/.composer/vendor/bin:$PATH"
# core framework:
- composer install --prefer-dist
- travis_retry composer install --prefer-dist
- tests/unit/data/travis/mongodb-setup.sh
- tests/unit/data/travis/apc-setup.sh
- tests/unit/data/travis/memcache-setup.sh
- tests/unit/data/travis/cubrid-setup.sh
# codeception
- composer global require "codeception/codeception=2.0.*" "codeception/specify=*" "codeception/verify=*"
- travis_retry composer global require "codeception/codeception=2.0.*" "codeception/specify=*" "codeception/verify=*"
# basic and advanced application:
- tests/unit/data/travis/setup-apps.sh
......@@ -88,5 +88,5 @@ script:
after_script:
- cd ../../..
- wget https://scrutinizer-ci.com/ocular.phar
- travis_retry wget https://scrutinizer-ci.com/ocular.phar
- php ocular.phar code-coverage:upload --format=php-clover coverage.clover
......@@ -10,13 +10,16 @@ Yii 2 requires PHP 5.4 and embraces the best practices and protocols found in mo
[![Latest Stable Version](https://poser.pugx.org/yiisoft/yii2/v/stable.png)](https://packagist.org/packages/yiisoft/yii2)
[![Total Downloads](https://poser.pugx.org/yiisoft/yii2/downloads.png)](https://packagist.org/packages/yiisoft/yii2)
[![Dependency Status](https://www.versioneye.com/php/yiisoft:yii2/dev-master/badge.png)](https://www.versioneye.com/php/yiisoft:yii2/dev-master)
[![Reference Status](https://www.versioneye.com/php/yiisoft:yii2/reference_badge.svg)](https://www.versioneye.com/php/yiisoft:yii2/references)
[![Build Status](https://secure.travis-ci.org/yiisoft/yii2.png)](http://travis-ci.org/yiisoft/yii2)
[![Dependency Status](https://www.versioneye.com/php/yiisoft:yii2/dev-master/badge.png)](https://www.versioneye.com/php/yiisoft:yii2/dev-master)
[![HHVM Status](http://hhvm.h4cc.de/badge/yiisoft/yii2-dev.png)](http://hhvm.h4cc.de/package/yiisoft/yii2-dev)
[![Code Coverage](https://scrutinizer-ci.com/g/yiisoft/yii2/badges/coverage.png?s=31d80f1036099e9d6a3e4d7738f6b000b3c3d10e)](https://scrutinizer-ci.com/g/yiisoft/yii2/)
[![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/yiisoft/yii2/badges/quality-score.png?s=b1074a1ff6d0b214d54fa5ab7abbb90fc092471d)](https://scrutinizer-ci.com/g/yiisoft/yii2/)
[![Code Climate](https://codeclimate.com/github/yiisoft/yii2.png)](https://codeclimate.com/github/yiisoft/yii2)
[![Reference Status](https://www.versioneye.com/php/yiisoft:yii2/reference_badge.svg)](https://www.versioneye.com/php/yiisoft:yii2/references)
[![Issue Stats Issues](http://issuestats.com/github/yiisoft/yii2/badge/issue)](http://issuestats.com/github/yiisoft/yii2)
[![Issue Stats Pull request](http://issuestats.com/github/yiisoft/yii2/badge/pr)](http://issuestats.com/github/yiisoft/yii2)
......
......@@ -15,6 +15,7 @@ class LoginForm extends Model
private $_user = false;
/**
* @inheritdoc
*/
......
......@@ -18,6 +18,7 @@ class ResetPasswordForm extends Model
*/
private $_user;
/**
* Creates a form model given a token.
*
......
......@@ -3,5 +3,16 @@
* Application configuration shared by all applications functional tests
*/
return [
'components' => [
'request' => [
// it's not recommended to run functional tests with CSRF validation enabled
'enableCsrfValidation' => false,
// but if you absolutely need it set cookie domain to localhost
/*
'csrfCookie' => [
'domain' => 'localhost',
],
*/
],
],
];
\ No newline at end of file
......@@ -16,6 +16,7 @@ class LoginForm extends Model
private $_user = false;
/**
* @return array the validation rules.
*/
......
......@@ -9,6 +9,17 @@ return yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../../config/web.php'),
require(__DIR__ . '/config.php'),
[
'components' => [
'request' => [
// it's not recommended to run functional tests with CSRF validation enabled
'enableCsrfValidation' => false,
// but if you absolutely need it set cookie domain to localhost
/*
'csrfCookie' => [
'domain' => 'localhost',
],
*/
],
],
]
);
......@@ -128,14 +128,11 @@ class TranslationController extends Controller
foreach ($lines as $key => $val) {
if (mb_substr($val, 0, 1, 'utf-8') === '@') {
$lines[$key] = '<span class="info">' . Html::encode($val) . '</span>';
}
else if (mb_substr($val, 0, 1, 'utf-8') === '+') {
} elseif (mb_substr($val, 0, 1, 'utf-8') === '+') {
$lines[$key] = '<ins>' . Html::encode($val) . '</ins>';
}
else if (mb_substr($val, 0, 1, 'utf-8') === '-') {
} elseif (mb_substr($val, 0, 1, 'utf-8') === '-') {
$lines[$key] = '<del>' . Html::encode($val) . '</del>';
}
else {
} else {
$lines[$key] = Html::encode($val);
}
}
......
......@@ -2,11 +2,11 @@ Caché HTTP
==========
Además del almacenamiento de caché en el servidor que hemos descrito en secciones anteriores, las aplicaciones Web
pueden hacer uso del caché en el lado del cliente para así ahorrar tiempo y recursos para generar y transmitir el
pueden hacer uso de la caché en el lado del cliente para así ahorrar tiempo y recursos para generar y transmitir el
mismo contenido una y otra vez.
Para usar la caché del lado del cliente, puedes configurar [[yii\filters\HttpCache]] como un filtro en el controlador
para aquellas acciones cuyo resultado deba estar estar almacenado en la caché en el lado del cliente. [[yii\filters\HttpCache|HttpCache]]
para aquellas acciones cuyo resultado deba estar almacenado en la caché en el lado del cliente. [[yii\filters\HttpCache|HttpCache]]
solo funciona en peticiones `GET` y `HEAD`. Puede manejar tres tipos de cabeceras (headers) HTTP relacionadas en este tipo de
consultas:
......@@ -62,7 +62,7 @@ lado del servidor y la transmisión del contenido de la página son ambos omitid
## La Cabecera `ETag` <a name="etag"></a>
La cabecera "Entity Tag" (o para abreviar `ETag`) usa un hash para representar el contenido de una página. Si la página
ha sido cambiada, el hash también cambiará. Al comprar el hash guardado en el lado del cliente con el hash generado en
ha sido cambiada, el hash también cambiará. Al comparar el hash guardado en el lado del cliente con el hash generado en
el servidor, la caché puede determinar si la página ha cambiado y deber ser retransmitida.
Puedes configurar la propiedad [[yii\filters\HttpCache::etagSeed]] para activar el envío de la cabecera `ETag`.
......@@ -97,9 +97,9 @@ public function behaviors()
```
El código anterior establece que la caché HTTP debe ser activada únicamente para la acción `view`. Debería generar una
cabecera HTTP `ETag` basándose en el título y contenido del artículo consultado. Cuando un navegador vista la página
cabecera HTTP `ETag` basándose en el título y contenido del artículo consultado. Cuando un navegador visita la página
`view` por primera vez, la página se generará en el servidor y será enviada al navegador; Si el navegador visita la
misma página de nuevo y ha ocurrido un cambio en el título o contenido del artículo, el servidor no volverá a generar
misma página de nuevo y no ha ocurrido un cambio en el título o contenido del artículo, el servidor no volverá a generar
la página, y el navegador usará la versión guardada en la caché del lado del cliente. Como resultado, la representación del
lado del servidor y la transmisión del contenido de la página son ambos omitidos.
......@@ -110,9 +110,8 @@ La generación de un ETag que requiera muchos recursos puede echar por tierra el
introducir una sobrecarga innecesaria, ya que debe ser re-evaluada en cada solicitud (request). Trata de encontrar una
expresión sencilla para invalidar la caché si la página ha sido modificada.
> Nota: En cumplimiento con [RFC 2616, section 13.3.4](http://tools.ietf.org/html/rfc2616#section-13.3.4),
`HttpCache` enviará ambas cabeceras `ETag` y `Last-Modified` si ambas estaán configuradas. En consecuencia, ambas serán
utilizadas para la validación de la caché si han sido enviadas por el cliente.
> Nota: En cumplimiento con [RFC 7232](http://tools.ietf.org/html/rfc7232#section-2.4),
`HttpCache` enviará ambas cabeceras `ETag` y `Last-Modified` si ambas están configuradas. Y si el clientes envía tanto la cabecera `If-None-Match` como la cabecera `If-Modified-Since`, solo la primera será respetada.
## La Cabecera `Cache-Control` <a name="cache-control"></a>
......@@ -126,10 +125,10 @@ Cache-Control: public, max-age=3600
## Limitador de la Sesión de Caché <a name="session-cache-limiter"></a>
Cuando una página utiliza la sesión, PHP enviará automaticamente cabeceras HTTP relacionadas con la caché tal y como se
Cuando una página utiliza la sesión, PHP enviará automáticamente cabeceras HTTP relacionadas con la caché tal y como se
especifican en `session.cache_limiter` de la configuración INI de PHP. Estas cabeceras pueden interferir o deshabilitar
el almacenamiento de caché que desees de `HttpCache`. Para evitar este problema, por defecto `HttpCache` deshabilitará
automaticamente el envío de estas cabeceras. Si deseas modificar este comportamiento, tienes que configurar la propiedad
automáticamente el envío de estas cabeceras. Si deseas modificar este comportamiento, tienes que configurar la propiedad
[[yii\filters\HttpCache::sessionCacheLimiter]]. La propiedad puede tomar un valor de cadena, incluyendo `public`, `private`,
`private_no_expire`, and `nocache`. Por favor, consulta el manual PHP acerca de [session_cache_limiter()](http://www.php.net/manual/es/function.session-cache-limiter.php)
para una mejor explicación sobre esos valores.
......
......@@ -101,7 +101,7 @@ Probándolo <a name="trying-it-out"></a>
Después de crear la acción y la vista, puedes acceder a la nueva página abriendo el siguiente URL:
```
http://hostname/index.php?r=site/say&mensaje=Hello+World
http://hostname/index.php?r=site/say&message=Hello+World
```
![Hello World](images/start-hello-world.png)
......
......@@ -25,21 +25,21 @@ All Rights Reserved.
* [フォームを扱う](start-forms.md)
* [データベースを扱う](start-databases.md)
* [Gii でコードを生成する](start-gii.md)
* [この先を見](start-looking-ahead.md)
* [この先を見通す](start-looking-ahead.md)
アプリケーションの構造
----------------------
* [概要](structure-overview.md)
* [エントリスクリプト](structure-entry-scripts.md)
* [エントリスクリプト](structure-entry-scripts.md)
* [アプリケーション](structure-applications.md)
* [アプリケーションコンポーネント](structure-application-components.md)
* [コントローラ](structure-controllers.md)
* [モデル](structure-models.md)
* [ビュー](structure-views.md)
* [モジュール](structure-modules.md)
* [フィルタ](structure-filters.md)
* [フィルタ](structure-filters.md)
* [ウィジェット](structure-widgets.md)
* [アセット](structure-assets.md)
* [エクステンション](structure-extensions.md)
......@@ -49,7 +49,7 @@ All Rights Reserved.
----------------
* [概要](runtime-overview.md)
* [ブートストラッピング](runtime-bootstrapping.md)
* [ブートストラッ](runtime-bootstrapping.md)
* [ルーティング](runtime-routing.md)
* [リクエスト](runtime-requests.md)
* [レスポンス](runtime-responses.md)
......@@ -66,7 +66,7 @@ All Rights Reserved.
* [プロパティ](concept-properties.md)
* [イベント](concept-events.md)
* [ビヘイビア](concept-behaviors.md)
* [設定](concept-configurations.md)
* [コンフィギュレーション](concept-configurations.md)
* [エイリアス](concept-aliases.md)
* [クラスのオートロード](concept-autoloading.md)
* [サービスロケータ](concept-service-locator.md)
......
......@@ -2,12 +2,12 @@
==================
この節では、`country` という名前のデータベーステーブルから読み出した国データを表示する新しいページの作り方を説明します。
この目的を達するために、データベース接続を設定し、[アクティブレコード](db-active-record.md) クラスを作成し、
この目的を達するために、データベース接続を構成し、[アクティブレコード](db-active-record.md) クラスを作成し、
[アクション](structure-controllers.md) を定義し、そして [ビュー](structure-views.md) を作成します。
このチュートリアルを通じて、次のことをする方法を学びます:
* DB 接続を設定する
* DB 接続を構成する
* アクティブレコードのクラスを定義する
* アクティブレコードのクラスを使ってデータを検索する
* 改ページを伴う方法でビューにデータを表示する
......@@ -51,7 +51,7 @@ INSERT INTO `country` VALUES ('US','United States',278357000);
そして、`country` テーブルは、10 行のデータを持っています。
DB 接続を設定する<a name="configuring-db-connection"></a>
DB 接続を構成する<a name="configuring-db-connection"></a>
-----------------
先に進む前に、[PDO](http://www.php.net/manual/en/book.pdo.php) PHP 拡張および使用しているデータベースの PDO ドライバ
......@@ -73,15 +73,15 @@ return [
];
```
この `config/db.php` というファイルは典型的なファイルベースの [設定](concept-configurations.md) ツールです。
この設定ファイルが [[yii\db\Connection]] インスタンスの作成と初期化に必要なパラメータを規定します。そして、
この `config/db.php` というファイルは典型的なファイルベースの [コンフィギュレーション](concept-configurations.md) ツールです。
このコンフィギュレーションファイルが [[yii\db\Connection]] インスタンスの作成と初期化に必要なパラメータを規定します。そして、
[[yii\db\Connection]] インスタンスを通じて、背後のデータベースに対して SQL クエリを実行することが出来るようになります。
上記のようにして設定された DB 接続は、アプリケーションコードの中で `Yii::$app->db` という式でアクセスすることが出来ます。
上記のようにして構成された DB 接続は、アプリケーションコードの中で `Yii::$app->db` という式でアクセスすることが出来ます。
> Info|情報: `config/db.php` は、メインのアプリケーション設定ファイルである `config/web.php` にインクルードされます。
> Info|情報: `config/db.php` は、メインのアプリケーションコンフィギュレーションファイルである `config/web.php` にインクルードされます。
この `config/web.php`[アプリケーション](structure-applications.md) インスタンスが初期化される仕方を規定します。
更なる情報については、[設定](concept-configurations.md) の節を参照してください。
更なる情報については、[コンフィギュレーション](concept-configurations.md) の節を参照してください。
アクティブレコードを作成する<a name="creating-active-record"></a>
......
......@@ -17,8 +17,8 @@ Gii を開始する<a name="starting-gii"></a>
--------------
[Gii](tool-gii.md) は Yii の [モジュール](structure-modules.md) として提供されます。
Gii は、アプリケーションの [[yii\base\Application::modules|modules]] プロパティの中で設定することで有効にすることが出来ます。
アプリケーションを生成した仕方にもよりますが、`config/web.php`設定ファイルの中に、多分、下記のコードが既に提供されているでしょう:
Gii は、アプリケーションの [[yii\base\Application::modules|modules]] プロパティの中で構成することで有効にすることが出来ます。
アプリケーションを生成した仕方にもよりますが、`config/web.php`コンフィギュレーションファイルの中に、多分、下記のコードが既に提供されているでしょう:
```php
$config = [ ... ];
......@@ -29,7 +29,7 @@ if (YII_ENV_DEV) {
}
```
上記の設定は、[開発環境](concept-configurations.md#environment-constants) において、アプリケーションは
上記のコンフィギュレーションは、[開発環境](concept-configurations.md#environment-constants) において、アプリケーションは
`gii` という名前のモジュールをインクルードすべきこと、そして `gii`[[yii\gii\Module]] というクラスのものであることを記述しています。
アプリケーションの [エントリスクリプト](structure-entry-scripts.md) である `web/index.php` をチェックすると、次の行があることに気付くでしょう。
......@@ -39,7 +39,7 @@ if (YII_ENV_DEV) {
defined('YII_ENV') or define('YII_ENV', 'dev');
```
この行のおかげで、アプリケーションは開発モードになり、上記の設定によって、Gii が有効になります。
この行のおかげで、アプリケーションは開発モードになり、上記のコンフィギュレーションによって、Gii が有効になります。
これで、下記の URL によって Gii にアクセスすることが出来ます:
```
......@@ -47,7 +47,7 @@ http://hostname/index.php?r=gii
```
> Note|注意: ローカルホスト以外のマシンから GII にアクセスしようとすると、既定ではセキュリティ上の
> 目的からアクセスが拒否されます。下記のように Gii を設定して、許可される IP アドレスを追加することが出来ます。
> 目的からアクセスが拒否されます。下記のように Gii を構成して、許可される IP アドレスを追加することが出来ます。
>
```php
'gii' => [
......
......@@ -54,7 +54,7 @@ Composer 縺後う繝ウ繧ケ繝医繝ォ縺輔l縺溘i縲√え繧ァ繝悶°繧峨い繧ッ繧サ繧ケ縺ァ縺阪
1. [yiiframework.com](http://www.yiiframework.com/download/) からアーカイブファイルをダウンロードする。
2. ダウンロードしたファイルをウェブからアクセスできるフォルダーに展開する。
3. `config/web.php` ファイルを編集して、`cookieValidationKey` 設定アイテムに秘密キーを入力す
3. `config/web.php` ファイルを編集して、`cookieValidationKey` というコンフィギュレーション項目に秘密キーを入力する
(Composer を使って Yii をインストールするときは、これは自動的に実行されます):
```php
......@@ -109,7 +109,7 @@ Yii 縺ョ譛菴主ソヲ∵擅莉カ繧呈コ縺溘☆繧医≧縺ォ PHP 縺ョ繧、繝ウ繧ケ繝医繝ォ繧呈ァ区
また、アプリケーションがデータベースを必要とする場合は、[PDO PHP 拡張](http://www.php.net/manual/ja/pdo.installation.php) および対応するデータベースドライバ (MySQL データベースのための `pdo_mysql` など) をインストールしなければなりません。
ウェブサーバを設定する<a name="configuring-web-servers"></a>
ウェブサーバを構成する<a name="configuring-web-servers"></a>
----------------------
> Info|情報: もし Yii の試運転をしているだけで、実運用のサーバに配置する意図がないのであれば、当面、この項は飛ばしても構いません。
......@@ -131,7 +131,7 @@ Yii 2.0 縺ッ縲√∪縺溘’acebook 縺ョ [HHVM](http://hhvm.com/) 縺ィ繧ゆコ呈鋤諤ァ縺後
更なる詳細については、[共有ホスティング環境](tutorial-shared-hosting.md) の節を参照してください。
### 推奨される Apache の設定<a name="recommended-apache-configuration"></a>
### 推奨される Apache の構成<a name="recommended-apache-configuration"></a>
下記の設定を Apache の `httpd.conf` ファイルまたはバーチャルホスト設定の中で使います。
`path/to/basic/web` の部分を `basic/web` の実際のパスに置き換えなければならないことに注意してください。
......@@ -154,7 +154,7 @@ DocumentRoot "path/to/basic/web"
```
### 推奨される Nginx の設定<a name="recommended-nginx-configuration"></a>
### 推奨される Nginx の構成<a name="recommended-nginx-configuration"></a>
[Nginx](http://wiki.nginx.org/) を使うためには、PHP を [FPM SAPI](http://jp1.php.net/install.fpm) としてインストールしていなければなりません。
下記の設定を使い、`path/to/basic/web` の部分を `basic/web` の実際のパスに置き換え、`mysite.local` を実際のサーバのホスト名に置き換えてください。
......@@ -199,7 +199,7 @@ server {
}
```
この設定を使う場合は、同時に `php.ini` ファイルで `cgi.fix_pathinfo=0` も設定して、
この構成を使う場合は、同時に `php.ini` ファイルで `cgi.fix_pathinfo=0` も設定して、
多数の不要な `stat()` の呼び出しを避けるべきです。
また、HTTPS サーバを走らせている場合には、安全な接続であることを Yii が正しく検知できるように、
......
この先を見通す
==============
「はじめよう」の章全体を読み通したなら、いまやあなたは、完全な Yii のアプリケーションを作成したことがある、と言うことが出来ます。
その過程で、あなたは HTML フォームを通じてユーザからデータを取得することや、データベースからデータを取得すること、また、ページ付けをしてデータを表示することなど、
必要とされることが多いいくつかの機能を実装する方法を学びました。
また、[Gii](tool-gii.md) を使ってコードを自動的に生成する方法も学びました。
Gii をコード生成に使うと、ウェブ開発のプロセスの大部分が、いくつかのフォームに入力していくだけの簡単な仕事になります。
この節では、Yii フレームワークを使うときの生産性を更に高めるために利用できるリソースについてまとめます。
* ドキュメンテーション
- 公式ガイド:
Definitive(最も確実な) という名前が示すように、このガイドは Yii がどのように動作すべきものかを正確に記述し、
Yii を使用するについての全般的な手引きを提供するものです。
これは唯一最重要な Yii のチュートリアルであり、Yii のコードを少しでも書く前に読むべきものです。
- クラスリファレンス:
これは Yii によって提供される全てのクラスの使用法を記述しています。
主として、コードを書いている時に、特定のクラス、メソッド、プロパティについて理解したい場合に読まれるべきものです。
クラスリファレンスの使用は、フレームワーク全体の文脈的な理解が出来てからにするのが最善です。
- Wiki の記事:
Wiki の記事は、Yii のユーザが自身の経験に基づいて書いたものです。
ほとんどの記事は、料理本のレシピのように書かれており、特定の問題を Yii を使って解決する方法を示しています。
これらの記事の品質は公式ガイドほどには良くないかもしれませんが、
より広範なトピックをカバーしていることと、たいていは即座に使えるソリューションを提供してくれることにおいて有用なものです。
-
* [エクステンション](http://www.yiiframework.com/extensions/):
Yii は、ユーザによって作られた数千におよぶエクステンションのライブラリを誇りとしています。
エクステンションはあなたのアプリケーションに簡単に組み込むことが出来、そうすることでアプリケーションの開発作業をより一層速くて簡単なものにします。
* コミュニティ
- フォーラム: <http://www.yiiframework.com/forum/>
- IRC チャット: freenode ネットワーク (<irc://irc.freenode.net/yii>) の #yii チャンネル
- GitHub: <https://github.com/yiisoft/yii2>
- Facebook: <https://www.facebook.com/groups/yiitalk/>
- Twitter: <https://twitter.com/yiiframework>
- LinkedIn: <https://www.linkedin.com/groups/yii-framework-1483367>
......@@ -2,7 +2,7 @@
==========================
Yii のインストールが終ると、実際に動く Yii のアプリケーションにアクセスすることが出来るようになります。
その URL は、`http://hostname/basic/web/index.php` あるいは `http://hostname/index.php` など、設定によて異なります。
その URL は、`http://hostname/basic/web/index.php` あるいは `http://hostname/index.php` など、設定によて異なります。
この節では、アプリケーションに組み込み済みの機能を紹介し、コードがどのように組織されているか、
そして、一般にアプリケーションがリクエストをどのように処理するかを説明します。
......@@ -41,9 +41,9 @@ Yii のインストールが終ると、実際に動く Yii のアプリケー
```
basic/ アプリケーションのベースパス
composer.json Composer によって使用される。パッケージ情報を記述
config/ アプリケーションその他の設定を格納
console.php コンソールアプリケーションの設定
web.php ウェブアプリケーションの設定
config/ アプリケーションその他のコンフィギュレーションを格納
console.php コンソールアプリケーションのコンフィギュレーション
web.php ウェブアプリケーションのコンフィギュレーション
commands/ コンソールコマンドのクラスを格納
controllers/ コントローラのクラスを格納
models/ モデルのクラスを格納
......@@ -81,7 +81,7 @@ Yii は [モデル・ビュー・コントローラ (MVC)](http://wikipedia.org/
![リクエストのライフサイクル](images/application-lifecycle.png)
1. ユーザが [エントリスクリプト](structure-entry-scripts.md) `web/index.php` に対してリクエストを出します。
2. エントリスクリプトはアプリケーションの [設定](concept-configurations.md) を読み出して、
2. エントリスクリプトはアプリケーションの [コンフィギュレーション](concept-configurations.md) を読み出して、
リクエストを処理する [アプリケーション](structure-applications.md) のインスタンスを作成します。
3. アプリケーションは、[リクエスト](runtime-requests.md) アプリケーションコンポーネントの助力を得て、
リクエストされた [ルート](runtime-routing.md) を解決します。
......
エントリスクリプト
==================
エントリスクリプトは、アプリケーションのブートストラップ過程のチェーンにおける最初の環です。
アプリケーションは (ウェブアプリケーションであれ、コンソールアプリケーションであれ)単一のエントリスクリプトを持ちます。
エンドユーザはエントリスクリプトに対してリクエストを発行し、エントリスクリプトはアプリケーションのインスタンスを作成して、
それにリクエストを送付します。
ウェブアプリケーションのエントリスクリプトは、エンドユーザからアクセス出来るように、
ウェブからのアクセスが可能なディレクトリの下に保管されなければなりません。
大抵は `index.php` と名付けられますが、ウェブサーバが見つけることが出来る限り、どのような名前を使っても構いません。
コンソールアプリケーションのエントリスクリプトは、通常は、アプリケーションの [ベースパス](structure-applications.md)
下に保管され、`yii` と名付けられます (`.php` の拡張子を伴います) 。
これは、ユーザが `./yii <route> [引数] [オプション]` というコマンドによってコンソールアプリケーションを走らせることが出来るようにするためのスクリプトであり、実行可能なパーミッションを与えられるべきものです。
エントリスクリプトは主として次の仕事をします:
* グローバルな定数を定義する;
* [Composer のオートローダ](http://getcomposer.org/doc/01-basic-usage.md#autoloading) を登録する;
* [[Yii]] クラスファイルをインクルードする;
* アプリケーションのコンフィギュレーションを読み出す;
* [アプリケーション](structure-applications.md) のインスタンスを生成して構成する;
* [[yii\base\Application::run()]] を呼んで、受け取ったリクエストを処理する。
## ウェブアプリケーション<a name="web-applications"></a>
次に示すのが、[ベーシックウェブアプリケーションテンプレート](start-installation.md) のエントリスクリプトです:
```php
<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
// Composer のオートローダを登録
require(__DIR__ . '/../vendor/autoload.php');
// Yii クラスファイルをインクルード
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
// アプリケーションのコンフィギュレーションを読み出す
$config = require(__DIR__ . '/../config/web.php');
// アプリケーションを作成し、構成して、走らせる
(new yii\web\Application($config))->run();
```
## コンソールアプリケーション<a name="console-applications"></a>
同様に、下記がコンソールアプリケーションのエントリスクリプトです:le application:
```php
#!/usr/bin/env php
<?php
/**
* Yii console bootstrap file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
defined('YII_DEBUG') or define('YII_DEBUG', true);
// fcgi が既定では STDIN と STDOUT を定義していないので
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
// Composer のオートローダを登録
require(__DIR__ . '/vendor/autoload.php');
// Yii クラスファイルをインクルード
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php');
// アプリケーションのコンフィギュレーションを読み出す
$config = require(__DIR__ . '/config/console.php');
$application = new yii\console\Application($config);
$exitCode = $application->run();
exit($exitCode);
```
## 定数を定義する<a name="defining-constants"></a>
グローバルな定数を定義するには、エントリスクリプトが最善の場所です。
Yii は下記の三つの定数をサポートしています:
* `YII_DEBUG`: アプリケーションがデバッグモードで走るかどうかを規定します。
デバッグモードにおいては、アプリケーションはより多くのログ情報を保持し、
例外が投げられたときに、より詳細なエラーのコールスタックを表示します。
この理由により、デバッグモードは主として開発時に使用されるべきものとなります。
`YII_DEBUG` の既定値は false です。
* `YII_ENV`: どういう環境でアプリケーションが走るかを規定します。
詳細については、[コンフィギュレーション](concept-configurations.md#environment-constants) の節で説明されます。
`YII_ENV` の既定値は `'prod'` です。これはアプリケーションが実運用環境で走ることを意味します。
* `YII_ENABLE_ERROR_HANDLER`: Yii によって提供されるエラーハンドラを有効にするかどうかを規定します。
この定数の既定値は true です。
定数を定義するときには、しばしば次のようなコードを用います:
```php
defined('YII_DEBUG') or define('YII_DEBUG', true);
```
これは下記のコードと同じ意味のものです:
```php
if (!defined('YII_DEBUG')) {
define('YII_DEBUG', true);
}
```
明らかに前者の方が簡潔で理解しやすいでしょう。
PHP ファイルがインクルードされる時に定数の効力が生じるようにするために、定数の定義はエントリスクリプトの冒頭でなされるべきです。
概要
====
Yii のアプリケーションは [モデル・ビュー・コントローラ (MVC)](http://ja.wikipedia.org/wiki/Model_View_Controller) デザインパターンに従って組織されます。
[モデル](structure-models.md) は、データ、ビジネスロジック、規則を表現します;
[ビュー](structure-views.md) は、モデルの出力表現です;
そして [コントローラ](structure-controllers.md) は入力を受け取って、それを [モデル](structure-models.md)[ビュー](structure-views.md) のためのコマンドに変換します。
MVC 以外にも、Yii のアプリケーションは下記の要素を持っています:
* [エントリスクリプト](structure-entry-scripts.md): エンドユーザから直接アクセスできる PHP スクリプトです。
これはリクエスト処理サイクルを開始する役目を持っています。
* [アプリケーション](structure-applications.md): グローバルにアクセス可能なオブジェクトであり、
アプリケーションコンポーネントを管理し、連携させて、リクエストに応えます。
* [アプリケーションコンポーネント](structure-application-components.md): アプリケーションと共に登録されたオブジェクトであり、リクエストに応えるための様々なサービスを提供します。
* [モジュール](structure-modules.md): それ自身に完全な MVC を含む自己完結的なパッケージです。
アプリケーションは複数のモジュールとして組織することが出来ます。
* [フィルター](structure-filters.md): 各リクエストが実際に処理される前と後に、コントローラから呼び出される必要があるコードを表現します。
* [ウィジェット](structure-widgets.md): [ビュー](structure-views.md) に埋め込むことが出来るオブジェクトです。コントローラのロジックを含むことが可能で、異なるビューで再利用することが出来ます。
下の図がアプリケーションの静的な構造を示すものです:
![アプリケーションの静的な構造](images/application-structure.png)
......@@ -277,7 +277,7 @@ for an argument: U_ARGUMENT_TYPE_MISMATCH":
демонстрирует возможность подстановки корректного рода в зависимости от параметра:
```php
echo \Yii::t('app', '{name} - {gender} и {gender, select, женщина{ей} мужчина{ему} other{ему} нравится Yii!', [
echo \Yii::t('app', '{name} - {gender} и {gender, select, женщина{ей} мужчина{ему} other{ему}} нравится Yii!', [
'name' => 'Василий',
'gender' => 'мужчина',
]);
......
......@@ -114,7 +114,7 @@ if ($this->beginCache($id1)) {
可以为嵌套的缓存设置不同的配置项。例如,内层缓存和外层缓存使用不同的过期时间。甚至当外层缓存的数据过期失效了,内层缓存仍然可能提供有效的片段缓存数据。但是,反之则不然。如果外层片段缓存没有过期而被视为有效,此时即使内层片段缓存已经失效,它也将继续提供同样的缓存副本。因此,你必须谨慎处理缓存嵌套中的过期时间和依赖,否则外层的片段很有可能返回的是不符合你预期的失效数据。
> 译注:外层的失效时间应该短于内层,外层的依赖条件应该低于内层,以确保最小的片段,返回的是最新的数据。
> 译注:外层的失效时间应该短于内层,外层的依赖条件应该低于内层,以确保最小的片段,返回的是最新的数据。
## 动态内容 <a name="dynamic-content"></a>
......
......@@ -15,7 +15,7 @@ Yii 依靠[类自动加载机制](http://www.php.net/manual/en/language.oop5.aut
* 每个类都必须保存为单独文件,且其完整路径能用以下算法取得:
```php
// $className 是一个开头包含反斜杠的完整类名(译注:请自行谷歌:fully qualified class name)
// $className 是一个开头包含反斜杠的完整类名(译注:请自行谷歌:fully qualified class name)
$classFile = Yii::getAlias('@' . str_replace('\\', '/', $className) . '.php');
```
......
......@@ -267,7 +267,7 @@ class User extends ActiveRecord
保存 `User` 对象,将会发现它的 `created_at``updated_at` 属性自动填充了当前时间戳:
``php
```php
$user = new User;
$user->email = 'test@example.com';
$user->save();
......
......@@ -65,7 +65,7 @@ $foo->on(Foo::EVENT_HELLO, function ($event) {
```
时间处理器顺序
事件处理器顺序
-----------------
可以附加一个或多个处理器到一个事件。当事件被触发,已附加的处理器将按附加次序依次调用。如果某个处理器需要停止其后的处理器调用,可以设置 `$event` 参数的 [yii\base\Event::handled]] 属性为真,如下:
......@@ -78,7 +78,7 @@ $foo->on(Foo::EVENT_HELLO, function ($event) {
默认新附加的事件处理器排在已存在处理器队列的最后。因此,这个处理器将在事件被触发时最后一个调用。在处理器队列最前面插入新处理器将使该处理器最先调用,可以传递第四个参数 `$append` 为假并调用 [[yii\base\Component::on()]] 方法实现:
``php
```php
$foo->on(Foo::EVENT_HELLO, function ($event) {
// 这个处理器将被插入到处理器队列的第一位...
}, $data, false);
......
......@@ -166,7 +166,7 @@ $sql = 'SELECT * FROM customer';
$customers = Customer::findBySql($sql)->all();
```
> 小技巧:在上面的代码中,`Customer::STATUS_ACTIVE` 是一个在 `Customer` 类里定义的常量。(译注:这种常量的值一般都是tinyint)相较于直接在代码中写死字符串或数字,使用一个更有意义的常量名称是一种更好的编程习惯。
> 小技巧:在上面的代码中,`Customer::STATUS_ACTIVE` 是一个在 `Customer` 类里定义的常量。(译注:这种常量的值一般都是tinyint)相较于直接在代码中写死字符串或数字,使用一个更有意义的常量名称是一种更好的编程习惯。
有两个快捷方法:`findOne``findAll()` 用来返回一个或者一组`ActiveRecord`实例。前者返回第一个匹配到的实例,后者返回所有。
例如:
......@@ -847,7 +847,7 @@ public static function find()
}
```
注意,你之后所有的查询都不能用 [[yii\db\ActiveQuery::where()|where()]],但是可以用 [[yii\db\ActiveQuery::andWhere()|andWhere()]] 和 [[yii\db\ActiveQuery::orWhere()|orWhere()]],他们不会覆盖掉默认作用域。(译注:如果你要使用默认作用域,就不能在 xxx::find()后使用where()方法,你必须使用andXXX()或者orXXX()系的方法,否则默认作用域不会起效果,至于原因,打开where()方法的代码一看便知)
注意,你之后所有的查询都不能用 [[yii\db\ActiveQuery::where()|where()]],但是可以用 [[yii\db\ActiveQuery::andWhere()|andWhere()]] 和 [[yii\db\ActiveQuery::orWhere()|orWhere()]],他们不会覆盖掉默认作用域。(译注:如果你要使用默认作用域,就不能在 xxx::find()后使用where()方法,你必须使用andXXX()或者orXXX()系的方法,否则默认作用域不会起效果,至于原因,打开where()方法的代码一看便知)
事务操作
......@@ -894,7 +894,7 @@ class ProductController extends \yii\web\Controller
}
}
```
(译注:我觉得上面应该是原手册里的bug)
(译注:我觉得上面应该是原手册里的bug)
在控制器层使用事务:
......
......@@ -24,7 +24,7 @@ Composer 自动加载器,以及通过 `Yii` 类加载的 Yii 自动加载器
因为引导工作必须在处理**每一次**请求之前都进行一遍,因此让该过程尽可能轻量化就异常重要,请尽可能地优化这一步骤。
请尽量不要注册太多引导组件。只有他需要在 HTTP 请求处理的全部生命周期中都作用时才需要使用它。举一个用到它的范例:一个模块需要注册额外的 URL 解析规则,就应该把它列在应用的
[bootstrap 属性](structure-applications.md#bootstrap)之中,这样该 URL 解析规则才能在解析请求之前生效。(译注:换言之,为了性能需要,除了 URL
[bootstrap 属性](structure-applications.md#bootstrap)之中,这样该 URL 解析规则才能在解析请求之前生效。(译注:换言之,为了性能需要,除了 URL
解析等少量操作之外,绝大多数组件都应该按需加载,而不是都放在引导过程中。)
在生产环境中,可以开启字节码缓存,比如 APC,来进一步最小化加载和解析 PHP 文件所需的时间。
......
路由
=======
[入口脚本](structure-entry-scripts.md)在调用 [[yii\web\Application::run()|run()]]
方法时,它进行的第一个操作就是解析输入的请求,然后实例化对应的[控制器操作](structure-controllers.md)处理这个请求。该过程就被称为**引导路由(routing)**。(译注:中文里既是动词也是名词)
## 解析路由 <a name="resolving-route"></a>
引导路由第一步,是解析传入请求为一个路由。如 [控制器(Controllers)](structure-controllers.md#routes)
所描述的那样,路由是一个用于定位控制器操作的地址。这个过程通过 `request` 应用组件的 [[yii\web\Request::resolve()|resolve()]]
方法实现,该方法会调用 [URL 管理器](runtime-url-handling.md) 进行实质上的请求解析工作。
The first step of routing is to parse the incoming request into a route which, as described in
the [Controllers](structure-controllers.md#routes) section, is used to address a controller action.
This is done by [[yii\web\Request::resolve()|resolve()]] method of the `request` application component.
The method invokes the [URL manager](runtime-url-handling.md) to do the actual request parsing work.
默认情况下,传入请求会包含一个名为 `r``GET` 参数,它的值即被视为路由。但是如果启用
[[yii\web\UrlManager::enablePrettyUrl|pretty URL feature]],确定请求路由时则会进行更多处理。具体的细节请参考
[URL 的解析与生成](runtime-url-handling.md) 章节。
By default, if the incoming request contains a `GET` parameter named `r`, its value will be considered
as the route. However, if the [[yii\web\UrlManager::enablePrettyUrl|pretty URL feature]] is enabled,
more work will be done to determine the requested route. For more details, please refer to
the [URL Parsing and Generation](runtime-url-handling.md) section.
若好死不死地路由最终无法被确定,那么 `request` 组件会抛出 [[yii\web\NotFoundHttpException]] 异常(译注:大名鼎鼎的 404)。
In case a route cannot be determined, the `request` component will throw a [[yii\web\NotFoundHttpException]].
### 默认路由 <a name="default-route"></a>
如果进来的请求并没有提供一个具体的路由,一般这种情况多为于对首页的请求,此时就会启用由
[[yii\web\Application::defaultRoute]] 属性所指定的路由。该属性的默认值为 `site/index`,指向 `site` 控制器的 `index`
操作。你可以像这样在应用配置中自定义该属性:
If an incoming request does not specify a route, which often happens to the request for homepages,
the route specified by [[yii\web\Application::defaultRoute]] will be used. The default value of this property
is `site/index`, which refers to the `index` action of the `site` controller. You may customize this property
in the application configuration like the following:
```php
return [
// ...
'defaultRoute' => 'main/index',
];
```
### `catchAll` 路由(全拦截路由) <a name="catchall-route"></a>
有时候,你会想要将你的 Web 应用临时置于维护模式,所有的请求下都会显示同一张信息页。有很多种方法都可以实现这一点。但是其中一个最简单快捷的方法的是在应用配置中设置
[[yii\web\Application::catchAll]] 属性:
Sometimes, you may want to put your Web application in maintenance mode temporarily and display the same
informational page for all requests. There are many ways to accomplish this goal. But one of the simplest
ways is to configure the [[yii\web\Application::catchAll]] property like the following in the application configuration:
```php
return [
// ...
'catchAll' => ['site/offline'],
];
```
`catchAll` 属性需要一个数组做参数,该数组的第一个元素为路由,剩下的元素会(以名值对的形式)指定绑定于该操作的各个参数。
The `catchAll` property should take an array whose first element specifies a route, and
the rest of the elements (name-value pairs) specify the parameters to be bound to the action.
当设置了 `catchAll` 属性时,他会替换掉所有从输入的请求中解析出来的路由。如果是上文的这种设置,用于处理所有传入请求的操作都会是相同的 `site/offline`
When the `catchAll` property is set, it will replace any route resolved from the incoming requests.
With the above configuration, the same `site/offline` action will be used to handle all incoming requests.
## 创建一个操作 <a name="creating-action"></a>
一旦请求路由被确定了,紧接着的步骤就是创建一个“操作(action)”对象响应该路由。
Once the requested route is determined, the next step is to create the action object corresponding to the route.
路由可以通过里面的斜杠分割成多个组成片段,举个栗子,`site/index` 可以分解为 `site``index`
两部分。每个片段都是指向某一模块(Module),控制器(Controller)或操作(action)的一个 ID。
The route is broken down into multiple parts by the slashes in it. For example, `site/index` will be
broken into `site` and `index`. Each part is an ID which may refer to a module, a controller or an action.
从路由的首个片段开始,应用会经过以下流程依次创建模块(如果有),控制器,以及操作:
Starting from the first part in the route, the application conducts the following steps to create modules (if any),
the controller and the action:
1. 设置应用主体为当前模块。
2. 检查当前模块的 [[yii\base\Module::controllerMap|controller map(控制器映射表)]] 是否包含当前 ID。如果是,会根据该表中的配置创建一个控制器对象,然后跳到步骤五执行该路由的后续片段。
3. 检查该 ID 是否指向当前模块中 [[yii\base\Module::modules|modules]] 属性里的模块列表中的一个模块。如果是,会根据该模块表中的配置创建一个模块对象,然后会以新创建的模块为环境,跳回步骤二解析下一段路由。
4. 将该 ID 视为控制器 ID,并创建控制器对象。用下个步骤解析路由里剩下的片段。
5. 控制器会在他的 [[yii\base\Controller::actions()|action map(操作映射表)]]里搜索当前 ID。如果找得到,它会根据该映射表中的配置创建一个操作对象;反之,控制器则会尝试创建一个与该 ID
相对应,由某个 action 方法所定义的行内操作(inline action)。
1. Set the application as the current module.
2. Check if the [[yii\base\Module::controllerMap|controller map]] of the current module contains the current ID.
If so, a controller object will be created according to the controller configuration found in the map,
and do Step 5 with the rest parts of the route.
3. Check if the ID refers to a module listed in the [[yii\base\Module::modules|modules]] property of
the current module. If so, a module is created according to the configuration found in the module list,
and do Step 2 with the next part in the route under the context of the newly created module.
4. Treat the ID as a controller ID and create a controller object. Do the next step with the rest part of
the route.
5. The controller looks for the current ID in its [[yii\base\Controller::actions()|action map]]. If found,
it creates an action according to the configuration found in the map. Otherwise, the controller will
attempt to create an inline action which is defined by an action method corresponding to the current ID.
在上面的步骤里,如果有任何错误发生,都会抛出 [[yii\web\NotFoundHttpException]](译注:就是404),标识出路由引导失败。
Among the above steps, if any error occurs, a [[yii\web\NotFoundHttpException]] will be thrown, indicating
failure of the routing.
使用表单
==================
本章将介绍如何创建一个从用户那搜集数据的表单页。该页将显示一个包含 name 输入框和 email 输入框的表单。当搜集完这两部分信息后,页面将会显示用户输入的信息。
本章节介绍如何创建一个让用户提交数据的表单页。该页将显示一个包含 name 输入框和 email 输入框的表单。当提交这两部分信息后,页面将会显示用户所输入的信息。
为了实现这个目标,除了创建一个[操作](structure-controllers.md)和两个[视图](structure-views)外,还需要创建一个[模型](structure-models.md)
......@@ -39,16 +39,16 @@ class EntryForm extends Model
}
```
该类继承自 [[yii\base\Model]],Yii 提供的一个基类,通常用来代表表单数据。
该类继承自Yii 提供的一个基类 [[yii\base\Model]],该基类通常用来表示数据。
> 补充:[[yii\base\Model]] 被用于普通模型类的父类并与数据表**无关**。[[yii\db\ActiveRecord]] 通常是普通模型类的父类但与数据表有关联。
> 补充:[[yii\base\Model]] 被用于普通模型类的父类并与数据表**无关**。[[yii\db\ActiveRecord]] 通常是普通模型类的父类但与数据表有关联(译注:[[yii\db\ActiveRecord]] 类其实也是继承自 [[yii\base\Model]],增加了数据库处理)
`EntryForm` 类包含 `name``email` 两个公共变量,用来储存用户输入的数据。它还包含一个名为 `rules()` 的方法,用来返回数据验证规则的集合。上面声明的验证规则表示:
`EntryForm` 类包含 `name``email` 两个公共成员,用来储存用户输入的数据。它还包含一个名为 `rules()` 的方法,用来返回数据验证规则的集合。上面声明的验证规则表示:
* `name``email` 值都是必须的
* `mail` 的值必须满足 email 地址验证
* `email` 的值必须满足email规则验证
如果你有一个从用户那搜集数据的 `EntryForm` 对象,你可以调用它的 [[yii\base\Model::validate()|validate()]] 方法触发数据验证。如果有数据验证失败,将把 [[yii\base\Model::hasErrors|hasErrors]] 属性设为 ture,想要知道具体发生什么错误就调用 [[yii\base\Model::getErrors|getErrors]]。
如果你有一个处理用户提交数据的 `EntryForm` 对象,你可以调用它的 [[yii\base\Model::validate()|validate()]] 方法触发数据验证。如果有数据验证失败,将把 [[yii\base\Model::hasErrors|hasErrors]] 属性设为 ture,想要知道具体发生什么错误就调用 [[yii\base\Model::getErrors|getErrors]]。
```php
<?php
......@@ -67,7 +67,7 @@ if ($model->validate()) {
创建操作 <a name="creating-action"></a>
------------------
接下来你需要`site` 控制器中创建一个 `entry` 操作用于新建的模型。操作的创建和使用已经在[说一声你好](start-hello.md)小节中解释了。
下面你得`site` 控制器中创建一个 `entry` 操作用于新建的模型。操作的创建和使用已经在[说一声你好](start-hello.md)小节中解释了。
```php
<?php
......@@ -104,7 +104,7 @@ class SiteController extends Controller
> 补充:表达式 `Yii::$app` 代表[应用](structure-applications.md)实例,它是一个全局可访问的单例。同时它也是一个[服务定位器](concept-service-locator.md),能提供 `request`,`response`,`db` 等等特定功能的组件。在上面的代码里就是使用 `request` 组件来访问应用实例收到的 `$_POST` 数据。
用户成功提交表单后,操作将会渲染一个名为 `entry-confirm` 的视图去确认用户输入的数据。如果没填表单就提交,或数据包含错误`entry` 视图将会渲染输出,连同表单一起输出的还有验证错误的详细信息。
用户提交表单后,操作将会渲染一个名为 `entry-confirm` 的视图去确认用户输入的数据。如果没填表单就提交,或数据包含错误(译者:如 email 格式不对)`entry` 视图将会渲染输出,连同表单一起输出的还有验证错误的详细信息。
> 注意:在这个简单例子里我们只是呈现了有效数据的确认页面。实践中你应该考虑使用 [[yii\web\Controller::refresh()|refresh()]] 或 [[yii\web\Controller::redirect()|redirect()]] 去避免[表单重复提交问题](http://en.wikipedia.org/wiki/Post/Redirect/Get)。
......@@ -148,10 +148,10 @@ use yii\widgets\ActiveForm;
<?php ActiveForm::end(); ?>
```
视图使用了一个功能强大的[小部件](structure-widgets.md) [[yii\widgets\ActiveForm|ActiveForm]] 去生成 HTML 表单。其中的 `begin()``end()` 分别用来渲染表单的开始和关闭标签。在这两个方法之间使用了 [[yii\widgets\ActiveForm::field()|field()]] 方法去创建表单栏。第一个表单栏用于 “name”,第二个表单栏用于 “email”。之后使用 [[yii\helpers\Html::submitButton()]] 方法生成提交按钮。
视图使用了一个功能强大的[小部件](structure-widgets.md) [[yii\widgets\ActiveForm|ActiveForm]] 去生成 HTML 表单。其中的 `begin()``end()` 分别用来渲染表单的开始和关闭标签。在这两个方法之间使用了 [[yii\widgets\ActiveForm::field()|field()]] 方法去创建输入框。第一个输入框用于 “name”,第二个输入框用于 “email”。之后使用 [[yii\helpers\Html::submitButton()]] 方法生成提交按钮。
试运行 <a name="trying-it-out"></a>
尝试下 <a name="trying-it-out"></a>
-------------
用浏览器访问下面的 URL 看它能否工作:
......@@ -160,7 +160,7 @@ use yii\widgets\ActiveForm;
http://hostname/index.php?r=site/entry
```
你会看到一个包含两个表单栏的页面。每个表单栏的前面都有一个标签指明应该输入的数据类型。如果什么都不填就点击提交按钮,或填入格式不正确的 email 地址,将会看到在对应的表单栏下显示错误信息。
你会看到一个包含两个输入框的表单的页面。每个输入框的前面都有一个标签指明应该输入的数据类型。如果什么都不填就点击提交按钮,或填入格式不正确的 email 地址,将会看到在对应的输入框下显示错误信息。
![验证错误的表单](images/start-form-validation.png)
......@@ -172,13 +172,13 @@ http://hostname/index.php?r=site/entry
### 效果说明 <a name="magic-explained"></a>
你可能会好奇 HTML 表单暗地里是如何工作的,看起来它可以为每个表单栏显示文字标签,而当你没输入正确的信息时又不需要刷新页面就能给出错误提示,似乎有些神奇。
你可能会好奇 HTML 表单暗地里是如何工作的呢,看起来它可以为每个输入框显示文字标签,而当你没输入正确的信息时又不需要刷新页面就能给出错误提示,似乎有些神奇。
是的,其实数据首先由客户端 JavaScript 脚本验证,然后才会提交给服务器通过 PHP 验证。[[yii\widgets\ActiveForm]] 足够智能到把你在 `EntryForm` 模型中声明的验证规则转化成客户端 JavaScript 脚本去执行验证。如果用户浏览器禁用了 JavaScript, 服务器端仍然会像 `actionEntry()` 方法里这样验证一遍数据。这保证了任何情况下用户提交的数据都是有效的。
> 警告:客户端验证是提高用户体验的手段。无论它是否正常启用,服务端验证则都是必须的,请不要忽略它。
> 警告:客户端验证是提高用户体验的手段。无论它是否正常启用,服务端验证则都是必须的,请不要忽略它。
表单栏的文字标签是 `field()` 方法生成的,内容就是模型中该数据的属性名。例如模型中的 `name` 属性生成的标签就是 `Name`
输入框的文字标签是 `field()` 方法生成的,内容就是模型中该数据的属性名。例如模型中的 `name` 属性生成的标签就是 `Name`
你可以在视图中自定义标签:
......@@ -193,7 +193,7 @@ http://hostname/index.php?r=site/entry
总结 <a name="summary"></a>
-------
本章指南中你接触了 MVC 设计模式的每个部分。学到了如何创建一个模型代表用户数据并验证它的有效性。
本章指南中你接触了 MVC 设计模式的每个部分。学到了如何创建一个模型代表用户数据并验证它的有效性。
你还学到了如何从用户那获取数据并在浏览器上回显给用户。这本来是开发应用的过程中比较耗时的任务,好在 Yii 提供了强大的小部件让它变得如此简单。
......
......@@ -30,7 +30,7 @@ Composer 安装后,切换到一个可通过 Web 访问的目录,执行如下
> 注意:在安装过程中 Composer 可能会询问你 GitHub 账户的登录信息,因为可能在使用中超过了 GitHub API
(对匿名用户的)使用限制。因为 Composer 需要为所有扩展包从 GitHub
中获取大量信息,所以超限非常正常。(译注:也意味着作为程序猿没有 GitHub 账号,就真不能愉快地玩耍了)登陆 GitHub
中获取大量信息,所以超限非常正常。(译注:也意味着作为程序猿没有 GitHub 账号,就真不能愉快地玩耍了)登陆 GitHub
之后可以得到更高的 API 限额,这样 Composer 才能正常运行。更多细节请参考 [Composer
文档](https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens)(该段 Composer
中文文档[期待您的参与](https://github.com/5-say/composer-doc-cn/blob/master/cn-introduction/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens))。
......@@ -117,7 +117,7 @@ http://localhost/basic/web/index.php
DocumentRoot "path/to/basic/web"
<Directory "path/to/basic/web">
# 开启 mod_rewrite 用于美化 URL 功能的支持(译注:对应 pretty URL 选项)
# 开启 mod_rewrite 用于美化 URL 功能的支持(译注:对应 pretty URL 选项)
RewriteEngine on
# 如果请求的是真实存在的文件或目录,直接访问
RewriteCond %{REQUEST_FILENAME} !-f
......
......@@ -60,7 +60,7 @@ $config = require(__DIR__ . '/../config/web.php');
### 重要属性 <a name="important-properties"></a>
本小节所描述的属性通常需要设置,因为不的应用属性不同。
本小节所描述的属性通常需要设置,因为不的应用属性不同。
#### [[yii\base\Application::aliases|aliases]] <a name="aliases"></a>
......
......@@ -194,7 +194,7 @@ function foo($model, $attribute) {
- `filter`:用于检查输入值存在性必然会进行数据库查询,而该属性为用于进一步筛选该查询的过滤条件。可以为代表额外查询条件的字符串或数组(关于查询条件的格式,请参考 [[yii\db\Query::where()]]);或者样式为 `function ($query)` 的匿名函数,`$query` 参数为你希望在该函数内进行修改的 [[yii\db\Query|Query]] 对象。
- `allowArray`:是否允许输入值为数组。默认为 false。若该属性为 true 且输入值为数组,则数组的每个元素都必须在目标字段中存在。值得注意的是,若用吧 `targetAttribute` 设为多元素数组来验证被测值在多字段中的存在性时,该属性不能设置为 true。
> 译注:[exist](#exist) 和 [unique](#unique) 验证器的机理和参数都相似,有点像一体两面的阴和阳。
> 译注:[exist](#exist) 和 [unique](#unique) 验证器的机理和参数都相似,有点像一体两面的阴和阳。
- 他们的区别是 exist 要求 `targetAttribute` 键所代表的的属性在其值所代表字段中找得到;而 unique 正相反,要求键所代表的的属性不能在其值所代表字段中被找到。
- 从另一个角度来理解:他们都会在验证的过程中执行数据库查询,查询的条件即为where $v=$k (假设 `targetAttribute` 的其中一对键值对为 `$k => $v`)。unique 要求查询的结果数 `$count==0`,而 exist 则要求查询的结果数 `$count>0`
- 最后别忘了,unique 验证器不存在 `allowArray` 属性哦。
......@@ -423,7 +423,7 @@ function foo($model, $attribute) {
- 若键和值相同,你可以只指定值。(如:`['a2']` 就代表 `['a2'=>'a2']`
- `filter`:用于检查输入值唯一性必然会进行数据库查询,而该属性为用于进一步筛选该查询的过滤条件。可以为代表额外查询条件的字符串或数组(关于查询条件的格式,请参考 [[yii\db\Query::where()]]);或者样式为 `function ($query)` 的匿名函数,`$query` 参数为你希望在该函数内进行修改的 [[yii\db\Query|Query]] 对象。
> 译注:[exist](#exist) 和 [unique](#unique) 验证器的机理和参数都相似,有点像一体两面的阴和阳。
> 译注:[exist](#exist) 和 [unique](#unique) 验证器的机理和参数都相似,有点像一体两面的阴和阳。
- 他们的区别是 exist 要求 `targetAttribute` 键所代表的的属性在其值所代表字段中找得到;而 unique 正相反,要求键所代表的的属性不能在其值所代表字段中被找到。
- 从另一个角度来理解:他们都会在验证的过程中执行数据库查询,查询的条件即为where $v=$k (假设 `targetAttribute` 的其中一对键值对为 `$k => $v`)。unique 要求查询的结果数 `$count==0`,而 exist 则要求查询的结果数 `$count>0`
- 最后别忘了,unique 验证器不存在 `allowArray` 属性哦。
......
......@@ -84,7 +84,7 @@ $yiiConfig = require(__DIR__ . '/../config/yii/web.php');
new yii\web\Application($yiiConfig); // 千万别在这调用 run() 方法。(笑)
```
如你所见,这段代码与典型的 Yii 应用的[入口脚本](structure-entry-scripts.md)非常相似。唯一的不同之处在于在 Yii 应用创建成功之后,并不会紧接着调用 `run()` 方法。因为,`run()` 方法的调用会接管 HTTP 请求的处理流程。(译注:换言之,这就不是第三方系统而是 Yii 系统了,URL 规则也会跟着换成 Yii 的规则了)
如你所见,这段代码与典型的 Yii 应用的[入口脚本](structure-entry-scripts.md)非常相似。唯一的不同之处在于在 Yii 应用创建成功之后,并不会紧接着调用 `run()` 方法。因为,`run()` 方法的调用会接管 HTTP 请求的处理流程。(译注:换言之,这就不是第三方系统而是 Yii 系统了,URL 规则也会跟着换成 Yii 的规则了)
与 Yii 应用中一样,你可以依据运行该第三方系统的环境,针对性地配置 Yii 应用实例。比如,为了使用[活动记录](db-active-record.md)功能,你需要先用该第三方系统的 DB 连接信息,配置 Yii 的 `db` 应用组件。
......
......@@ -21,7 +21,8 @@ By default, Yii supports the following DBMS:
Configuration
-------------
To start interacting with a database (using DAO or otherwise), you need to configure the application's database connection component. The Data Source Name (DSN) configures to which database application and specific database the application should connect:
To start interacting with a database (using DAO or otherwise), you need to configure the application's database
connection component. The Data Source Name (DSN) configures to which database application and specific database the application should connect:
```php
return [
......@@ -50,9 +51,8 @@ return [
Please refer to the [PHP manual](http://www.php.net/manual/en/function.PDO-construct.php) for more details
on the format of the DSN string. Refer to [[yii\db\Connection]] for the full list of properties you can configure in the class.
A peculiarity exists when you want to work with the database through the `ODBC` layer. When using `ODBC`, the
connection `DSN` doesn't uniquely indicate what database type is being used. For that reason, you have to override the
`driverName` property of [[yii\db\Connection]] class to disambiguate that:
Note that if you are connecting with a database via ODBC, you should configure the [[yii\db\Connection::driverName]]
property so that Yii knows the actual database type. For example,
```php
'db' => [
......@@ -64,16 +64,8 @@ connection `DSN` doesn't uniquely indicate what database type is being used. For
],
```
Overriding `driverName` is not necessary when not going through ODBC.
Given the "db" component's configuration in the application, you can access the database connection using:
```php
$connection = \Yii::$app->db;
```
You can define more
than one connection component:
You may access the primary `db` connection via the expression `\Yii::$app->db`. You may also configure multiple
DB connections in a single application. Simply assign different IDs to them in the application configuration:
```php
return [
......
......@@ -46,7 +46,7 @@ echo \Yii::$app->urlManager->createAbsoluteUrl('blog/post/index');
// http://www.example.com/index.php/blog/post/index/
```
The exact format of the resuting URL depends on how the URL manager is configured. The above
The exact format of the resulting URL depends on how the URL manager is configured. The above
examples could also output:
* `/site/page/id/about/`
......
......@@ -56,7 +56,7 @@ For example, we need to store some information in our database but we need to ma
```php
// $data and $secretKey are obtained from the form
$encryptedData = Yii::$app->getSecurity()->encrypt($data, $secretKey);
$encryptedData = Yii::$app->getSecurity()->encryptByPassword($data, $secretKey);
// store $encryptedData to database
```
......@@ -64,7 +64,7 @@ Subsequently when user wants to read the data:
```php
// $secretKey is obtained from user input, $encryptedData is from the database
$data = Yii::$app->getSecurity()->decrypt($encryptedData, $secretKey);
$data = Yii::$app->getSecurity()->decryptByPassword($encryptedData, $secretKey);
```
Confirming data integrity
......
Looking Ahead
=============
If you've read through the entire "Getting Started" section, you have now created a complete Yii application. In the process, you have learned how to implement some commonly
If you've read through the entire "Getting Started" chapter, you have now created a complete Yii application. In the process, you have learned how to implement some commonly
needed features, such as getting data from users via an HTML form, fetching data from a database, and
displaying data in a paginated fashion. You have also learned how to use [Gii](tool-gii.md) to generate
code automatically. Using Gii for code generation turns the bulk of your Web development process into a task as simple as just filling out some forms.
......
......@@ -90,7 +90,7 @@ Entry scripts are the best place for defining global constants. Yii supports the
* `YII_DEBUG`: specifies whether the application is running in debug mode. When in debug mode, an application
will keep more log information, and will reveal detailed error call stacks if exceptions are thrown. For this
reason, debug mode should be used mainly during development. The default value of `YII_DEBUG` is false.
* `YII_ENV`: specifies which environment the application is running in. This has been described in
* `YII_ENV`: specifies which environment the application is running in. This will be described in
more detail in the [Configurations](concept-configurations.md#environment-constants) section.
The default value of `YII_ENV` is `'prod'`, meaning the application is running in production environment.
* `YII_ENABLE_ERROR_HANDLER`: specifies whether to enable the error handler provided by Yii. The default
......
......@@ -279,8 +279,7 @@ Loading fixtures
----------------
Fixture classes should be suffixed by `Fixture` class. By default fixtures will be searched under `tests\unit\fixtures` namespace, you can
change this behavior with config or command options. Note that you can also append fixtures data to already existing ones with command
option `--append`. You can exclude some fixtures due load or unload by specifying `-` before its name like `-User`.
change this behavior with config or command options. You can exclude some fixtures due load or unload by specifying `-` before its name like `-User`.
To load fixture, run the following command:
......@@ -301,9 +300,6 @@ yii fixture User
// load several fixtures
yii fixture User UserProfile
//load fixture, but don't clean storage before load and just append to already existed data
yii fixture User --append
// load all fixtures
yii fixture/load "*"
......
......@@ -17,3 +17,9 @@ Running basic and advanced template unit tests
----------------------------------------------
Please refer to instructions provided in `apps/advanced/tests/README.md` and `apps/basic/tests/README.md`.
Framework unit tests
--------------------
If you want to run unit tests for Yii framework itself follow
"[Getting started with Yii2 development](https://github.com/yiisoft/yii2/blob/master/docs/internals/getting-started.md)".
......@@ -146,8 +146,8 @@ and the one that will be generated. In this case you can also choose which files
> Tip: When using the Model Generator to update models after database change, you can copy the code from gii preview
and merge the changes with your own code. You can use IDE features like PHPStorms
[compare with clipboard](http://www.jetbrains.com/phpstorm/webhelp/comparing-files.html) for this,
which allows you to merge in relevant changes and leave out others that may revert your own code.
[compare with clipboard](http://www.jetbrains.com/phpstorm/webhelp/comparing-files.html), [Aptana Studio](http://www.aptana.com/products/studio3/download) or [Eclipse](http://www.eclipse.org/pdt/) based editor also allows [compare with clipboard](http://andrei.gmxhome.de/anyedit/examples.html) by using [AnyEdit tools plugin](http://andrei.gmxhome.de/anyedit/) for this, which allows you to merge in relevant changes and leave out others that may revert your own code.
After you have reviewed the code and selected the files to be generated you can click the "Generate" button to create
the files. If all went fine you are done. When you see errors that gii is not able to generate the files you have to
......
......@@ -269,14 +269,14 @@ Use the following formatting for switch:
```php
switch ($this->phpType) {
case 'string':
$a = (string)$value;
$a = (string) $value;
break;
case 'integer':
case 'int':
$a = (integer)$value;
$a = (int) $value;
break;
case 'boolean':
$a = (boolean)$value;
$a = (bool) $value;
break;
default:
$a = null;
......
......@@ -10,9 +10,15 @@ Brazilian Portuguese
China
-----
- **Paris Qian Sen 东方孤思子,[@qiansen1386](https://github.com/qiansen1386),qiansen1386ATgmail.com**
- **Paris Qian Sen 东方孤思子,[@qiansen1386](https://github.com/qiansen1386),qiansen1386@gmail.com**
- [@AbrahamGreyson 刘阳](https://github.com/AbrahamGreyson)
- [@Aliciamiao](https://github.com/aliciamiao)
- [@riverlet ](https://github.com/riverlet)
- [@fmalee](https://github.com/fmalee)
- [@funson86 花生](https://github.com/funson86)
- [@ivantree 长兴苗木](https://github.com/ivantree)
- [@netyum 未来](https://github.com/netyum)
- [@riverlet 小河](https://github.com/riverlet)
- [@yiichina 巡洋舰](https://github.com/yiichina)
Finnish
------
......
......@@ -5,6 +5,7 @@ Yii Framework 2 apidoc extension Change Log
-----------------------
- Bug #5623: Fixed crash when a class contains a setter that has no arguments e.g. `setXyz()` (cebe)
- Enh: Guide generator now skips `images` directory if it does not exist instead of throwing an error (cebe)
2.0.0 October 12, 2014
......
......@@ -67,7 +67,10 @@ class GuideController extends BaseController
$this->stdout('Publishing images...');
foreach ($sourceDirs as $source) {
FileHelper::copyDirectory(rtrim($source, '/\\') . '/images', $targetDir . '/images');
$imageDir = rtrim($source, '/\\') . '/images';
if (file_exists($imageDir)) {
FileHelper::copyDirectory($imageDir, $targetDir . '/images');
}
}
$this->stdout('done.' . PHP_EOL, Console::FG_GREEN);
}
......
......@@ -86,6 +86,12 @@ class AuthAction extends Action
*/
public $successCallback;
/**
* @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.
*/
public $redirectView;
/**
* @var string the redirect url after successful authorization.
*/
private $_successUrl = '';
......@@ -96,12 +102,6 @@ class AuthAction extends Action
/**
* @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.
*/
public $redirectView;
/**
* @param string $url successful URL.
*/
public function setSuccessUrl($url)
......
......@@ -35,6 +35,11 @@ class OAuthToken extends Object
*/
public $tokenSecretParamKey = 'oauth_token_secret';
/**
* @var integer object creation timestamp.
*/
public $createTimestamp;
/**
* @var string key in [[params]] array, which stores token expiration duration.
* If not set will attempt to fetch its value automatically.
*/
......@@ -45,11 +50,6 @@ class OAuthToken extends Object
private $_params = [];
/**
* @var integer object creation timestamp.
*/
public $createTimestamp;
public function init()
{
if ($this->createTimestamp === null) {
......
......@@ -82,20 +82,6 @@ class OpenId extends BaseClient implements ClientInterface
*/
public $cainfo;
/**
* @var string authentication return URL.
*/
private $_returnUrl;
/**
* @var string claimed identifier (identity)
*/
private $_claimedId;
/**
* @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.
*/
......@@ -116,6 +102,20 @@ class OpenId extends BaseClient implements ClientInterface
];
/**
* @var string authentication return URL.
*/
private $_returnUrl;
/**
* @var string claimed identifier (identity)
*/
private $_claimedId;
/**
* @var string client trust root (realm), by default [[\yii\web\Request::hostInfo]] value will be used.
*/
private $_trustRoot;
/**
* @inheritdoc
*/
public function init()
......
......@@ -24,6 +24,15 @@ use yii\base\NotSupportedException;
class RsaSha1 extends BaseMethod
{
/**
* @var string path to the file, which holds private key certificate.
*/
public $privateCertificateFile = '';
/**
* @var string path to the file, which holds public key certificate.
*/
public $publicCertificateFile = '';
/**
* @var string OpenSSL private key certificate content.
* This value can be fetched from file specified by [[privateCertificateFile]].
*/
......@@ -36,15 +45,6 @@ class RsaSha1 extends BaseMethod
/**
* @var string path to the file, which holds private key certificate.
*/
public $privateCertificateFile = '';
/**
* @var string path to the file, which holds public key certificate.
*/
public $publicCertificateFile = '';
/**
* @inheritdoc
*/
public function init()
......
......@@ -92,7 +92,7 @@ use yii\helpers\ArrayHelper;
class ActiveField extends \yii\widgets\ActiveField
{
/**
* @var bool whether to render [[checkboxList()]] and [[radioList()]] inline.
* @var boolean whether to render [[checkboxList()]] and [[radioList()]] inline.
*/
public $inline = false;
/**
......@@ -137,11 +137,11 @@ class ActiveField extends \yii\widgets\ActiveField
*/
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`.
* @var boolean 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`.
* @var boolean whether to render the label. Default is `true`.
*/
public $enableLabel = true;
......@@ -303,13 +303,13 @@ class ActiveField extends \yii\widgets\ActiveField
}
/**
* @param bool $value whether to render a inline list
* @param boolean $value whether to render a inline list
* @return static the field object itself
* Make sure you call this method before [[checkboxList()]] or [[radioList()]] to have any effect.
*/
public function inline($value = true)
{
$this->inline = (bool)$value;
$this->inline = (bool) $value;
return $this;
}
......
......@@ -139,7 +139,7 @@ class LogTarget extends Target
$summary = [
'tag' => $this->tag,
'url' => $request->getAbsoluteUrl(),
'ajax' => (int)$request->getIsAjax(),
'ajax' => (int) $request->getIsAjax(),
'method' => $request->getMethod(),
'ip' => $request->getUserIP(),
'time' => time(),
......
......@@ -138,7 +138,6 @@ use yii\helpers\VarDumper;
*/
class FixtureController extends \yii\console\controllers\FixtureController
{
/**
* @var string Alias to the template path, where all tables templates are stored.
*/
......
......@@ -102,7 +102,7 @@ class GenerateAction extends \yii\base\Action
return;
}
if ($this->generator->save($files, (array)$answers, $results)) {
if ($this->generator->save($files, (array) $answers, $results)) {
$this->controller->stdout("\nFiles were generated successfully!\n", Console::FG_GREEN);
} else {
$this->controller->stdout("\nSome errors occurred while generating the files.", Console::FG_RED);
......
......@@ -89,7 +89,7 @@ abstract class Migration extends Component implements MigrationInterface
*/
public function createIndex($collection, $columns, $options = [])
{
echo " > create index on " . $this->composeCollectionLogName($collection) . " (" . Json::encode((array)$columns) . empty($options) ? "" : ", " . Json::encode($options) . ") ...";
echo " > create index on " . $this->composeCollectionLogName($collection) . " (" . Json::encode((array) $columns) . empty($options) ? "" : ", " . Json::encode($options) . ") ...";
$time = microtime(true);
$this->db->getCollection($collection)->createIndex($columns, $options);
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
......@@ -102,7 +102,7 @@ abstract class Migration extends Component implements MigrationInterface
*/
public function dropIndex($collection, $columns)
{
echo " > drop index on " . $this->composeCollectionLogName($collection) . " (" . Json::encode((array)$columns) . ") ...";
echo " > drop index on " . $this->composeCollectionLogName($collection) . " (" . Json::encode((array) $columns) . ") ...";
$time = microtime(true);
$this->db->getCollection($collection)->dropIndex($columns);
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
......
......@@ -81,7 +81,7 @@ To get actual Mongo ID string your should typecast [[\MongoId]] instance to stri
$query = new Query;
$row = $query->from('customer')->one();
var_dump($row['_id']); // outputs: "object(MongoId)"
var_dump((string)$row['_id']); // outputs "string 'acdfgdacdhcbdafa'"
var_dump((string) $row['_id']); // outputs "string 'acdfgdacdhcbdafa'"
```
Although this fact is very useful sometimes, it often produces some problems.
......@@ -90,7 +90,7 @@ In these cases, ensure you have converted [[\MongoId]] into the string:
```php
/* @var $this yii\web\View */
echo $this->createUrl(['item/update', 'id' => (string)$row['_id']]);
echo $this->createUrl(['item/update', 'id' => (string) $row['_id']]);
```
While building condition, values for the key '_id' will be automatically cast to [[\MongoId]] instance,
......
......@@ -124,7 +124,7 @@ class ActiveRecord extends BaseActiveRecord
// only insert attributes that are not null
if ($value !== null) {
if (is_bool($value)) {
$value = (int)$value;
$value = (int) $value;
}
$setArgs[] = $attribute;
$setArgs[] = $value;
......@@ -175,7 +175,7 @@ class ActiveRecord extends BaseActiveRecord
}
if ($value !== null) {
if (is_bool($value)) {
$value = (int)$value;
$value = (int) $value;
}
$setArgs[] = $attribute;
$setArgs[] = $value;
......
......@@ -270,7 +270,7 @@ EOF;
$parts[] = $this->buildInCondition('in', [$column, $value], $columns);
} else {
if (is_bool($value)) {
$value = (int)$value;
$value = (int) $value;
}
if ($value === null) {
$parts[] = "redis.call('HEXISTS',key .. ':a:' .. pk, ".$this->quoteValue($column).")==0";
......
......@@ -26,7 +26,6 @@ class Extension
* @var ViewRenderer
*/
protected $viewRenderer;
/**
* @var Smarty
*/
......
......@@ -32,7 +32,6 @@ class ViewRenderer extends BaseViewRenderer
* @var string the directory or path alias pointing to where Smarty compiled templates will be stored.
*/
public $compilePath = '@runtime/Smarty/compile';
/**
* @var array Add additional directories to Smarty's search path for plugins.
*/
......@@ -46,21 +45,20 @@ class ViewRenderer extends BaseViewRenderer
*/
public $widgets = ['functions' => [], 'blocks' => []];
/**
* @var Smarty The Smarty object used for rendering
*/
protected $smarty;
/**
* @var array additional Smarty options
* @see http://www.smarty.net/docs/en/api.variables.tpl
*/
public $options = [];
/**
* @var string extension class name
*/
public $extensionClass = '\yii\smarty\Extension';
/**
* @var Smarty The Smarty object used for rendering
*/
protected $smarty;
/**
* Instantiates and configures the Smarty object.
......
......@@ -73,9 +73,9 @@ class ColumnSchema extends Object
case 'string':
return is_resource($value) ? $value : (string) $value;
case 'integer':
return (integer) $value;
return (int) $value;
case 'boolean':
return (boolean) $value;
return (bool) $value;
case 'double':
return (double) $value;
}
......
......@@ -822,7 +822,7 @@ class QueryBuilder extends Object
if ($values instanceof Query) {
// sub-query
list($sql, $params) = $this->build($values, $params);
$column = (array)$column;
$column = (array) $column;
if (is_array($column)) {
foreach ($column as $i => $col) {
if (strpos($col, '(') === false) {
......
......@@ -43,6 +43,7 @@ class Schema extends Object
* @var Connection the Sphinx connection
*/
public $db;
/**
* @var array list of ALL index names in the Sphinx
*/
......
......@@ -159,7 +159,7 @@ class Extension extends \Twig_Extension
public function addUses($args)
{
foreach ((array)$args as $key => $value) {
foreach ((array) $args as $key => $value) {
$value = str_replace('/', '\\', $value);
if (is_int($key)) {
// namespace or class import
......
......@@ -14,6 +14,7 @@ Yii Framework 2 Change Log
- Bug #5682: The `asset` command would incorrectly combine CSS files when `UrlManager::linkAssets` is true (dmvslv)
- Bug #5702: Parenthesis should be automatically added to `Validator::whenClient` to avoid js error (mdmunir, qiangxue)
- Bug #5745: Gii and debug modules may cause 404 exception when the route contains dashes (qiangxue)
- Bug #5780: `QueryBuilder::batchInsert()` may cause "undefined index" error (qiangxue)
- Bug: Gii console command help information does not contain global options (qiangxue)
- Bug: `yii\web\UrlRule` was unable to create URLs for rules containing unicode characters (samdark)
- Enh #5223: Query builder now supports selecting sub-queries as columns (qiangxue)
......@@ -24,8 +25,10 @@ Yii Framework 2 Change Log
- Enh #5613: Added `--overwrite` option to Gii console command to support overwriting all files (motin, qiangxue)
- Enh #5646: Call `yii\base\ErrorHandler::unregister()` instead of `restore_*_handlers` directly (aivus)
- Enh #5735: Added `yii\bootstrap\Tabs::renderTabContent` to support manually rendering tab contents (RomeroMsk)
- Enh #5806: Allow `Html::encode()` to be used when the application is not started (qiangxue)
- Enh: `Console::confirm()` now uses `Console::stdout()` instead of `echo` to be consistent with all other functions (cebe)
- Chg #3630: `yii\db\Command::queryInternal()` is now protected (samdark)
- Chg #5508: Dropped the support for the `--append` option for the `fixture` command (qiangxue)
2.0.0 October 12, 2014
----------------------
......
......@@ -176,7 +176,7 @@ class Security extends Component
/**
* Encrypts data.
* @param string $data data to be encrypted
* @param bool $passwordBased set true to use password-based key derivation
* @param boolean $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](https://tools.ietf.org/html/rfc5869#section-3.2) for more details.
......@@ -217,7 +217,7 @@ class Security extends Component
/**
* Decrypts data.
* @param string $data encrypted data to be decrypted.
* @param bool $passwordBased set true to use password-based key derivation
* @param boolean $passwordBased set true to use password-based key derivation
* @param string $secret the decryption password or key
* @param string $info context/application specific information, @see encrypt()
* @return bool|string the decrypted data or false on authentication failure
......@@ -290,9 +290,9 @@ class Security extends Component
* @param string $info optional info to bind the derived key material to application-
* and context-specific information, e.g. a user ID or API version, see
* [RFC 5869](https://tools.ietf.org/html/rfc5869)
* @param int $length length of the output key in bytes. If 0, the output key is
* @param integer $length length of the output key in bytes. If 0, the output key is
* the length of the hash algorithm output.
* @throws InvalidParamException
* @throws InvalidParamException when HMAC generation fails.
* @return string the derived key
*/
public function hkdf($algo, $inputKey, $salt = null, $info = null, $length = 0)
......@@ -335,12 +335,12 @@ class Security extends Component
* @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256'
* @param string $password the source password
* @param string $salt the random salt
* @param int $iterations the number of iterations of the hash algorithm. Set as high as
* @param integer $iterations the number of iterations of the hash algorithm. Set as high as
* possible to hinder dictionary password attacks.
* @param int $length length of the output key in bytes. If 0, the output key is
* @param integer $length length of the output key in bytes. If 0, the output key is
* the length of the hash algorithm output.
* @throws InvalidParamException
* @return string the derived key
* @throws InvalidParamException when hash generation fails due to invalid params given.
*/
public function pbkdf2($algo, $password, $salt, $iterations, $length = 0)
{
......@@ -398,8 +398,8 @@ class Security extends Component
* cryptographic key.
* @param boolean $rawHash whether the generated hash value is in raw binary format. If false, lowercase
* hex digits will be generated.
* @throws InvalidConfigException
* @return string the data prefixed with the keyed hash
* @throws InvalidConfigException when HMAC generation fails.
* @see validateData()
* @see generateRandomKey()
* @see hkdf()
......@@ -425,8 +425,8 @@ class Security extends Component
* It indicates whether the hash value in the data is in binary format. If false, it means the hash value consists
* of lowercase hex digits only.
* hex digits will be generated.
* @throws InvalidConfigException
* @return string the real data with the hash stripped off. False if the data is tampered.
* @throws InvalidConfigException when HMAC generation fails.
* @see hashData()
*/
public function validateData($data, $key, $rawHash = false)
......@@ -455,8 +455,9 @@ class Security extends Component
* @see generateRandomString() if you need a string.
*
* @param integer $length the number of bytes to generate
* @throws Exception on failure.
* @return string the generated random bytes
* @throws InvalidConfigException if mcrypt extension is not installed.
* @throws Exception on failure.
*/
public function generateRandomKey($length = 32)
{
......@@ -475,8 +476,9 @@ class Security extends Component
* The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.
*
* @param integer $length the length of the key in characters
* @throws Exception Exception on failure.
* @return string the generated random key
* @throws InvalidConfigException if mcrypt extension is not installed.
* @throws Exception on failure.
*/
public function generateRandomString($length = 32)
{
......@@ -513,11 +515,11 @@ class Security extends Component
* therefore slows down a brute-force attack. For best protection against brute for attacks,
* set it to the highest value that is tolerable on production servers. The time taken to
* compute the hash doubles for every increment by one of $cost.
* @throws Exception on bad password parameter or cost parameter
* @throws InvalidConfigException
* @return string The password hash string. When [[passwordHashStrategy]] is set to 'crypt',
* the output is always 60 ASCII characters, when set to 'password_hash' the output length
* might increase in future versions of PHP (http://php.net/manual/en/function.password-hash.php)
* @throws Exception on bad password parameter or cost parameter.
* @throws InvalidConfigException when an unsupported password hash strategy is configured.
* @see validatePassword()
*/
public function generatePasswordHash($password, $cost = 13)
......@@ -548,7 +550,7 @@ class Security extends Component
* @param string $hash The hash to verify the password against.
* @return boolean whether the password is correct.
* @throws InvalidParamException on bad password or hash parameters or if crypt() with Blowfish hash is not available.
* @throws InvalidConfigException on unsupported password hash strategy is configured.
* @throws InvalidConfigException when an unsupported password hash strategy is configured.
* @see generatePasswordHash()
*/
public function validatePassword($password, $hash)
......@@ -589,11 +591,11 @@ class Security extends Component
*
* @param integer $cost the cost parameter
* @return string the random salt value.
* @throws InvalidParamException if the cost parameter is not between 4 and 31
* @throws InvalidParamException if the cost parameter is out of the range of 4 to 31.
*/
protected function generateSalt($cost = 13)
{
$cost = (int)$cost;
$cost = (int) $cost;
if ($cost < 4 || $cost > 31) {
throw new InvalidParamException('Cost must be between 4 and 31.');
}
......
......@@ -128,7 +128,7 @@ class SluggableBehavior extends AttributeBehavior
$isNewSlug = true;
if ($this->attribute !== null) {
$attributes = (array)$this->attribute;
$attributes = (array) $this->attribute;
/* @var $owner BaseActiveRecord */
$owner = $this->owner;
if (!$owner->getIsNewRecord() && !empty($owner->{$this->slugAttribute})) {
......
......@@ -65,7 +65,7 @@ class TagDependency extends Dependency
public static function invalidate($cache, $tags)
{
$keys = [];
foreach ((array)$tags as $tag) {
foreach ((array) $tags as $tag) {
$keys[] = $cache->buildKey([__CLASS__, $tag]);
}
static::touchKeys($cache, $keys);
......
......@@ -601,7 +601,7 @@ EOD;
/**
* Creates template of configuration file for [[actionCompress]].
* @param string $configFile output file name.
* @return int CLI exit code
* @return integer CLI exit code
* @throws \yii\console\Exception on failure.
*/
public function actionTemplate($configFile)
......
......@@ -302,7 +302,7 @@ abstract class BaseMigrateController extends Controller
*
* @param string $version the version at which the migration history should be marked.
* This can be either the timestamp or the full name of the migration.
* @return int CLI exit code
* @return integer CLI exit code
* @throws Exception if the version argument is invalid or the version cannot be found.
*/
public function actionMark($version)
......@@ -562,7 +562,7 @@ abstract class BaseMigrateController extends Controller
/**
* Migrates to the certain version.
* @param string $version name in the full format.
* @return int CLI exit code
* @return integer CLI exit code
* @throws Exception if the provided version cannot be found.
*/
protected function migrateToVersion($version)
......
......@@ -30,9 +30,6 @@ use yii\test\FixtureTrait;
* #load all fixtures except User
* yii fixture "*" -User
*
* #append fixtures to already loaded
* yii fixture User --append
*
* #load fixtures with different namespace.
* yii fixture/load User --namespace=alias\my\custom\namespace\goes\here
* ~~~
......@@ -55,11 +52,6 @@ class FixtureController extends Controller
*/
public $namespace = 'tests\unit\fixtures';
/**
* @var bool whether to append new fixture data to the existing ones.
* Defaults to false, meaning if there is any existing fixture data, it will be removed.
*/
public $append = false;
/**
* @var array global fixtures that should be applied when loading and unloading. By default it is set to `InitDbFixture`
* that disables and enables integrity check, so your data can be safely loaded.
*/
......@@ -74,7 +66,7 @@ class FixtureController extends Controller
public function options($actionID)
{
return array_merge(parent::options($actionID), [
'namespace', 'globalFixtures', 'append'
'namespace', 'globalFixtures'
]);
}
......@@ -87,10 +79,6 @@ class FixtureController extends Controller
* # any existing fixture data will be removed first
* yii fixture/load User UserProfile
*
* # load the fixture data specified by User and UserProfile.
* # the new fixture data will be appended to the existing one
* yii fixture/load --append User UserProfile
*
* # load all available fixtures found under 'tests\unit\fixtures'
* yii fixture/load "*"
*
......@@ -100,7 +88,7 @@ class FixtureController extends Controller
*
* @throws Exception if the specified fixture does not exist.
*/
public function actionLoad($fixturesInput)
public function actionLoad()
{
$fixturesInput = func_get_args();
$filtered = $this->filterFixtures($fixturesInput);
......@@ -147,12 +135,11 @@ class FixtureController extends Controller
$fixturesObjects = $this->createFixtures($fixtures);
if (!$this->append) {
$this->unloadFixtures($fixturesObjects);
}
$this->loadFixtures($fixturesObjects);
$this->notifyLoaded($fixtures);
return static::EXIT_CODE_NORMAL;
}
/**
......
......@@ -50,7 +50,7 @@ class MessageController extends Controller
* you may use this configuration file with the "extract" command.
*
* @param string $filePath output file name or alias.
* @return int CLI exit code
* @return integer CLI exit code
* @throws Exception on failure.
*/
public function actionConfig($filePath)
......
......@@ -152,7 +152,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface
}
if (empty($this->select) && !empty($this->join)) {
foreach ((array)$this->from as $alias => $table) {
foreach ((array) $this->from as $alias => $table) {
if (is_string($alias)) {
$this->select = ["$alias.*"];
} elseif (is_string($table)) {
......
......@@ -98,9 +98,9 @@ class ColumnSchema extends Object
case 'string':
return is_resource($value) ? $value : (string) $value;
case 'integer':
return (integer) $value;
return (int) $value;
case 'boolean':
return (boolean) $value;
return (bool) $value;
case 'double':
return (double) $value;
}
......
......@@ -531,7 +531,7 @@ class Connection extends Component
Yii::endProfile($token, __METHOD__);
} catch (\PDOException $e) {
Yii::endProfile($token, __METHOD__);
throw new Exception($e->getMessage(), $e->errorInfo, (int)$e->getCode(), $e);
throw new Exception($e->getMessage(), $e->errorInfo, (int) $e->getCode(), $e);
}
}
......
......@@ -189,7 +189,7 @@ class QueryBuilder extends \yii\base\Object
foreach ($rows as $row) {
$vs = [];
foreach ($row as $i => $value) {
if (!is_array($value) && isset($columnSchemas[$columns[$i]])) {
if (!is_array($value) && isset($columns[$i]) && isset($columnSchemas[$columns[$i]])) {
$value = $columnSchemas[$columns[$i]]->dbTypecast($value);
}
if (is_string($value)) {
......@@ -680,7 +680,7 @@ class QueryBuilder extends \yii\base\Object
}
// 0:join type, 1:join table, 2:on-condition (optional)
list ($joinType, $table) = $join;
$tables = $this->quoteTableNames((array)$table, $params);
$tables = $this->quoteTableNames((array) $table, $params);
$table = reset($tables);
$joins[$i] = "$joinType $table";
if (isset($join[2])) {
......@@ -1055,7 +1055,7 @@ class QueryBuilder extends \yii\base\Object
if ($values instanceof Query) {
// sub-query
list($sql, $params) = $this->build($values, $params);
$column = (array)$column;
$column = (array) $column;
if (is_array($column)) {
foreach ($column as $i => $col) {
if (strpos($col, '(') === false) {
......
......@@ -425,7 +425,7 @@ SQL;
$column->name = $info['column_name'];
$column->precision = $info['numeric_precision'];
$column->scale = $info['numeric_scale'];
$column->size = $info['size'] === null ? null : (int)$info['size'];
$column->size = $info['size'] === null ? null : (int) $info['size'];
if (isset($this->typeMap[$column->dbType])) {
$column->type = $this->typeMap[$column->dbType];
} else {
......
......@@ -150,7 +150,7 @@ class QueryBuilder extends \yii\db\QueryBuilder
*/
public function checkIntegrity($check = true, $schema = '', $table = '')
{
return 'PRAGMA foreign_keys='.(int)$check;
return 'PRAGMA foreign_keys='.(int) $check;
}
/**
......
......@@ -50,7 +50,7 @@ class CheckboxColumn extends Column
*/
public $checkboxOptions = [];
/**
* @var bool whether it is possible to select multiple rows. Defaults to `true`.
* @var boolean whether it is possible to select multiple rows. Defaults to `true`.
*/
public $multiple = true;
......
......@@ -459,7 +459,7 @@ class GridView extends BaseListView
} else {
$options = $this->rowOptions;
}
$options['data-key'] = is_array($key) ? json_encode($key) : (string)$key;
$options['data-key'] = is_array($key) ? json_encode($key) : (string) $key;
return Html::tag('tr', implode('', $cells), $options);
}
......
......@@ -332,7 +332,7 @@ class BaseConsole
/**
* Returns the length of the string without ANSI color codes.
* @param string $string the string to measure
* @return int the length of the string not counting ANSI format characters
* @return integer the length of the string not counting ANSI format characters
*/
public static function ansiStrlen($string) {
return mb_strlen(static::stripAnsiFormat($string));
......
......@@ -33,6 +33,7 @@ class BaseFileHelper
*/
public static $mimeMagicFile = '@yii/helpers/mimeTypes.php';
/**
* Normalizes a file/directory path.
* The normalization does the following work:
......
......@@ -93,7 +93,7 @@ class BaseHtml
*/
public static function encode($content, $doubleEncode = true)
{
return htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, Yii::$app->charset, $doubleEncode);
return htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, Yii::$app ? Yii::$app->charset : 'UTF-8', $doubleEncode);
}
/**
......@@ -636,7 +636,7 @@ class BaseHtml
*/
public static function radio($name, $checked = false, $options = [])
{
$options['checked'] = (boolean) $checked;
$options['checked'] = (bool) $checked;
$value = array_key_exists('value', $options) ? $options['value'] : '1';
if (isset($options['uncheck'])) {
// add a hidden field so that if the radio button is not selected, it still submits a value
......@@ -678,7 +678,7 @@ class BaseHtml
*/
public static function checkbox($name, $checked = false, $options = [])
{
$options['checked'] = (boolean) $checked;
$options['checked'] = (bool) $checked;
$value = array_key_exists('value', $options) ? $options['value'] : '1';
if (isset($options['uncheck'])) {
// add a hidden field so that if the checkbox is not selected, it still submits a value
......
......@@ -238,6 +238,7 @@ class BaseInflector
*/
public static $transliterator = 'Any-Latin; NFKD';
/**
* Converts a word to its plural form.
* Note that this is for English only!
......
......@@ -81,7 +81,7 @@ class BaseUrl
*/
public static function toRoute($route, $scheme = false)
{
$route = (array)$route;
$route = (array) $route;
$route[0] = static::normalizeRoute($route[0]);
if ($scheme) {
......
......@@ -1031,6 +1031,7 @@ class Formatter extends Component
* @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
* @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
* @return array [parameters for Yii::t containing formatted number, internal position of size unit]
* @throws InvalidParamException if the input value is not numeric.
*/
private function formatSizeNumber($value, $decimals, $options, $textOptions)
{
......
......@@ -57,7 +57,7 @@ class MysqlMutex extends DbMutex
*/
protected function acquireLock($name, $timeout = 0)
{
return (boolean) $this->db
return (bool) $this->db
->createCommand('SELECT GET_LOCK(:name, :timeout)', [':name' => $name, ':timeout' => $timeout])
->queryScalar();
}
......@@ -70,7 +70,7 @@ class MysqlMutex extends DbMutex
*/
protected function releaseLock($name)
{
return (boolean) $this->db
return (bool) $this->db
->createCommand('SELECT RELEASE_LOCK(:name)', [':name' => $name])
->queryScalar();
}
......
......@@ -349,7 +349,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' => (string)$userId]);
->andWhere(['a.user_id' => (string) $userId]);
$roles = [];
foreach ($query->all($this->db) as $row) {
......@@ -391,7 +391,7 @@ class DbManager extends BaseManager
$query = (new Query)->select('item_name')
->from($this->assignmentTable)
->where(['user_id' => (string)$userId]);
->where(['user_id' => (string) $userId]);
$childrenList = $this->getChildrenList();
$result = [];
......@@ -482,7 +482,7 @@ class DbManager extends BaseManager
}
$row = (new Query)->from($this->assignmentTable)
->where(['user_id' => (string)$userId, 'item_name' => $roleName])
->where(['user_id' => (string) $userId, 'item_name' => $roleName])
->one($this->db);
if ($row === false) {
......@@ -507,7 +507,7 @@ class DbManager extends BaseManager
$query = (new Query)
->from($this->assignmentTable)
->where(['user_id' => (string)$userId]);
->where(['user_id' => (string) $userId]);
$assignments = [];
foreach ($query->all($this->db) as $row) {
......@@ -644,7 +644,7 @@ class DbManager extends BaseManager
}
return $this->db->createCommand()
->delete($this->assignmentTable, ['user_id' => (string)$userId, 'item_name' => $role->name])
->delete($this->assignmentTable, ['user_id' => (string) $userId, 'item_name' => $role->name])
->execute() > 0;
}
......@@ -658,7 +658,7 @@ class DbManager extends BaseManager
}
return $this->db->createCommand()
->delete($this->assignmentTable, ['user_id' => (string)$userId])
->delete($this->assignmentTable, ['user_id' => (string) $userId])
->execute() > 0;
}
......
......@@ -199,7 +199,7 @@ class YiiRequirementChecker
return false;
}
return ((integer) $value == 1 || strtolower($value) == 'on');
return ((int) $value == 1 || strtolower($value) == 'on');
}
/**
......@@ -244,7 +244,7 @@ class YiiRequirementChecker
return 0;
}
if (is_numeric($verboseSize)) {
return (integer) $verboseSize;
return (int) $verboseSize;
}
$sizeUnit = trim($verboseSize, '0123456789');
$size = str_replace($sizeUnit, '', $verboseSize);
......
......@@ -33,7 +33,7 @@ class CreateAction extends Action
/**
* Creates a new model.
* @return \yii\db\ActiveRecordInterface the model newly created
* @throws \Exception if there is any error when creating the model
* @throws ServerErrorHttpException if there is any error when creating the model
*/
public function run()
{
......
......@@ -30,7 +30,7 @@ class UpdateAction extends Action
* Updates an existing model.
* @param string $id the primary key of the model.
* @return \yii\db\ActiveRecordInterface the model being updated
* @throws \Exception if there is any error when updating the model
* @throws ServerErrorHttpException if there is any error when updating the model
*/
public function run($id)
{
......
......@@ -56,7 +56,7 @@ class Controller extends \yii\base\Controller
* @param \yii\base\Action $action the action to be bound with parameters
* @param array $params the parameters to be bound to the action
* @return array the valid parameters that the action can run with.
* @throws HttpException if there are missing or invalid parameters.
* @throws BadRequestHttpException if there are missing or invalid parameters.
*/
public function bindActionParams($action, $params)
{
......
......@@ -173,7 +173,7 @@ class Request extends \yii\base\Request
/**
* 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.
* @throws HttpException if the request cannot be resolved.
* @throws NotFoundHttpException if the request cannot be resolved.
*/
public function resolve()
{
......
......@@ -84,7 +84,7 @@ class UrlRule extends Object implements UrlRuleInterface
*/
public $mode;
/**
* @var bool a value indicating if parameters should be url encoded.
* @var boolean a value indicating if parameters should be url encoded.
*/
public $encodeParams = true;
......
......@@ -157,6 +157,7 @@ class ActiveForm extends Widget
* @internal
*/
public $attributes = [];
/**
* @var ActiveField[] the ActiveField objects that are currently active
*/
......
......@@ -5,9 +5,9 @@ namespace yiiunit\data\ar;
/**
* Model representing type table
*
* @property int $int_col
* @property int $int_col2 DEFAULT 1
* @property int $smallint_col DEFAULT 1
* @property integer $int_col
* @property integer $int_col2 DEFAULT 1
* @property integer $smallint_col DEFAULT 1
* @property string $char_col
* @property string $char_col2 DEFAULT 'something'
* @property string $char_col3
......
......@@ -215,8 +215,8 @@ class SecurityTest extends TestCase
* @param string $hash
* @param string $password
* @param string $salt
* @param int $iterations
* @param int $length
* @param integer $iterations
* @param integer $length
* @param string $okm
*/
public function testPbkdf2($hash, $password, $salt, $iterations, $length, $okm)
......@@ -303,7 +303,7 @@ class SecurityTest extends TestCase
* @param string $ikm
* @param string $salt
* @param string $info
* @param int $l
* @param integer $l
* @param string $prk
* @param string $okm
*/
......
......@@ -13,7 +13,7 @@ function time()
/**
* Mock for the microtime() function for caching classes
* @param bool $float
* @param boolean $float
* @return float
*/
function microtime($float = false)
......
......@@ -159,20 +159,6 @@ class FixtureControllerTest extends TestCase
$this->assertEmpty(FixtureStorage::$firstFixtureData, 'first fixture data should not be loaded');
}
public function testAppendFixtureData()
{
$this->assertEmpty(FixtureStorage::$firstFixtureData, 'first fixture data should be unloaded');
$this->_fixtureController->actionLoad('First');
$this->assertCount(1, FixtureStorage::$firstFixtureData, 'first fixture data should be loaded');
$this->_fixtureController->append = true;
$this->_fixtureController->actionLoad('First');
$this->assertCount(2, FixtureStorage::$firstFixtureData, 'first fixture data should be appended to already existed one');
}
/**
* @expectedException \yii\console\Exception
*/
......
......@@ -189,7 +189,7 @@ class CommandTest extends DatabaseTestCase
}
$this->assertEquals($numericCol, $row['numeric_col']);
if ($this->driverName === 'mysql' || defined('HHVM_VERSION') && $this->driverName === 'sqlite') {
$this->assertEquals($boolCol, (int)$row['bool_col']);
$this->assertEquals($boolCol, (int) $row['bool_col']);
} else {
$this->assertEquals($boolCol, $row['bool_col']);
}
......
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