From 2d12e1a1d65be4653f7cf31c38ac4326a992cd79 Mon Sep 17 00:00:00 2001 From: "Novrian Y.F" Date: Tue, 16 May 2017 05:31:19 +0700 Subject: [PATCH 01/71] Translate "Generating Code with Gii" guide to Bahasa Indonesia (#14162) --- docs/guide-id/start-gii.md | 139 +++++++++++++++++++++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 docs/guide-id/start-gii.md diff --git a/docs/guide-id/start-gii.md b/docs/guide-id/start-gii.md new file mode 100644 index 0000000000..ca3b176b2c --- /dev/null +++ b/docs/guide-id/start-gii.md @@ -0,0 +1,139 @@ +Membuat Kode menggunakan Gii +======================== + +Bagian ini akan menjelaskan bagaimana cara menggunakan [Gii](https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md) untuk membuat kode secara otomatis +yang mengimplementasikan fitur-fitur yang bersifat umum dalam sebuah web site. Menggunakan Gii untuk membuat kode sesederhana menginput informasi yang sesuai per satu instruksi seperti yang diterangkan pada halaman web Gii. + +Sepanjang bagian ini, anda akan mempelajari bagaimana cara untuk: + +* Mengaktifkan Gii pada aplikasi anda, +* Menggunakan Gii untuk membuat _class ActiveRecord_ +* Menggunakan Gii untuk membuat kode yang mengoperasikan CRUD untuk database, +* Memodifikasi kode yang sudah dibuat oleh Gii. + + +Memulai Gii +------------ + +[Gii](https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md) telah disediakan oleh Yii sebagai [module](structure-modules.md). Anda dapat mengaktifkan Gii +dengan mengatur konfigurasi Gii pada properti [[yii\base\Application::modules|modules]] dari objek aplikasi. Tergantung bagaimana anda mengatur aplikasi anda, kode di bawah ini sudah disediakan pada file konfigurasi `config/web.php`: + +```php +$config = [ ... ]; + +if (YII_ENV_DEV) { + $config['bootstrap'][] = 'gii'; + $config['modules']['gii'] = [ + 'class' => 'yii\gii\Module', + ]; +} +``` + +Konfigurasi di atas menyatakan bahwa, ketika mode [development environment](concept-configurations.md#environment-constants) aktif, +maka aplikasi harus mengikutkan module yang bernama `gii`, dimana objek tersebut merupakan class [[yii\gii\Module]]. + +Jika anda melihat [_entry script_](structure-entry-scripts.md) `web/index.php` pada aplikasi anda, anda akan +menemukan baris dibawah ini, yang menyatakan secara explisit bahwa `YII_ENV_DEV` sama dengan `true`. + +```php +defined('YII_ENV') or define('YII_ENV', 'dev'); +``` + +Karna baris tersebut, aplikasi anda harusnya sudah berada pada mode _development_, dan secara otomatis mengaktifkan Gii karena konfigurasi sebelumnya. Anda dapat mengakses Gii melalui URL di bawah ini: + +``` +http://hostname/index.php?r=gii +``` + +> Note: Jika anda mengakses Gii melalui komputer diluar komputer localhost anda, secara default akses tidak akan diperbolehkan +> karna alasan keamanan. Anda dapat mengatur Gii untuk menambah alamat IP yang di perbolehkan seperti ini, +> +```php +'gii' => [ + 'class' => 'yii\gii\Module', + 'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'] // adjust this to your needs +], +``` + +![Gii](images/start-gii.png) + + +Membuat class _Active Record_ +--------------------------------- + +Untuk menggunakan Gii dalam membuat class Active Record, pilih "Model Generator" (dengan cara mengklik link pada halaman index Gii). Kemudian isi form dengan data berikut: + +* Table Name: `country` +* Model Class: `Country` + +![Pembuat Model](images/start-gii-model.png) + +Selanjutnya, klik pada tombol "Preview". Anda akan melihat `models/Country.php` pada daftar class yang akan dibuat. Anda bisa mengklik nama dari class tersebut untuk melihat isi kodenya. + +Pada saat menggunakan Gii, jika anda sudah membuat file dengan nama yang sama sebelumnya dan akan menimpanya, klik +tombol `diff` disebelah nama file untuk melihat perbedaan antara kode yang akan dibuat +dengan kode yang ada saat ini. + +![Preview Pembuat Model](images/start-gii-model-preview.png) + +Jika akan menimpa file yang sudah ada, centang kotak di sebelah tulisan "overwrite" dan kemudian klik tombol "Generate". Jika anda membuat file baru, anda cukup mengklik tombol "Generate". + +Selanjutnya, anda akan melihat +halaman konfirmasi yang memberitahui bahwa kode berhasil dibuat. Jika sebelumnya anda sudah mempunyai file yang sama, anda juga akan melihat pesan yang memberitahukan bahwa file tersebut sudah ditimpa dengan file yang baru. + + +Membuat CRUD +-------------------- + +_CRUD_ adalah _Create, Read, Update,_ dan _Delete_, yang merepresentasikan empat tugas umum yang melibatkan website secara umum. Untuk membuat _CRUD_ menggunakan Gii, pilih tombol "CRUD Generator" (dengan cara mengklik pada halaman index Gii). Untuk contoh "negara", isi form yang ditampilkan dengan data berikut: + +* Model Class: `app\models\Country` +* Search Model Class: `app\models\CountrySearch` +* Controller Class: `app\controllers\CountryController` + +![Pembuat CRUD](images/start-gii-crud.png) + +Selanjutnya, klik tombol "Preview". Anda akan melihat daftar file-file yang akan dibuat, seperti gambar dibawah ini. + +![Preview Pembuat CRUD](images/start-gii-crud-preview.png) + +Jika anda sebelumnya sudah membuat file `controllers/CountryController.php` dan +`views/country/index.php` (pada bagian bekerja dengan database), centang kotak "overwrite" untuk menimpa file tersebut. (File pada bagian bekerja dengan database tidak memiliki dukungan CRUD secara penuh.) + + +Mari kita coba +------------- + +Untuk melihat bagaimana proses kerjanya, gunakan browser anda untuk mengakses URL dibawah ini: + +``` +http://hostname/index.php?r=country%2Findex +``` + +Anda akan melihat tabel data yang menampilkan negara dari tabel pada database. Anda dapat mengurutkan tabel, +atau memfilter dengan menginput pencarian filter pada baris judul kolom. + +Disetiap negara yang tampil pada tabel, anda dapat memilih apakah akan melihat (_view_) detail, memperbaharui (_update_), atau menghapus (_delete_) data tersebut, +anda juga dapat mengklik tombol "Create Country" yang berada di atas tabel tersebut untuk menampilkan form untuk membuat data negara yang baru. + +![Tabel data negara](images/start-gii-country-grid.png) + +![Memperbaharui data negara](images/start-gii-country-update.png) + +Dibawah ini adalah daftar file yang dihasilkan oleh Gii, mungkin saja anda ingin melakukan observasi bagaimana fitur-fitur ini di implementasikan, +atau melakukan modifikasi terhadap file-file yang dihasilkan: + +* Controller: `controllers/CountryController.php` +* Model: `models/Country.php` dan `models/CountrySearch.php` +* View: `views/country/*.php` + +> Info: Gii di desain agar mudah di modifikasi, dan dikembangkan. Menggunakan Gii + dapat membuat pengembangan aplikasi anda menjadi lebih cepat. Untuk informasi lebih lanjut, silahkan melihat + bagian [Gii](https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md). + + +Penutup +------- + +Pada bagian ini, anda telah mengetahui bagaimana cara menggunakan Gii untuk membuat kode yang mengimplementasikan +fungsi CRUD secara lengkap dalam mengelola data yang tersimpan pada database. From 921147dca5aeab59901aed16e0a9113f48a0f8bb Mon Sep 17 00:00:00 2001 From: bscheshirwork Date: Tue, 16 May 2017 13:24:49 +0300 Subject: [PATCH 02/71] Fixes #14161, #14150: fixed primary table aliasing (include case manual set alias) in validators --- framework/validators/ExistValidator.php | 35 ++++++++++++++------ framework/validators/UniqueValidator.php | 42 +++++++++++++++--------- 2 files changed, 51 insertions(+), 26 deletions(-) diff --git a/framework/validators/ExistValidator.php b/framework/validators/ExistValidator.php index 7182a8e8cb..6e561fd1ca 100644 --- a/framework/validators/ExistValidator.php +++ b/framework/validators/ExistValidator.php @@ -10,6 +10,7 @@ namespace yii\validators; use Yii; use yii\base\InvalidConfigException; use yii\base\Model; +use yii\db\ActiveQuery; use yii\db\ActiveRecord; /** @@ -206,6 +207,29 @@ class ExistValidator extends Validator return $query; } + /** + * Returns conditions with alias + * @param ActiveQuery $query + * @param array $conditions array of condition, keys to be modified + * @param null|string $alias set empty string for no apply alias. Set null for apply primary table alias + * @return array + */ + private function applyTableAlias($query, $conditions, $alias = null) + { + if ($alias === null) { + $alias = array_keys($query->getTablesUsedInFrom())[0]; + } + $prefixedConditions = []; + foreach ($conditions as $columnName => $columnValue) { + $prefixedColumn = "{$alias}.[[" . preg_replace( + '/^' . preg_quote($alias) . '\.(.*)$/', + "$1", + $columnName) . "]]"; + $prefixedConditions[$prefixedColumn] = $columnValue; + } + return $prefixedConditions; + } + /** * Prefix conditions with aliases * @@ -218,15 +242,6 @@ class ExistValidator extends Validator $targetModelClass = $this->getTargetClass($model); /** @var ActiveRecord $targetModelClass */ - $query = $targetModelClass::find(); - $tableAliases = array_keys($query->getTablesUsedInFrom()); - $primaryTableAlias = $tableAliases[0]; - $prefixedConditions = []; - foreach ($conditions as $columnName => $columnValue) { - $prefixedColumn = "{$primaryTableAlias}.[[{$columnName}]]"; - $prefixedConditions[$prefixedColumn] = $columnValue; - } - - return $prefixedConditions; + return $this->applyTableAlias($targetModelClass::find(), $conditions); } } diff --git a/framework/validators/UniqueValidator.php b/framework/validators/UniqueValidator.php index 2c7731e3db..b834d6dfa2 100644 --- a/framework/validators/UniqueValidator.php +++ b/framework/validators/UniqueValidator.php @@ -173,12 +173,8 @@ class UniqueValidator extends Validator // if current $model is in the database already we can't use exists() if ($query instanceof \yii\db\ActiveQuery) { // only select primary key to optimize query - $primaryAlias = array_keys($query->getTablesUsedInFrom())[0]; - $columns = $targetClass::primaryKey(); - foreach($columns as $c => $column) { - $columns[$c] = "{$primaryAlias}.[[$column]]"; - } - $query->select($columns); + $columnsCondition = array_flip($targetClass::primaryKey()); + $query->select(array_flip($this->applyTableAlias($query, $columnsCondition))); } $models = $query->limit(2)->asArray()->all(); $n = count($models); @@ -279,6 +275,29 @@ class UniqueValidator extends Validator ]); } + /** + * Returns conditions with alias + * @param ActiveQuery $query + * @param array $conditions array of condition, keys to be modified + * @param null|string $alias set empty string for no apply alias. Set null for apply primary table alias + * @return array + */ + private function applyTableAlias($query, $conditions, $alias = null) + { + if ($alias === null) { + $alias = array_keys($query->getTablesUsedInFrom())[0]; + } + $prefixedConditions = []; + foreach ($conditions as $columnName => $columnValue) { + $prefixedColumn = "{$alias}.[[" . preg_replace( + '/^' . preg_quote($alias) . '\.(.*)$/', + "$1", + $columnName) . "]]"; + $prefixedConditions[$prefixedColumn] = $columnValue; + } + return $prefixedConditions; + } + /** * Prefix conditions with aliases * @@ -291,15 +310,6 @@ class UniqueValidator extends Validator $targetModelClass = $this->getTargetClass($model); /** @var ActiveRecord $targetModelClass */ - $query = $targetModelClass::find(); - $tableAliases = array_keys($query->getTablesUsedInFrom()); - $primaryTableAlias = $tableAliases[0]; - $prefixedConditions = []; - foreach ($conditions as $columnName => $columnValue) { - $prefixedColumn = "{$primaryTableAlias}.[[{$columnName}]]"; - $prefixedConditions[$prefixedColumn] = $columnValue; - } - - return $prefixedConditions; + return $this->applyTableAlias($targetModelClass::find(), $conditions); } } From 837322822863aa293cfae0361a7cb821b7ab22c8 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Wed, 17 May 2017 22:38:25 +0200 Subject: [PATCH 03/71] added namespace example to the autoload guide --- docs/guide/concept-autoloading.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/guide/concept-autoloading.md b/docs/guide/concept-autoloading.md index bba9ec71a2..fe5055bcca 100644 --- a/docs/guide/concept-autoloading.md +++ b/docs/guide/concept-autoloading.md @@ -37,6 +37,8 @@ the front-end tier has a root alias `@frontend`, while the back-end tier root al you may put the front-end classes under the namespace `frontend` while the back-end classes are under `backend`. This will allow these classes to be autoloaded by the Yii autoloader. +To add a custom namespace to the autoloader you need to define an alias for the base directory of the namespace using [[Yii::setAlias()]]. +For example to load classes in the `foo` namespace that are located in the `path/to/foo` directory you will call `Yii::setAlias('@foo', 'path/to/foo')`. Class Map --------- From 734f2aa71e564cd3de63731c4babbd691d510481 Mon Sep 17 00:00:00 2001 From: "Novrian Y.F" Date: Thu, 18 May 2017 22:06:29 +0700 Subject: [PATCH 04/71] Translate "Looking Ahead" guide to Bahasa Indonesia (#14177) --- docs/guide-id/start-looking-ahead.md | 35 ++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 docs/guide-id/start-looking-ahead.md diff --git a/docs/guide-id/start-looking-ahead.md b/docs/guide-id/start-looking-ahead.md new file mode 100644 index 0000000000..854a043871 --- /dev/null +++ b/docs/guide-id/start-looking-ahead.md @@ -0,0 +1,35 @@ +Menatap ke Depan +================ + +Jika anda membaca sepanjang bab "Mulai", sekarang anda sudah membuat aplikasi dengan Yii. Pada proses ini, anda sudah mempelajari bagaimana mengimplementasikan fitur-fitur umum +yang dibutuhkan, seperti mengambil data dari pengguna melalui form HTML, mengambil data dari database, dan +menampilkan data dengan halaman per halaman. Anda juga sudah mempelajari bagaimana menggunakan [Gii](https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md) untuk membuat +kode secara otomatis. Menggunakan Gii dalam membuat kode, mengubah tugas-tugas pengembangan web yang cukup banyak menjadi satu tugas sederhana, sesederhana mengisi form. + +Bagian ini akan merangkum bacaan Yii yang tersedia untuk membantu anda menjadi lebih produktif dalam menggunakan framework ini. + +* Dokumentasi + - [Panduan Definitif](http://www.yiiframework.com/doc-2.0/guide-README.html): + Sesuai dengan judulnya, panduan ini merincikan bagaimana Yii seharusnya bekerja dan menyediakan petunjuk umum + tentang menggunakan Yii. Panduan ini sangat-sangat penting, dan panduan ini yang harus anda baca + sebelum menulis kode Yii. + - [Referensi Class](http://www.yiiframework.com/doc-2.0/index.html): + Ini menjelaskan bagaimana menggunakan semua class yang disediakan oleh Yii. Pada umumnya anda akan menggunakan ini ketika anda sedang menulis + kode dan ingin memahami bagaimana penggunaan _class, method, property_. Sebaiknya anda membaca referensi class ini ketika anda memilik pemahaman dasar tentang seluruh bagian framework. + - [Artikel Wiki](http://www.yiiframework.com/wiki/?tag=yii2): + Artikel wiki ditulis oleh para pengguna Yii berdasarkan pengalaman pribadi masing-masing. Kebanyakan dari artikel ini ditulis + seperti layaknya panduan memasak, dan menunjukkan bagaimana menyelesaikan beberapa masalah dengan menggunakan Yii. Walaupun kualitas artikel-artikel ini + mungkin tidak selengkap Panduan Definitif, tetapi artikel ini terkadang lebih bermanfaat karna membahas topik yang cukup luas + dan mungkin mampu menyediakan solusi-solusi yang sederhana. + - [Buku](http://www.yiiframework.com/doc/) +* [Extensions](http://www.yiiframework.com/extensions/): + Yang harus dibanggakan adalah Yii memiliki ribuan library extension yang dibuat oleh pengguna yang dapat dipasang di aplikasi anda dengan mudah, dan akan membuat pengembangan aplikasi anda lebih mudah dan cepat. +* Komunitas + - Forum: + - IRC: Kanal #yii di freenode () + - Gitter: + - GitHub: + - Facebook: + - Twitter: + - LinkedIn: + - Stackoverflow: From fcfcdbdc34d57af74b2eb3a5d6da5a03b3dd90b1 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Tue, 23 May 2017 23:21:03 +0200 Subject: [PATCH 05/71] advanced example on filter validator fixes #4284 --- docs/guide/input-validation.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/docs/guide/input-validation.md b/docs/guide/input-validation.md index 0828c70efc..59bbbb56a6 100644 --- a/docs/guide/input-validation.md +++ b/docs/guide/input-validation.md @@ -215,6 +215,26 @@ data filtering. As you can see, these validation rules do not really validate the inputs. Instead, they will process the values and save them back to the attributes being validated. +A complete processing of user input is shown in the following example code, which will ensure only integer +values are stored in an attribute: + +```php +['age', 'trim'], +['age', 'default', 'value' => null], +['age', 'integer', 'integerOnly' => true, 'min' => 0], +['age', 'filter', 'filter' => 'intval', 'skipOnEmpty' => true], +``` + +The above code will perform the following operations on the input: + +1. Trim whitespace from the input value. +2. Make sure empty input is stored as `null` in the database; we differentiate between a value being "not set" + and the actual value `0`. If `null` is not allowed you can set another default value here. +3. Validate that the value is an integer greater than 0 if it is not empty. Normal validators have + [[yii\validators\Validator::$skipOnEmpty|$skipOnEmpty]] set to `true`. +4. Make sure the value is of type integer, e.g. casting a string `'42'` to integer `42`. + Here we set [[yii\validators\FilterValidator::$skipOnEmpty|$skipOnEmpty]] to `true`, which is `false` by default + on the [[yii\validators\FilterValidator|filter]] validator. ### Handling Empty Inputs From 273c33de87702b26e4dab78c8faccf5bfc71400c Mon Sep 17 00:00:00 2001 From: yyxx9988 Date: Wed, 24 May 2017 12:55:12 +0800 Subject: [PATCH 06/71] Simplified Chinese translation of filter validator (#14195) * Simplified Chinese Translation of filter validator * Using more specific words --- docs/guide-zh-CN/input-validation.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/guide-zh-CN/input-validation.md b/docs/guide-zh-CN/input-validation.md index 8a8816c510..75c6b0d753 100644 --- a/docs/guide-zh-CN/input-validation.md +++ b/docs/guide-zh-CN/input-validation.md @@ -160,6 +160,18 @@ return [ 如你所见,这些验证规则并不真的对输入数据进行任何验证。而是,对输入数据进行一些处理,然后把它们存回当前被验证的模型特性。 +下面的代码示例展示了对用户输入的完整处理,这将确保只将整数值存储在一个属性中: +```php +['age', 'trim'], +['age', 'default', 'value' => null], +['age', 'integer', 'integerOnly' => true, 'min' => 0], +['age', 'filter', 'filter' => 'intval', 'skipOnEmpty' => true], +``` +以上代码将对输入执行以下操作: +1. 从输入值中去除前后空白。 +2. 确保空输入在数据库中存储为`null`;我们区分 `未设置` 值和实际值为 `0` 之间的区别。如果值不允许为`null`,则可以在此处设置另一个默认值。 +3. 如果该值不为空,则验证该值是否为大于0的整数。大多数验证器的 [[yii\validators\Validator::$skipOnEmpty|$skipOnEmpty]] 属性都被设置为`true`。 +4. 确保该值为整数类型,例如将字符串 `'42'` 转换为整数 `42`。在这里,我们将 [[yii\validators\FilterValidator::$skipOnEmpty|$skipOnEmpty]] 设置为 `true`,默认情况下,在 [[yii\validators\FilterValidator|filter]] 验证器里这个属性是 `false`。 ### 处理空输入 From ac70262bfc917a60bac2526b2421781526e73dd3 Mon Sep 17 00:00:00 2001 From: corpsepk Date: Wed, 24 May 2017 18:59:35 +0300 Subject: [PATCH 07/71] Fixed typo in BaseFileHelper::findFiles() docs (#14200) [skip ci] --- framework/helpers/BaseFileHelper.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/helpers/BaseFileHelper.php b/framework/helpers/BaseFileHelper.php index 95ba9d779f..bdef6d6267 100644 --- a/framework/helpers/BaseFileHelper.php +++ b/framework/helpers/BaseFileHelper.php @@ -383,7 +383,7 @@ class BaseFileHelper * If the pattern does not contain a slash (`/`), it is treated as a shell glob pattern * and checked for a match against the pathname relative to `$dir`. * Otherwise, the pattern is treated as a shell glob suitable for consumption by `fnmatch(3)` - * `with the `FNM_PATHNAME` flag: wildcards in the pattern will not match a `/` in the pathname. + * with the `FNM_PATHNAME` flag: wildcards in the pattern will not match a `/` in the pathname. * For example, `views/*.php` matches `views/index.php` but not `views/controller/index.php`. * A leading slash matches the beginning of the pathname. For example, `/*.php` matches `index.php` but not `views/start/index.php`. * An optional prefix `!` which negates the pattern; any matching file excluded by a previous pattern will become included again. From 21a7a68e45dbda108490f96f14db21eb9c2099a3 Mon Sep 17 00:00:00 2001 From: Ilya Rogov Date: Thu, 25 May 2017 12:12:13 +0300 Subject: [PATCH 08/71] Add test coverage of yii\helpers\BaseArrayHelper (#14205) --- tests/framework/helpers/ArrayHelperTest.php | 32 +++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/tests/framework/helpers/ArrayHelperTest.php b/tests/framework/helpers/ArrayHelperTest.php index 282ae7f304..4d4e737f4f 100644 --- a/tests/framework/helpers/ArrayHelperTest.php +++ b/tests/framework/helpers/ArrayHelperTest.php @@ -51,6 +51,10 @@ class ArrayHelperTest extends TestCase public function testToArray() { + $dataArrayable = $this->getMock('yii\\base\\Arrayable'); + $dataArrayable->method('toArray')->willReturn([]); + $this->assertEquals([], ArrayHelper::toArray($dataArrayable)); + $this->assertEquals(['foo'], ArrayHelper::toArray('foo')); $object = new Post1; $this->assertEquals(get_object_vars($object), ArrayHelper::toArray($object)); $object = new Post2; @@ -187,6 +191,11 @@ class ArrayHelperTest extends TestCase public function testMultisort() { + // empty key + $dataEmpty = []; + ArrayHelper::multisort($dataEmpty, ''); + $this->assertEquals([], $dataEmpty); + // single key $array = [ ['name' => 'b', 'age' => 3], @@ -327,6 +336,24 @@ class ArrayHelperTest extends TestCase '- Enh: test3', ], $changelog); } + + /** + * @expectedException \yii\base\InvalidParamException + */ + public function testMultisortInvalidParamExceptionDirection() + { + $data = ['foo' => 'bar']; + ArrayHelper::multisort($data, ['foo'], []); + } + + /** + * @expectedException \yii\base\InvalidParamException + */ + public function testMultisortInvalidParamExceptionSortFlag() + { + $data = ['foo' => 'bar']; + ArrayHelper::multisort($data, ['foo'], ['foo'], []); + } public function testMerge() { @@ -358,6 +385,7 @@ class ArrayHelperTest extends TestCase 'features' => [ 'debug', ], + 'foo', ]; $result = ArrayHelper::merge($a, $b, $c); @@ -373,6 +401,7 @@ class ArrayHelperTest extends TestCase 'gii', 'debug', ], + 'foo', ]; $this->assertEquals($expected, $result); @@ -769,6 +798,7 @@ class ArrayHelperTest extends TestCase $this->assertFalse(ArrayHelper::isAssociative('test')); $this->assertFalse(ArrayHelper::isAssociative([])); $this->assertFalse(ArrayHelper::isAssociative([1, 2, 3])); + $this->assertFalse(ArrayHelper::isAssociative([1], false)); $this->assertTrue(ArrayHelper::isAssociative(['name' => 1, 'value' => 'test'])); $this->assertFalse(ArrayHelper::isAssociative(['name' => 1, 'value' => 'test', 3])); $this->assertTrue(ArrayHelper::isAssociative(['name' => 1, 'value' => 'test', 3], false)); @@ -781,6 +811,7 @@ class ArrayHelperTest extends TestCase $this->assertTrue(ArrayHelper::isIndexed([1, 2, 3])); $this->assertTrue(ArrayHelper::isIndexed([2 => 'a', 3 => 'b'])); $this->assertFalse(ArrayHelper::isIndexed([2 => 'a', 3 => 'b'], true)); + $this->assertFalse(ArrayHelper::isIndexed(['a' => 'b'], false)); } public function testHtmlEncode() @@ -961,5 +992,6 @@ class ArrayHelperTest extends TestCase ]); $this->assertEquals(ArrayHelper::filter($array, ['X']), []); $this->assertEquals(ArrayHelper::filter($array, ['X.Y']), []); + $this->assertEquals(ArrayHelper::filter($array, ['A.X']), []); } } From dbeadba0858718ad0746bcc8a4ac2ab4a683d817 Mon Sep 17 00:00:00 2001 From: "Novrian Y.F" Date: Thu, 25 May 2017 22:50:13 +0700 Subject: [PATCH 09/71] Translate some application structure guide to Bahasa Indonesia (#14209) [skip ci] * Add blocktypes.json file in Indonesian Guide * Translate "Application Structure Overview" to Bahasa Indonesia * Translate "Entry Script" guide to Bahasa Indonesia * Translate "Structure App - Application" to Bahasa Indonesia * Translate "Application Component" guide to Bahasa Indonesia * Add translators.json attribution in Indonesian Documentation --- docs/guide-id/blocktypes.json | 6 + .../structure-application-components.md | 119 ++++ docs/guide-id/structure-applications.md | 609 ++++++++++++++++++ docs/guide-id/structure-entry-scripts.md | 113 ++++ docs/guide-id/structure-overview.md | 26 + docs/guide-id/translators.json | 6 + 6 files changed, 879 insertions(+) create mode 100644 docs/guide-id/blocktypes.json create mode 100644 docs/guide-id/structure-application-components.md create mode 100644 docs/guide-id/structure-applications.md create mode 100644 docs/guide-id/structure-entry-scripts.md create mode 100644 docs/guide-id/structure-overview.md create mode 100644 docs/guide-id/translators.json diff --git a/docs/guide-id/blocktypes.json b/docs/guide-id/blocktypes.json new file mode 100644 index 0000000000..8a1c67352d --- /dev/null +++ b/docs/guide-id/blocktypes.json @@ -0,0 +1,6 @@ +{ + "Warning:": "Perhatian:", + "Note:": "Catatan:", + "Info:": "Info:", + "Tip:": "Tips:" +} diff --git a/docs/guide-id/structure-application-components.md b/docs/guide-id/structure-application-components.md new file mode 100644 index 0000000000..fdcbee58f5 --- /dev/null +++ b/docs/guide-id/structure-application-components.md @@ -0,0 +1,119 @@ +Komponen Aplikasi +================= + +Objek Aplikasi _(Application)_ adalah [service locators](concept-service-locator.md). Objek ini menampung seperangkat +apa yang kita sebut sebagai *komponen aplikasi* yang menyediakan berbagai layanan untuk menangani proses _request_. Sebagai contoh, +_component_ `urlManager` bertanggung jawab untuk menentukan _route_ dari _request_ menuju _controller_ yang sesuai; +_component_ `db` menyediakan layanan terkait database; dan sebagainya. + +Setiap _component_ aplikasi memiliki sebuah ID yang mengidentifikasi dirinya secara unik dengan _component_ aplikasi lainnya +di dalam aplikasi yang sama. Anda dapat mengakses _component_ aplikasi melalui _expression_ berikut ini: + +```php +\Yii::$app->componentID +``` + +Sebagai contoh, anda dapat menggunakan `\Yii::$app->db` untuk mengambil [[yii\db\Connection|koneksi ke DB]], +dan `\Yii::$app->cache` untuk mengambil [[yii\caching\Cache|cache utama]] yang terdaftar dalam aplikasi. + +Sebuah _component_ aplikasi dibuat pertama kali pada saat objek tersebut pertama diakses menggunakan _expression_ di atas. Pengaksesan +berikutnya akan mengembalikan objek _component_ yang sama. + +_Component_ aplikasi bisa merupakan objek apa saja. Anda dapat mendaftarkannya dengan mengatur +_property_ [[yii\base\Application::components]] pada [konfigurasi aplikasi](structure-applications.md#application-configurations). +Sebagai contoh, + +```php +[ + 'components' => [ + // mendaftarkan component "cache" menggunakan nama class + 'cache' => 'yii\caching\ApcCache', + + // mendaftaran component "db" menggunakan konfigurasi array + 'db' => [ + 'class' => 'yii\db\Connection', + 'dsn' => 'mysql:host=localhost;dbname=demo', + 'username' => 'root', + 'password' => '', + ], + + // mendaftaran component "search" menggunakan anonymous function + 'search' => function () { + return new app\components\SolrService; + }, + ], +] +``` + +> Info: Walaupun anda dapat mendaftarkan _component_ aplikasi sebanyak yang anda inginkan, anda harus bijaksana dalam melakukan hal ini. + _Component_ aplikasi seperti layaknya variabel global. Menggunakan _component_ aplikasi yang terlalu banyak dapat berpotensi + membuat kode anda menjadi rumit untuk diujicoba dan dikelola. Dalam banyak kasus, anda cukup membuat _component_ lokal + dan menggunakannya pada saat diperlukan. + + +## _Bootstrap Components_ + +Seperti yang disebutkan di atas, sebuah _component_ aplikasi akan dibuat ketika _component_ diakses pertama kali. +Jika tidak diakses sepanjang _request_ diproses, objek tersebut tidak akan dibuat. Terkadang, anda ingin +membuat objek _component_ aplikasi tersebut untuk setiap _request_, walaupun _component_ tersebut tidak diakses secara eksplisit. +Untuk melakukannya, anda dapat memasukkan ID _component_ tersebut ke _property_ [[yii\base\Application::bootstrap|bootstrap]] dari objek _Application_. + +Sebagai contoh, konfigurasi aplikasi di bawah ini memastikan bahwa objek _component_ `log` akan selalu dibuat disetiap _request_: + +```php +[ + 'bootstrap' => [ + 'log', + ], + 'components' => [ + 'log' => [ + // Konfigurasi untuk component "log" + ], + ], +] +``` + + +## _Component_ Aplikasi Inti + +Yii menentukan seperangkat _component_ aplikasi inti dengan ID tetap dan konfigurasi default. Sebagai contoh, +_component_ [[yii\web\Application::request|request]] digunakan untuk memperoleh informasi tentang +_request_ dari pengguna dan merubahnya menjadi [route](runtime-routing.md). _Component_ [[yii\base\Application::db|db]] +merepresentasikan sebuah koneksi ke database yang bisa anda gunakan untuk menjalankan _query_ ke database. +Dengan bantuan _component_ inti inilah maka aplikasi Yii bisa menangani _request_ dari pengguna. + +Dibawah ini adalah daftar dari _component_ aplikasi inti. Anda dapat mengatur dan memodifikasinya +seperti _component_ aplikasi pada umumnya. Ketika anda mengatur _component_ aplikasi inti, +jika anda tidak mendefinisikan _class_-nya, maka _class_ default yang akan digunakan. + +* [[yii\web\AssetManager|assetManager]]: mengatur bundel aset _(asset bundles)_ dan publikasi aset _(asset publishing)_. + Harap melihat bagian [Pengelolaan Aset](structure-assets.md) untuk informasi lebih lanjut. +* [[yii\db\Connection|db]]: merepresentasikan sebuah koneksi database yang bisa anda gunakan untuk melakukan _query_ ke database. + Sebagai catatan, ketika anda mengatur _component_ ini, anda harus menentukan nama _class_ dari _component_ dan _property_ lain dari + _component_ yang dibutuhkan, seperti [[yii\db\Connection::dsn]]. + Harap melihat bagian [Data Access Objects](db-dao.md) untuk informasi lebih lanjut. +* [[yii\base\Application::errorHandler|errorHandler]]: menangani error PHP dan _exception_. + Harap melihat bagian [Menangani Error](runtime-handling-errors.md) untuk informasi lebih lanjut. +* [[yii\i18n\Formatter|formatter]]: memformat data ketika data tersebut ditampilkan ke pengguna. Sebagai contoh, sebuah angka + mungkin ditampilkan menggunakan separator ribuan, dan tanggal mungkin diformat dalam format panjang. + Harap melihat bagian [Memformat Data](output-formatting.md) untuk informasi lebih lanjut. +* [[yii\i18n\I18N|i18n]]: mendukung penerjemahan dan format pesan _(message)_. + Harap melihat bagian [Internasionalisasi](tutorial-i18n.md) untuk informasi lebih lanjut. +* [[yii\log\Dispatcher|log]]: mengelola target log. + Harap melihat bagian [Log](runtime-logging.md) untuk informasi lebih lanjut. +* [[yii\swiftmailer\Mailer|mailer]]: mendukung pembuatan dan pengiriman email. + Harap melihat bagian [Mail](tutorial-mailing.md) untuk informasi lebih lanjut. +* [[yii\base\Application::response|response]]: merepresentasikan _response_ yang dikirimkan ke pengguna. + Harap melihat bagian [Response](runtime-responses.md) untuk informasi lebih lanjut. +* [[yii\base\Application::request|request]]: merepresentasikan _request_ yang diterima dari pengguna. + Harap melihat bagian [Request](runtime-requests.md) untuk informasi lebih lanjut. +* [[yii\web\Session|session]]: merepresentasikan informasi _session_. _Component_ ini hanya tersedia pada + objek [[yii\web\Application|Aplikasi Web]]. + Harap melihat bagian [Session dan Cookie](runtime-sessions-cookies.md) untuk informasi lebih lanjut. +* [[yii\web\UrlManager|urlManager]]: mendukung penguraian dan pembuatan URL. + Harap melihat bagian [Route dan Pembuatan URL](runtime-routing.md) untuk informasi lebih lanjut. +* [[yii\web\User|user]]: merepresentasikan informasi otentikasi dari pengguna. _Component_ ini hanya tersedia pada + objek [[yii\web\Application|Aplikasi Web]]. + Harap melihat bagian [Otentikasi](security-authentication.md) untuk informasi lebih lanjut. +* [[yii\web\View|view]]: mendukung proses _render view_. + Harap melihat bagian [View](structure-views.md) untuk informasi lebih lanjut. diff --git a/docs/guide-id/structure-applications.md b/docs/guide-id/structure-applications.md new file mode 100644 index 0000000000..ff0278e27b --- /dev/null +++ b/docs/guide-id/structure-applications.md @@ -0,0 +1,609 @@ +Aplikasi +======== + +Aplikasi _(Application)_ adalah objek yang mengelola semua struktur dan siklus dari sistem aplikasi Yii. +Setiap aplikasi sistem Yii mengandung satu objek aplikasi yang dibuat dalam +[skrip masuk](structure-entry-scripts.md) dan mampu diakses secara global melalui _expression_ `\Yii::$app`. + +> Info: Jika kami mengatakan "sebuah aplikasi", itu bisa diartikan sebagai sebuah objek aplikasi + atau sebuah sistem aplikasi, tergantung bagaimana konteksnya. + +Terdapat dua tipe aplikasi: [[yii\web\Application|Aplikasi Web]] dan +[[yii\console\Application|Aplikasi Konsol]]. Sesuai dengan namanya, yang pertama bertujuan untuk menangani +_web request_, sedangkan yang kedua menangani _request_ perintah pada konsol. + + +## Konfigurasi Aplikasi + +Ketika [skrip masuk](structure-entry-scripts.md) membuat objek aplikasi, objek ini akan mengambil dan memuat +sebuah [array konfigurasi](concept-configurations.md) dan menerapkannya pada objek aplikasi seperti berikut ini: + +```php +require(__DIR__ . '/../vendor/autoload.php'); +require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php'); + +// memuat konfigurasi aplikasi +$config = require(__DIR__ . '/../config/web.php'); + +// membuat objek aplikasi & menerapkan konfigurasi +(new yii\web\Application($config))->run(); +``` + +Seperti layaknya [konfigurasi](concept-configurations.md) normal, konfigurasi aplikasi menentukan bagaimana +proses inisialisasi _property_ dari objek aplikasi. Karena konfigurasi aplikasi pada umumnya +sangat kompleks, oleh karena itu konfigurasi tersebut di simpan dalam [file konfigurasi](concept-configurations.md#configuration-files), +seperti file `web.php` pada contoh di atas. + + +## _Property_ Aplikasi + +Terdapat cukup banyak _property_ aplikasi penting yang harus anda atur dalam konfigurasi aplikasi. +_Property_ ini secara khusus menjelaskan _environment_ yang sedang dijalankan oleh aplikasi. +Sebagai contoh, aplikasi ingin mengetahui bagaimana cara memuat [controller](structure-controllers.md), +dimana seharusnya aplikasi menyimpan file-file yang bersifat sementara _(temporary files)_, dll. Kami akan meringkas _property_ tersebut dibawah ini: + + +### _Property_ Wajib + +Dalam aplikasi apapun, anda harus menentukan setidaknya dua _property_:[[yii\base\Application::id|id]] +dan [[yii\base\Application::basePath|basePath]]. + + +#### [[yii\base\Application::id|id]] + +_Property_ [[yii\base\Application::id|id]] menentukan ID unik yang membedakan objek aplikasi +dengan yang lainnya. Ini pada umumnya digunakan secara programatik. Walaupun hal ini bukanlah sebuah keharusan, karena persoalan pertukaran informasi, +anda sangat direkomendasikan hanya menggunakan karakter alfanumerik ketika menentukan ID dari sebuah aplikasi. + + +#### [[yii\base\Application::basePath|basePath]] + +_Property_ [[yii\base\Application::basePath|basePath]] menentukan direktori _root_ dari sebuah aplikasi. +Yaitu direktori yang menyimpan semua sumber kode aplikasi sistem, dan aksesnya diproteksi dari luar. Didalam direktori ini, +anda akan melihat sub-direktori seperti `models`, `views`, dan `controllers` yang menyimpan sumber kode +dari pola MVC. + +Anda dapat menentukan _property_ [[yii\base\Application::basePath|basePath]] menggunakan _directory path_ +atau [path alias](concept-aliases.md). Kedua bentuk ini, direktori yang dimaksud harus benar-benar ada, jika tidak maka sebuah _exception_ +akan di-_throw_. _Path_ akan dinormalkan dengan memanggil _function_ `realpath()`. + +_Property_ [[yii\base\Application::basePath|basePath]] pada umumnya digunakan untuk mengambil _path_ penting +lainnya (contoh _runtime path_). Karna itulah _alias path_ yang dinamakan `@app` disediakan untuk merepresentasikan _path_ +ini. _Path-path_ lainnya boleh dipanggil menggunakan alias ini (contoh: `@app/runtime` untuk merujuk ke direktori runtime). + + +### _Property_ Penting + +_Property_ yang dijelaskan di sub-bagian ini cenderung harus di tentukan karena mereka digunakan secara berbeda +di lintas aplikasi. + + +#### [[yii\base\Application::aliases|Alias]] + +_Property_ ini memungkinkan anda untuk menentukan seperangkat [alias](concept-aliases.md) dalam bentuk _array_. +_Array Key_ merupakan nama alias, dan _Array Value_ adalah definisi path yang dimaksud. +Sebagai contoh: + +```php +[ + 'aliases' => [ + '@nama1' => 'path/menuju/ke/path1', + '@nama2' => 'path/menuju/ke/path2', + ], +] +``` + +Karna tersedianya _property_ ini, anda bisa menentukan beberapa alias pada konfigurasi aplikasi dibanding +dengan memanggil _method_ [[Yii::setAlias()]]. + + +#### [[yii\base\Application::bootstrap|bootstrap]] + +_Property_ ini merupakan _property_ yang bermanfaat. _Property_ ini memungkinkan anda untuk menentukan _component_ berbentuk _array_ yang harus +dijalankan dalam [[yii\base\Application::bootstrap()|proses bootstrap]]. +Sebagai contoh, jika anda memerintahkan sebuah [module](structure-modules.md) untuk merubah [pengaturan URL](runtime-routing.md), +anda dapat menyusun ID-nya sebagai elemen dari _property_ ini. + +Setiap _component_ yang terdaftar pada _property_ ini dapat ditentukan berdasarkan salah satu dari format berikut ini: + +- ID dari _Component_ aplikasi yang ditentukan melalui [component](#components), +- ID dari _module_ yang ditentukan melalui [module](#modules), +- Nama _class_, +- Konfigurasi _array_, +- _anonymous function_ yang membuat dan mengembalikan _(return)_ sebuah _component_. + +Sebagai contoh: + +```php +[ + 'bootstrap' => [ + // Component ID atau Module ID + 'demo', + + // Nama Class + 'app\components\Profiler', + + // Konfigurasi dalam bentuk array + [ + 'class' => 'app\components\Profiler', + 'level' => 3, + ], + + // anonymous function + function () { + return new app\components\Profiler(); + } + ], +] +``` + +> Info: Jika ID _module_ tersebut sama dengan ID _component_ aplikasi, _component_ aplikasi tersebut yang akan dipakai +> pada saat proses _boostrap_. Jika anda ingin menggunakan _module_, anda dapat menentukannya melalui _anonymous function_ +> seperti berikut ini: +> +> ```php +> [ +> function () { +> return Yii::$app->getModule('user'); +> }, +> ] +> ``` + + +Sepanjang proses _bootstrap_, setiap _component_ akan dibuat objeknya. Jika _class component_ +mengimplementasikan _method interface_ [[yii\base\BootstrapInterface]], _method_ [[yii\base\BootstrapInterface::bootstrap()|bootstrap()]] dari class tersebut +juga akan dipanggil. + +Salah satu contoh praktis lainnya adalah konfigurasi aplikasi untuk [Template Proyek Dasar](start-installation.md), +dimana _module_ `debug` dan `gii` ditentukan sebagai _component bootstrap_ ketika aplikasi sedang dijalankan +dalam mode pengembangan: + +```php +if (YII_ENV_DEV) { + // penyesuaian konfigurasi untuk environment 'dev' + $config['bootstrap'][] = 'debug'; + $config['modules']['debug'] = 'yii\debug\Module'; + + $config['bootstrap'][] = 'gii'; + $config['modules']['gii'] = 'yii\gii\Module'; +} +``` + +> Note: Menentukan terlalu banyak _component_ pada `bootstrap` akan menurunkan performa dari aplikasi anda, dikarenakan + _component_ yang sama tersebut harus dijalakan dalam setiap _request_. Jadi gunakanlah _component bootstrap_ dengan bijaksana. + +#### [[yii\web\Application::catchAll|catchAll]] + +_Property_ ini hanya dikenali oleh [[yii\web\Application|Web applications]]. _Property_ ini menentukan +sebuah [action dari controller](structure-controllers.md) yang ditugaskan menangani semua _request_ dari pengguna. _Property_ ini biasanya +digunakan ketika aplikasi dalam mode pemeliharaan _(maintenance)_ yang mengarahkan semua _request_ menuju satu _action_. + +Konfigurasinya yaitu sebuah _array_ dimana elemen pertama menentukan _route_ dari _action_. +Element lainnya _(sepasang key-value)_ menentukan parameter yang akan diteruskan ke _action_. Sebagai contoh: + +```php +[ + 'catchAll' => [ + 'offline/notice', + 'param1' => 'value1', + 'param2' => 'value2', + ], +] +``` + +> Info: Panel _Debug_ pada _development environment_ tidak akan berfungsi ketika _property_ ini diisi. + +#### [[yii\base\Application::components|components]] + +_Property_ ini adalah salah satu _property_ yang sangat penting. _Property_ ini memperbolehkan anda mendaftarkan beberapa _component_ +yang disebut [_component_ aplikasi](structure-application-components.md) yang bisa anda gunakan di tempat lain. Sebagai contoh: + +```php +[ + 'components' => [ + 'cache' => [ + 'class' => 'yii\caching\FileCache', + ], + 'user' => [ + 'identityClass' => 'app\models\User', + 'enableAutoLogin' => true, + ], + ], +] +``` + +Setiap _component_ aplikasi ditentukan dengan sepasang _key-value_ ke dalam _array_. _Key_ merepresentasikan ID _component_, +dimana _value_ merepresentasikan nama class dari _component_ atau [konfigurasi _array_](concept-configurations.md). + +Anda dapat mendaftaran _component_ apapun ke dalam objek aplikasi, dan nantinya _component_ tersebut dapat diakses secara global +menggunakan _expression_ `\Yii::$app->componentID`. + +Harap membaca bagian [_Component_ Aplikasi](structure-application-components.md) untuk penjelasan lebih lanjut. + + +#### [[yii\base\Application::controllerMap|controllerMap]] + +_Property_ ini memperbolehkan anda untuk melakukan _mapping_ sebuah ID _controller_ ke class _controller_ yang anda inginkan. Secara default, Yii melakukan mapping +ID _controller_ ke _class controller_ berdasarkan [kaidah yang ditentukan](#controllerNamespace) (Contoh: ID `post` akan di _mapping_ +ke `app\controllers\PostController`). Dengan menentukan _property_ ini, anda diperbolehkan untuk tidak mengikuti kaidah untuk +spesifik _controller_. Pada contoh dibawah ini, `account` akan di _mapping_ ke +`app\controllers\UserController`, sedangkan `article` akan di _mapping_ ke `app\controllers\PostController`. + +```php +[ + 'controllerMap' => [ + 'account' => 'app\controllers\UserController', + 'article' => [ + 'class' => 'app\controllers\PostController', + 'enableCsrfValidation' => false, + ], + ], +] +``` + +_Key array_ dari _property_ ini merepresentasikan ID _controller_, sedangkan _value_ merepresentasikan nama _class +yang dimaksud atau [konfigurasi _array_](concept-configurations.md). + + +#### [[yii\base\Application::controllerNamespace|controllerNamespace]] + +_Property_ ini menentukan _namespace_ default dimana _class controller_ tersebut harus dicari. Default ke +`app\controllers`. Jika ID _controller_ adalah `post`, secara kaidah, nama _class controller_-nya (tanpa +_namespace_) adalah `PostController`, dan `app\controllers\PostController` adalah nama class lengkapnya _(Fully Qualified Class Name)_. + +_class controller_ juga boleh disimpan dalam sub-direktori dari direktori yang dimaksud _namespace_ ini. +Sebagai contoh, jika ada ID _controller_ `admin/post`, nama class lengkap yang dimaksud adalah +`app\controllers\admin\PostController`. + +Sangatlah penting bahwa nama class lengkap dari _controller_ tersebut [bisa di-autoload](concept-autoloading.md) +dan _namespace_ dari _class controller_ anda cocok dengan nilai dari _property_ ini. Jika tidak, +anda akan melihat error "Halaman tidak ditemukan" ketika mengakses aplikasi. + +Jika saja anda tidak ingin mengikut kaidah-kaidah yang dijelaskan di atas, anda boleh menentukan _property_ +[controllerMap](#controllerMap). + + +#### [[yii\base\Application::language|language]] + +_Property_ ini menentukan bahasa apa yang seharusnya ditampilkan pada konten aplikasi ke pengguna. +Nilai default dari _property_ ini adalah `en`, yang merupakan Bahasa Inggris. Anda harus menentukan _property_ ini +jika aplikasi anda menyediakan konten dalam berbagai bahasa. + +Nilai dari _property_ ini menentukan banyak aspek dari [internasionalisasi](tutorial-i18n.md), +termasuk penerjemahan pesan, format tanggal, format penomoran, dll. Sebagai contoh, _widget_ [[yii\jui\DatePicker]] +akan menggunakan _property_ ini secara _default_ untuk menentukan bahasa apa yang digunakan pada kalender yang ditampilkan dan bagaimana +format tanggal pada kalender tersebut. + +Disarankan agar anda menentukan bahasa dalam format [Tag Bahasa IETF](http://en.wikipedia.org/wiki/IETF_language_tag). +Sebagai contoh, `en` berarti Bahasa Inggris, sedangkan `en-US` berarti Bahasa Inggris yang digunakan di Amerika Serikat. + +Informasi selengkapnya mengenai _property_ ini dapat dipelajari di bagian [Internasionalisasi](tutorial-i18n.md). + + +#### [[yii\base\Application::modules|modules]] + +_Property_ ini menentukan [module](structure-modules.md) apa yang akan digunakan oleh aplikasi. + +_Property_ ini ditentukan menggunakan _array_ dari _class class modul_ atau [konfigurasi _array_](concept-configurations.md) dimana _array key_ +merupakan ID dari _module_ tersebut. Berikut contohnya: + +```php +[ + 'modules' => [ + // modul "booking" dengan class module yang ditentukan + 'booking' => 'app\modules\booking\BookingModule', + + // modul "comment" yang ditentukan menggunakan konfigurasi array + 'comment' => [ + 'class' => 'app\modules\comment\CommentModule', + 'db' => 'db', + ], + ], +] +``` + +Silahkan melihat bagian [Modules](structure-modules.md) untuk informasi lebih lanjut. + + +#### [[yii\base\Application::name|name]] + +_Property_ ini menentukan nama aplikasi yang bisa ditampilkan ke pengguna. Berbeda dengan +_property_ [[yii\base\Application::id|id]], yang mengharuskan nilainya unik, nilai dari _property_ ini secara umum bertujuan untuk +keperluan tampilan saja; tidak perlu unik. + +Anda tidak perlu menentukan _property_ ini jika memang tidak ada kode anda yang akan menggunakannya. + + +#### [[yii\base\Application::params|params]] + +_Property_ ini menentukan parameter berbentuk _array_ yang bisa diakses secara global oleh aplikasi. Dibanding menuliskan secara manual +angka dan _string_ di kode anda, merupakan hal yang bagus jika anda menentukan hal tersebut sebagai parameter-parameter aplikasi +di satu tempat yang sama, dan menggunakannya pada tempat dimana dia dibutuhkan. Sebagai contoh, anda mungkin menentukan ukuran _thumbnail_ +sebagai parameter seperti contoh dibawah ini: + +```php +[ + 'params' => [ + 'thumbnail.size' => [128, 128], + ], +] +``` + +Kemudian, pada kode dimana anda akan menggunakan ukuran tersebut, anda cukup menggunakannya seperti kode dibawah ini: + +```php +$size = \Yii::$app->params['thumbnail.size']; +$width = \Yii::$app->params['thumbnail.size'][0]; +``` + +Jika di suatu hari anda memutuskan untuk mengganti ukuran _thumbnail_ tersebut, anda cukup menggantinya di konfigurasi aplikasi; +anda tidak perlu mengganti di semua kode dimana anda menggunakannya. + + +#### [[yii\base\Application::sourceLanguage|sourceLanguage]] + +_Property_ ini menentukan bahasa apa yang digunakan dalam menulis kode aplikasi. Nilai default-nya adalah `'en-US'`, +yang berarti Bahasa Inggris (Amerika Serikat). Anda sebaiknya menentukan _property_ ini jika teks pada kode anda bukanlah Bahasa Inggris. + +Seperti layaknya _property_ [language](#language), anda seharusnya menentukan _property_ ini dalam +format [Tag Bahasa IETF](http://en.wikipedia.org/wiki/IETF_language_tag). Sebagai contoh, `en` berarti Bahasa Inggris, +sedangkan `en-US` berarti Bahasa Inggris (Amerika Serikat). + +Untuk informasi lebih lanjut mengenai _property_ ini bisa anda pelajari pada bagian [Internasionalisasi](tutorial-i18n.md). + + +#### [[yii\base\Application::timeZone|timeZone]] + +_Property_ ini disediakan sebagai cara alternatif untuk menentukan zona waktu default dari _PHP runtime_. +Dengan menentukan _property_ ini, pada dasarnya anda memanggil _function_ PHP +[date_default_timezone_set()](http://php.net/manual/en/function.date-default-timezone-set.php). Sebagi contoh: + +```php +[ + 'timeZone' => 'America/Los_Angeles', +] +``` + + +#### [[yii\base\Application::version|version]] + +_Property_ ini menentukan versi dari aplikasi anda. Secara default nilainya adalah `'1.0'`. Anda tidak harus menentukan +_property_ ini jika tidak ada kode anda yang akan menggunakannya. + + +### _Property_ yang Bermanfaat + +_Property_ yang dijelaskan pada sub-bagian ini tidak secara umum digunakan karena nilai default-nya +sudah ditentukan berdasarkan kaidah-kaidah yang umum digunakan. Tetapi anda boleh menentukannya sendiri jikalau anda tidak ingin mengikuti kaidah-kaidah tersebut. + + +#### [[yii\base\Application::charset|charset]] + +_Property_ ini menentukan _charset_ yang digunakan oleh aplikasi. Nilai default-nya adalah `'UTF-8'`, dimana harus +digunakan sebisa mungkin pada kebanyakan aplikasi, kecuali anda sedang membangun sistem lama yang banyak menggunakan data yang tidak termasuk dalam _Unicode_. + + +#### [[yii\base\Application::defaultRoute|defaultRoute]] + +_Property_ ini menentukan [route](runtime-routing.md) yang harus aplikasi gunakan ketika sebuah _request_ +tidak memiliki _route_. _Route_ dapat terdiri dari ID _child module_, ID _controller_, dan/atau ID _action_. +Sebagai contoh, `help`, `post/create`, atau `admin/post/create`. Jika ID _action_ tidak diberikan, maka _property_ ini akan mengambil +nilai default yang ditentukan di [[yii\base\Controller::defaultAction]]. + +Untuk [[yii\web\Application|aplikasi Web]], nilai default dari _property_ ini adalah `'site'`, yang berarti +_controller_ `SiteController` dan default _action_-nya yang akan digunakan. Hasilnya, jika anda mengakses +aplikasi tanpa menentukan _route_ yang spesifik, maka akan menampilkan output dari `app\controllers\SiteController::actionIndex()`. + +Untuk [[yii\console\Application|aplikasi konsol]], nilai default-nya adalah `'help'`, yang berarti akan menggunakan +[[yii\console\controllers\HelpController::actionIndex()]] sebagai perintah utamanya. Hasilnya, jika anda menjalankan perintah `yii` +tanpa memasukkan argumen, maka akan menampilkan informasi bantuan penggunaan. + + +#### [[yii\base\Application::extensions|extensions]] + +_Property_ ini menentukan daftar dari [extension](structure-extensions.md) yang terpasang dan digunakan oleh aplikasi. +Secara default, akan mengambil _array_ yang dikembalikan oleh file `@vendor/yiisoft/extensions.php`. File `extensions.php` +dibuat dan dikelola secara otomatis jika anda menggunakan [Composer](https://getcomposer.org) untuk memasang _extensions_. +Secara umum, anda tidak perlu menentukan _property_ ini. + +Dalam kasus khusus jika anda ingin mengelola _extension_ secara manual, anda boleh menentukan _property_ ini seperti kode dibawah ini: + +```php +[ + 'extensions' => [ + [ + 'name' => 'extension name', + 'version' => 'version number', + 'bootstrap' => 'BootstrapClassName', // Tidak wajib, bisa juga berupa konfigurasi array + 'alias' => [ // Tidak Wajib + '@alias1' => 'to/path1', + '@alias2' => 'to/path2', + ], + ], + + // ... extension lain yang ditentukan seperti kode di atas ... + + ], +] +``` + +Seperti yang anda lihat, _property_ ini menerima spesifikasi _extension_ dalam bentuk _array_. Setiap _extension_ ditentukan dengan _array_ +yang terdiri dari elemen `name` dan `version`. Jika _extension_ harus dijalankan ketika proses [bootstrap](runtime-bootstrapping.md) +, elemen `bootstrap` dapat dispesifikasikan dengan nama _class bootstrap_-nya atau [konfigurasi array](concept-configurations.md) +. _Extension_ juga dapat menentukan beberapa [alias](concept-aliases.md). + + +#### [[yii\base\Application::layout|layout]] + +_Property_ ini menentukan nama dari default layout yang akan digunakan ketika me-render sebuah [view](structure-views.md). +Nilai default-nya adalah `'main'`, yang berarti akan menggunakan file layout `main.php` yang disimpan di [layout path](#layoutPath). +Jika kedua dari [layout path](#layoutPath) dan [view path](#viewPath) mengambil nilai default, +maka representasi file layoutnya adalah _path alias_ `@app/views/layouts/main.php`. + +Anda dapat menentukan nilai _property_ ini menjadi `false` jika anda ingin menonaktifkan layout secara default, tetapi anda seharusnya tidak memerlukannya. + + +#### [[yii\base\Application::layoutPath|layoutPath]] + +_Property_ ini menentukan path dimana sistem akan mencari file layout. Nilai default-nya adalah +sub-direktori `layouts` di dalam [view path](#viewPath). Jika [view path](#viewPath) mengambil +nilai defaultnya, maka path layout defaultnya adalah path alias `@app/views/layouts`. + +Anda dapat menentukannya sebagai direktori atau path [alias](concept-aliases.md). + + +#### [[yii\base\Application::runtimePath|runtimePath]] + +_Property_ ini menentukan dimana path file yang bersifat sementara, seperti file _log_ dan _cache_. +Nilai default-nya adalah direktori yang direpresentasikan oleh alias `@app/runtime`. + +Anda dapat menentukan nilainya dengan direktori atau path [alias](concept-aliases.md). Sebagai catatan, _path runtime_ wajib +memiliki akses tulis _(writeable)_ oleh _web server_ yang menjalankan aplikasi. Dan path tersebut sebaiknya diproteksi aksesnya dari +pengguna, karena file yang bersifat sementara di dalamnya mungkin mengandung informasi sensitif. + +Untuk menyederhanakan akses ke path ini, Yii sudah menentukan path alias dengan nama `@runtime`. + + +#### [[yii\base\Application::viewPath|viewPath]] + +_Property_ ini menentukan direktori _root_ dimana file-file _view_ akan disimpan. Nilai default-nya adalah direktori +yang di representasikan oleh alias `@app/views`. Anda dapat menentukan nilainya dengan direktori atau path [alias](concept-aliases.md). + + +#### [[yii\base\Application::vendorPath|vendorPath]] + +_Property_ ini menentukan direktori _vendor_ yang di kelola oleh [Composer](https://getcomposer.org). Direktori ini akan +menyimpan semua _library_ pihak ketiga yang digunakan oleh aplikasi anda, termasuk Yii _framework_. Nilai default-nya adalah +direktori yang di representasikan oleh alias `@app/vendor`. + +Anda dapat menentukan nilai _property_ ini dengan direktori atau path [alias](concept-aliases.md). Jika anda mengganti +nilai _property_ ini, pastikan anda juga menyesuaikan konfigurasi Composer. + +Untuk memudahkan akses ke path ini, Yii sudah menentukan path alias dengan nama `@vendor`. + + +#### [[yii\console\Application::enableCoreCommands|enableCoreCommands]] + +_Property_ ini hanya dikenali oleh [[yii\console\Application|console applications]]. _Property_ ini menentukan +apakah perintah inti yang dibawa oleh rilisan Yii harus diaktifkan. Nilai default-nya adalah `true`. + + +## _Event_ Aplikasi + +Sebuah objek _aplikasi_ menjalankan beberapa _event_ sepanjang siklus penanganan _request_. Anda dapat menempelkan penanganan _event_ +untuk _event-event_ ini di dalam konfigurasi aplikasi seperti di bawah ini: + +```php +[ + 'on beforeRequest' => function ($event) { + // ... + }, +] +``` + +Penggunaan dari sintaks `on eventName` akan dijelaskan pada bagian +[Konfigurasi](concept-configurations.md#configuration-format). + +Sebagai alternatif, anda dapat menempelkan penanganan _event_ ke dalam [proses bootstrap](runtime-bootstrapping.md) +setelah objek aplikasi telah dibuat. Sebagai contoh: + +```php +\Yii::$app->on(\yii\base\Application::EVENT_BEFORE_REQUEST, function ($event) { + // ... +}); +``` + +### [[yii\base\Application::EVENT_BEFORE_REQUEST|EVENT_BEFORE_REQUEST]] + +_Event_ ini dijalankan *sebelum* objek aplikasi menangani sebuah _request_. Nama _event_-nya adalah `beforeRequest`. + +Ketika _event_ ini dijalankan, objek aplikasi sudah dibuat dan di inisialisasi. Jadi waktu ini merupakan waktu yang tepat +untuk memasukkan kode anda melalui mekanisme _event_ untuk mengintervensi penanganan _request_. Sebagai contoh, +di penanganan _event_, anda dapat menentukan _property_ [[yii\base\Application::language]] secara dinamis berdasarkan parameter tertentu. + + +### [[yii\base\Application::EVENT_AFTER_REQUEST|EVENT_AFTER_REQUEST]] + +_Event_ ini dijalankan *setelah* objek aplikasi menyelesaikan penanganan sebuah _request_ tetapi *sebelum* mengirimkan _response_. + +Ketika _event_ ini dijalankan, proses penanganan _request_ sudah selesai dan anda dapat menggunakan kesempatan untuk melakukan beberapa tugas +untuk memodifikasi _request_ atau _response_. + +Sebagai catatan, _component_ [[yii\web\Response|response]] juga menjalankan beberapa _event_ pada saat mengirim +isi _response_ ke pengguna. _Event_ tersebut akan dijalankan *setelah* _event_ ini. + + +### [[yii\base\Application::EVENT_BEFORE_ACTION|EVENT_BEFORE_ACTION]] + +_Event_ ini dijalankan *sebelum* semua [action dari controller](structure-controllers.md) diproses. +Nama _event_-nya adalah `beforeAction`. + +Parameter _event_ merupakan objek dari [[yii\base\ActionEvent]]. Sebuah penanganan _event_ boleh menentukan +_property_ [[yii\base\ActionEvent::isValid]] menjadi `false` untuk memberhentikan proses jalannya _action_. +Sebagai contoh: + +```php +[ + 'on beforeAction' => function ($event) { + if (kondisi tertentu) { + $event->isValid = false; + } else { + } + }, +] +``` + +Sebagai catatan, _event_ `beforeAction` yang sama juga dijalankan oleh [module](structure-modules.md) +dan [controller](structure-controllers.md). _Event_ pada objek aplikasi yang menjalankan _event_ ini +untuk pertama kali, dilanjutkan oleh _module_ (jika ada), dan terakhir oleh _controller_. Jika sebuah penanganan _event_ +menentukan _property_ [[yii\base\ActionEvent::isValid]] menjadi `false`, semua _event_ selanjutnya TIDAK akan dijalankan. + + +### [[yii\base\Application::EVENT_AFTER_ACTION|EVENT_AFTER_ACTION]] + +_Event_ ini dijalankan *setelah* menjalankan seluruh [action dari controller](structure-controllers.md). +Nama _event_-nya adalah `afterAction`. + +Parameter _event_ adalah objek dari [[yii\base\ActionEvent]]. Menggunakan +_property_ [[yii\base\ActionEvent::result]], _method_ penanganan _event_ dapat mengakses atau merubah hasil dari _action_. +Sebagai contoh: + +```php +[ + 'on afterAction' => function ($event) { + if (kondisi tertentu) { + // rubah nilai dari $event->result + } else { + } + }, +] +``` + +Sebagai catatan, _event_ `afterAction` yang sama juga dijalankan oleh [module](structure-modules.md) +dan [controllers](structure-controllers.md). Objek-objek ini menjalankan _event_ ini sama seperti `beforeAction`, +hanya saja urutannya merupakan kebalikan dari urutan di _event_ `beforeAction`. _Controller_ adalah objek pertama yang menjalankan _event_ ini, +setelah itu _module_ (jika ada), dan terakhir di level aplikasi. + + +## Application Lifecycle + +![Siklus Aplikasi](images/application-lifecycle.png) + +Ketika [skrip masuk](structure-entry-scripts.md) sedang dijalankan untuk menangani sebuah _request_, +aplikasi akan melewati proses siklus dibawah ini: + +1. Skrip masuk mengambil konfigurasi aplikasi dalam bentuk array. +2. Skrip masuk membuat objek aplikasi: + * [[yii\base\Application::preInit()|preInit()]] dipanggil, dimana akan mengatur beberapa _property_ aplikasi + yang sangat penting seperti [[yii\base\Application::basePath|basePath]]. + * Mendaftarkan [[yii\base\Application::errorHandler|penanganan error]]. + * Mengatur _property_ aplikasi. + * [[yii\base\Application::init()|init()]] dipanggil, yang selanjutnya memanggil + [[yii\base\Application::bootstrap()|bootstrap()]] untuk menjalankan proses _bootstrap component_. +3. Skrip masuk memanggil [[yii\base\Application::run()]] untuk menjalankan aplikasi: + * Menjalankan _event_ [[yii\base\Application::EVENT_BEFORE_REQUEST|EVENT_BEFORE_REQUEST]]. + * Menangani _request_: memproses _request_ menjadi [route](runtime-routing.md) dan parameter-parameternya; + membuat objek _module_, _controller_, dan _action_ yang dispesifikasikan oleh _route_; dan menjalankan _action_. + * Menjalankan _event_ [[yii\base\Application::EVENT_AFTER_REQUEST|EVENT_AFTER_REQUEST]]. + * Mengirim _response_ ke pengguna. +4. Skrip masuk mendapatkan _status exit_ dari aplikasi dan menyelesaikan proses penanganan _request_. diff --git a/docs/guide-id/structure-entry-scripts.md b/docs/guide-id/structure-entry-scripts.md new file mode 100644 index 0000000000..f9facadf26 --- /dev/null +++ b/docs/guide-id/structure-entry-scripts.md @@ -0,0 +1,113 @@ +Skrip Masuk +=========== + +Skrip masuk adalah langkah pertama pada proses _bootstrap_ aplikasi. Dalam sebuah aplikasi (apakah +itu aplikasi web atau aplikasi konsol) memiliki satu skrip masuk. Pengguna mengirim _request_ ke +skrip masuk dimana skrip tersebut membangun objek aplikasi dan meneruskan _request_ ke objek tersebut. + +Skrip masuk untuk aplikasi web harus disimpan pada direktori yang dapat diakses dari web sehingga +dapat di akses oleh pengguna. Secara umum, skrip tersebut diberi nama `index.php`, tetapi boleh menggunakan nama lain, +selama _web server_ bisa mengakses skrip tersebut. + +Skrip masuk untuk aplikasi konsol pada umumnya disimpan di dalam [base path](structure-applications.md) +dari objek aplikasi dan diberi nama `yii` (dengan suffix `.php`). Skrip tersebut harus memiliki akses _execute_ +sehingga pengguna dapat menjalan aplikasi konsol menggunakan perintah `./yii [argument] [option]`. + +Skrip masuk umumnya mengerjakan tugas berikut ini: + +* Menentukan _global constant_; +* Mendaftarkan [autoloader Composer](https://getcomposer.org/doc/01-basic-usage.md#autoloading); +* Memasukkan file _class_ [[Yii]]; +* Mengambil konfigurasi aplikasi, dan memuatnya; +* Membuat dan mengatur objek [application](structure-applications.md); +* Memanggil [[yii\base\Application::run()]] untuk memproses _request_ yang diterima; + + +## Aplikasi Web + +Kode berikut ini adalah kode yang terdapat pada skrip masuk [Template Proyek Dasar](start-installation.md). + +```php +run(); +``` + + +## Aplikasi Konsol + +Demikian juga dengan aplikasi konsol, kode berikut ini adalah kode yang terdapat pada skrip masuk aplikasi konsol : + +```php +#!/usr/bin/env php +run(); +exit($exitCode); +``` + + +## Menentukan _Constant_ + +Skrip masuk adalah file yang tepat untuk menentukan _global constant_. Yii mengenali tiga _constant_ berikut ini: + +* `YII_DEBUG`: untuk menentukan apakah aplikasi sedang dalam mode _debug_. Pada saat mode _debug_, aplikasi + akan menyimpan informasi log lebih banyak, dan akan menampilkan detail error urutan pemanggilan _(error call stack)_ jika ada _exception_ yang di-_throw_. Alasan inilah, + kenapa mode _debug_ sebaiknya digunakan pada tahap pengembangan. Nilai _default_ dari `YII_DEBUG` adalah `false`. +* `YII_ENV`: untuk menentukan pada mode _environment_ manakah aplikasi ini dijalankan. _Constant_ ini akan dijelaskan lebih lanjut di + bagian [Konfigurasi](concept-configurations.md#environment-constants). + Nilai _default_ dari `YII_ENV` adalah `prod`, yang berarti aplikasi sedang dijalankan pada _production environment_. +* `YII_ENABLE_ERROR_HANDLER`: untuk menentukan apakah akan mengaktifkan penanganan eror yang disediakan oleh Yii. Nilai _default_ + dari _constant_ ini adalah `true`. + +Untuk menentukan _constant_, kita biasanya menggunakan kode berikut ini: + +```php +defined('YII_DEBUG') or define('YII_DEBUG', true); +``` + +kode di atas memiliki tujuan yang sama dengan kode berikut ini: + +```php +if (!defined('YII_DEBUG')) { + define('YII_DEBUG', true); +} +``` + +Jelas, kode yang pertama lah yang lebih ringkas dan lebih mudah untuk dimengerti. + +Penentuan _constant_ sebaiknya ditulis di baris-baris awal pada skrip masuk sehingga akan berfungsi +ketika file PHP lain akan dimasukkan _(include)_. diff --git a/docs/guide-id/structure-overview.md b/docs/guide-id/structure-overview.md new file mode 100644 index 0000000000..dc7807aaf8 --- /dev/null +++ b/docs/guide-id/structure-overview.md @@ -0,0 +1,26 @@ +Tinjauan +======== + +Aplikasi Yii diorganisir berdasarkan pola arsitektur [model-view-controller (MVC)](http://wikipedia.org/wiki/Model-view-controller). +[Model](structure-models.md) merepresentasikan data, pengaturan dan proses bisnis; [view](structure-views.md) +adalah output yang merepresentasikan model; dan [controller](structure-controllers.md) mengelola input dan merubahnya +menjadi perintah-perintah untuk [model](structure-models.md) dan [view](structure-views.md). + +Selain MVC, aplikasi Yii juga memiliki entitas berikut: + +* [entry scripts](structure-entry-scripts.md): Ini adalah skrip PHP yang diakses secara langsung oleh pengguna. + Ini bertugas untuk memulai siklus penanganan _request_. +* [applications](structure-applications.md): Ini adalah objek yang dapat diakses secara global, yang mengelola _component_ aplikasi + dan mengaturnya untuk memenuhi sebuah _request_. +* [application components](structure-application-components.md): Ini adalah objek-objek yang didaftarkan pada objek _application_ dan + menyediakan beragam layanan untuk memenuhi _request_. +* [modules](structure-modules.md): Ini adalah paket _(package)_ mandiri yang berisikan MVC lengkap. + Sebuah aplikasi boleh diistilahkan sebagai module-module yang telah diorganisir. +* [filters](structure-filters.md): Ini merepresentaikan kode yang mutlak untuk dijalakan sebelum dan sesudah + penanganan dari tiap-tiap _request_ yang dikelola oleh _controller_. +* [widgets](structure-widgets.md): Ini adalah objek-objek yang dapat ditanam kedalam [views](structure-views.md). Ini + dapat mengandung logika _controller_ dan dapat digunakan berulang-ulang pada _view_ yang berbeda. + +Diagram dibawah ini menunjukkan struktur statis dari sebuah aplikasi: + +![Struktur Statis Aplikasi](images/application-structure.png) diff --git a/docs/guide-id/translators.json b/docs/guide-id/translators.json new file mode 100644 index 0000000000..4dd60fa4d7 --- /dev/null +++ b/docs/guide-id/translators.json @@ -0,0 +1,6 @@ +[ + 'Misbahul D. Munir', + 'Muhammad Cahya', + 'Seto Kuslaksono', + 'Novrian Y.F.' +] From 9b8b965fcbb7caec7e65825c09db1bf315b7affb Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Fri, 26 May 2017 00:31:30 +0300 Subject: [PATCH 10/71] Fixes #14211: Fixed regression in Unique and Exist validators --- framework/db/ActiveQuery.php | 4 ++-- tests/framework/db/ActiveQueryTest.php | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/framework/db/ActiveQuery.php b/framework/db/ActiveQuery.php index 6940956b05..81c01bcd66 100644 --- a/framework/db/ActiveQuery.php +++ b/framework/db/ActiveQuery.php @@ -822,7 +822,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface .*? (?:['"`\]]|}}) | - \w+ + .*? ) (?: (?: @@ -835,7 +835,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface .*? (?:['"`\]]|}}) | - \w+ + .*? ) )? \s* diff --git a/tests/framework/db/ActiveQueryTest.php b/tests/framework/db/ActiveQueryTest.php index f8e4b0747b..792f896439 100644 --- a/tests/framework/db/ActiveQueryTest.php +++ b/tests/framework/db/ActiveQueryTest.php @@ -357,4 +357,19 @@ abstract class ActiveQueryTest extends DatabaseTestCase '{{%order_item}}' => '{{%order_item}}', ], $tables); } + + /** + * @see https://github.com/yiisoft/yii2/issues/14211 + */ + public function testGetTableAliasFromTableNameWithDatabase() + { + $query = new ActiveQuery(null); + $query->from = 'tickets.workflows'; + + $tables = $query->getTablesUsedInFrom(); + + $this->assertEquals([ + '{{tickets.workflows}}' => '{{tickets.workflows}}', + ], $tables); + } } From a1d4a237cb7847852e992255ff7347ab025a3293 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Fri, 26 May 2017 10:34:37 +0200 Subject: [PATCH 11/71] fixed indonesian translators.json file --- docs/guide-id/translators.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/guide-id/translators.json b/docs/guide-id/translators.json index 4dd60fa4d7..f9d6adf32f 100644 --- a/docs/guide-id/translators.json +++ b/docs/guide-id/translators.json @@ -1,6 +1,6 @@ [ - 'Misbahul D. Munir', - 'Muhammad Cahya', - 'Seto Kuslaksono', - 'Novrian Y.F.' + "Misbahul D. Munir", + "Muhammad Cahya", + "Seto Kuslaksono", + "Novrian Y.F." ] From d82b4fa03b4794caed1e8b7e1568e6038f1e5ca7 Mon Sep 17 00:00:00 2001 From: ihipop Date: Fri, 26 May 2017 16:58:19 +0800 Subject: [PATCH 12/71] add doc for issue #8420 #8420 --- docs/guide/db-query-builder.md | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/docs/guide/db-query-builder.md b/docs/guide/db-query-builder.md index de863a2a0e..c2453bce99 100644 --- a/docs/guide/db-query-builder.md +++ b/docs/guide/db-query-builder.md @@ -652,12 +652,11 @@ value which will be used as the index value for the current row. ### Batch Query -When working with large amounts of data, methods such as [[yii\db\Query::all()]] are not suitable -because they require loading all data into the memory. To keep the memory requirement low, Yii -provides the so-called batch query support. A batch query makes use of the data cursor and fetches -data in batches. +When working with large amounts of data, methods such as [[yii\db\Query::all()]] are not suitable because they require loading all data into the memory. To keep the memory requirement low, an `Unbuffered Query`](http://php.net/manual/en/mysqlinfo.concepts.buffering.php) is needed, in this mode, the MySQL Server will hold the result dataset cursor, waiting the client to get them every iter. **Unless all the dataset have been retrieved, no other query could be done through this connection, and the table may remains locked by MySQL and cannot be written to by other queries according to your actually logic. Please remember these drawbacks** -Batch query can be used like the following: + Yii provides the so-called batch query support. A batch query makes use of the data cursor and fetches data in batches, but the `$db` parameter is not the one that have `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` disabled before `version 2.0.11.2` by default, [and maybe won't ever](https://github.com/yiisoft/yii2/issues/8420), because there is no [`Silver Bullet` ](https://github.com/yiisoft/yii2/issues/8420#issuecomment-295679232) for this (still under discussion for now). Before PHP 5.6, the memory usage of buffered query in drivers does not count towards PHP's memory limit, but it takes the memory actually, it may eat all your servers' memory and get your PHP-FPM process killed. It is Suggested that you create a new connection to MySql Server , which the `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` is set to `false` at you need manually. + +Assume that you have a set a connection to `$unbuffered_db` which the `BUFFERED_QUERY` is off. Batch query can be used like the following at a low memory cost of PHP: ```php use yii\db\Query; @@ -666,27 +665,27 @@ $query = (new Query()) ->from('user') ->orderBy('id'); -foreach ($query->batch() as $users) { +foreach ($query->batch(100,$unbuffered_db) as $users) { // $users is an array of 100 or fewer rows from the user table } // or if you want to iterate the row one by one -foreach ($query->each() as $user) { +foreach ($query->each(100,$unbuffered_db) as $user) { // $user represents one row of data from the user table } ``` -The method [[yii\db\Query::batch()]] and [[yii\db\Query::each()]] return an [[yii\db\BatchQueryResult]] object -which implements the `Iterator` interface and thus can be used in the `foreach` construct. +The method [[yii\db\Query::batch()]] and [[yii\db\Query::each()]] return an [[yii\db\BatchQueryResult]] object which implements the `Iterator` interface and thus can be used in the `foreach` construct. During the first iteration, a SQL query is made to the database. Data are then fetched in batches in the remaining iterations. By default, the batch size is 100, meaning 100 rows of data are being fetched in each batch. You can change the batch size by passing the first parameter to the `batch()` or `each()` method. -Compared to the [[yii\db\Query::all()]], the batch query only loads 100 rows of data at a time into the memory. -If you process the data and then discard it right away, the batch query can help reduce memory usage. +Compared to the [[yii\db\Query::all()]], the batch query only loads 100 rows of data at a time into the memory in `UNBUFFERED_QUERY` mode. + +If `BUFFERED_QUERY` not configured properly, the `batch()` or `each()` method still hold all the dataset in memory, this is be done in the driver level. If you specify the query result to be indexed by some column via [[yii\db\Query::indexBy()]], the batch query -will still keep the proper index. For example, +will still keep the proper index. For example: ```php $query = (new \yii\db\Query()) From 6a9a255d06daa9f7821387baf91a49e6596c843a Mon Sep 17 00:00:00 2001 From: ihipop Date: Fri, 26 May 2017 17:13:52 +0800 Subject: [PATCH 13/71] typo --- docs/guide/db-query-builder.md | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/docs/guide/db-query-builder.md b/docs/guide/db-query-builder.md index c2453bce99..922e930b6b 100644 --- a/docs/guide/db-query-builder.md +++ b/docs/guide/db-query-builder.md @@ -652,9 +652,15 @@ value which will be used as the index value for the current row. ### Batch Query -When working with large amounts of data, methods such as [[yii\db\Query::all()]] are not suitable because they require loading all data into the memory. To keep the memory requirement low, an `Unbuffered Query`](http://php.net/manual/en/mysqlinfo.concepts.buffering.php) is needed, in this mode, the MySQL Server will hold the result dataset cursor, waiting the client to get them every iter. **Unless all the dataset have been retrieved, no other query could be done through this connection, and the table may remains locked by MySQL and cannot be written to by other queries according to your actually logic. Please remember these drawbacks** +When working with large amounts of data, methods such as [[yii\db\Query::all()]] are not suitable because they require loading all data into the memory. To keep the memory requirement low, +an [`Unbuffered Query`](http://php.net/manual/en/mysqlinfo.concepts.buffering.php) is needed, in this mode, the MySQL Server will hold the result dataset cursor, waiting the client to get them every iter. +**Unless all the dataset have been retrieved, no other query could be done through this connection, and the table may remains locked by MySQL and cannot be written to by other queries according to your +actually logic and design of your project. Please remember these drawbacks** - Yii provides the so-called batch query support. A batch query makes use of the data cursor and fetches data in batches, but the `$db` parameter is not the one that have `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` disabled before `version 2.0.11.2` by default, [and maybe won't ever](https://github.com/yiisoft/yii2/issues/8420), because there is no [`Silver Bullet` ](https://github.com/yiisoft/yii2/issues/8420#issuecomment-295679232) for this (still under discussion for now). Before PHP 5.6, the memory usage of buffered query in drivers does not count towards PHP's memory limit, but it takes the memory actually, it may eat all your servers' memory and get your PHP-FPM process killed. It is Suggested that you create a new connection to MySql Server , which the `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` is set to `false` at you need manually. +Yii provides the so-called batch query support. A batch query makes use of the data cursor and fetches data in batches, but the `$db` parameter is not the one that have `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` +disabled before `version 2.0.11.2` by default, [and maybe won't ever](https://github.com/yiisoft/yii2/issues/8420) (still under discussion for now), because there is no [`Silver Bullet` ](https://github.com/yiisoft/yii2/issues/8420#issuecomment-295679232) for this. +Before PHP 5.6, the memory usage of buffered query in drivers does not count towards PHP's memory limit, but it takes the memory actually, it may eat all your servers' memory and get your PHP-FPM +process killed. It is Suggested that you create a new connection to MySql Server , which the `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` is set to `false` at you need manually. Assume that you have a set a connection to `$unbuffered_db` which the `BUFFERED_QUERY` is off. Batch query can be used like the following at a low memory cost of PHP: @@ -680,12 +686,13 @@ During the first iteration, a SQL query is made to the database. Data are then f in the remaining iterations. By default, the batch size is 100, meaning 100 rows of data are being fetched in each batch. You can change the batch size by passing the first parameter to the `batch()` or `each()` method. -Compared to the [[yii\db\Query::all()]], the batch query only loads 100 rows of data at a time into the memory in `UNBUFFERED_QUERY` mode. +Compared to the [[yii\db\Query::all()]], the batch query only loads 100 rows of data at a time into the memory in `UNBUFFERED_QUERY` mode. -If `BUFFERED_QUERY` not configured properly, the `batch()` or `each()` method still hold all the dataset in memory, this is be done in the driver level. +If `BUFFERED_QUERY` not configured properly, the `batch()` or `each()` method still hold all the dataset in PDO's memory, this is be done in the driver level. -If you specify the query result to be indexed by some column via [[yii\db\Query::indexBy()]], the batch query -will still keep the proper index. For example: +If you specify the query result to be indexed by some column via [[yii\db\Query::indexBy()]], the batch query will still keep the proper index. + +For example: ```php $query = (new \yii\db\Query()) From d0a5372170d8bd04b3f8f3769d8c521cfa9fc1cb Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Fri, 26 May 2017 12:17:33 +0300 Subject: [PATCH 14/71] Adjusted text [skip ci] --- docs/guide/db-query-builder.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/docs/guide/db-query-builder.md b/docs/guide/db-query-builder.md index 922e930b6b..06a635264b 100644 --- a/docs/guide/db-query-builder.md +++ b/docs/guide/db-query-builder.md @@ -652,10 +652,9 @@ value which will be used as the index value for the current row. ### Batch Query -When working with large amounts of data, methods such as [[yii\db\Query::all()]] are not suitable because they require loading all data into the memory. To keep the memory requirement low, -an [`Unbuffered Query`](http://php.net/manual/en/mysqlinfo.concepts.buffering.php) is needed, in this mode, the MySQL Server will hold the result dataset cursor, waiting the client to get them every iter. -**Unless all the dataset have been retrieved, no other query could be done through this connection, and the table may remains locked by MySQL and cannot be written to by other queries according to your -actually logic and design of your project. Please remember these drawbacks** +When working with large amounts of data, methods such as [[yii\db\Query::all()]] are not suitable because they require loading all data into the memory. To keep the memory requirement low, an [`Unbuffered Query`](http://php.net/manual/en/mysqlinfo.concepts.buffering.php) is needed. In this mode, the MySQL Server will hold the result data set cursor, waiting the client to get data for every iteration. + +> Warning: Unless whole data set has been retrieved, no other query could be done through the same connection. The table may remains locked by MySQL and cannot be written to by other queries. Yii provides the so-called batch query support. A batch query makes use of the data cursor and fetches data in batches, but the `$db` parameter is not the one that have `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` disabled before `version 2.0.11.2` by default, [and maybe won't ever](https://github.com/yiisoft/yii2/issues/8420) (still under discussion for now), because there is no [`Silver Bullet` ](https://github.com/yiisoft/yii2/issues/8420#issuecomment-295679232) for this. From 2711eb572241b931550f41fbfcbf366929680058 Mon Sep 17 00:00:00 2001 From: ihipop Date: Fri, 26 May 2017 17:17:49 +0800 Subject: [PATCH 15/71] MySql -> MySQL typo --- docs/guide/db-query-builder.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guide/db-query-builder.md b/docs/guide/db-query-builder.md index 06a635264b..d8cc8c59ee 100644 --- a/docs/guide/db-query-builder.md +++ b/docs/guide/db-query-builder.md @@ -659,7 +659,7 @@ When working with large amounts of data, methods such as [[yii\db\Query::all()]] Yii provides the so-called batch query support. A batch query makes use of the data cursor and fetches data in batches, but the `$db` parameter is not the one that have `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` disabled before `version 2.0.11.2` by default, [and maybe won't ever](https://github.com/yiisoft/yii2/issues/8420) (still under discussion for now), because there is no [`Silver Bullet` ](https://github.com/yiisoft/yii2/issues/8420#issuecomment-295679232) for this. Before PHP 5.6, the memory usage of buffered query in drivers does not count towards PHP's memory limit, but it takes the memory actually, it may eat all your servers' memory and get your PHP-FPM -process killed. It is Suggested that you create a new connection to MySql Server , which the `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` is set to `false` at you need manually. +process killed. It is Suggested that you create a new connection to MySQL Server , which the `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` is set to `false` at your need manually. Assume that you have a set a connection to `$unbuffered_db` which the `BUFFERED_QUERY` is off. Batch query can be used like the following at a low memory cost of PHP: From c1e6e6da62c6b2dca8b762f2af06bc9e95be1e8f Mon Sep 17 00:00:00 2001 From: ihipop Date: Fri, 26 May 2017 17:33:07 +0800 Subject: [PATCH 16/71] Adjusted typo text [skip ci] --- docs/guide/db-query-builder.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/guide/db-query-builder.md b/docs/guide/db-query-builder.md index d8cc8c59ee..2fa84217d1 100644 --- a/docs/guide/db-query-builder.md +++ b/docs/guide/db-query-builder.md @@ -657,7 +657,7 @@ When working with large amounts of data, methods such as [[yii\db\Query::all()]] > Warning: Unless whole data set has been retrieved, no other query could be done through the same connection. The table may remains locked by MySQL and cannot be written to by other queries. Yii provides the so-called batch query support. A batch query makes use of the data cursor and fetches data in batches, but the `$db` parameter is not the one that have `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` -disabled before `version 2.0.11.2` by default, [and maybe won't ever](https://github.com/yiisoft/yii2/issues/8420) (still under discussion for now), because there is no [`Silver Bullet` ](https://github.com/yiisoft/yii2/issues/8420#issuecomment-295679232) for this. +disabled before `version 2.0.11.2` by default, [and maybe won't ever](https://github.com/yiisoft/yii2/issues/8420) (still under discussion for now), because there is [`No Silver Bullet`](https://github.com/yiisoft/yii2/issues/8420#issuecomment-295679232) for this. Before PHP 5.6, the memory usage of buffered query in drivers does not count towards PHP's memory limit, but it takes the memory actually, it may eat all your servers' memory and get your PHP-FPM process killed. It is Suggested that you create a new connection to MySQL Server , which the `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` is set to `false` at your need manually. @@ -687,7 +687,7 @@ You can change the batch size by passing the first parameter to the `batch()` or Compared to the [[yii\db\Query::all()]], the batch query only loads 100 rows of data at a time into the memory in `UNBUFFERED_QUERY` mode. -If `BUFFERED_QUERY` not configured properly, the `batch()` or `each()` method still hold all the dataset in PDO's memory, this is be done in the driver level. +If `BUFFERED_QUERY` not configured properly, the `batch()` or `each()` method still hold all the data set in PDO's memory, this is be done in the driver level. If you specify the query result to be indexed by some column via [[yii\db\Query::indexBy()]], the batch query will still keep the proper index. From 7c6620a65f65f8e7dd151d09c1918001e4e46712 Mon Sep 17 00:00:00 2001 From: Alex-Code Date: Wed, 29 Mar 2017 11:38:50 +0100 Subject: [PATCH 17/71] Fixes #13846: Fixed `Query::count()` issue with `orderBy` --- framework/CHANGELOG.md | 1 + framework/db/Query.php | 4 +++- tests/framework/db/QueryTest.php | 3 +++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 5a4d28ab54..d786d4e5ff 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -103,6 +103,7 @@ Yii Framework 2 Change Log - Bug #14072: Fixed a bug where `\yii\db\Command::createTable()`, `addForeignKey()`, `dropForeignKey()`, `addCommentOnColumn()`, and `dropCommentFromColumn()` weren't refreshing the table cache on `yii\db\Schema` (brandonkelly) - Bug #10305: Oracle SQL queries with `IN` condition and more than 1000 parameters are working now (silverfire) - Enh #14098: `yii\helpers\BaseFileHelper::normalizeOptions()` is now protected (brandonkelly) +- Bug #13846: Fixed `Query::count()` issue with `orderBy` (Alex-Code) 2.0.11.2 February 08, 2017 -------------------------- diff --git a/framework/db/Query.php b/framework/db/Query.php index b20a8b4cb0..a97b655669 100644 --- a/framework/db/Query.php +++ b/framework/db/Query.php @@ -413,18 +413,20 @@ class Query extends Component implements QueryInterface && empty($this->groupBy) && empty($this->having) && empty($this->union) - && empty($this->orderBy) ) { $select = $this->select; + $order = $this->orderBy; $limit = $this->limit; $offset = $this->offset; $this->select = [$selectExpression]; + $this->orderBy = null; $this->limit = null; $this->offset = null; $command = $this->createCommand($db); $this->select = $select; + $this->orderBy = $order; $this->limit = $limit; $this->offset = $offset; diff --git a/tests/framework/db/QueryTest.php b/tests/framework/db/QueryTest.php index 1275a3f391..50d038a43f 100644 --- a/tests/framework/db/QueryTest.php +++ b/tests/framework/db/QueryTest.php @@ -340,6 +340,9 @@ abstract class QueryTest extends DatabaseTestCase // testing that orderBy() should be ignored here as it does not affect the count anyway. $count = (new Query)->from('customer')->orderBy('status')->count('*', $db); $this->assertEquals(3, $count); + + $count = (new Query)->from('customer')->orderBy('id')->limit(1)->count('*', $db); + $this->assertEquals(3, $count); } /** From 49ab20139c256237efc79e559a73b91ba9b65f0e Mon Sep 17 00:00:00 2001 From: viwek Date: Sun, 28 May 2017 18:15:36 +0545 Subject: [PATCH 18/71] Inserted missing * on line 972 (#14224) [skip ci] --- framework/db/BaseActiveRecord.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/db/BaseActiveRecord.php b/framework/db/BaseActiveRecord.php index 5ad00331eb..b302ba06b5 100644 --- a/framework/db/BaseActiveRecord.php +++ b/framework/db/BaseActiveRecord.php @@ -969,7 +969,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface * } * * // ...custom code here... - return true; + * return true; * } * ``` * From b07f2018de7f2badd5c1b2230a64e3dd9b6be706 Mon Sep 17 00:00:00 2001 From: Ilya Rogov Date: Sun, 28 May 2017 15:31:42 +0300 Subject: [PATCH 19/71] Add test coverage of yii\helpers\BaseMarkdown (#14223) --- tests/framework/helpers/MarkdownTest.php | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/framework/helpers/MarkdownTest.php b/tests/framework/helpers/MarkdownTest.php index 3e993609f1..847884ff22 100644 --- a/tests/framework/helpers/MarkdownTest.php +++ b/tests/framework/helpers/MarkdownTest.php @@ -36,4 +36,20 @@ TEXT; $this->assertNotEquals(Markdown::process($text), Markdown::process($text, 'original')); $this->assertEquals(Markdown::process($text), Markdown::process($text, 'gfm-comment')); } + + /** + * @expectedException \yii\base\InvalidParamException + * @expectedExceptionMessage Markdown flavor 'undefined' is not defined. + */ + public function testProcessInvalidParamException() + { + Markdown::process('foo', 'undefined'); + } + + public function testProcessParagraph() + { + $actual = Markdown::processParagraph('foo'); + $expected = 'foo'; + $this->assertEquals($expected, $actual); + } } From 0d9cd0ccd72a080ce52c4f2d5ccd8d15060b3a42 Mon Sep 17 00:00:00 2001 From: Ilya Rogov Date: Sun, 28 May 2017 15:32:41 +0300 Subject: [PATCH 20/71] Add test coverage of yii\helpers\BaseJson (#14217) --- tests/framework/helpers/JsonTest.php | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/tests/framework/helpers/JsonTest.php b/tests/framework/helpers/JsonTest.php index 9788858a4e..4222a3ae16 100644 --- a/tests/framework/helpers/JsonTest.php +++ b/tests/framework/helpers/JsonTest.php @@ -24,6 +24,12 @@ class JsonTest extends TestCase public function testEncode() { + // Arrayable data encoding + $dataArrayable = $this->getMock('yii\\base\\Arrayable'); + $dataArrayable->method('toArray')->willReturn([]); + $actual = Json::encode($dataArrayable); + $this->assertSame('{}', $actual); + // basic data encoding $data = '1'; $this->assertSame('"1"', Json::encode($data)); @@ -145,6 +151,11 @@ class JsonTest extends TestCase public function testDecode() { + // empty value + $json = ''; + $actual = Json::decode($json); + $this->assertSame(null, $actual); + // basic data decoding $json = '"1"'; $this->assertSame('1', Json::decode($json)); @@ -158,6 +169,16 @@ class JsonTest extends TestCase $this->expectException('yii\base\InvalidParamException'); Json::decode($json); } + + + /** + * @expectedException \yii\base\InvalidParamException + * @expectedExceptionMessage Invalid JSON data. + */ + public function testDecodeInvalidParamException() + { + Json::decode([]); + } public function testHandleJsonError() { @@ -193,4 +214,4 @@ class JsonModel extends Model implements \JsonSerializable { return $this->data; } -} \ No newline at end of file +} From 974a1eeb483496b6914af6366ff23d02172b8cb0 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Sun, 28 May 2017 15:48:27 +0300 Subject: [PATCH 21/71] Adjusted text [skip ci] --- docs/guide/db-query-builder.md | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/docs/guide/db-query-builder.md b/docs/guide/db-query-builder.md index 2fa84217d1..23861e4766 100644 --- a/docs/guide/db-query-builder.md +++ b/docs/guide/db-query-builder.md @@ -652,17 +652,12 @@ value which will be used as the index value for the current row. ### Batch Query -When working with large amounts of data, methods such as [[yii\db\Query::all()]] are not suitable because they require loading all data into the memory. To keep the memory requirement low, an [`Unbuffered Query`](http://php.net/manual/en/mysqlinfo.concepts.buffering.php) is needed. In this mode, the MySQL Server will hold the result data set cursor, waiting the client to get data for every iteration. - -> Warning: Unless whole data set has been retrieved, no other query could be done through the same connection. The table may remains locked by MySQL and cannot be written to by other queries. - -Yii provides the so-called batch query support. A batch query makes use of the data cursor and fetches data in batches, but the `$db` parameter is not the one that have `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` -disabled before `version 2.0.11.2` by default, [and maybe won't ever](https://github.com/yiisoft/yii2/issues/8420) (still under discussion for now), because there is [`No Silver Bullet`](https://github.com/yiisoft/yii2/issues/8420#issuecomment-295679232) for this. -Before PHP 5.6, the memory usage of buffered query in drivers does not count towards PHP's memory limit, but it takes the memory actually, it may eat all your servers' memory and get your PHP-FPM -process killed. It is Suggested that you create a new connection to MySQL Server , which the `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` is set to `false` at your need manually. - -Assume that you have a set a connection to `$unbuffered_db` which the `BUFFERED_QUERY` is off. Batch query can be used like the following at a low memory cost of PHP: +When working with large amounts of data, methods such as [[yii\db\Query::all()]] are not suitable because they require loading all data into the memory. To solve the issue Yii provides batch query support. Server holds the result data set cursor, waiting the client to get data for every iteration. +> Warning: In order to use it and keep the memory requirement low in case of using MySQL, an [`Unbuffered Query`](http://php.net/manual/en/mysqlinfo.concepts.buffering.php) should be used by setting connection `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` to `false`. Unless whole data set has been retrieved, no other query could be done through the same connection. The table may remain locked by MySQL and cannot be written to by other queries. Thus, new connection should be created for this purpose. +> +> Assume that you have set up a connection to `$unbuffered_db` with `BUFFERED_QUERY` set to `false`. Batch query can be used like the following at a low memory cost of PHP: +> ```php use yii\db\Query; @@ -670,24 +665,25 @@ $query = (new Query()) ->from('user') ->orderBy('id'); -foreach ($query->batch(100,$unbuffered_db) as $users) { +foreach ($query->batch(100, $unbuffered_db) as $users) { // $users is an array of 100 or fewer rows from the user table } // or if you want to iterate the row one by one -foreach ($query->each(100,$unbuffered_db) as $user) { +foreach ($query->each(100, $unbuffered_db) as $user) { // $user represents one row of data from the user table } ``` + The method [[yii\db\Query::batch()]] and [[yii\db\Query::each()]] return an [[yii\db\BatchQueryResult]] object which implements the `Iterator` interface and thus can be used in the `foreach` construct. During the first iteration, a SQL query is made to the database. Data are then fetched in batches in the remaining iterations. By default, the batch size is 100, meaning 100 rows of data are being fetched in each batch. You can change the batch size by passing the first parameter to the `batch()` or `each()` method. -Compared to the [[yii\db\Query::all()]], the batch query only loads 100 rows of data at a time into the memory in `UNBUFFERED_QUERY` mode. +Compared to the [[yii\db\Query::all()]], the batch query only loads 100 rows of data at a time into the memory. -If `BUFFERED_QUERY` not configured properly, the `batch()` or `each()` method still hold all the data set in PDO's memory, this is be done in the driver level. +> Warning: If `BUFFERED_QUERY` is not configured properly, the `batch()` or `each()` method still hold all the data set in PDO's memory, this is done at the driver level. If you specify the query result to be indexed by some column via [[yii\db\Query::indexBy()]], the batch query will still keep the proper index. From f98e2604936309c0e78a4674b054d53f1ec600b9 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Sun, 28 May 2017 15:51:31 +0300 Subject: [PATCH 22/71] Adjusted text [skip ci] --- docs/guide/db-query-builder.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/guide/db-query-builder.md b/docs/guide/db-query-builder.md index 23861e4766..43fc6bd373 100644 --- a/docs/guide/db-query-builder.md +++ b/docs/guide/db-query-builder.md @@ -655,9 +655,9 @@ value which will be used as the index value for the current row. When working with large amounts of data, methods such as [[yii\db\Query::all()]] are not suitable because they require loading all data into the memory. To solve the issue Yii provides batch query support. Server holds the result data set cursor, waiting the client to get data for every iteration. > Warning: In order to use it and keep the memory requirement low in case of using MySQL, an [`Unbuffered Query`](http://php.net/manual/en/mysqlinfo.concepts.buffering.php) should be used by setting connection `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` to `false`. Unless whole data set has been retrieved, no other query could be done through the same connection. The table may remain locked by MySQL and cannot be written to by other queries. Thus, new connection should be created for this purpose. -> -> Assume that you have set up a connection to `$unbuffered_db` with `BUFFERED_QUERY` set to `false`. Batch query can be used like the following at a low memory cost of PHP: -> + +Batch query can be used like the following: + ```php use yii\db\Query; @@ -665,16 +665,18 @@ $query = (new Query()) ->from('user') ->orderBy('id'); -foreach ($query->batch(100, $unbuffered_db) as $users) { +foreach ($query->batch(100) as $users) { // $users is an array of 100 or fewer rows from the user table } // or if you want to iterate the row one by one -foreach ($query->each(100, $unbuffered_db) as $user) { +foreach ($query->each(100) as $user) { // $user represents one row of data from the user table } ``` +> Note: In case of MySQL an instance of unbuffered connection should be passed to the second argument of `batch()` calls. +Assuming that you have set up a connection to `$unbuffered_db` with `BUFFERED_QUERY` set to `false`, it would be `batch(100, $unbuffered_db)`. The method [[yii\db\Query::batch()]] and [[yii\db\Query::each()]] return an [[yii\db\BatchQueryResult]] object which implements the `Iterator` interface and thus can be used in the `foreach` construct. During the first iteration, a SQL query is made to the database. Data are then fetched in batches From f7e3d980ea6987efcb7acf0847cd228892b58a67 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Sun, 28 May 2017 15:52:31 +0300 Subject: [PATCH 23/71] Adjusted text [skip ci] --- docs/guide/db-query-builder.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guide/db-query-builder.md b/docs/guide/db-query-builder.md index 43fc6bd373..4ecc2135df 100644 --- a/docs/guide/db-query-builder.md +++ b/docs/guide/db-query-builder.md @@ -652,7 +652,7 @@ value which will be used as the index value for the current row. ### Batch Query -When working with large amounts of data, methods such as [[yii\db\Query::all()]] are not suitable because they require loading all data into the memory. To solve the issue Yii provides batch query support. Server holds the result data set cursor, waiting the client to get data for every iteration. +When working with large amounts of data, methods such as [[yii\db\Query::all()]] are not suitable because they require loading all data into the memory. To solve the issue Yii provides batch query support. Server holds the result data set cursor, waiting the client to get next batch of data. > Warning: In order to use it and keep the memory requirement low in case of using MySQL, an [`Unbuffered Query`](http://php.net/manual/en/mysqlinfo.concepts.buffering.php) should be used by setting connection `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` to `false`. Unless whole data set has been retrieved, no other query could be done through the same connection. The table may remain locked by MySQL and cannot be written to by other queries. Thus, new connection should be created for this purpose. From 57a448d0f8889f04f800180f04f427ea23e87162 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Sun, 28 May 2017 15:53:45 +0300 Subject: [PATCH 24/71] Adjusted text [skip ci] --- docs/guide/db-query-builder.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/guide/db-query-builder.md b/docs/guide/db-query-builder.md index 4ecc2135df..4983cc2724 100644 --- a/docs/guide/db-query-builder.md +++ b/docs/guide/db-query-builder.md @@ -665,17 +665,17 @@ $query = (new Query()) ->from('user') ->orderBy('id'); -foreach ($query->batch(100) as $users) { +foreach ($query->batch() as $users) { // $users is an array of 100 or fewer rows from the user table } // or if you want to iterate the row one by one -foreach ($query->each(100) as $user) { +foreach ($query->each() as $user) { // $user represents one row of data from the user table } ``` -> Note: In case of MySQL an instance of unbuffered connection should be passed to the second argument of `batch()` calls. +> Note: In case of MySQL an instance of unbuffered connection should be passed to the second argument of `batch()` and `each()` calls. Assuming that you have set up a connection to `$unbuffered_db` with `BUFFERED_QUERY` set to `false`, it would be `batch(100, $unbuffered_db)`. The method [[yii\db\Query::batch()]] and [[yii\db\Query::each()]] return an [[yii\db\BatchQueryResult]] object which implements the `Iterator` interface and thus can be used in the `foreach` construct. From e2218cbbaeb888ce5a5eff86c9071ec81f475e39 Mon Sep 17 00:00:00 2001 From: Ilya Rogov Date: Sun, 28 May 2017 16:03:36 +0300 Subject: [PATCH 25/71] Add test coverage of yii\helpers\Html (#14220) --- tests/framework/helpers/HtmlTest.php | 210 +++++++++++++++++++++++++++ 1 file changed, 210 insertions(+) diff --git a/tests/framework/helpers/HtmlTest.php b/tests/framework/helpers/HtmlTest.php index af84a69655..09465c0c5a 100644 --- a/tests/framework/helpers/HtmlTest.php +++ b/tests/framework/helpers/HtmlTest.php @@ -90,6 +90,7 @@ class HtmlTest extends TestCase $this->assertEquals('', Html::cssFile('')); $this->assertEquals("", Html::cssFile('http://example.com', ['condition' => 'IE 9'])); $this->assertEquals("\n" . '' . "\n", Html::cssFile('http://example.com', ['condition' => '(gte IE 9)|(!IE)'])); + $this->assertEquals('', Html::cssFile('http://example.com', ['noscript' => true])); } public function testJsFile() @@ -100,6 +101,76 @@ class HtmlTest extends TestCase $this->assertEquals("\n" . '' . "\n", Html::jsFile('http://example.com', ['condition' => '(gte IE 9)|(!IE)'])); } + public function testCsrfMetaTagsDisableCsrfValidation() + { + $this->mockApplication([ + 'components' => [ + 'request' => [ + 'class' => 'yii\web\Request', + 'enableCsrfValidation' => false, + ], + ], + ]); + $this->assertEquals('', Html::csrfMetaTags()); + } + + public function testCsrfMetaTagsEnableCsrfValidation() + { + $this->mockApplication([ + 'components' => [ + 'request' => [ + 'class' => 'yii\web\Request', + 'enableCsrfValidation' => true, + 'cookieValidationKey' => 'key', + ], + 'response' => [ + 'class' => 'yii\web\Response', + ], + ], + ]); + $pattern = '%A'; + $actual = Html::csrfMetaTags(); + $this->assertStringMatchesFormat($pattern, $actual); + } + + public function testCsrfMetaTagsEnableCsrfValidationWithoutCookieValidationKey() + { + $request = $this->getMock('yii\\web\\Request'); + $request->method('enableCsrfValidation')->willReturn(true); + Yii::$app->set('request', $request); + $pattern = '%A'; + $actual = Html::csrfMetaTags(); + $this->assertStringMatchesFormat($pattern, $actual); + } + + /** + * @dataProvider dataProviderBeginFormSimulateViaPost + * + * @param string $expected + * @param string $method + */ + public function testBeginFormSimulateViaPost($expected, $method) + { + $actual = Html::beginForm('/foo', $method); + $this->assertStringMatchesFormat($expected, $actual); + } + + /** + * Data provider for [[testBeginFormSimulateViaPost()]] + * @return array test data + */ + public function dataProviderBeginFormSimulateViaPost() + { + return [ + ['
', 'GET'], + ['', 'POST'], + ['%A', 'DELETE'], + ['%A', 'GETFOO'], + ['%A', 'POSTFOO'], + ['%A', 'POSTFOOPOST'], + ]; + } + public function testBeginForm() { $this->assertEquals('', Html::beginForm()); @@ -109,6 +180,10 @@ class HtmlTest extends TestCase '', ]; $this->assertEquals('' . "\n" . implode("\n", $hiddens), Html::beginForm('/example?id=1&title=%3C', 'get')); + + $expected = '%A'; + $actual = Html::beginForm('/foo?p', 'GET'); + $this->assertStringMatchesFormat($expected, $actual); } public function testEndForm() @@ -421,6 +496,13 @@ EOD; 'value2' => ['selected' => true] ], ])); + + $expected = << + + +EOD; + $this->assertEqualsWithoutLE($expected, Html::dropDownList('test', null, [], ['multiple' => 'true'])); } public function testListBox() @@ -644,6 +726,8 @@ EOD; ])); $this->assertEquals('
    ', Html::ul([], ['class' => 'test'])); + + $this->assertStringMatchesFormat('%A', Html::ul([], ['tag' => 'foo'])); } public function testOl() @@ -760,6 +844,13 @@ EOD; $this->assertEquals('', Html::renderTagAttributes(['class' => []])); $this->assertEquals(' style="width: 100px; height: 200px;"', Html::renderTagAttributes(['style' => ['width' => '100px', 'height' => '200px']])); $this->assertEquals('', Html::renderTagAttributes(['style' => []])); + + $attributes = [ + 'data' => [ + 'foo' => [], + ], + ]; + $this->assertEquals(' data-foo=\'[]\'', Html::renderTagAttributes($attributes)); } public function testAddCssClass() @@ -1326,6 +1417,125 @@ EOD; $this->expectException('yii\base\InvalidParamException'); Html::getAttributeName($name); } + + public function testActiveFileInput() + { + $expected = ''; + $model = new HtmlTestModel(); + $actual = Html::activeFileInput($model, 'types', ['name' => 'foo']); + $this->assertEqualsWithoutLE($expected, $actual); + } + + /** + * @expectedException \yii\base\InvalidParamException + * @expectedExceptionMessage Attribute name must contain word characters only. + */ + public function testGetAttributeValueInvalidParamException() + { + $model = new HtmlTestModel(); + Html::getAttributeValue($model, '-'); + } + + public function testGetAttributeValue() + { + $model = new HtmlTestModel(); + + $expected = null; + $actual = Html::getAttributeValue($model, 'types'); + $this->assertSame($expected, $actual); + + $activeRecord = $this->getMock('yii\\db\\ActiveRecordInterface'); + $activeRecord->method('getPrimaryKey')->willReturn(1); + $model->types = $activeRecord; + + $expected = 1; + $actual = Html::getAttributeValue($model, 'types'); + $this->assertSame($expected, $actual); + + $model->types = [ + $activeRecord, + ]; + + $expected = [1]; + $actual = Html::getAttributeValue($model, 'types'); + $this->assertSame($expected, $actual); + } + + /** + * @expectedException \yii\base\InvalidParamException + * @expectedExceptionMessage Attribute name must contain word characters only. + */ + public function testGetInputNameInvalidParamExceptionAttribute() + { + $model = new HtmlTestModel(); + Html::getInputName($model, '-'); + } + + /** + * @expectedException \yii\base\InvalidParamException + * @expectedExceptionMessageRegExp /(.*)formName\(\) cannot be empty for tabular inputs.$/ + */ + public function testGetInputNameInvalidParamExceptionFormName() + { + $model = $this->getMock('yii\\base\\Model'); + $model->method('formName')->willReturn(''); + Html::getInputName($model, '[foo]bar'); + } + + public function testGetInputName() + { + $model = $this->getMock('yii\\base\\Model'); + $model->method('formName')->willReturn(''); + $expected = 'types'; + $actual = Html::getInputName($model, 'types'); + $this->assertSame($expected, $actual); + } + + + public function testEscapeJsRegularExpression() + { + $expected = '/[a-z0-9-]+/'; + $actual = Html::escapeJsRegularExpression('([a-z0-9-]+)'); + $this->assertSame($expected, $actual); + + $expected = '/([a-z0-9-]+)/gim'; + $actual = Html::escapeJsRegularExpression('/([a-z0-9-]+)/Ugimex'); + $this->assertSame($expected, $actual); + } + + public function testActiveDropDownList() + { + $expected = << +HTML; + $model = new HtmlTestModel(); + $actual = Html::activeDropDownList($model, 'types', [], ['multiple' => 'true']); + $this->assertEqualsWithoutLE($expected, $actual); + } + + public function testActiveCheckboxList() + { + $model = new HtmlTestModel(); + + $expected = <<
    +HTML; + $actual = Html::activeRadioList($model, 'types', ['foo']); + $this->assertEqualsWithoutLE($expected, $actual); + } + + public function testActiveRadioList() + { + $model = new HtmlTestModel(); + + $expected = <<
    +HTML; + $actual = Html::activeCheckboxList($model, 'types', ['foo']); + $this->assertEqualsWithoutLE($expected, $actual); + } } /** From 85294ab4e3d03b648a5ed97858a16d5744e9d69b Mon Sep 17 00:00:00 2001 From: Victor Heng Date: Mon, 29 May 2017 14:41:00 +0800 Subject: [PATCH 26/71] Add migration file example for DbSession (#14227) [skip ci] Creating a `char` primaryKey in a migration is non-obvious. Used solution from this [issue comment](https://github.com/yiisoft/yii2/issues/10889#issuecomment-302995086). --- docs/guide/runtime-sessions-cookies.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/docs/guide/runtime-sessions-cookies.md b/docs/guide/runtime-sessions-cookies.md index d30be612f1..c95c8bf115 100644 --- a/docs/guide/runtime-sessions-cookies.md +++ b/docs/guide/runtime-sessions-cookies.md @@ -178,6 +178,31 @@ where 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the BLOB the length of the `id` column. For example, if `session.hash_function=sha256`, you should use a length 64 instead of 40. +Alternatively, this can be accomplished with the following migration: + +```php +createTable('{{%session}}', [ + 'id' => $this->char(64)->notNull(), + 'expire' => $this->integer(), + 'data' => $this->binary() + ]); + $this->addPrimaryKey('pk-id', '{{%session}}', 'id'); + } + + public function down() + { + $this->dropTable('{{%session}}'); + } +} +``` ### Flash Data From ed0c755f7ccca7295af3f657f2f5c76ba9906e9a Mon Sep 17 00:00:00 2001 From: Beowulfenator Date: Tue, 30 May 2017 17:49:18 +0300 Subject: [PATCH 27/71] Adjusted text [skip ci] --- docs/guide/db-query-builder.md | 68 +++++++++++++++++++++++++++++----- 1 file changed, 58 insertions(+), 10 deletions(-) diff --git a/docs/guide/db-query-builder.md b/docs/guide/db-query-builder.md index 4983cc2724..7bab09758c 100644 --- a/docs/guide/db-query-builder.md +++ b/docs/guide/db-query-builder.md @@ -652,9 +652,9 @@ value which will be used as the index value for the current row. ### Batch Query -When working with large amounts of data, methods such as [[yii\db\Query::all()]] are not suitable because they require loading all data into the memory. To solve the issue Yii provides batch query support. Server holds the result data set cursor, waiting the client to get next batch of data. +When working with large amounts of data, methods such as [[yii\db\Query::all()]] are not suitable because they require loading the whole query result into the client's memory. To solve this issue Yii provides batch query support. The server holds the query result, and the client uses a cursor to iterate over the result set one batch at a time. -> Warning: In order to use it and keep the memory requirement low in case of using MySQL, an [`Unbuffered Query`](http://php.net/manual/en/mysqlinfo.concepts.buffering.php) should be used by setting connection `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` to `false`. Unless whole data set has been retrieved, no other query could be done through the same connection. The table may remain locked by MySQL and cannot be written to by other queries. Thus, new connection should be created for this purpose. +> Warning: There are known limitations and workarounds for the MySQL implementation of batch queries. See below. Batch query can be used like the following: @@ -669,24 +669,20 @@ foreach ($query->batch() as $users) { // $users is an array of 100 or fewer rows from the user table } -// or if you want to iterate the row one by one +// or to iterate the row one by one foreach ($query->each() as $user) { - // $user represents one row of data from the user table + // data is being fetched from the server in batches of 100, + // but $user represents one row of data from the user table } ``` -> Note: In case of MySQL an instance of unbuffered connection should be passed to the second argument of `batch()` and `each()` calls. -Assuming that you have set up a connection to `$unbuffered_db` with `BUFFERED_QUERY` set to `false`, it would be `batch(100, $unbuffered_db)`. - The method [[yii\db\Query::batch()]] and [[yii\db\Query::each()]] return an [[yii\db\BatchQueryResult]] object which implements the `Iterator` interface and thus can be used in the `foreach` construct. -During the first iteration, a SQL query is made to the database. Data are then fetched in batches +During the first iteration, a SQL query is made to the database. Data is then fetched in batches in the remaining iterations. By default, the batch size is 100, meaning 100 rows of data are being fetched in each batch. You can change the batch size by passing the first parameter to the `batch()` or `each()` method. Compared to the [[yii\db\Query::all()]], the batch query only loads 100 rows of data at a time into the memory. -> Warning: If `BUFFERED_QUERY` is not configured properly, the `batch()` or `each()` method still hold all the data set in PDO's memory, this is done at the driver level. - If you specify the query result to be indexed by some column via [[yii\db\Query::indexBy()]], the batch query will still keep the proper index. For example: @@ -704,3 +700,55 @@ foreach ($query->each() as $username => $user) { // ... } ``` + +#### Limitations of batch query in MySQL + +MySQL implementation of batch queries relies on the PDO driver library. By default, MySQL queries are [`buffered`](http://php.net/manual/en/mysqlinfo.concepts.buffering.php). This defeats the purpose of using the cursor to get the data, because it doesn't prevent the whole result set from being loaded into the client's memory by the driver. + +> Note: When `libmysqlclient` is used (typical of PHP5), PHP's memory limit won't count the memory used for result sets. It may seem that batch queries work correctly, but in reality the whole dataset is loaded into client's memory, and has the potential of using it up. + +To disable buffering and reduce client memory requirements PDO connection property `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` can be set to `false`. However, until the whole dataset has been retrieved, no other query can be made through the same connection. This may prevent `ActiveRecord` from making a query to get the table schema when it needs to. If this is not a problem (the table schema is cached already), it is possible to switch the original connection into unbuffered mode, and then back when the batch query is done. + +```php +Yii::$app->db->pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); + +// Do batch query + +Yii::$app->db->pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true); +``` + +> Note: For the duration of the batch query, the table or parts of it may become locked, delaying or denying write access for other connections. When using unbuffered queries, try to keep the cursor open for as little time as possible. + +If the schema is not cached, or it is necessary to run other queries while the batch query is being processed, you can create a separate unbuffered connection to the database: + +```php +$unbufferedDb = new \yii\db\Connection([ + 'dsn' => Yii::$app->db->dsn, + 'username' => Yii::$app->db->username, + 'password' => Yii::$app->db->password, + 'charset' => Yii::$app->db->charset, +]); +$unbufferedDb->open(); +$unbufferedDb->pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); +``` + +Queries are created normally. The new connection is used to run batch queries and retrieve results either in batches or one by one: + +```php +// getting data in batches of 1000 +foreach ($query->batch(1000, $unbufferedDb) as $users) { + // ... +} + + +// data is fetched from server in batches of 1000, but is iterated one by one +foreach ($query->each(1000, $unbufferedDb) as $user) { + // ... +} +``` + +When the connection is no longer necessary, it can be closed: + +```php +$unbufferedDb->close(); +``` \ No newline at end of file From 51dd58cf34ec0491c5fa4e0717188b9a75c369ff Mon Sep 17 00:00:00 2001 From: Skiba Max Date: Fri, 10 Feb 2017 16:07:05 +0200 Subject: [PATCH 28/71] Fixed #13551: loading fixtures in subdirectories --- .../console/controllers/FixtureController.php | 27 ++++++++++++++++- .../controllers/fixtures/FixtureStorage.php | 6 ++++ .../fixtures/subdir/FirstFixture.php | 20 +++++++++++++ .../fixtures/subdir/SecondFixture.php | 20 +++++++++++++ .../controllers/FixtureControllerTest.php | 30 +++++++++++++++++-- 5 files changed, 99 insertions(+), 4 deletions(-) create mode 100644 tests/data/console/controllers/fixtures/subdir/FirstFixture.php create mode 100644 tests/data/console/controllers/fixtures/subdir/SecondFixture.php diff --git a/framework/console/controllers/FixtureController.php b/framework/console/controllers/FixtureController.php index 8934a2cd0c..83e801b675 100644 --- a/framework/console/controllers/FixtureController.php +++ b/framework/console/controllers/FixtureController.php @@ -415,12 +415,35 @@ class FixtureController extends Controller $foundFixtures = []; foreach ($files as $fixture) { - $foundFixtures[] = basename($fixture, 'Fixture.php'); + $relativeName = $this->getFixtureRelativeName($fixture); + $foundFixtures[] = $relativeName; } return $foundFixtures; } + /** + * Calculates $fixture's name relatively to $templatePath. + * Basically, strips getFixturePath() and 'Fixture.php' prefix from fixture's full path + * @see getFixturePath() + * @param string $fullFixturePath Full fixture path + * @return string Relative fixture name + */ + private function getFixtureRelativeName($fullFixturePath) + { + // $fixturesPath is normalized to unix format in getFixturesPath() + $fixturesPath = $this->getFixturePath(); + // normalize $fixture to unix format + $fullFixturePath = str_replace("\\", "/", $fullFixturePath); + // strip $fixturesPath from $fixture's full path + $relativeName = str_replace($fixturesPath . "/", "", $fullFixturePath); + // get fixtures's directory + $relativeDir = dirname($relativeName) === '.' ? '' : dirname($relativeName) . '/'; + // get fixture name relatively to $fixturesPath + $relativeName = $relativeDir . basename($fullFixturePath, 'Fixture.php'); + return $relativeName; + } + /** * Returns valid fixtures config that can be used to load them. * @param array $fixtures fixtures to configure @@ -432,6 +455,8 @@ class FixtureController extends Controller foreach ($fixtures as $fixture) { $isNamespaced = (strpos($fixture, '\\') !== false); + // replace linux' path slashes to namespace backslashes, in case if $fixture is non-namespaced relative path + $fixture = str_replace('/', '\\', $fixture); $fullClassName = $isNamespaced ? $fixture . 'Fixture' : $this->namespace . '\\' . $fixture . 'Fixture'; if (class_exists($fullClassName)) { diff --git a/tests/data/console/controllers/fixtures/FixtureStorage.php b/tests/data/console/controllers/fixtures/FixtureStorage.php index 4e411128c3..73d8bae594 100644 --- a/tests/data/console/controllers/fixtures/FixtureStorage.php +++ b/tests/data/console/controllers/fixtures/FixtureStorage.php @@ -11,11 +11,17 @@ class FixtureStorage public static $secondFixtureData = []; + public static $subdirFirstFixtureData = []; + + public static $subdirSecondFixtureData = []; + public static function clear() { static::$globalFixturesData = []; static::$firstFixtureData = []; static::$secondFixtureData = []; + static::$subdirFirstFixtureData = []; + static::$subdirSecondFixtureData= []; } } diff --git a/tests/data/console/controllers/fixtures/subdir/FirstFixture.php b/tests/data/console/controllers/fixtures/subdir/FirstFixture.php new file mode 100644 index 0000000000..65c7505630 --- /dev/null +++ b/tests/data/console/controllers/fixtures/subdir/FirstFixture.php @@ -0,0 +1,20 @@ +assertEmpty(FixtureStorage::$globalFixturesData, 'global fixture data should be empty'); $this->assertEmpty(FixtureStorage::$firstFixtureData, 'first fixture data should be empty'); $this->assertEmpty(FixtureStorage::$secondFixtureData, 'second fixture data should be empty'); + $this->assertEmpty(FixtureStorage::$subdirFirstFixtureData, 'subdir / first fixture data should be empty'); + $this->assertEmpty(FixtureStorage::$subdirSecondFixtureData, 'subdir / second fixture data should be empty'); $this->_fixtureController->actionLoad(['*']); $this->assertCount(1, FixtureStorage::$globalFixturesData, 'global fixture data should be loaded'); $this->assertCount(1, FixtureStorage::$firstFixtureData, 'first fixture data should be loaded'); $this->assertCount(1, FixtureStorage::$secondFixtureData, 'second fixture data should be loaded'); + $this->assertCount(1, FixtureStorage::$subdirFirstFixtureData, 'subdir / first fixture data should be loaded'); + $this->assertCount(1, FixtureStorage::$subdirSecondFixtureData, 'subdir / second fixture data should be loaded'); } public function testUnloadAll() @@ -89,25 +93,33 @@ class FixtureControllerTest extends TestCase FixtureStorage::$globalFixturesData[] = 'some seeded global fixture data'; FixtureStorage::$firstFixtureData[] = 'some seeded first fixture data'; FixtureStorage::$secondFixtureData[] = 'some seeded second fixture data'; + FixtureStorage::$subdirFirstFixtureData[] = 'some seeded subdir/first fixture data'; + FixtureStorage::$subdirSecondFixtureData[] = 'some seeded subdir/second fixture data'; $this->assertCount(1, FixtureStorage::$globalFixturesData, 'global fixture data should be loaded'); $this->assertCount(1, FixtureStorage::$firstFixtureData, 'first fixture data should be loaded'); $this->assertCount(1, FixtureStorage::$secondFixtureData, 'second fixture data should be loaded'); + $this->assertCount(1, FixtureStorage::$subdirFirstFixtureData, 'subdir/first fixture data should be loaded'); + $this->assertCount(1, FixtureStorage::$subdirSecondFixtureData, 'subdir/second fixture data should be loaded'); $this->_fixtureController->actionUnload(['*']); $this->assertEmpty(FixtureStorage::$globalFixturesData, 'global fixture data should be unloaded'); $this->assertEmpty(FixtureStorage::$firstFixtureData, 'first fixture data should be unloaded'); $this->assertEmpty(FixtureStorage::$secondFixtureData, 'second fixture data should be unloaded'); + $this->assertEmpty(FixtureStorage::$subdirFirstFixtureData, 'subdir/first fixture data should be unloaded'); + $this->assertEmpty(FixtureStorage::$subdirSecondFixtureData, 'subdir/second fixture data should be unloaded'); } public function testLoadParticularExceptOnes() { - $this->_fixtureController->actionLoad(['First', '-Second', '-Global']); + $this->_fixtureController->actionLoad(['First', 'subdir/First', '-Second', '-Global', '-subdir/Second']); $this->assertCount(1, FixtureStorage::$firstFixtureData, 'first fixture data should be loaded'); + $this->assertCount(1, FixtureStorage::$subdirFirstFixtureData, 'subdir/first fixture data should be loaded'); $this->assertEmpty(FixtureStorage::$globalFixturesData, 'global fixture data should not be loaded'); $this->assertEmpty(FixtureStorage::$secondFixtureData, 'second fixture data should not be loaded'); + $this->assertEmpty(FixtureStorage::$subdirSecondFixtureData, 'subdir/second fixture data should not be loaded'); } public function testUnloadParticularExceptOnes() @@ -115,25 +127,33 @@ class FixtureControllerTest extends TestCase FixtureStorage::$globalFixturesData[] = 'some seeded global fixture data'; FixtureStorage::$firstFixtureData[] = 'some seeded first fixture data'; FixtureStorage::$secondFixtureData[] = 'some seeded second fixture data'; + FixtureStorage::$subdirFirstFixtureData[] = 'some seeded subdir/first fixture data'; + FixtureStorage::$subdirSecondFixtureData[] = 'some seeded subdir/second fixture data'; $this->_fixtureController->actionUnload([ 'First', + 'subdir/First', '-Second', '-Global', + '-subdir/Second', ]); $this->assertEmpty(FixtureStorage::$firstFixtureData, 'first fixture data should be unloaded'); + $this->assertEmpty(FixtureStorage::$subdirFirstFixtureData, 'subdir/first fixture data should be unloaded'); $this->assertNotEmpty(FixtureStorage::$globalFixturesData, 'global fixture data should not be unloaded'); $this->assertNotEmpty(FixtureStorage::$secondFixtureData, 'second fixture data should not be unloaded'); + $this->assertNotEmpty(FixtureStorage::$subdirSecondFixtureData, 'subdir/second fixture data should not be unloaded'); } public function testLoadAllExceptOnes() { - $this->_fixtureController->actionLoad(['*', '-Second', '-Global']); + $this->_fixtureController->actionLoad(['*', '-Second', '-Global', '-subdir/First']); $this->assertCount(1, FixtureStorage::$firstFixtureData, 'first fixture data should be loaded'); + $this->assertCount(1, FixtureStorage::$subdirSecondFixtureData, 'subdir/second fixture data should be loaded'); $this->assertEmpty(FixtureStorage::$globalFixturesData, 'global fixture data should not be loaded'); $this->assertEmpty(FixtureStorage::$secondFixtureData, 'second fixture data should not be loaded'); + $this->assertEmpty(FixtureStorage::$subdirFirstFixtureData, 'subdir/first fixture data should not be loaded'); } public function testUnloadAllExceptOnes() @@ -141,12 +161,16 @@ class FixtureControllerTest extends TestCase FixtureStorage::$globalFixturesData[] = 'some seeded global fixture data'; FixtureStorage::$firstFixtureData[] = 'some seeded first fixture data'; FixtureStorage::$secondFixtureData[] = 'some seeded second fixture data'; + FixtureStorage::$subdirFirstFixtureData[] = 'some seeded subdir/first fixture data'; + FixtureStorage::$subdirSecondFixtureData[] = 'some seeded subdir/second fixture data'; - $this->_fixtureController->actionUnload(['*', '-Second', '-Global']); + $this->_fixtureController->actionUnload(['*', '-Second', '-Global', '-subdir/First']); $this->assertEmpty(FixtureStorage::$firstFixtureData, 'first fixture data should be unloaded'); + $this->assertEmpty(FixtureStorage::$subdirSecondFixtureData, 'subdir/second fixture data should be unloaded'); $this->assertNotEmpty(FixtureStorage::$globalFixturesData, 'global fixture data should not be unloaded'); $this->assertNotEmpty(FixtureStorage::$secondFixtureData, 'second fixture data should not be unloaded'); + $this->assertNotEmpty(FixtureStorage::$subdirFirstFixtureData, 'subdir/first fixture data should not be unloaded'); } public function testNothingToLoadParticularExceptOnes() From f7c9e6b8528b22d086ea1fd95e0b99f8a3d24e35 Mon Sep 17 00:00:00 2001 From: SilverFire - Dmitry Naumenko Date: Tue, 30 May 2017 21:23:27 +0300 Subject: [PATCH 29/71] Enhanced FixtureController::getFixtureRelativeName() Updated CHANGELOG --- framework/CHANGELOG.md | 1 + .../console/controllers/FixtureController.php | 25 ++++++++----------- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index d786d4e5ff..7348a4c887 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -29,6 +29,7 @@ Yii Framework 2 Change Log - Bug #13513: Fixed RBAC migration to work correctly on Oracle DBMS (silverfire) - Bug #13537: Fixed `yii\web\CacheSession::destroySession()` to work correctly when session is not written yet (silverfire, papalapa) - Bug #13538: Fixed `yii\db\BaseActiveRecord::deleteAll()` changes method signature declared by `yii\db\ActiveRecordInterface::deleteAll()` (klimov-paul) +- Bug #13551: Fixed `FixtureController` to load fixtures from subdirectories (d1rtyf1ng3rs, silverfire) - Bug #13571: Fix `yii\db\mssql\QueryBuilder::checkIntegrity` for all tables (boboldehampsink) - Bug #13577: `yii\db\QueryBuilder::truncateTable` should work consistent over all databases (boboldehampsink) - Bug #13582: PK column in `yii\db\pgsql\QueryBuilder::resetSequence()` was not quoted properly (boboldehampsink) diff --git a/framework/console/controllers/FixtureController.php b/framework/console/controllers/FixtureController.php index 83e801b675..8355900fc6 100644 --- a/framework/console/controllers/FixtureController.php +++ b/framework/console/controllers/FixtureController.php @@ -415,33 +415,28 @@ class FixtureController extends Controller $foundFixtures = []; foreach ($files as $fixture) { - $relativeName = $this->getFixtureRelativeName($fixture); - $foundFixtures[] = $relativeName; + $foundFixtures[] = $this->getFixtureRelativeName($fixture); } return $foundFixtures; } /** - * Calculates $fixture's name relatively to $templatePath. - * Basically, strips getFixturePath() and 'Fixture.php' prefix from fixture's full path + * Calculates fixture's name + * Basically, strips [[getFixturePath()]] and `Fixture.php' suffix from fixture's full path * @see getFixturePath() * @param string $fullFixturePath Full fixture path * @return string Relative fixture name */ private function getFixtureRelativeName($fullFixturePath) { - // $fixturesPath is normalized to unix format in getFixturesPath() - $fixturesPath = $this->getFixturePath(); - // normalize $fixture to unix format - $fullFixturePath = str_replace("\\", "/", $fullFixturePath); - // strip $fixturesPath from $fixture's full path - $relativeName = str_replace($fixturesPath . "/", "", $fullFixturePath); - // get fixtures's directory - $relativeDir = dirname($relativeName) === '.' ? '' : dirname($relativeName) . '/'; - // get fixture name relatively to $fixturesPath - $relativeName = $relativeDir . basename($fullFixturePath, 'Fixture.php'); - return $relativeName; + $fixturesPath = FileHelper::normalizePath($this->getFixturePath()); + $fullFixturePath = FileHelper::normalizePath($fullFixturePath); + + $relativeName = substr($fullFixturePath, strlen($fixturesPath)+1); + $relativeDir = dirname($relativeName) === '.' ? '' : dirname($relativeName) . DIRECTORY_SEPARATOR; + + return $relativeDir . basename($fullFixturePath, 'Fixture.php'); } /** From 7d209b41436b28fcbfc5a3fbe13d036fca628ad9 Mon Sep 17 00:00:00 2001 From: ihipop Date: Wed, 31 May 2017 11:20:18 +0800 Subject: [PATCH 30/71] =?UTF-8?q?Adjusted=20text=EF=BC=8Cadd=20some=20adiv?= =?UTF-8?q?se=20[skip=20ci]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/guide/db-query-builder.md | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/guide/db-query-builder.md b/docs/guide/db-query-builder.md index 7bab09758c..15758b8296 100644 --- a/docs/guide/db-query-builder.md +++ b/docs/guide/db-query-builder.md @@ -654,7 +654,7 @@ value which will be used as the index value for the current row. When working with large amounts of data, methods such as [[yii\db\Query::all()]] are not suitable because they require loading the whole query result into the client's memory. To solve this issue Yii provides batch query support. The server holds the query result, and the client uses a cursor to iterate over the result set one batch at a time. -> Warning: There are known limitations and workarounds for the MySQL implementation of batch queries. See below. +> Warning: There are known limitations and workarounds for the MySQL implementation of batch queries. See below. Batch query can be used like the following: @@ -707,7 +707,7 @@ MySQL implementation of batch queries relies on the PDO driver library. By defau > Note: When `libmysqlclient` is used (typical of PHP5), PHP's memory limit won't count the memory used for result sets. It may seem that batch queries work correctly, but in reality the whole dataset is loaded into client's memory, and has the potential of using it up. -To disable buffering and reduce client memory requirements PDO connection property `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` can be set to `false`. However, until the whole dataset has been retrieved, no other query can be made through the same connection. This may prevent `ActiveRecord` from making a query to get the table schema when it needs to. If this is not a problem (the table schema is cached already), it is possible to switch the original connection into unbuffered mode, and then back when the batch query is done. +To disable buffering and reduce client memory requirements, PDO connection property `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` must be set to `false`. However, until the whole dataset has been retrieved, no other query can be made through the same connection. This may prevent `ActiveRecord` from making a query to get the table schema when it needs to. If this is not a problem (the table schema is cached already), it is possible to switch the original connection into unbuffered mode, and then roll back when the batch query is done. ```php Yii::$app->db->pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); @@ -717,7 +717,7 @@ Yii::$app->db->pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); Yii::$app->db->pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true); ``` -> Note: For the duration of the batch query, the table or parts of it may become locked, delaying or denying write access for other connections. When using unbuffered queries, try to keep the cursor open for as little time as possible. +> Note: In the case of MyISAM, for the duration of the batch query, the table may become locked, delaying or denying write access for other connections. When using unbuffered queries, try to keep the cursor open for as little time as possible. If the schema is not cached, or it is necessary to run other queries while the batch query is being processed, you can create a separate unbuffered connection to the database: @@ -732,10 +732,12 @@ $unbufferedDb->open(); $unbufferedDb->pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); ``` -Queries are created normally. The new connection is used to run batch queries and retrieve results either in batches or one by one: +If you want to ensure that the `$unbufferedDb` has exactly the same PDO attributes like the original buffered `$db` but the `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY` is `false`, [consider a deep copy of `$db`](https://github.com/yiisoft/yii2/issues/8420#issuecomment-301423833), set it to false manually. + +Then, queries are created normally. The new connection is used to run batch queries and retrieve results either in batches or one by one: ```php -// getting data in batches of 1000 +// getting data in batches of 1000 foreach ($query->batch(1000, $unbufferedDb) as $users) { // ... } @@ -747,8 +749,10 @@ foreach ($query->each(1000, $unbufferedDb) as $user) { } ``` -When the connection is no longer necessary, it can be closed: +When the connection is no longer necessary and the result set has been retrieved, it can be closed: ```php $unbufferedDb->close(); -``` \ No newline at end of file +``` + +> Note: unbuffered query uses less memory on the PHP-side, but can increase the load on the MySQL server. It is recommended to design your own code with your production practice for extra massive data, [for example, divide the range for integer keys, loop them with Unbuffered Queries](https://github.com/yiisoft/yii2/issues/8420#issuecomment-296109257). From 18bb002c99daaf4b3975bef79b05fd922949e637 Mon Sep 17 00:00:00 2001 From: Felipe Sateler Date: Sat, 16 May 2015 14:36:02 -0300 Subject: [PATCH 31/71] Document queryParams in the authorization guide --- docs/guide/security-authorization.md | 44 +++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/docs/guide/security-authorization.md b/docs/guide/security-authorization.md index 1c40765a3e..91bf0182c7 100644 --- a/docs/guide/security-authorization.md +++ b/docs/guide/security-authorization.md @@ -100,6 +100,9 @@ The comparison is case-sensitive. If this option is empty or not set, it means t Using other role names will trigger the invocation of [[yii\web\User::can()]], which requires enabling RBAC (to be described in the next subsection). If this option is empty or not set, it means this rule applies to all roles. + * [[yii\filters\AccessRule::roleParams|roleParams]]: specifies the parameters that will be passed to [[yii\web\User::can()]]. + See the section below describing RBAC rules to see how it can be used. If this option is empty or not set, then no parameters will be passed. + * [[yii\filters\AccessRule::ips|ips]]: specifies which [[yii\web\Request::userIP|client IP addresses]] this rule matches. An IP address can contain the wildcard `*` at the end so that it matches IP addresses with the same prefix. For example, '192.168.*' matches all IP addresses in the segment '192.168.'. If this option is empty or not set, @@ -356,6 +359,7 @@ created previously author cannot edit his own post. Let's fix it. First we need namespace app\rbac; use yii\rbac\Rule; +use app\models\Post; /** * Checks if authorID matches user passed via params @@ -372,7 +376,14 @@ class AuthorRule extends Rule */ public function execute($user, $item, $params) { - return isset($params['post']) ? $params['post']->createdBy == $user : false; + if (isset($params['post'])) { + $post = $params['post']; + if (is_integer($post)) { + $post = Post::findOne($post); + } + return $post->createdBy == $user; + } + return false; } } ``` @@ -487,6 +498,37 @@ public function behaviors() If all the CRUD operations are managed together then it's a good idea to use a single permission, like `managePost`, and check it in [[yii\web\Controller::beforeAction()]]. +You can also use rules from the [[yii\filters\AccessControl|AccessControl]] filter. For that you specify the +[[yii\filters\AccessRule::roleParams|roleParams]] that you need to pass to the [[yii\filters\AccessRule|AccessRule]]: + + +```php +use yii\filters\AccessControl; + +class PostsController extends Controller +{ + public function behaviors() + { + return [ + 'access' => [ + 'class' => AccessControl::className(), + 'rules' => [ + [ + 'actions' => ['update'], + 'roles' => ['updatePost'], + 'roleParams' => function() { + return ['post' => Yii::$app->request->get('id')]; + }, + 'allow' => true, + ], + ], + ], + ]; + } +} +``` + + ### Using Default Roles A default role is a role that is *implicitly* assigned to *all* users. The call to [[yii\rbac\ManagerInterface::assign()]] From 88bbd61988daebb62d604dc995f4df360b8246e9 Mon Sep 17 00:00:00 2001 From: Felipe Sateler Date: Thu, 14 May 2015 21:28:33 -0300 Subject: [PATCH 32/71] Alternative implementation for passing parameters to AccessRule roles fixes #8426: `yii\filters\AccessRule` now allows passing GET or other parameters to the role checking function replaces #8426 --- framework/CHANGELOG.md | 1 + framework/filters/AccessRule.php | 39 ++++++++++++++- tests/framework/filters/AccessRuleTest.php | 56 +++++++++++++++++----- 3 files changed, 83 insertions(+), 13 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 7348a4c887..2a009b2cb5 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -59,6 +59,7 @@ Yii Framework 2 Change Log - Bug #14074: Fixed default value of `yii\console\controllers\FixtureController::$globalFixtures` to contain valid class name (lynicidn) - Bug #14094: Fixed bug when single `yii\web\UrlManager::createUrl()` call my result multiple calls of `yii\web\UrlRule::createUrl()` for the same rule (rossoneri) - Bug #14133: Fixed bug when calculating timings with mixed nested profile begin and end in `yii\log\Logger::calculateTimings()` (bizley) +- Enh #8426: `yii\filters\AccessRule` now allows passing parameters to the role checking function (fsateler, cebe, Faryshta) - Enh #8641: Enhanced `yii\console\Request::resolve()` to prevent passing parameters, that begin from digits (silverfire) - Enh #11288: Added support for caching of `yii\web\UrlRule::createUrl()` results in `yii\web\UrlManager` for rules with defaults (rob006) - Enh #12528: Added option to disable query logging and profiling in DB command (cebe) diff --git a/framework/filters/AccessRule.php b/framework/filters/AccessRule.php index b5a09fd380..892dbd24fb 100644 --- a/framework/filters/AccessRule.php +++ b/framework/filters/AccessRule.php @@ -7,6 +7,7 @@ namespace yii\filters; +use Closure; use yii\base\Component; use yii\base\Action; use yii\base\InvalidConfigException; @@ -55,8 +56,37 @@ class AccessRule extends Component * In this case, [[User::can()]] will be called to check access. * * If this property is not set or empty, it means this rule applies to all roles. + * @see $roleParams */ public $roles; + /** + * @var array|Closure parameters to pass to the [[User::can()]] function for evaluating + * user permissions in [[$roles]]. + * + * If this is an array, it will be passed directly to [[User::can()]]. + * You may also specify a closure that returns an array. This can be used to + * evaluate the array values only if they are needed. + * This can be used for example like this: + * + * ```php + * 'rules' => [ + * [ + * 'allow' => true, + * 'actions' => ['update'], + * 'roles' => ['updatePost'], + * 'roleParams' => function($rule) { + * return ['postId' => Yii::$app->request->get('id')]; + * }, + * ], + * ], + * ``` + * + * A reference to the [[AccessRule]] instance will be passed to the closure as the first parameter. + * + * @see $roles + * @since 2.0.12 + */ + public $roleParams = []; /** * @var array list of user IP addresses that this rule applies to. An IP address * can contain the wildcard `*` at the end so that it matches IP addresses with the same prefix. @@ -161,8 +191,13 @@ class AccessRule extends Component if (!$user->getIsGuest()) { return true; } - } elseif ($user->can($role)) { - return true; + } else { + if (!isset($roleParams)) { + $roleParams = $this->roleParams instanceof Closure ? call_user_func($this->roleParams, $this) : $this->roleParams; + } + if ($user->can($role, $roleParams)) { + return true; + } } } diff --git a/tests/framework/filters/AccessRuleTest.php b/tests/framework/filters/AccessRuleTest.php index 45a46a1f3a..e3c338488a 100644 --- a/tests/framework/filters/AccessRuleTest.php +++ b/tests/framework/filters/AccessRuleTest.php @@ -2,6 +2,7 @@ namespace yiiunit\framework\filters; +use Closure; use Yii; use yii\base\Action; use yii\filters\AccessRule; @@ -10,6 +11,7 @@ use yii\web\Request; use yii\web\User; use yiiunit\framework\filters\stubs\MockAuthManager; use yiiunit\framework\filters\stubs\UserIdentity; +use yiiunit\framework\rbac\AuthorRule; /** * @group filters @@ -81,10 +83,20 @@ class AccessRuleTest extends \yiiunit\TestCase $updatePost->description = 'Update post'; $auth->add($updatePost); + // add "updateOwnPost" permission + $updateOwnPost = $auth->createPermission('updateOwnPost'); + $updateOwnPost->description = 'Update post'; + $updateRule = new AuthorRule(); + $auth->add($updateRule); + $updateOwnPost->ruleName = $updateRule->name; + $auth->add($updateOwnPost); + $auth->addChild($updateOwnPost, $updatePost); + // add "author" role and give this role the "createPost" permission $author = $auth->createRole('author'); $auth->add($author); $auth->addChild($author, $createPost); + $auth->addChild($author, $updateOwnPost); // add "admin" role and give this role the "updatePost" permission // as well as the permissions of the "author" role @@ -142,14 +154,34 @@ class AccessRuleTest extends \yiiunit\TestCase */ public function matchRoleProvider() { return [ - ['create', true, 'user1', true], - ['create', true, 'user2', true], - ['create', true, 'user3', null], - ['create', true, 'unknown', null], - ['create', false, 'user1', false], - ['create', false, 'user2', false], - ['create', false, 'user3', null], - ['create', false, 'unknown', null], + ['create', true, 'user1', [], true], + ['create', true, 'user2', [], true], + ['create', true, 'user3', [], null], + ['create', true, 'unknown', [], null], + ['create', false, 'user1', [], false], + ['create', false, 'user2', [], false], + ['create', false, 'user3', [], null], + ['create', false, 'unknown', [], null], + + // user2 is author, can only edit own posts + ['update', true, 'user2', ['authorID' => 'user2'], true], + ['update', true, 'user2', ['authorID' => 'user1'], null], + // user1 is admin, can update all posts + ['update', true, 'user1', ['authorID' => 'user1'], true], + ['update', true, 'user1', ['authorID' => 'user2'], true], + // unknown user can not edit anything + ['update', true, 'unknown', ['authorID' => 'user1'], null], + ['update', true, 'unknown', ['authorID' => 'user2'], null], + + // user2 is author, can only edit own posts + ['update', true, 'user2', function() { return ['authorID' => 'user2']; }, true], + ['update', true, 'user2', function() { return ['authorID' => 'user1']; }, null], + // user1 is admin, can update all posts + ['update', true, 'user1', function() { return ['authorID' => 'user1']; }, true], + ['update', true, 'user1', function() { return ['authorID' => 'user2']; }, true], + // unknown user can not edit anything + ['update', true, 'unknown', function() { return ['authorID' => 'user1']; }, null], + ['update', true, 'unknown', function() { return ['authorID' => 'user2']; }, null], ]; } @@ -160,17 +192,19 @@ class AccessRuleTest extends \yiiunit\TestCase * @param string $actionid the action id * @param boolean $allow whether the rule should allow access * @param string $userid the userid to check + * @param array|Closure $roleParams params for $roleParams * @param boolean $expected the expected result or null */ - public function testMatchRole($actionid, $allow, $userid, $expected) { + public function testMatchRole($actionid, $allow, $userid, $roleParams, $expected) { $action = $this->mockAction(); $auth = $this->mockAuthManager(); $request = $this->mockRequest(); $rule = new AccessRule([ 'allow' => $allow, - 'roles' => ['createPost'], - 'actions' => ['create'], + 'roles' => [$actionid === 'create' ? 'createPost' : 'updatePost'], + 'actions' => [$actionid], + 'roleParams' => $roleParams, ]); $action->id = $actionid; From 339972fb343c3f5515d0514740860663847bc91d Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Mon, 8 May 2017 13:01:19 +0200 Subject: [PATCH 33/71] simplified guide example --- docs/guide/security-authorization.md | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/docs/guide/security-authorization.md b/docs/guide/security-authorization.md index 91bf0182c7..fed710e4f9 100644 --- a/docs/guide/security-authorization.md +++ b/docs/guide/security-authorization.md @@ -376,14 +376,7 @@ class AuthorRule extends Rule */ public function execute($user, $item, $params) { - if (isset($params['post'])) { - $post = $params['post']; - if (is_integer($post)) { - $post = Post::findOne($post); - } - return $post->createdBy == $user; - } - return false; + return isset($params['post']) ? $params['post']->createdBy == $user : false; } } ``` @@ -517,7 +510,7 @@ class PostsController extends Controller 'actions' => ['update'], 'roles' => ['updatePost'], 'roleParams' => function() { - return ['post' => Yii::$app->request->get('id')]; + return ['post' => Post::findOne(Yii::$app->request->get('id'))]; }, 'allow' => true, ], From a1f396c5d85751c6a4dd313462967c4d98e5d748 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Wed, 31 May 2017 15:36:50 +0200 Subject: [PATCH 34/71] improved docs --- docs/guide/security-authorization.md | 50 +++++++++++++--------------- framework/filters/AccessRule.php | 14 +++++--- 2 files changed, 34 insertions(+), 30 deletions(-) diff --git a/docs/guide/security-authorization.md b/docs/guide/security-authorization.md index fed710e4f9..55dc045893 100644 --- a/docs/guide/security-authorization.md +++ b/docs/guide/security-authorization.md @@ -491,36 +491,34 @@ public function behaviors() If all the CRUD operations are managed together then it's a good idea to use a single permission, like `managePost`, and check it in [[yii\web\Controller::beforeAction()]]. -You can also use rules from the [[yii\filters\AccessControl|AccessControl]] filter. For that you specify the -[[yii\filters\AccessRule::roleParams|roleParams]] that you need to pass to the [[yii\filters\AccessRule|AccessRule]]: - +In the above example, no parameters are passed with the roles specified for accessing an action, but in case of the +`updatePost` permission, we need to pass a `post` parameter for it to work properly. +You can pass parameters to [[yii\web\User::can()]] by specifying [[yii\filters\AccessRule::roleParams|roleParams]] on +the access rule: ```php -use yii\filters\AccessControl; - -class PostsController extends Controller -{ - public function behaviors() - { - return [ - 'access' => [ - 'class' => AccessControl::className(), - 'rules' => [ - [ - 'actions' => ['update'], - 'roles' => ['updatePost'], - 'roleParams' => function() { - return ['post' => Post::findOne(Yii::$app->request->get('id'))]; - }, - 'allow' => true, - ], - ], - ], - ]; - } -} +[ + 'allow' => true, + 'actions' => ['update'], + 'roles' => ['updatePost'], + 'roleParams' => function() { + return ['post' => Post::findOne(Yii::$app->request->get('id'))]; + }, +], ``` +In the above example, [[yii\filters\AccessRule::roleParams|roleParams]] is a Closure that will be evaluated when +the access rule is checked, so the model will only be loaded when needed. +If the creation of role parameters is a simple operation, you may just specify an array, like so: + +```php +[ + 'allow' => true, + 'actions' => ['update'], + 'roles' => ['updatePost'], + 'roleParams' => ['postId' => Yii::$app->request->get('id')]; +], +``` ### Using Default Roles diff --git a/framework/filters/AccessRule.php b/framework/filters/AccessRule.php index 892dbd24fb..26d3d2b8ff 100644 --- a/framework/filters/AccessRule.php +++ b/framework/filters/AccessRule.php @@ -63,10 +63,16 @@ class AccessRule extends Component * @var array|Closure parameters to pass to the [[User::can()]] function for evaluating * user permissions in [[$roles]]. * - * If this is an array, it will be passed directly to [[User::can()]]. + * If this is an array, it will be passed directly to [[User::can()]]. For example for passing an + * ID from the current request, you may use the following: + * + * ```php + * ['postId' => Yii::$app->request->get('id')] + * ``` + * * You may also specify a closure that returns an array. This can be used to - * evaluate the array values only if they are needed. - * This can be used for example like this: + * evaluate the array values only if they are needed, for example when a model needs to be + * loaded like in the following code: * * ```php * 'rules' => [ @@ -75,7 +81,7 @@ class AccessRule extends Component * 'actions' => ['update'], * 'roles' => ['updatePost'], * 'roleParams' => function($rule) { - * return ['postId' => Yii::$app->request->get('id')]; + * return ['post' => Post::findOne(Yii::$app->request->get('id'))]; * }, * ], * ], From 2feb0945ca924e2cc5b58999cc450acc206b4253 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Wed, 31 May 2017 18:52:36 +0200 Subject: [PATCH 35/71] Fixed RBAC databases tests tests were reusing static DB connection instance resulting in all tests to be run against MySQL only! PgSQL and Sqlite tests are now failing because of the issue reported in #13501. --- tests/framework/rbac/DbManagerTestCase.php | 49 +++++++++++-------- .../framework/rbac/PgSQLManagerCacheTest.php | 29 +++++++++++ tests/framework/rbac/SqliteManagerTest.php | 11 +++++ 3 files changed, 68 insertions(+), 21 deletions(-) create mode 100644 tests/framework/rbac/PgSQLManagerCacheTest.php diff --git a/tests/framework/rbac/DbManagerTestCase.php b/tests/framework/rbac/DbManagerTestCase.php index d21db3f254..5473e4acc4 100644 --- a/tests/framework/rbac/DbManagerTestCase.php +++ b/tests/framework/rbac/DbManagerTestCase.php @@ -22,7 +22,7 @@ abstract class DbManagerTestCase extends ManagerTestCase /** * @var Connection */ - protected static $db; + protected $db; protected static function runConsoleAction($route, $params = []) { @@ -34,7 +34,7 @@ abstract class DbManagerTestCase extends ManagerTestCase 'migrate' => EchoMigrateController::className(), ], 'components' => [ - 'db' => static::getConnection(), + 'db' => static::createConnection(), 'authManager' => '\yii\rbac\DbManager', ], ]); @@ -67,9 +67,6 @@ abstract class DbManagerTestCase extends ManagerTestCase public static function tearDownAfterClass() { static::runConsoleAction('migrate/down', ['migrationPath' => '@yii/rbac/migrations/', 'interactive' => false]); - if (static::$db) { - static::$db->close(); - } Yii::$app = null; parent::tearDownAfterClass(); } @@ -84,6 +81,10 @@ abstract class DbManagerTestCase extends ManagerTestCase { parent::tearDown(); $this->auth->removeAll(); + if ($this->db && static::$driverName !== 'sqlite') { + $this->db->close(); + } + $this->db = null; } /** @@ -92,24 +93,30 @@ abstract class DbManagerTestCase extends ManagerTestCase * @throws \yii\base\InvalidConfigException * @return \yii\db\Connection */ - public static function getConnection() + public function getConnection() { - if (static::$db == null) { - $db = new Connection; - $db->dsn = static::$database['dsn']; - if (isset(static::$database['username'])) { - $db->username = static::$database['username']; - $db->password = static::$database['password']; - } - if (isset(static::$database['attributes'])) { - $db->attributes = static::$database['attributes']; - } - if (!$db->isActive) { - $db->open(); - } - static::$db = $db; + if ($this->db === null) { + $this->db = static::createConnection(); } - return static::$db; + return $this->db; + } + + public static function createConnection() + { + $db = new Connection; + $db->dsn = static::$database['dsn']; + echo "\n" . $db->dsn . "\n"; + if (isset(static::$database['username'])) { + $db->username = static::$database['username']; + $db->password = static::$database['password']; + } + if (isset(static::$database['attributes'])) { + $db->attributes = static::$database['attributes']; + } + if (!$db->isActive) { + $db->open(); + } + return $db; } /** diff --git a/tests/framework/rbac/PgSQLManagerCacheTest.php b/tests/framework/rbac/PgSQLManagerCacheTest.php new file mode 100644 index 0000000000..7a24cebd0b --- /dev/null +++ b/tests/framework/rbac/PgSQLManagerCacheTest.php @@ -0,0 +1,29 @@ + $this->getConnection(), + 'cache' => new FileCache(['cachePath' => '@yiiunit/runtime/cache']), + 'defaultRoles' => ['myDefaultRole'] + ]); + } + +} diff --git a/tests/framework/rbac/SqliteManagerTest.php b/tests/framework/rbac/SqliteManagerTest.php index 2b77fd0f22..7e18a9499e 100644 --- a/tests/framework/rbac/SqliteManagerTest.php +++ b/tests/framework/rbac/SqliteManagerTest.php @@ -9,4 +9,15 @@ namespace yiiunit\framework\rbac; class SqliteManagerTest extends DbManagerTestCase { protected static $driverName = 'sqlite'; + + protected static $sqliteDb; + + public static function createConnection() + { + // sqlite db is in memory so it can not be reused + if (static::$sqliteDb === null) { + static::$sqliteDb = parent::createConnection(); + } + return static::$sqliteDb; + } } From 3e94919592acce23166cf4eb55caf84c4c47f287 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Wed, 31 May 2017 19:14:21 +0200 Subject: [PATCH 36/71] added failing test for #13593 --- tests/framework/rbac/DbManagerTestCase.php | 1 - tests/framework/rbac/ManagerTestCase.php | 20 ++++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/tests/framework/rbac/DbManagerTestCase.php b/tests/framework/rbac/DbManagerTestCase.php index 5473e4acc4..822d815a3c 100644 --- a/tests/framework/rbac/DbManagerTestCase.php +++ b/tests/framework/rbac/DbManagerTestCase.php @@ -105,7 +105,6 @@ abstract class DbManagerTestCase extends ManagerTestCase { $db = new Connection; $db->dsn = static::$database['dsn']; - echo "\n" . $db->dsn . "\n"; if (isset(static::$database['username'])) { $db->username = static::$database['username']; $db->password = static::$database['password']; diff --git a/tests/framework/rbac/ManagerTestCase.php b/tests/framework/rbac/ManagerTestCase.php index 6bd5df7f88..41c922b8b3 100644 --- a/tests/framework/rbac/ManagerTestCase.php +++ b/tests/framework/rbac/ManagerTestCase.php @@ -213,6 +213,7 @@ abstract class ManagerTestCase extends TestCase $this->auth->add($uniqueTrait); $createPost = $this->auth->createPermission('createPost'); + $createPost->data = 'createPostData'; $createPost->description = 'create a post'; $this->auth->add($createPost); @@ -241,6 +242,7 @@ abstract class ManagerTestCase extends TestCase $this->auth->addChild($reader, $readPost); $author = $this->auth->createRole('author'); + $author->data = 'authorData'; $this->auth->add($author); $this->auth->addChild($author, $createPost); $this->auth->addChild($author, $updatePost); @@ -281,6 +283,24 @@ abstract class ManagerTestCase extends TestCase } } + public function testGetRole() + { + $this->prepareData(); + $author = $this->auth->getRole('author'); + $this->assertEquals(Item::TYPE_ROLE, $author->type); + $this->assertEquals('author', $author->name); + $this->assertEquals('authorData', $author->data); + } + + public function testGetPermission() + { + $this->prepareData(); + $createPost = $this->auth->getPermission('createPost'); + $this->assertEquals(Item::TYPE_PERMISSION, $createPost->type); + $this->assertEquals('createPost', $createPost->name); + $this->assertEquals('createPostData', $createPost->data); + } + public function testGetRolesByUser() { $this->prepareData(); From 67b9a57e86161ce6d9e6d561708795c9d39ff767 Mon Sep 17 00:00:00 2001 From: nanodesu88 Date: Thu, 16 Feb 2017 20:32:21 +0400 Subject: [PATCH 37/71] additional fix for #13501 close #13593 --- framework/CHANGELOG.md | 2 +- framework/rbac/DbManager.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 2a009b2cb5..bf6f7cde84 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -52,7 +52,7 @@ Yii Framework 2 Change Log - Bug #13848: `yii\di\Instance::ensure()` wasn't throwing an exception when `$type` is specified and `$reference` object isn't instance of `$type` (c-jonua) - Bug #13890: `yii\log\DbTarget` log messages where not written when a database transaction was rolled back, added support for cloning a `yii\db\Connection` (shirase, cebe) - Bug #13901: Fixed passing unused parameter to `formatMessage()` call in `\yii\validators\IpValidator` (Kolyunya) -- Bug #13961: Fixed `unserialize()` error during RBAC rule retrieving from PostgreSQL DBMS (vsguts) +- Bug #13961: Fixed `unserialize()` error during RBAC rule retrieving from PostgreSQL DBMS (vsguts, nanodesu88, cebe) - Bug #14012: `yii\db\pgsql\Schema::findViewNames()` was skipping materialized views (insolita) - Bug #14033: Fixed `yii\filters\AccessRule::matchIp()` erroring in case IP is not defined under HHVM (Kolyunya) - Bug #14052: Fixed processing parse errors on PHP 7 since these are instances of `\ParseError` (samdark) diff --git a/framework/rbac/DbManager.php b/framework/rbac/DbManager.php index e16c91beb0..a42176b62b 100644 --- a/framework/rbac/DbManager.php +++ b/framework/rbac/DbManager.php @@ -436,7 +436,7 @@ class DbManager extends BaseManager { $class = $row['type'] == Item::TYPE_PERMISSION ? Permission::className() : Role::className(); - if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) { + if (!isset($row['data']) || ($data = @unserialize(is_resource($row['data']) ? stream_get_contents($row['data']) : $row['data'])) === false) { $data = null; } From 6e7ea782c0e4924540f7929dfef7bf78f8abab4d Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Wed, 31 May 2017 14:46:27 +0200 Subject: [PATCH 38/71] fix cloning of DB connection for sqlite in-memory db fixes #14131 close #14232 --- framework/db/Connection.php | 5 ++++- tests/framework/db/ConnectionTest.php | 21 ++++++++++++++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/framework/db/Connection.php b/framework/db/Connection.php index 7531644cc1..a75c80a8fa 100644 --- a/framework/db/Connection.php +++ b/framework/db/Connection.php @@ -1090,8 +1090,11 @@ class Connection extends Component $this->_master = false; $this->_slave = false; - $this->pdo = null; $this->_schema = null; $this->_transaction = null; + if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) { + // reset PDO connection, unless its sqlite in-memory, which can only have one connection + $this->pdo = null; + } } } diff --git a/tests/framework/db/ConnectionTest.php b/tests/framework/db/ConnectionTest.php index 7d6a1121ce..772ce0949a 100644 --- a/tests/framework/db/ConnectionTest.php +++ b/tests/framework/db/ConnectionTest.php @@ -351,7 +351,12 @@ abstract class ConnectionTest extends DatabaseTestCase $this->assertNotNull($connection->pdo); $this->assertNull($conn2->transaction); - $this->assertNull($conn2->pdo); + if ($this->driverName === 'sqlite') { + // in-memory sqlite should not reset PDO + $this->assertNotNull($conn2->pdo); + } else { + $this->assertNull($conn2->pdo); + } $connection->beginTransaction(); @@ -359,13 +364,23 @@ abstract class ConnectionTest extends DatabaseTestCase $this->assertNotNull($connection->pdo); $this->assertNull($conn2->transaction); - $this->assertNull($conn2->pdo); + if ($this->driverName === 'sqlite') { + // in-memory sqlite should not reset PDO + $this->assertNotNull($conn2->pdo); + } else { + $this->assertNull($conn2->pdo); + } $conn3 = clone $connection; $this->assertNotNull($connection->transaction); $this->assertNotNull($connection->pdo); $this->assertNull($conn3->transaction); - $this->assertNull($conn3->pdo); + if ($this->driverName === 'sqlite') { + // in-memory sqlite should not reset PDO + $this->assertNotNull($conn3->pdo); + } else { + $this->assertNull($conn3->pdo); + } } } From 17a1d91e4a517f4f15dce973bf3c50dd939dce63 Mon Sep 17 00:00:00 2001 From: leandrogehlen Date: Wed, 22 Feb 2017 18:51:36 -0300 Subject: [PATCH 39/71] Allows override query relation in descendant class fixes #13441 close #13642 --- framework/CHANGELOG.md | 2 ++ framework/db/BaseActiveRecord.php | 25 +++++++++++++++++-------- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index bf6f7cde84..9d68175c70 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -83,6 +83,7 @@ Yii Framework 2 Change Log - Enh #13576: Added support of `srcset` to `yii\helpers\Html::img()` (Kolyunya) - Enh #13577: Implemented `yii\db\mssql\QueryBuilder::resetSequence()` (boboldehampsink) - Enh #13582: Added tests for all `yii\db\QueryBuilder::resetSequence()` implementations, fixed SQLite implementation (boboldehampsink) +- Enh #13642: Allow overriding the function for creating related queries in ActiveRecord by adding `createRelationQuery()` (leandrogehlen) - Enh #13650: Improved `yii\base\Security::hkdf()` to take advantage of native `hash_hkdf()` implementation in PHP >= 7.1.2 (charlesportwoodii) - Enh #13695: `yii\web\Response::setStatusCode()` method now returns the Response object itself (kyle-mccarthy) - Enh #13698: `yii\grid\DataColumn` filter is automatically generated as dropdown list in case of `format` set to `boolean` (bizley) @@ -107,6 +108,7 @@ Yii Framework 2 Change Log - Enh #14098: `yii\helpers\BaseFileHelper::normalizeOptions()` is now protected (brandonkelly) - Bug #13846: Fixed `Query::count()` issue with `orderBy` (Alex-Code) + 2.0.11.2 February 08, 2017 -------------------------- diff --git a/framework/db/BaseActiveRecord.php b/framework/db/BaseActiveRecord.php index b302ba06b5..459699196a 100644 --- a/framework/db/BaseActiveRecord.php +++ b/framework/db/BaseActiveRecord.php @@ -370,13 +370,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface */ public function hasOne($class, $link) { - /* @var $class ActiveRecordInterface */ - /* @var $query ActiveQuery */ - $query = $class::find(); - $query->primaryModel = $this; - $query->link = $link; - $query->multiple = false; - return $query; + return $this->createRelationQuery($class, $link, false); } /** @@ -410,13 +404,28 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface * @return ActiveQueryInterface the relational query object. */ public function hasMany($class, $link) + { + return $this->createRelationQuery($class, $link, true); + } + + /** + * Creates a query instance for `has-one` or `has-many` relation. + * @param string $class the class name of the related record. + * @param array $link the primary-foreign key constraint. + * @param boolean $multiple whether this query represents a relation to more than one record. + * @return ActiveQueryInterface the relational query object. + * @since 2.0.12 + * @see hasOne() + * @see hasMany() + */ + protected function createRelationQuery($class, $link, $multiple) { /* @var $class ActiveRecordInterface */ /* @var $query ActiveQuery */ $query = $class::find(); $query->primaryModel = $this; $query->link = $link; - $query->multiple = true; + $query->multiple = $multiple; return $query; } From 0beb59305c638d2c8c0dbff9962a0a860f405ac4 Mon Sep 17 00:00:00 2001 From: Paul Klimov Date: Fri, 2 Jun 2017 01:30:21 +0300 Subject: [PATCH 40/71] Fixes #13058: Fixed caught exception thrown during view file rendering produces wrong output --- framework/CHANGELOG.md | 1 + framework/base/View.php | 22 +++++++++-- tests/framework/base/ViewTest.php | 65 +++++++++++++++++++++++++++++++ 3 files changed, 85 insertions(+), 3 deletions(-) create mode 100644 tests/framework/base/ViewTest.php diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 9d68175c70..432fc7e88e 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -16,6 +16,7 @@ Yii Framework 2 Change Log - Bug #11404: `yii\base\Model::loadMultiple()` returns true even if `yii\base\Model::load()` returns false (zvook) - Bug #11719: Fixed `yii\db\Connection::$enableQueryCache` caused infinite loop when the same connection was used for `yii\caching\DbCache` (michaelarnauts) - Bug #12715: Exception `SAVEPOINT LEVEL1 does not exist` instead of deadlock exception (Vovan-VE) +- Bug #13058: Fixed caught exception thrown during view file rendering produces wrong output (klimov-paul) - Bug #13086, #13656: Fixed bug with optional parameters at the beginning of pattern in `yii\web\UrlRule` (rob006) - Bug #13087: Fixed getting active validators for safe attribute (developeruz, klimov-paul) - Bug #13306: Wildcard in `reloadableScripts` in `yii.js` allows 0 characters (arogachev) diff --git a/framework/base/View.php b/framework/base/View.php index f08547542a..85ad7f0957 100644 --- a/framework/base/View.php +++ b/framework/base/View.php @@ -322,12 +322,28 @@ class View extends Component */ public function renderPhpFile($_file_, $_params_ = []) { + $_obInitialLevel_ = ob_get_level(); ob_start(); ob_implicit_flush(false); extract($_params_, EXTR_OVERWRITE); - require($_file_); - - return ob_get_clean(); + try { + require($_file_); + return ob_get_clean(); + } catch (\Exception $e) { + while (ob_get_level() > $_obInitialLevel_) { + if (!@ob_end_clean()) { + ob_clean(); + } + } + throw $e; + } catch (\Throwable $e) { + while (ob_get_level() > $_obInitialLevel_) { + if (!@ob_end_clean()) { + ob_clean(); + } + } + throw $e; + } } /** diff --git a/tests/framework/base/ViewTest.php b/tests/framework/base/ViewTest.php new file mode 100644 index 0000000000..1611732f0e --- /dev/null +++ b/tests/framework/base/ViewTest.php @@ -0,0 +1,65 @@ +mockApplication(); + $this->testViewPath = Yii::getAlias('@yiiunit/runtime') . DIRECTORY_SEPARATOR . str_replace('\\', '_', get_class($this)) . uniqid(); + FileHelper::createDirectory($this->testViewPath); + } + + public function tearDown() + { + FileHelper::removeDirectory($this->testViewPath); + parent::tearDown(); + } + + /** + * @see https://github.com/yiisoft/yii2/issues/13058 + */ + public function testExceptionOnRenderFile() + { + $view = new View(); + + $exceptionViewFile = $this->testViewPath . DIRECTORY_SEPARATOR . 'exception.php'; + file_put_contents($exceptionViewFile, <<Exception + +PHP +); + $normalViewFile = $this->testViewPath . DIRECTORY_SEPARATOR . 'no-exception.php'; + file_put_contents($normalViewFile, <<No Exception +PHP + ); + + $obInitialLevel = ob_get_level(); + + try { + $view->renderFile($exceptionViewFile); + } catch (\Exception $e) { + // shutdown exception + } + $view->renderFile($normalViewFile); + + $this->assertEquals($obInitialLevel, ob_get_level()); + } +} \ No newline at end of file From 4b9e48b8dc6ef2d910bc860680c584e9df0fd472 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Fri, 2 Jun 2017 10:44:42 +0200 Subject: [PATCH 41/71] improved docs: link term "path alias" to the guide --- framework/BaseYii.php | 6 +++++- framework/base/Controller.php | 6 +++--- framework/base/Module.php | 4 ++-- framework/base/Request.php | 2 +- framework/base/Theme.php | 6 +++--- framework/base/View.php | 6 +++--- framework/base/Widget.php | 4 ++-- framework/caching/FileCache.php | 2 +- framework/caching/FileDependency.php | 2 +- framework/captcha/CaptchaAction.php | 2 +- framework/console/controllers/AssetController.php | 2 +- .../console/controllers/BaseMigrateController.php | 4 ++-- framework/console/controllers/ServeController.php | 2 +- framework/db/Connection.php | 2 +- framework/log/FileTarget.php | 2 +- framework/mail/BaseMailer.php | 10 +++++----- framework/mail/MailerInterface.php | 2 +- framework/mutex/FileMutex.php | 2 +- framework/rbac/PhpManager.php | 6 +++--- framework/test/ActiveFixture.php | 2 +- framework/test/ArrayFixture.php | 2 +- framework/test/BaseActiveFixture.php | 2 +- framework/test/InitDbFixture.php | 2 +- framework/web/AssetConverter.php | 4 ++-- framework/web/Session.php | 2 +- framework/widgets/ContentDecorator.php | 2 +- 26 files changed, 46 insertions(+), 42 deletions(-) diff --git a/framework/BaseYii.php b/framework/BaseYii.php index df0c809d1a..d23c611402 100644 --- a/framework/BaseYii.php +++ b/framework/BaseYii.php @@ -62,7 +62,7 @@ class BaseYii /** * @var array class map used by the Yii autoloading mechanism. * The array keys are the class names (without leading backslashes), and the array values - * are the corresponding class file paths (or path aliases). This property mainly affects + * are the corresponding class file paths (or [path aliases](guide:concept-aliases)). This property mainly affects * how [[autoload()]] works. * @see autoload() */ @@ -119,6 +119,8 @@ class BaseYii * * Note, this method does not check if the returned path exists or not. * + * See the [guide article on aliases](guide:concept-aliases) for more information. + * * @param string $alias the alias to be translated. * @param bool $throwException whether to throw an exception if the given alias is invalid. * If this is false and an invalid alias is given, false will be returned by this method. @@ -196,6 +198,8 @@ class BaseYii * * Any trailing '/' and '\' characters in the given path will be trimmed. * + * See the [guide article on aliases](guide:concept-aliases) for more information. + * * @param string $alias the alias name (e.g. "@yii"). It must start with a '@' character. * It may contain the forward slash '/' which serves as boundary character when performing * alias translation by [[getAlias()]]. diff --git a/framework/base/Controller.php b/framework/base/Controller.php index 84b51419f6..d9c52e19f5 100644 --- a/framework/base/Controller.php +++ b/framework/base/Controller.php @@ -342,7 +342,7 @@ class Controller extends Component implements ViewContextInterface * * The view to be rendered can be specified in one of the following formats: * - * - path alias (e.g. "@app/views/site/index"); + * - [path alias](guide:concept-aliases) (e.g. "@app/views/site/index"); * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes. * The actual view file will be looked for under the [[Application::viewPath|view path]] of the application. * - absolute path within module (e.g. "/site/index"): the view name starts with a single slash. @@ -362,7 +362,7 @@ class Controller extends Component implements ViewContextInterface * 2. In the second step, it determines the actual layout file according to the previously found layout name * and context module. The layout name can be: * - * - a path alias (e.g. "@app/views/layouts/main"); + * - a [path alias](guide:concept-aliases) (e.g. "@app/views/layouts/main"); * - an absolute path (e.g. "/main"): the layout name starts with a slash. The actual layout file will be * looked for under the [[Application::layoutPath|layout path]] of the application; * - a relative path (e.g. "main"): the actual layout file will be looked for under the @@ -413,7 +413,7 @@ class Controller extends Component implements ViewContextInterface /** * Renders a view file. - * @param string $file the view file to be rendered. This can be either a file path or a path alias. + * @param string $file the view file to be rendered. This can be either a file path or a [path alias](guide:concept-aliases). * @param array $params the parameters (name-value pairs) that should be made available in the view. * @return string the rendering result. * @throws InvalidParamException if the view file does not exist. diff --git a/framework/base/Module.php b/framework/base/Module.php index e631d87498..9820202d70 100644 --- a/framework/base/Module.php +++ b/framework/base/Module.php @@ -231,7 +231,7 @@ class Module extends ServiceLocator /** * Sets the root directory of the module. * This method can only be invoked at the beginning of the constructor. - * @param string $path the root directory of the module. This can be either a directory name or a path alias. + * @param string $path the root directory of the module. This can be either a directory name or a [path alias](guide:concept-aliases). * @throws InvalidParamException if the directory does not exist. */ public function setBasePath($path) @@ -294,7 +294,7 @@ class Module extends ServiceLocator /** * Sets the directory that contains the layout files. - * @param string $path the root directory or path alias of layout files. + * @param string $path the root directory or [path alias](guide:concept-aliases) of layout files. * @throws InvalidParamException if the directory is invalid */ public function setLayoutPath($path) diff --git a/framework/base/Request.php b/framework/base/Request.php index eaae73b6b2..53af930f79 100644 --- a/framework/base/Request.php +++ b/framework/base/Request.php @@ -73,7 +73,7 @@ abstract class Request extends Component * The entry script file path can normally be determined based on the `SCRIPT_FILENAME` SERVER variable. * However, for some server configurations, this may not be correct or feasible. * This setter is provided so that the entry script file path can be manually specified. - * @param string $value the entry script file path. This can be either a file path or a path alias. + * @param string $value the entry script file path. This can be either a file path or a [path alias](guide:concept-aliases). * @throws InvalidConfigException if the provided entry script file path is invalid. */ public function setScriptFile($value) diff --git a/framework/base/Theme.php b/framework/base/Theme.php index aa60581c29..7ea7f247ba 100644 --- a/framework/base/Theme.php +++ b/framework/base/Theme.php @@ -76,7 +76,7 @@ class Theme extends Component /** * @var array the mapping between view directories and their corresponding themed versions. * This property is used by [[applyTo()]] when a view is trying to apply the theme. - * Path aliases can be used when specifying directories. + * [Path aliases](guide:concept-aliases) can be used when specifying directories. * If this property is empty or not set, a mapping [[Application::basePath]] to [[basePath]] will be used. */ public $pathMap; @@ -94,7 +94,7 @@ class Theme extends Component } /** - * @param string $url the base URL or path alias for this theme. All resources of this theme are considered + * @param string $url the base URL or [path alias](guide:concept-aliases) for this theme. All resources of this theme are considered * to be under this base URL. */ public function setBaseUrl($url) @@ -114,7 +114,7 @@ class Theme extends Component } /** - * @param string $path the root path or path alias of this theme. All resources of this theme are located + * @param string $path the root path or [path alias](guide:concept-aliases) of this theme. All resources of this theme are located * under this directory. * @see pathMap */ diff --git a/framework/base/View.php b/framework/base/View.php index 85ad7f0957..ecfa616d21 100644 --- a/framework/base/View.php +++ b/framework/base/View.php @@ -126,7 +126,7 @@ class View extends Component * * The view to be rendered can be specified in one of the following formats: * - * - path alias (e.g. "@app/views/site/index"); + * - [path alias](guide:concept-aliases) (e.g. "@app/views/site/index"); * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes. * The actual view file will be looked for under the [[Application::viewPath|view path]] of the application. * - absolute path within current module (e.g. "/site/index"): the view name starts with a single slash. @@ -154,7 +154,7 @@ class View extends Component /** * Finds the view file based on the given view name. - * @param string $view the view name or the path alias of the view file. Please refer to [[render()]] + * @param string $view the view name or the [path alias](guide:concept-aliases) of the view file. Please refer to [[render()]] * on how to specify this parameter. * @param object $context the context to be assigned to the view and can later be accessed via [[context]] * in the view. If the context implements [[ViewContextInterface]], it may also be used to locate @@ -429,7 +429,7 @@ class View extends Component * ``` * * @param string $viewFile the view file that will be used to decorate the content enclosed by this widget. - * This can be specified as either the view file path or path alias. + * This can be specified as either the view file path or [path alias](guide:concept-aliases). * @param array $params the variables (name => value) to be extracted and made available in the decorative view. * @return ContentDecorator the ContentDecorator widget instance * @see ContentDecorator diff --git a/framework/base/Widget.php b/framework/base/Widget.php index 80af12fa6e..b791391a11 100644 --- a/framework/base/Widget.php +++ b/framework/base/Widget.php @@ -214,7 +214,7 @@ class Widget extends Component implements ViewContextInterface * Renders a view. * The view to be rendered can be specified in one of the following formats: * - * - path alias (e.g. "@app/views/site/index"); + * - [path alias](guide:concept-aliases) (e.g. "@app/views/site/index"); * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes. * The actual view file will be looked for under the [[Application::viewPath|view path]] of the application. * - absolute path within module (e.g. "/site/index"): the view name starts with a single slash. @@ -236,7 +236,7 @@ class Widget extends Component implements ViewContextInterface /** * Renders a view file. - * @param string $file the view file to be rendered. This can be either a file path or a path alias. + * @param string $file the view file to be rendered. This can be either a file path or a [path alias](guide:concept-aliases). * @param array $params the parameters (name-value pairs) that should be made available in the view. * @return string the rendering result. * @throws InvalidParamException if the view file does not exist. diff --git a/framework/caching/FileCache.php b/framework/caching/FileCache.php index 7069fe4020..31939b0740 100644 --- a/framework/caching/FileCache.php +++ b/framework/caching/FileCache.php @@ -35,7 +35,7 @@ class FileCache extends Cache */ public $keyPrefix = ''; /** - * @var string the directory to store cache files. You may use path alias here. + * @var string the directory to store cache files. You may use [path alias](guide:concept-aliases) here. * If not set, it will use the "cache" subdirectory under the application runtime path. */ public $cachePath = '@runtime/cache'; diff --git a/framework/caching/FileDependency.php b/framework/caching/FileDependency.php index 49c4e1e4c4..4ab98588b8 100644 --- a/framework/caching/FileDependency.php +++ b/framework/caching/FileDependency.php @@ -24,7 +24,7 @@ use yii\base\InvalidConfigException; class FileDependency extends Dependency { /** - * @var string the file path or path alias whose last modification time is used to + * @var string the file path or [path alias](guide:concept-aliases) whose last modification time is used to * check if the dependency has been changed. */ public $fileName; diff --git a/framework/captcha/CaptchaAction.php b/framework/captcha/CaptchaAction.php index 679fc254dd..81f3b3dfeb 100644 --- a/framework/captcha/CaptchaAction.php +++ b/framework/captcha/CaptchaAction.php @@ -87,7 +87,7 @@ class CaptchaAction extends Action */ public $offset = -2; /** - * @var string the TrueType font file. This can be either a file path or path alias. + * @var string the TrueType font file. This can be either a file path or [path alias](guide:concept-aliases). */ public $fontFile = '@yii/captcha/SpicyRice.ttf'; /** diff --git a/framework/console/controllers/AssetController.php b/framework/console/controllers/AssetController.php index 5ed5bb0ccb..d16220ad2a 100644 --- a/framework/console/controllers/AssetController.php +++ b/framework/console/controllers/AssetController.php @@ -31,7 +31,7 @@ use yii\web\AssetBundle; * * 4. Adjust your web application config to use compressed assets. * - * Note: in the console environment some path aliases like `@webroot` and `@web` may not exist, + * Note: in the console environment some [path aliases](guide:concept-aliases) like `@webroot` and `@web` may not exist, * so corresponding paths inside the configuration should be specified directly. * * Note: by default this command relies on an external tools to perform actual files compression, diff --git a/framework/console/controllers/BaseMigrateController.php b/framework/console/controllers/BaseMigrateController.php index 1da144c3da..6675a49a1b 100644 --- a/framework/console/controllers/BaseMigrateController.php +++ b/framework/console/controllers/BaseMigrateController.php @@ -33,7 +33,7 @@ abstract class BaseMigrateController extends Controller public $defaultAction = 'up'; /** * @var string the directory containing the migration classes. This can be either - * a path alias or a directory path. + * a [path alias](guide:concept-aliases) or a directory path. * * Migration classes located at this path should be declared without a namespace. * Use [[migrationNamespaces]] property in case you are using namespaced migrations. @@ -45,7 +45,7 @@ abstract class BaseMigrateController extends Controller /** * @var array list of namespaces containing the migration classes. * - * Migration namespaces should be resolvable as a path alias if prefixed with `@`, e.g. if you specify + * Migration namespaces should be resolvable as a [path alias](guide:concept-aliases) if prefixed with `@`, e.g. if you specify * the namespace `app\migrations`, the code `Yii::getAlias('@app/migrations')` should be able to return * the file path to the directory this namespace refers to. * diff --git a/framework/console/controllers/ServeController.php b/framework/console/controllers/ServeController.php index db8523c71e..65f15133fd 100644 --- a/framework/console/controllers/ServeController.php +++ b/framework/console/controllers/ServeController.php @@ -32,7 +32,7 @@ class ServeController extends Controller */ public $port = 8080; /** - * @var string path or path alias to directory to serve + * @var string path or [path alias](guide:concept-aliases) to directory to serve */ public $docroot = '@app/web'; /** diff --git a/framework/db/Connection.php b/framework/db/Connection.php index a75c80a8fa..d666bc526f 100644 --- a/framework/db/Connection.php +++ b/framework/db/Connection.php @@ -156,7 +156,7 @@ class Connection extends Component * Please refer to the [PHP manual](http://php.net/manual/en/pdo.construct.php) on * the format of the DSN string. * - * For [SQLite](http://php.net/manual/en/ref.pdo-sqlite.connection.php) you may use a path alias + * For [SQLite](http://php.net/manual/en/ref.pdo-sqlite.connection.php) you may use a [path alias](guide:concept-aliases) * for specifying the database path, e.g. `sqlite:@app/data/db.sql`. * * @see charset diff --git a/framework/log/FileTarget.php b/framework/log/FileTarget.php index e4c895c0e3..fabf50e599 100644 --- a/framework/log/FileTarget.php +++ b/framework/log/FileTarget.php @@ -26,7 +26,7 @@ use yii\helpers\FileHelper; class FileTarget extends Target { /** - * @var string log file path or path alias. If not set, it will use the "@runtime/logs/app.log" file. + * @var string log file path or [path alias](guide:concept-aliases). If not set, it will use the "@runtime/logs/app.log" file. * The directory containing the log files will be automatically created if not existing. */ public $logFile; diff --git a/framework/mail/BaseMailer.php b/framework/mail/BaseMailer.php index 07ab9c1768..98ede5d0d5 100644 --- a/framework/mail/BaseMailer.php +++ b/framework/mail/BaseMailer.php @@ -47,7 +47,7 @@ abstract class BaseMailer extends Component implements MailerInterface, ViewCont * The property can take the following values: * * - a relative view name: a view file relative to [[viewPath]], e.g., 'layouts/html'. - * - a path alias: an absolute view file path specified as a path alias, e.g., '@app/mail/html'. + * - a [path alias](guide:concept-aliases): an absolute view file path specified as a path alias, e.g., '@app/mail/html'. * - a boolean false: the layout is disabled. */ public $htmlLayout = 'layouts/html'; @@ -155,7 +155,7 @@ abstract class BaseMailer extends Component implements MailerInterface, ViewCont * * @param string|array|null $view the view to be used for rendering the message body. This can be: * - * - a string, which represents the view name or path alias for rendering the HTML body of the email. + * - a string, which represents the view name or [path alias](guide:concept-aliases) for rendering the HTML body of the email. * In this case, the text body will be generated by applying `strip_tags()` to the HTML body. * - an array with 'html' and/or 'text' elements. The 'html' element refers to the view name or path alias * for rendering the HTML body, while 'text' element is for rendering the text body. For example, @@ -291,9 +291,9 @@ abstract class BaseMailer extends Component implements MailerInterface, ViewCont /** * Renders the specified view with optional parameters and layout. * The view will be rendered using the [[view]] component. - * @param string $view the view name or the path alias of the view file. + * @param string $view the view name or the [path alias](guide:concept-aliases) of the view file. * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file. - * @param string|bool $layout layout view name or path alias. If false, no layout will be applied. + * @param string|bool $layout layout view name or [path alias](guide:concept-aliases). If false, no layout will be applied. * @return string the rendering result. */ public function render($view, $params = [], $layout = false) @@ -359,7 +359,7 @@ abstract class BaseMailer extends Component implements MailerInterface, ViewCont /** * @param string $path the directory that contains the view files for composing mail messages - * This can be specified as an absolute path or a path alias. + * This can be specified as an absolute path or a [path alias](guide:concept-aliases). */ public function setViewPath($path) { diff --git a/framework/mail/MailerInterface.php b/framework/mail/MailerInterface.php index 12542de0e1..d6c2cd71e6 100644 --- a/framework/mail/MailerInterface.php +++ b/framework/mail/MailerInterface.php @@ -33,7 +33,7 @@ interface MailerInterface * * @param string|array|null $view the view to be used for rendering the message body. This can be: * - * - a string, which represents the view name or path alias for rendering the HTML body of the email. + * - a string, which represents the view name or [path alias](guide:concept-aliases) for rendering the HTML body of the email. * In this case, the text body will be generated by applying `strip_tags()` to the HTML body. * - an array with 'html' and/or 'text' elements. The 'html' element refers to the view name or path alias * for rendering the HTML body, while 'text' element is for rendering the text body. For example, diff --git a/framework/mutex/FileMutex.php b/framework/mutex/FileMutex.php index d673785e1f..973c633c60 100644 --- a/framework/mutex/FileMutex.php +++ b/framework/mutex/FileMutex.php @@ -41,7 +41,7 @@ use yii\helpers\FileHelper; class FileMutex extends Mutex { /** - * @var string the directory to store mutex files. You may use path alias here. + * @var string the directory to store mutex files. You may use [path alias](guide:concept-aliases) here. * Defaults to the "mutex" subdirectory under the application runtime path. */ public $mutexPath = '@runtime/mutex'; diff --git a/framework/rbac/PhpManager.php b/framework/rbac/PhpManager.php index 26eccaa677..6b6b5aed89 100644 --- a/framework/rbac/PhpManager.php +++ b/framework/rbac/PhpManager.php @@ -38,7 +38,7 @@ class PhpManager extends BaseManager { /** * @var string the path of the PHP script that contains the authorization items. - * This can be either a file path or a path alias to the file. + * This can be either a file path or a [path alias](guide:concept-aliases) to the file. * Make sure this file is writable by the Web server process if the authorization needs to be changed online. * @see loadFromFile() * @see saveToFile() @@ -46,7 +46,7 @@ class PhpManager extends BaseManager public $itemFile = '@app/rbac/items.php'; /** * @var string the path of the PHP script that contains the authorization assignments. - * This can be either a file path or a path alias to the file. + * This can be either a file path or a [path alias](guide:concept-aliases) to the file. * Make sure this file is writable by the Web server process if the authorization needs to be changed online. * @see loadFromFile() * @see saveToFile() @@ -54,7 +54,7 @@ class PhpManager extends BaseManager public $assignmentFile = '@app/rbac/assignments.php'; /** * @var string the path of the PHP script that contains the authorization rules. - * This can be either a file path or a path alias to the file. + * This can be either a file path or a [path alias](guide:concept-aliases) to the file. * Make sure this file is writable by the Web server process if the authorization needs to be changed online. * @see loadFromFile() * @see saveToFile() diff --git a/framework/test/ActiveFixture.php b/framework/test/ActiveFixture.php index eed2c97ed1..bdac34a99e 100644 --- a/framework/test/ActiveFixture.php +++ b/framework/test/ActiveFixture.php @@ -40,7 +40,7 @@ class ActiveFixture extends BaseActiveFixture */ public $tableName; /** - * @var string|bool the file path or path alias of the data file that contains the fixture data + * @var string|bool the file path or [path alias](guide:concept-aliases) of the data file that contains the fixture data * to be returned by [[getData()]]. If this is not set, it will default to `FixturePath/data/TableName.php`, * where `FixturePath` stands for the directory containing this fixture class, and `TableName` stands for the * name of the table associated with this fixture. You can set this property to be false to prevent loading any data. diff --git a/framework/test/ArrayFixture.php b/framework/test/ArrayFixture.php index 7262e16e44..f96d72162d 100644 --- a/framework/test/ArrayFixture.php +++ b/framework/test/ArrayFixture.php @@ -28,7 +28,7 @@ class ArrayFixture extends Fixture implements \IteratorAggregate, \ArrayAccess, */ public $data = []; /** - * @var string|bool the file path or path alias of the data file that contains the fixture data + * @var string|bool the file path or [path alias](guide:concept-aliases) of the data file that contains the fixture data * to be returned by [[getData()]]. You can set this property to be false to prevent loading any data. */ public $dataFile; diff --git a/framework/test/BaseActiveFixture.php b/framework/test/BaseActiveFixture.php index e3b60920ee..fd86f1ff12 100644 --- a/framework/test/BaseActiveFixture.php +++ b/framework/test/BaseActiveFixture.php @@ -32,7 +32,7 @@ abstract class BaseActiveFixture extends DbFixture implements \IteratorAggregate */ public $data = []; /** - * @var string|bool the file path or path alias of the data file that contains the fixture data + * @var string|bool the file path or [path alias](guide:concept-aliases) of the data file that contains the fixture data * to be returned by [[getData()]]. You can set this property to be false to prevent loading any data. */ public $dataFile; diff --git a/framework/test/InitDbFixture.php b/framework/test/InitDbFixture.php index 285269edf3..4212f4b87f 100644 --- a/framework/test/InitDbFixture.php +++ b/framework/test/InitDbFixture.php @@ -30,7 +30,7 @@ class InitDbFixture extends DbFixture { /** * @var string the init script file that should be executed when loading this fixture. - * This should be either a file path or path alias. Note that if the file does not exist, + * This should be either a file path or [path alias](guide:concept-aliases). Note that if the file does not exist, * no error will be raised. */ public $initScript = '@app/tests/fixtures/initdb.php'; diff --git a/framework/web/AssetConverter.php b/framework/web/AssetConverter.php index a311a9fcbd..55e67d1276 100644 --- a/framework/web/AssetConverter.php +++ b/framework/web/AssetConverter.php @@ -26,7 +26,7 @@ class AssetConverter extends Component implements AssetConverterInterface * The keys are the asset file extension names, and the values are the corresponding * target script types (either "css" or "js") and the commands used for the conversion. * - * You may also use a path alias to specify the location of the command: + * You may also use a [path alias](guide:concept-aliases) to specify the location of the command: * * ```php * [ @@ -78,7 +78,7 @@ class AssetConverter extends Component implements AssetConverterInterface /** * Runs a command to convert asset files. - * @param string $command the command to run. If prefixed with an `@` it will be treated as a path alias. + * @param string $command the command to run. If prefixed with an `@` it will be treated as a [path alias](guide:concept-aliases). * @param string $basePath asset base path and command working directory * @param string $asset the name of the asset file * @param string $result the name of the file to be generated by the converter command diff --git a/framework/web/Session.php b/framework/web/Session.php index 588c29f9fb..99c7fb3ee6 100644 --- a/framework/web/Session.php +++ b/framework/web/Session.php @@ -333,7 +333,7 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co /** * Sets the current session save path. * This is a wrapper for [PHP session_save_path()](http://php.net/manual/en/function.session-save-path.php). - * @param string $value the current session save path. This can be either a directory name or a path alias. + * @param string $value the current session save path. This can be either a directory name or a [path alias](guide:concept-aliases). * @throws InvalidParamException if the path is not a valid directory */ public function setSavePath($value) diff --git a/framework/widgets/ContentDecorator.php b/framework/widgets/ContentDecorator.php index 26dee57c41..862960a9ad 100644 --- a/framework/widgets/ContentDecorator.php +++ b/framework/widgets/ContentDecorator.php @@ -44,7 +44,7 @@ class ContentDecorator extends Widget { /** * @var string the view file that will be used to decorate the content enclosed by this widget. - * This can be specified as either the view file path or path alias. + * This can be specified as either the view file path or [path alias](guide:concept-aliases). */ public $viewFile; /** From cb9462b22497e0c1c21294e58f3c8c61119013a0 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Thu, 1 Jun 2017 18:13:38 +0200 Subject: [PATCH 42/71] Added support for specifying aliases for migrationNamespaces This is used to specify pathes to migrations that do not have namespaces. While not directly supported by the migration command provideded by the framework, these migrations exist in a lot of extensions because custom implementations of migration controllers out of the framework were using this approach to load multiple migrations from multiple paths. Even the framework itself currently ships non-namespaced migrations: - https://github.com/yiisoft/yii2/blob/17a1d91e4a517f4f15dce973bf3c50dd939dce63/framework/rbac/migrations/m140506_102106_rbac_init.php - https://github.com/yiisoft/yii2/blob/17a1d91e4a517f4f15dce973bf3c50dd939dce63/framework/caching/migrations/m150909_153426_cache_init.php - https://github.com/yiisoft/yii2/blob/17a1d91e4a517f4f15dce973bf3c50dd939dce63/framework/log/migrations/m141106_185632_log_init.php This change allows existing applications to adopt the new namespace-based approach while keeping existing migrations. While it would be possible to add namespaces to migrations in the application itself, it is not easily possible to add namespaces to migrations that come from external sources like extensions. --- docs/guide/db-migrations.md | 5 +++++ .../controllers/BaseMigrateController.php | 20 ++++++++++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/docs/guide/db-migrations.md b/docs/guide/db-migrations.md index 7a15bf683e..4d848f6a33 100644 --- a/docs/guide/db-migrations.md +++ b/docs/guide/db-migrations.md @@ -933,6 +933,11 @@ yii migrate/create 'app\\migrations\\createUserTable' contain a namespace, namespaced migration can be applied only via [[yii\console\controllers\MigrateController::migrationNamespaces]] property. +Since version 2.0.12 the [[yii\console\controllers\MigrateController::migrationNamespaces|migrationNamespaces]] property +also accepts [aliases](concept-aliases.md) for specifying directories that contain migrations without a namespace. +This is mainly added to be used in existing projects which use migrations from different locations. These migrations mainly come +from external sources, like Yii extensions developed by other developers, +which can not be changed to use namespaces easily when starting to use the new approach. ### Separated Migrations diff --git a/framework/console/controllers/BaseMigrateController.php b/framework/console/controllers/BaseMigrateController.php index 6675a49a1b..74e866dd52 100644 --- a/framework/console/controllers/BaseMigrateController.php +++ b/framework/console/controllers/BaseMigrateController.php @@ -40,6 +40,7 @@ abstract class BaseMigrateController extends Controller * * If you have set up [[migrationNamespaces]], you may set this field to `null` in order * to disable usage of migrations that are not namespaced. + * @see $migrationNamespaces */ public $migrationPath = '@app/migrations'; /** @@ -58,7 +59,12 @@ abstract class BaseMigrateController extends Controller * ] * ``` * + * Since version 2.0.12 you may also specify [aliases](guide:concept-aliases) to directories that contain + * migrations without namespace. This is mainly useful to support old extensions that provide migrations + * without namespace and to adopt the new feature of namespaced migrations while keeping existing migrations. + * * @since 2.0.10 + * @see $migrationPath */ public $migrationNamespaces = []; /** @@ -594,6 +600,9 @@ abstract class BaseMigrateController extends Controller if ($this->migrationPath === null) { $migrationNamespaces = $this->migrationNamespaces; $namespace = array_shift($migrationNamespaces); + if (strncmp($namespace, '@', 1) === 0) { + $namespace = str_replace('/', '\\', substr($namespace, 1)); + } } } @@ -619,7 +628,8 @@ abstract class BaseMigrateController extends Controller return $this->migrationPath; } - if (!in_array($namespace, $this->migrationNamespaces, true)) { + if (!in_array($namespace, $this->migrationNamespaces, true) && + !in_array('@' . str_replace('\\', '/', $namespace), $this->migrationNamespaces, true)) { throw new Exception("Namespace '{$namespace}' not found in `migrationNamespaces`"); } @@ -634,7 +644,11 @@ abstract class BaseMigrateController extends Controller */ private function getNamespacePath($namespace) { - return str_replace('/', DIRECTORY_SEPARATOR, Yii::getAlias('@' . str_replace('\\', '/', $namespace))); + if (strncmp($namespace, '@', 1) === 0) { + return Yii::getAlias($namespace); + } else { + return str_replace('/', DIRECTORY_SEPARATOR, Yii::getAlias('@' . str_replace('\\', '/', $namespace))); + } } /** @@ -796,7 +810,7 @@ abstract class BaseMigrateController extends Controller $path = $migrationPath . DIRECTORY_SEPARATOR . $file; if (preg_match('/^(m(\d{6}_?\d{6})\D.*?)\.php$/is', $file, $matches) && is_file($path)) { $class = $matches[1]; - if (!empty($namespace)) { + if (!empty($namespace) && strncmp($namespace, '@', 1) !== 0) { $class = $namespace . '\\' . $class; } $time = str_replace('_', '', $matches[2]); From deb1def9d35480a240be0c4c616a90b3f1f6fed1 Mon Sep 17 00:00:00 2001 From: Tobias Munk Date: Thu, 1 Jun 2017 18:22:37 +0200 Subject: [PATCH 43/71] added alias syntax support fixes #13356 fixes #13359 --- framework/CHANGELOG.md | 1 + framework/console/controllers/BaseMigrateController.php | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 432fc7e88e..12b889d7b3 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -73,6 +73,7 @@ Yii Framework 2 Change Log - Enh #13254: Core validators no longer require `Yii::$app` to be set (sammousa) - Enh #13260: Added support for sorting by expression to `\yii\data\Sort` (LAV45, klimov-paul) - Enh #13278: `yii\caching\DbQueryDependency` created allowing specification of the cache dependency via `yii\db\QueryInterface` (klimov-paul) +- Enh #13356: Support aliases in `MigrateController::$migrationNamespaces` to load non-namespaced migrations for BC with existing applications and extensions (schmunk42, cebe) - Enh #13360: Added Dockerized test setup for the framework tests (schmunk42) - Enh #13369: Added ability to render current `yii\widgets\LinkPager` page disabled (aquy) - Enh #13376: Data provider now automatically sets an ID so there is no need to set it manually in case multiple data providers are used with pagination (SamMousa) diff --git a/framework/console/controllers/BaseMigrateController.php b/framework/console/controllers/BaseMigrateController.php index 74e866dd52..e72110c2bd 100644 --- a/framework/console/controllers/BaseMigrateController.php +++ b/framework/console/controllers/BaseMigrateController.php @@ -13,6 +13,7 @@ use yii\console\Exception; use yii\console\Controller; use yii\helpers\Console; use yii\helpers\FileHelper; +use yii\helpers\StringHelper; /** * BaseMigrateController is the base class for migrate controllers. @@ -718,6 +719,9 @@ abstract class BaseMigrateController extends Controller if (strpos($class, '\\') === false) { $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php'; require_once($file); + } elseif (!class_exists($class, true)) { + // if the class with namespace does not exist, try to load it without namespace + $class = StringHelper::basename($class); } return new $class(); From 5288577221f6f9877920bb72accf5348ef64777f Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Fri, 2 Jun 2017 13:10:19 +0200 Subject: [PATCH 44/71] make migrationPath accept an array --- docs/guide/db-migrations.md | 4 +- framework/CHANGELOG.md | 2 +- .../controllers/BaseMigrateController.php | 70 ++++++---- .../console/controllers/MigrateController.php | 15 ++- .../MigrateControllerTestTrait.php | 120 +++++++++++++++++- 5 files changed, 175 insertions(+), 36 deletions(-) diff --git a/docs/guide/db-migrations.md b/docs/guide/db-migrations.md index 4d848f6a33..2fa582e572 100644 --- a/docs/guide/db-migrations.md +++ b/docs/guide/db-migrations.md @@ -933,8 +933,8 @@ yii migrate/create 'app\\migrations\\createUserTable' contain a namespace, namespaced migration can be applied only via [[yii\console\controllers\MigrateController::migrationNamespaces]] property. -Since version 2.0.12 the [[yii\console\controllers\MigrateController::migrationNamespaces|migrationNamespaces]] property -also accepts [aliases](concept-aliases.md) for specifying directories that contain migrations without a namespace. +Since version 2.0.12 the [[yii\console\controllers\MigrateController::migrationPath|migrationPath]] property +also accepts an array for specifying multiple directories that contain migrations without a namespace. This is mainly added to be used in existing projects which use migrations from different locations. These migrations mainly come from external sources, like Yii extensions developed by other developers, which can not be changed to use namespaces easily when starting to use the new approach. diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 12b889d7b3..2816aadae0 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -73,7 +73,7 @@ Yii Framework 2 Change Log - Enh #13254: Core validators no longer require `Yii::$app` to be set (sammousa) - Enh #13260: Added support for sorting by expression to `\yii\data\Sort` (LAV45, klimov-paul) - Enh #13278: `yii\caching\DbQueryDependency` created allowing specification of the cache dependency via `yii\db\QueryInterface` (klimov-paul) -- Enh #13356: Support aliases in `MigrateController::$migrationNamespaces` to load non-namespaced migrations for BC with existing applications and extensions (schmunk42, cebe) +- Enh #13356: Support multiple paths in `MigrateController::$migrationPath` to load non-namespaced migrations for BC with existing applications and extensions (schmunk42, cebe) - Enh #13360: Added Dockerized test setup for the framework tests (schmunk42) - Enh #13369: Added ability to render current `yii\widgets\LinkPager` page disabled (aquy) - Enh #13376: Data provider now automatically sets an ID so there is no need to set it manually in case multiple data providers are used with pagination (SamMousa) diff --git a/framework/console/controllers/BaseMigrateController.php b/framework/console/controllers/BaseMigrateController.php index e72110c2bd..2b97df2a5d 100644 --- a/framework/console/controllers/BaseMigrateController.php +++ b/framework/console/controllers/BaseMigrateController.php @@ -33,7 +33,7 @@ abstract class BaseMigrateController extends Controller */ public $defaultAction = 'up'; /** - * @var string the directory containing the migration classes. This can be either + * @var string|array the directory containing the migration classes. This can be either * a [path alias](guide:concept-aliases) or a directory path. * * Migration classes located at this path should be declared without a namespace. @@ -41,6 +41,15 @@ abstract class BaseMigrateController extends Controller * * If you have set up [[migrationNamespaces]], you may set this field to `null` in order * to disable usage of migrations that are not namespaced. + * + * Since version 2.0.12 you may also specify an array of migration paths that should be searched for + * migrations to load. This is mainly useful to support old extensions that provide migrations + * without namespace and to adopt the new feature of namespaced migrations while keeping existing migrations. + * + * In general, to load migrations from different locations, [[migrationNamespaces]] is the preferable solution + * as the migration name contains the origin of the migration in the history, which is not the case when + * using multiple migration paths. + * * @see $migrationNamespaces */ public $migrationPath = '@app/migrations'; @@ -50,6 +59,7 @@ abstract class BaseMigrateController extends Controller * Migration namespaces should be resolvable as a [path alias](guide:concept-aliases) if prefixed with `@`, e.g. if you specify * the namespace `app\migrations`, the code `Yii::getAlias('@app/migrations')` should be able to return * the file path to the directory this namespace refers to. + * This corresponds with the [autoloading conventions](guide:concept-autoloading) of Yii. * * For example: * @@ -60,17 +70,13 @@ abstract class BaseMigrateController extends Controller * ] * ``` * - * Since version 2.0.12 you may also specify [aliases](guide:concept-aliases) to directories that contain - * migrations without namespace. This is mainly useful to support old extensions that provide migrations - * without namespace and to adopt the new feature of namespaced migrations while keeping existing migrations. - * * @since 2.0.10 * @see $migrationPath */ public $migrationNamespaces = []; /** * @var string the template file for generating new migrations. - * This can be either a path alias (e.g. "@app/migrations/template.php") + * This can be either a [path alias](guide:concept-aliases) (e.g. "@app/migrations/template.php") * or a file path. */ public $templateFile; @@ -106,7 +112,11 @@ abstract class BaseMigrateController extends Controller $this->migrationNamespaces[$key] = trim($value, '\\'); } - if ($this->migrationPath !== null) { + if (is_array($this->migrationPath)) { + foreach($this->migrationPath as $i => $path) { + $this->migrationPath[$i] = Yii::getAlias($path); + } + } elseif ($this->migrationPath !== null) { $path = Yii::getAlias($this->migrationPath); if (!is_dir($path)) { if ($action->id !== 'create') { @@ -601,9 +611,6 @@ abstract class BaseMigrateController extends Controller if ($this->migrationPath === null) { $migrationNamespaces = $this->migrationNamespaces; $namespace = array_shift($migrationNamespaces); - if (strncmp($namespace, '@', 1) === 0) { - $namespace = str_replace('/', '\\', substr($namespace, 1)); - } } } @@ -626,11 +633,10 @@ abstract class BaseMigrateController extends Controller private function findMigrationPath($namespace) { if (empty($namespace)) { - return $this->migrationPath; + return is_array($this->migrationPath) ? reset($this->migrationPath) : $this->migrationPath; } - if (!in_array($namespace, $this->migrationNamespaces, true) && - !in_array('@' . str_replace('\\', '/', $namespace), $this->migrationNamespaces, true)) { + if (!in_array($namespace, $this->migrationNamespaces, true)) { throw new Exception("Namespace '{$namespace}' not found in `migrationNamespaces`"); } @@ -645,11 +651,7 @@ abstract class BaseMigrateController extends Controller */ private function getNamespacePath($namespace) { - if (strncmp($namespace, '@', 1) === 0) { - return Yii::getAlias($namespace); - } else { - return str_replace('/', DIRECTORY_SEPARATOR, Yii::getAlias('@' . str_replace('\\', '/', $namespace))); - } + return str_replace('/', DIRECTORY_SEPARATOR, Yii::getAlias('@' . str_replace('\\', '/', $namespace))); } /** @@ -717,11 +719,18 @@ abstract class BaseMigrateController extends Controller { $class = trim($class, '\\'); if (strpos($class, '\\') === false) { - $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php'; - require_once($file); - } elseif (!class_exists($class, true)) { - // if the class with namespace does not exist, try to load it without namespace - $class = StringHelper::basename($class); + if (is_array($this->migrationPath)) { + foreach($this->migrationPath as $path) { + $file = $path . DIRECTORY_SEPARATOR . $class . '.php'; + if (is_file($file)) { + require_once($file); + break; + } + } + } else { + $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php'; + require_once($file); + } } return new $class(); @@ -794,15 +803,20 @@ abstract class BaseMigrateController extends Controller } $migrationPaths = []; - if (!empty($this->migrationPath)) { - $migrationPaths[''] = $this->migrationPath; + if (is_array($this->migrationPath)) { + foreach($this->migrationPath as $path) { + $migrationPaths[] = [$path, '']; + } + } elseif (!empty($this->migrationPath)) { + $migrationPaths[] = [$this->migrationPath, '']; } foreach ($this->migrationNamespaces as $namespace) { - $migrationPaths[$namespace] = $this->getNamespacePath($namespace); + $migrationPaths[] = [$this->getNamespacePath($namespace), $namespace]; } $migrations = []; - foreach ($migrationPaths as $namespace => $migrationPath) { + foreach ($migrationPaths as $item) { + list($migrationPath, $namespace) = $item; if (!file_exists($migrationPath)) { continue; } @@ -814,7 +828,7 @@ abstract class BaseMigrateController extends Controller $path = $migrationPath . DIRECTORY_SEPARATOR . $file; if (preg_match('/^(m(\d{6}_?\d{6})\D.*?)\.php$/is', $file, $matches) && is_file($path)) { $class = $matches[1]; - if (!empty($namespace) && strncmp($namespace, '@', 1) !== 0) { + if (!empty($namespace)) { $class = $namespace . '\\' . $class; } $time = str_replace('_', '', $matches[2]); diff --git a/framework/console/controllers/MigrateController.php b/framework/console/controllers/MigrateController.php index 2b9866afbf..3df4136c73 100644 --- a/framework/console/controllers/MigrateController.php +++ b/framework/console/controllers/MigrateController.php @@ -184,10 +184,21 @@ class MigrateController extends BaseMigrateController { $class = trim($class, '\\'); if (strpos($class, '\\') === false) { - $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php'; - require_once($file); + if (is_array($this->migrationPath)) { + foreach($this->migrationPath as $path) { + $file = $path . DIRECTORY_SEPARATOR . $class . '.php'; + if (is_file($file)) { + require_once($file); + break; + } + } + } else { + $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php'; + require_once($file); + } } + return new $class(['db' => $this->db]); } diff --git a/tests/framework/console/controllers/MigrateControllerTestTrait.php b/tests/framework/console/controllers/MigrateControllerTestTrait.php index acbb904f8c..39fef0cf17 100644 --- a/tests/framework/console/controllers/MigrateControllerTestTrait.php +++ b/tests/framework/console/controllers/MigrateControllerTestTrait.php @@ -46,6 +46,8 @@ trait MigrateControllerTestTrait public function tearDownMigrationPath() { FileHelper::removeDirectory($this->migrationPath); + FileHelper::removeDirectory(Yii::getAlias('@yiiunit/runtime/app_migrations')); + FileHelper::removeDirectory(Yii::getAlias('@yiiunit/runtime/extension_migrations')); } /** @@ -93,7 +95,7 @@ trait MigrateControllerTestTrait * @param string|null $date * @return string generated class name */ - protected function createMigration($name, $date = null) + protected function createMigration($name, $date = null, $path = null) { if ($date === null) { $date = gmdate('ymd_His'); @@ -115,7 +117,7 @@ class {$class} extends {$baseClass} } } CODE; - file_put_contents($this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php', $code); + file_put_contents(($path ? Yii::getAlias($path) : $this->migrationPath) . DIRECTORY_SEPARATOR . $class . '.php', $code); return $class; } @@ -469,4 +471,116 @@ CODE; $this->assertMigrationHistory(['m*_base', $this->migrationNamespace . '\\M*To1']); } -} \ No newline at end of file + + /** + * Test migration with using multiple migration paths and namespaces + */ + public function testCombinedMigrationProcess() + { + FileHelper::createDirectory(Yii::getAlias('@yiiunit/runtime/app_migrations')); + FileHelper::createDirectory(Yii::getAlias('@yiiunit/runtime/extension_migrations')); + $controllerConfig = [ + 'migrationPath' => [$appPath = '@yiiunit/runtime/app_migrations', $extensionPath = '@yiiunit/runtime/extension_migrations'], + 'migrationNamespaces' => [$this->migrationNamespace] + ]; + + $this->createMigration('app_migration1', '010101_000001', $appPath); + $this->createMigration('ext_migration1', '010101_000002', $extensionPath); + $this->createMigration('app_migration2', '010101_000003', $appPath); + $this->createNamespaceMigration('NsMigration', '010101000004'); + + // yii migrate/up 1 + $this->runMigrateControllerAction('up', [1], $controllerConfig); + $this->assertMigrationHistory(['m*_base', 'm010101_000001_app_migration1']); + + // yii migrate/up + $this->runMigrateControllerAction('up', [], $controllerConfig); + $this->assertMigrationHistory([ + 'm*_base', + 'm010101_000001_app_migration1', + 'm010101_000002_ext_migration1', + 'm010101_000003_app_migration2', + $this->migrationNamespace . '\\M010101000004NsMigration', + ]); + + // yii migrate/to m010101_000002_ext_migration1 + $this->runMigrateControllerAction('to', ['m010101_000002_ext_migration1'], $controllerConfig); + $this->assertMigrationHistory([ + 'm*_base', + 'm010101_000001_app_migration1', + ]); + + // yii migrate/mark M010101000004NsMigration + $this->runMigrateControllerAction('mark', ['m010101_000003_app_migration2'], $controllerConfig); + $this->assertMigrationHistory([ + 'm*_base', + 'm010101_000001_app_migration1', + 'm010101_000002_ext_migration1', + 'm010101_000003_app_migration2', + ]); + + // yii migrate/up + $this->runMigrateControllerAction('up', [], $controllerConfig); + $this->assertMigrationHistory([ + 'm*_base', + 'm010101_000001_app_migration1', + 'm010101_000002_ext_migration1', + 'm010101_000003_app_migration2', + $this->migrationNamespace . '\\M010101000004NsMigration', + ]); + + // yii migrate/redo 2 + $this->runMigrateControllerAction('redo', [2], $controllerConfig); + $this->assertMigrationHistory([ + 'm*_base', + 'm010101_000001_app_migration1', + 'm010101_000002_ext_migration1', + 'm010101_000003_app_migration2', + $this->migrationNamespace . '\\M010101000004NsMigration', + ]); + + // yii migrate/down + $this->runMigrateControllerAction('down', [], $controllerConfig); + $this->assertMigrationHistory([ + 'm*_base', + 'm010101_000001_app_migration1', + 'm010101_000002_ext_migration1', + 'm010101_000003_app_migration2', + ]); + + // yii migrate/redo + $this->runMigrateControllerAction('redo', [], $controllerConfig); + $this->assertMigrationHistory([ + 'm*_base', + 'm010101_000001_app_migration1', + 'm010101_000002_ext_migration1', + 'm010101_000003_app_migration2', + ]); + + // yii migrate/down 2 + $this->runMigrateControllerAction('down', [2], $controllerConfig); + $this->assertMigrationHistory([ + 'm*_base', + 'm010101_000001_app_migration1', + ]); + + // yii migrate/create app_migration3 + $this->runMigrateControllerAction('create', ['app_migration3'], $controllerConfig); + $this->assertMigrationHistory([ + 'm*_base', + 'm010101_000001_app_migration1', + ]); + + // yii migrate/up + $this->runMigrateControllerAction('up', [], $controllerConfig); + $this->assertMigrationHistory([ + 'm*_base', + 'm010101_000001_app_migration1', + 'm010101_000002_ext_migration1', + 'm010101_000003_app_migration2', + $this->migrationNamespace . '\\M010101000004NsMigration', + 'm*_app_migration3' + ]); + $this->assertCount(1, FileHelper::findFiles(Yii::getAlias($appPath), ['only'=> ['m*_app_migration3.php']])); + } +} From 6ec6f8d76cc637ede75a1c601d4d37b7d36a0347 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Fri, 2 Jun 2017 13:32:02 +0200 Subject: [PATCH 45/71] moved include file logic to separate method --- docs/guide/db-migrations.md | 5 +++-- .../controllers/BaseMigrateController.php | 17 +++++++++++++++-- .../console/controllers/MigrateController.php | 18 +----------------- 3 files changed, 19 insertions(+), 21 deletions(-) diff --git a/docs/guide/db-migrations.md b/docs/guide/db-migrations.md index 2fa582e572..e7ae53a688 100644 --- a/docs/guide/db-migrations.md +++ b/docs/guide/db-migrations.md @@ -835,9 +835,10 @@ The migration command comes with a few command-line options that can be used to When this is `true`, the user will be prompted before the command performs certain actions. You may want to set this to `false` if the command is being used in a background process. -* `migrationPath`: string (defaults to `@app/migrations`), specifies the directory storing all migration +* `migrationPath`: string|array (defaults to `@app/migrations`), specifies the directory storing all migration class files. This can be specified as either a directory path or a path [alias](concept-aliases.md). - Note that the directory must exist, or the command may trigger an error. + Note that the directory must exist, or the command may trigger an error. Since version 2.0.12 an array can be + specified for loading migrations from multiple sources. * `migrationTable`: string (defaults to `migration`), specifies the name of the database table for storing migration history information. The table will be automatically created by the command if it does not exist. diff --git a/framework/console/controllers/BaseMigrateController.php b/framework/console/controllers/BaseMigrateController.php index 2b97df2a5d..a4d05c8bec 100644 --- a/framework/console/controllers/BaseMigrateController.php +++ b/framework/console/controllers/BaseMigrateController.php @@ -716,6 +716,21 @@ abstract class BaseMigrateController extends Controller * @return \yii\db\MigrationInterface the migration instance */ protected function createMigration($class) + { + $this->includeMigrationFile($class); + return new $class(); + } + + /** + * Includes the migration file for a given migration class name. + * + * This function will do nothing on namespaced migrations, which are loaded by + * autoloading automatically. It will include the migration file, by searching + * [[migrationPath]] for classes without namespace. + * @param string $class the migration class name. + * @since 2.0.12 + */ + protected function includeMigrationFile($class) { $class = trim($class, '\\'); if (strpos($class, '\\') === false) { @@ -732,8 +747,6 @@ abstract class BaseMigrateController extends Controller require_once($file); } } - - return new $class(); } /** diff --git a/framework/console/controllers/MigrateController.php b/framework/console/controllers/MigrateController.php index 3df4136c73..c6c9315295 100644 --- a/framework/console/controllers/MigrateController.php +++ b/framework/console/controllers/MigrateController.php @@ -182,23 +182,7 @@ class MigrateController extends BaseMigrateController */ protected function createMigration($class) { - $class = trim($class, '\\'); - if (strpos($class, '\\') === false) { - if (is_array($this->migrationPath)) { - foreach($this->migrationPath as $path) { - $file = $path . DIRECTORY_SEPARATOR . $class . '.php'; - if (is_file($file)) { - require_once($file); - break; - } - } - } else { - $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php'; - require_once($file); - } - } - - + $this->includeMigrationFile($class); return new $class(['db' => $this->db]); } From cd3c6404cb658b2a0d397959c5428779d706f045 Mon Sep 17 00:00:00 2001 From: Paul Klimov Date: Fri, 2 Jun 2017 21:19:38 +0300 Subject: [PATCH 46/71] Fixes #4999: Added support for wildcards at `yii\filters\AccessRule::$controllers` --- framework/CHANGELOG.md | 1 + framework/filters/AccessRule.php | 15 +++++- tests/framework/filters/AccessRuleTest.php | 60 +++++++++++++++++++++- 3 files changed, 74 insertions(+), 2 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 432fc7e88e..be2fee9aab 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -103,6 +103,7 @@ Yii Framework 2 Change Log - Enh #14059: Removed unused AR instantiating for calling of static methods (ElisDN) - Enh #14067: `yii\web\View::clear()` sets populated arrays to empty arrays instead of null, also changed default values to empty array (craiglondon) - Enh #4793: `yii\filters\AccessControl` now can be used without `user` component (bizley) +- Enh #4999: Added support for wildcards at `yii\filters\AccessRule::$controllers` (klimov-paul) - Enh: Added `yii\di\Instance::__set_state()` method to restore object after serialization using `var_export()` function (silvefire) - Bug #14072: Fixed a bug where `\yii\db\Command::createTable()`, `addForeignKey()`, `dropForeignKey()`, `addCommentOnColumn()`, and `dropCommentFromColumn()` weren't refreshing the table cache on `yii\db\Schema` (brandonkelly) - Bug #10305: Oracle SQL queries with `IN` condition and more than 1000 parameters are working now (silverfire) diff --git a/framework/filters/AccessRule.php b/framework/filters/AccessRule.php index 26d3d2b8ff..513a7039f1 100644 --- a/framework/filters/AccessRule.php +++ b/framework/filters/AccessRule.php @@ -43,6 +43,8 @@ class AccessRule extends Component * The comparison is case-sensitive. * * If not set or empty, it means this rule applies to all controllers. + * + * Since version 2.0.12 controller IDs can be specified as wildcards, e.g. `module/*`. */ public $controllers; /** @@ -172,7 +174,18 @@ class AccessRule extends Component */ protected function matchController($controller) { - return empty($this->controllers) || in_array($controller->uniqueId, $this->controllers, true); + if (empty($this->controllers)) { + return true; + } + + $id = $controller->getUniqueId(); + foreach ($this->controllers as $pattern) { + if (fnmatch($pattern, $id)) { + return true; + } + } + + return false; } /** diff --git a/tests/framework/filters/AccessRuleTest.php b/tests/framework/filters/AccessRuleTest.php index e3c338488a..9de4d80d5a 100644 --- a/tests/framework/filters/AccessRuleTest.php +++ b/tests/framework/filters/AccessRuleTest.php @@ -141,7 +141,65 @@ class AccessRuleTest extends \yiiunit\TestCase $this->assertNull($rule->allows($action, $user, $request)); } - // TODO test match controller + public function testMatchController() + { + $action = $this->mockAction(); + $user = false; + $request = $this->mockRequest(); + + $rule = new AccessRule([ + 'allow' => true, + 'controllers' => ['test', 'other'], + ]); + + $action->controller->id = 'test'; + $this->assertTrue($rule->allows($action, $user, $request)); + + $action->controller->id = 'other'; + $this->assertTrue($rule->allows($action, $user, $request)); + $action->controller->id = 'foreign'; + $this->assertNull($rule->allows($action, $user, $request)); + + $rule->allow = false; + + $action->controller->id = 'test'; + $this->assertFalse($rule->allows($action, $user, $request)); + $action->controller->id = 'other'; + $this->assertFalse($rule->allows($action, $user, $request)); + $action->controller->id = 'foreign'; + $this->assertNull($rule->allows($action, $user, $request)); + } + + /** + * @depends testMatchController + */ + public function testMatchControllerWildcard() + { + $action = $this->mockAction(); + $user = false; + $request = $this->mockRequest(); + + $rule = new AccessRule([ + 'allow' => true, + 'controllers' => ['module/*', '*/controller'], + ]); + + $action->controller->id = 'module/test'; + $this->assertTrue($rule->allows($action, $user, $request)); + $action->controller->id = 'any-module/controller'; + $this->assertTrue($rule->allows($action, $user, $request)); + $action->controller->id = 'other/other'; + $this->assertNull($rule->allows($action, $user, $request)); + + $rule->allow = false; + + $action->controller->id = 'module/test'; + $this->assertFalse($rule->allows($action, $user, $request)); + $action->controller->id = 'any-module/controller'; + $this->assertFalse($rule->allows($action, $user, $request)); + $action->controller->id = 'other/other'; + $this->assertNull($rule->allows($action, $user, $request)); + } /** * Data provider for testMatchRole From 844eacba26f392b5fbc2e491c256634e5ce25faa Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Mon, 5 Jun 2017 11:31:38 +0200 Subject: [PATCH 47/71] Update BaseMigrateController.php make sure console arguments are recognized as array. --- framework/console/controllers/BaseMigrateController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/console/controllers/BaseMigrateController.php b/framework/console/controllers/BaseMigrateController.php index a4d05c8bec..c84d81f9a8 100644 --- a/framework/console/controllers/BaseMigrateController.php +++ b/framework/console/controllers/BaseMigrateController.php @@ -52,7 +52,7 @@ abstract class BaseMigrateController extends Controller * * @see $migrationNamespaces */ - public $migrationPath = '@app/migrations'; + public $migrationPath = ['@app/migrations']; /** * @var array list of namespaces containing the migration classes. * From 40e5702b6bc80fdd2ea0fc10e4296ca21e7087fe Mon Sep 17 00:00:00 2001 From: Paul Klimov Date: Mon, 5 Jun 2017 12:50:02 +0300 Subject: [PATCH 48/71] Fixes #5108 `DateValidator` resets `$timestampAttribute` value on empty attribute (#14242) * `yii\validators\DateValidator` now resets `$timestampAttribute` value on empty validated attribute value * array-value test at `DateValidatorTest` restored --- framework/CHANGELOG.md | 1 + framework/validators/DateValidator.php | 7 ++++ .../validators/DateValidatorTest.php | 37 +++++++++++++++++-- 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 1ccc0f280b..41379d4c97 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -104,6 +104,7 @@ Yii Framework 2 Change Log - Enh #14059: Removed unused AR instantiating for calling of static methods (ElisDN) - Enh #14067: `yii\web\View::clear()` sets populated arrays to empty arrays instead of null, also changed default values to empty array (craiglondon) - Enh #4793: `yii\filters\AccessControl` now can be used without `user` component (bizley) +- Enh #5108: `yii\validators\DateValidator` now resets `$timestampAttribute` value on empty validated attribute value (klimov-paul) - Enh #4999: Added support for wildcards at `yii\filters\AccessRule::$controllers` (klimov-paul) - Enh: Added `yii\di\Instance::__set_state()` method to restore object after serialization using `var_export()` function (silvefire) - Bug #14072: Fixed a bug where `\yii\db\Command::createTable()`, `addForeignKey()`, `dropForeignKey()`, `addCommentOnColumn()`, and `dropCommentFromColumn()` weren't refreshing the table cache on `yii\db\Schema` (brandonkelly) diff --git a/framework/validators/DateValidator.php b/framework/validators/DateValidator.php index 53e605fec7..871f522285 100644 --- a/framework/validators/DateValidator.php +++ b/framework/validators/DateValidator.php @@ -266,6 +266,13 @@ class DateValidator extends Validator public function validateAttribute($model, $attribute) { $value = $model->$attribute; + if ($this->isEmpty($value)) { + if ($this->timestampAttribute !== null) { + $model->{$this->timestampAttribute} = null; + } + return; + } + $timestamp = $this->parseDateValue($value); if ($timestamp === false) { if ($this->timestampAttribute === $attribute) { diff --git a/tests/framework/validators/DateValidatorTest.php b/tests/framework/validators/DateValidatorTest.php index a0dde97f61..bbf39d32ab 100644 --- a/tests/framework/validators/DateValidatorTest.php +++ b/tests/framework/validators/DateValidatorTest.php @@ -155,11 +155,11 @@ class DateValidatorTest extends TestCase 1379030400, // 2013-09-13 00:00:00 $model->attr_timestamp ); + // array value $val = new DateValidator(['format' => 'php:Y-m-d']); - $model = FakedValidationModel::createWithAttributes(['attr_date' => []]); + $model = FakedValidationModel::createWithAttributes(['attr_date' => ['2013-09-13']]); $val->validateAttribute($model, 'attr_date'); $this->assertTrue($model->hasErrors('attr_date')); - } /** @@ -199,10 +199,12 @@ class DateValidatorTest extends TestCase 1379030400, // 2013-09-13 00:00:00 $model->attr_timestamp ); + // array value $val = new DateValidator(['format' => 'yyyy-MM-dd']); - $model = FakedValidationModel::createWithAttributes(['attr_date' => []]); + $model = FakedValidationModel::createWithAttributes(['attr_date' => ['2013-09-13']]); $val->validateAttribute($model, 'attr_date'); $this->assertTrue($model->hasErrors('attr_date')); + // invalid format $val = new DateValidator(['format' => 'yyyy-MM-dd']); $model = FakedValidationModel::createWithAttributes(['attr_date' => '2012-12-12foo']); $val->validateAttribute($model, 'attr_date'); @@ -601,4 +603,33 @@ class DateValidatorTest extends TestCase $val->validateAttribute($model, 'attr_date'); $this->assertTrue($model->hasErrors('attr_date')); } + + /** + * @depends testValidateAttributePHPFormat + */ + public function testTimestampAttributeOnEmpty() + { + $validator = new DateValidator([ + 'format' => 'php:Y/m/d', + 'timestampAttribute' => 'attr_date', + 'skipOnEmpty' => false, + ]); + $model = new FakedValidationModel(); + $model->attr_date = ''; + $validator->validateAttribute($model, 'attr_date'); + $this->assertFalse($model->hasErrors('attr_date')); + $this->assertNull($model->attr_date); + + $validator = new DateValidator([ + 'format' => 'php:Y/m/d', + 'timestampAttribute' => 'attr_timestamp', + 'skipOnEmpty' => false, + ]); + $model = new FakedValidationModel(); + $model->attr_date = ''; + $model->attr_timestamp = 1379030400; + $validator->validateAttribute($model, 'attr_date'); + $this->assertFalse($model->hasErrors('attr_date')); + $this->assertNull($model->attr_timestamp); + } } From 226f524da369b67a35f697c887eb07f9b99d610c Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Mon, 5 Jun 2017 13:25:51 +0200 Subject: [PATCH 49/71] skip failing HHVM test see https://github.com/yiisoft/yii2/issues/14244 --- tests/framework/rbac/DbManagerTestCase.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/framework/rbac/DbManagerTestCase.php b/tests/framework/rbac/DbManagerTestCase.php index 822d815a3c..13231e7a96 100644 --- a/tests/framework/rbac/DbManagerTestCase.php +++ b/tests/framework/rbac/DbManagerTestCase.php @@ -73,6 +73,9 @@ abstract class DbManagerTestCase extends ManagerTestCase protected function setUp() { + if (defined('HHVM_VERSION') && static::$driverName === 'pgsql') { + static::markTestSkipped('HHVM PDO for pgsql does not work with binary columns, which are essential for rbac schema. See https://github.com/yiisoft/yii2/issues/14244'); + } parent::setUp(); $this->auth = $this->createManager(); } From 717c545d2cae5fb5d5472023312ad3774b10efd7 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Mon, 5 Jun 2017 16:04:32 +0200 Subject: [PATCH 50/71] moved wrong changelog entry --- framework/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 41379d4c97..6402976400 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -73,6 +73,7 @@ Yii Framework 2 Change Log - Enh #13254: Core validators no longer require `Yii::$app` to be set (sammousa) - Enh #13260: Added support for sorting by expression to `\yii\data\Sort` (LAV45, klimov-paul) - Enh #13278: `yii\caching\DbQueryDependency` created allowing specification of the cache dependency via `yii\db\QueryInterface` (klimov-paul) +- Enh #13352: Added option to not render empty row in `yii\grid\GridView` when data is empty and `emptyText` set to `false` (arogachev) - Enh #13356: Support multiple paths in `MigrateController::$migrationPath` to load non-namespaced migrations for BC with existing applications and extensions (schmunk42, cebe) - Enh #13360: Added Dockerized test setup for the framework tests (schmunk42) - Enh #13369: Added ability to render current `yii\widgets\LinkPager` page disabled (aquy) @@ -251,7 +252,6 @@ Yii Framework 2 Change Log - Enh #13268: Added logging of memory usage (bashkarev) - Enh #13417: Allow customizing `yii\data\ActiveDataProvider` in `yii\rest\IndexAction` (leandrogehlen) - Enh #13453: Select only primary key when counting records in UniqueValidator (developeruz) -- Enh #13352: Added option to not render empty row in `yii\grid\GridView` when data is empty and `emptyText` set to `false` (arogachev) - Enh: Added constants for specifying `yii\validators\CompareValidator::$type` (cebe) - Enh: Refactored `yii\web\ErrorAction` to make it reusable (silverfire) - Enh: Added support for field `yii\console\controllers\BaseMigrateController::$migrationNamespaces` setup from CLI (schmunk42) From c09a03ab8ecfa345a4d2d779ca7db256b86e90c0 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Mon, 5 Jun 2017 16:26:51 +0200 Subject: [PATCH 51/71] fixed version and missing `@since` annotation --- composer.json | 2 +- framework/web/XmlResponseFormatter.php | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 1803dc86b8..775c8623bc 100644 --- a/composer.json +++ b/composer.json @@ -76,7 +76,7 @@ "ezyang/htmlpurifier": "~4.6", "cebe/markdown": "~1.0.0 | ~1.1.0", "bower-asset/jquery": "2.2.*@stable | 2.1.*@stable | 1.11.*@stable | 1.12.*@stable", - "bower-asset/jquery.inputmask": "~3.2.2 | ~3.3.3", + "bower-asset/jquery.inputmask": "~3.2.2 | ~3.3.5", "bower-asset/punycode": "1.3.*", "bower-asset/yii2-pjax": "~2.0.1" }, diff --git a/framework/web/XmlResponseFormatter.php b/framework/web/XmlResponseFormatter.php index fadf5bb499..c76b27dfb3 100644 --- a/framework/web/XmlResponseFormatter.php +++ b/framework/web/XmlResponseFormatter.php @@ -169,6 +169,7 @@ class XmlResponseFormatter extends Component implements ResponseFormatterInterfa * @param mixed $name * @return bool * @see http://stackoverflow.com/questions/2519845/how-to-check-if-string-is-a-valid-xml-element-name/2519943#2519943 + * @since 2.0.12 */ protected function isValidXmlName($name) { From be658f82bf515f1c1040cb6f987280f436258dc0 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Mon, 5 Jun 2017 16:33:41 +0200 Subject: [PATCH 52/71] release version 2.0.12 --- framework/BaseYii.php | 2 +- framework/CHANGELOG.md | 24 +++++++++++------------ framework/behaviors/SluggableBehavior.php | 2 +- framework/classes.php | 2 ++ framework/data/BaseDataProvider.php | 1 + framework/db/ActiveQuery.php | 2 ++ framework/db/BaseActiveRecord.php | 2 +- framework/db/Connection.php | 1 + framework/db/QueryBuilder.php | 1 + framework/db/cubrid/QueryBuilder.php | 1 + framework/db/mssql/QueryBuilder.php | 1 + framework/db/oci/QueryBuilder.php | 1 + framework/db/pgsql/Schema.php | 2 -- framework/db/sqlite/QueryBuilder.php | 1 + framework/helpers/BaseHtml.php | 1 - framework/rbac/BaseManager.php | 3 +++ framework/validators/Validator.php | 4 ++-- framework/web/CompositeUrlRule.php | 3 +++ framework/web/Request.php | 3 ++- framework/web/Response.php | 1 + framework/web/UrlRule.php | 5 ++++- 21 files changed, 41 insertions(+), 22 deletions(-) diff --git a/framework/BaseYii.php b/framework/BaseYii.php index d23c611402..5b71034f37 100644 --- a/framework/BaseYii.php +++ b/framework/BaseYii.php @@ -93,7 +93,7 @@ class BaseYii */ public static function getVersion() { - return '2.0.12-dev'; + return '2.0.12'; } /** diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 6402976400..1a7f144ae7 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -1,15 +1,15 @@ Yii Framework 2 Change Log ========================== -2.0.12 under development --------------------------- +2.0.12 June 05, 2017 +-------------------- -- Bug #13842: Fixed ambiguous table SQL error while using `yii\validators\ExistValidator` and `yii\validators\UniqueValidator` (vladis84, samdark) -- Bug #5442: Fixed problem on load fixture dependencies with database related tests (leandrogehlen) - Bug #4408: Add support for unicode word characters and `+` character in attribute names (sammousa, kmindi) +- Bug #5442: Fixed problem on load fixture dependencies with database related tests (leandrogehlen) - Bug #7946: Fixed a bug when the `form` attribute was not propagated to the hidden input of the checkbox (Kolyunya) - Bug #8120: Fixes LIKE special characters escaping for Cubrid/MSSQL/Oracle/SQLite in `yii\db\QueryBuilder` (sergeymakinen) - Bug #9669: AssetManager and `FileHelper::copyDirectory()` were copying empty directories when using `only` or `except` options. Added an option to disable this (cebe) +- Bug #10305: Oracle SQL queries with `IN` condition and more than 1000 parameters are working now (silverfire) - Bug #10346: Fixed "DOMException: Invalid Character Error" in `yii\web\XmlResponseFormatter::buildXml()` (sasha-ch) - Bug #10372: Fixed console controller including complex typed arguments in help (sammousa) - Bug #11230: Include `defaultRoles` in `yii\rbac\DbManager->getRolesByUser()` results (developeruz) @@ -36,7 +36,6 @@ Yii Framework 2 Change Log - Bug #13582: PK column in `yii\db\pgsql\QueryBuilder::resetSequence()` was not quoted properly (boboldehampsink) - Bug #13592: Fixes `yii\db\oci\Schema::setTransactionIsolationLevel()` in Oracle (sergeymakinen) - Bug #13594: Fixes insufficient quoting in `yii\db\QueryBuilder::prepareInsertSelectSubQuery()` (sergeymakinen) -- Bug #14042: Fixed ambiguous column name in SELECT in UniqueValidator (cebe) - Bug #13649: Fixes issue where `['uncheck' => false]` and `['label' => false]` options for `ActiveRadio` and `ActiveCheckbox` were ignored (Alex-Code) - Bug #13657: Fixed `yii\helpers\StringHelper::truncateHtml()` skip extra tags at the end (sam002) - Bug #13670: Fixed alias option from console when it includes `-` or `_` in option name (pana1990) @@ -50,16 +49,23 @@ Yii Framework 2 Change Log - Bug #13776: Fixed setting precision and scale for decimal columns in MSSQL (arturf) - Bug #13790: Fixed error in `\yii\widgets\MaskedInput` JavaScript by raising version required (samdark) - Bug #13807: Fixed `yii\db\QueryBuilder` to inherit subquery params when building a `INSERT INTO ... SELECT` query (sergeymakinen) +- Bug #13842: Fixed ambiguous table SQL error while using `yii\validators\ExistValidator` and `yii\validators\UniqueValidator` (vladis84, samdark) +- Bug #13846: Fixed `Query::count()` issue with `orderBy` (Alex-Code) - Bug #13848: `yii\di\Instance::ensure()` wasn't throwing an exception when `$type` is specified and `$reference` object isn't instance of `$type` (c-jonua) - Bug #13890: `yii\log\DbTarget` log messages where not written when a database transaction was rolled back, added support for cloning a `yii\db\Connection` (shirase, cebe) - Bug #13901: Fixed passing unused parameter to `formatMessage()` call in `\yii\validators\IpValidator` (Kolyunya) - Bug #13961: Fixed `unserialize()` error during RBAC rule retrieving from PostgreSQL DBMS (vsguts, nanodesu88, cebe) - Bug #14012: `yii\db\pgsql\Schema::findViewNames()` was skipping materialized views (insolita) - Bug #14033: Fixed `yii\filters\AccessRule::matchIp()` erroring in case IP is not defined under HHVM (Kolyunya) +- Bug #14042: Fixed ambiguous column name in SELECT in UniqueValidator (cebe) - Bug #14052: Fixed processing parse errors on PHP 7 since these are instances of `\ParseError` (samdark) +- Bug #14072: Fixed a bug where `\yii\db\Command::createTable()`, `addForeignKey()`, `dropForeignKey()`, `addCommentOnColumn()`, and `dropCommentFromColumn()` weren't refreshing the table cache on `yii\db\Schema` (brandonkelly) - Bug #14074: Fixed default value of `yii\console\controllers\FixtureController::$globalFixtures` to contain valid class name (lynicidn) - Bug #14094: Fixed bug when single `yii\web\UrlManager::createUrl()` call my result multiple calls of `yii\web\UrlRule::createUrl()` for the same rule (rossoneri) - Bug #14133: Fixed bug when calculating timings with mixed nested profile begin and end in `yii\log\Logger::calculateTimings()` (bizley) +- Enh #4793: `yii\filters\AccessControl` now can be used without `user` component (bizley) +- Enh #4999: Added support for wildcards at `yii\filters\AccessRule::$controllers` (klimov-paul) +- Enh #5108: `yii\validators\DateValidator` now resets `$timestampAttribute` value on empty validated attribute value (klimov-paul) - Enh #8426: `yii\filters\AccessRule` now allows passing parameters to the role checking function (fsateler, cebe, Faryshta) - Enh #8641: Enhanced `yii\console\Request::resolve()` to prevent passing parameters, that begin from digits (silverfire) - Enh #11288: Added support for caching of `yii\web\UrlRule::createUrl()` results in `yii\web\UrlManager` for rules with defaults (rob006) @@ -104,14 +110,8 @@ Yii Framework 2 Change Log - Enh #13994: Refactored `yii\filters\RateLimiter`. Added tests (vladis84) - Enh #14059: Removed unused AR instantiating for calling of static methods (ElisDN) - Enh #14067: `yii\web\View::clear()` sets populated arrays to empty arrays instead of null, also changed default values to empty array (craiglondon) -- Enh #4793: `yii\filters\AccessControl` now can be used without `user` component (bizley) -- Enh #5108: `yii\validators\DateValidator` now resets `$timestampAttribute` value on empty validated attribute value (klimov-paul) -- Enh #4999: Added support for wildcards at `yii\filters\AccessRule::$controllers` (klimov-paul) -- Enh: Added `yii\di\Instance::__set_state()` method to restore object after serialization using `var_export()` function (silvefire) -- Bug #14072: Fixed a bug where `\yii\db\Command::createTable()`, `addForeignKey()`, `dropForeignKey()`, `addCommentOnColumn()`, and `dropCommentFromColumn()` weren't refreshing the table cache on `yii\db\Schema` (brandonkelly) -- Bug #10305: Oracle SQL queries with `IN` condition and more than 1000 parameters are working now (silverfire) - Enh #14098: `yii\helpers\BaseFileHelper::normalizeOptions()` is now protected (brandonkelly) -- Bug #13846: Fixed `Query::count()` issue with `orderBy` (Alex-Code) +- Enh: Added `yii\di\Instance::__set_state()` method to restore object after serialization using `var_export()` function (silvefire) 2.0.11.2 February 08, 2017 diff --git a/framework/behaviors/SluggableBehavior.php b/framework/behaviors/SluggableBehavior.php index d1c2e04efc..57d35e392a 100644 --- a/framework/behaviors/SluggableBehavior.php +++ b/framework/behaviors/SluggableBehavior.php @@ -66,7 +66,7 @@ class SluggableBehavior extends AttributeBehavior public $slugAttribute = 'slug'; /** * @var string|array|null the attribute or list of attributes whose value will be converted into a slug - * or `null` meaning that the `$value` property will be used to generate a slug. + * or `null` meaning that the `$value` property will be used to generate a slug. */ public $attribute; /** diff --git a/framework/classes.php b/framework/classes.php index 4d9a566218..ddd86cc75e 100644 --- a/framework/classes.php +++ b/framework/classes.php @@ -66,6 +66,7 @@ return [ 'yii\caching\ChainedDependency' => YII2_PATH . '/caching/ChainedDependency.php', 'yii\caching\DbCache' => YII2_PATH . '/caching/DbCache.php', 'yii\caching\DbDependency' => YII2_PATH . '/caching/DbDependency.php', + 'yii\caching\DbQueryDependency' => YII2_PATH . '/caching/DbQueryDependency.php', 'yii\caching\Dependency' => YII2_PATH . '/caching/Dependency.php', 'yii\caching\DummyCache' => YII2_PATH . '/caching/DummyCache.php', 'yii\caching\ExpressionDependency' => YII2_PATH . '/caching/ExpressionDependency.php', @@ -116,6 +117,7 @@ return [ 'yii\db\StaleObjectException' => YII2_PATH . '/db/StaleObjectException.php', 'yii\db\TableSchema' => YII2_PATH . '/db/TableSchema.php', 'yii\db\Transaction' => YII2_PATH . '/db/Transaction.php', + 'yii\db\ViewFinderTrait' => YII2_PATH . '/db/ViewFinderTrait.php', 'yii\db\cubrid\ColumnSchemaBuilder' => YII2_PATH . '/db/cubrid/ColumnSchemaBuilder.php', 'yii\db\cubrid\QueryBuilder' => YII2_PATH . '/db/cubrid/QueryBuilder.php', 'yii\db\cubrid\Schema' => YII2_PATH . '/db/cubrid/Schema.php', diff --git a/framework/data/BaseDataProvider.php b/framework/data/BaseDataProvider.php index b63131d3cf..19b47126e2 100644 --- a/framework/data/BaseDataProvider.php +++ b/framework/data/BaseDataProvider.php @@ -51,6 +51,7 @@ abstract class BaseDataProvider extends Component implements DataProviderInterfa private $_models; private $_totalCount; + /** * @inheritdoc */ diff --git a/framework/db/ActiveQuery.php b/framework/db/ActiveQuery.php index 81c01bcd66..d6dbb105ad 100644 --- a/framework/db/ActiveQuery.php +++ b/framework/db/ActiveQuery.php @@ -66,6 +66,8 @@ use yii\base\InvalidConfigException; * marks a relation as inverse of another relation and [[onCondition()]] which adds a condition that * is to be added to relational query join condition. * + * @property string[] $tablesUsedInFrom Table names indexed by aliases. This property is read-only. + * * @author Qiang Xue * @author Carsten Brandt * @since 2.0 diff --git a/framework/db/BaseActiveRecord.php b/framework/db/BaseActiveRecord.php index 459699196a..05b95ab3c6 100644 --- a/framework/db/BaseActiveRecord.php +++ b/framework/db/BaseActiveRecord.php @@ -412,7 +412,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface * Creates a query instance for `has-one` or `has-many` relation. * @param string $class the class name of the related record. * @param array $link the primary-foreign key constraint. - * @param boolean $multiple whether this query represents a relation to more than one record. + * @param bool $multiple whether this query represents a relation to more than one record. * @return ActiveQueryInterface the relational query object. * @since 2.0.12 * @see hasOne() diff --git a/framework/db/Connection.php b/framework/db/Connection.php index d666bc526f..f00e08ecbf 100644 --- a/framework/db/Connection.php +++ b/framework/db/Connection.php @@ -389,6 +389,7 @@ class Connection extends Component * @see enableLogging */ public $enableProfiling = true; + /** * @var Transaction the currently active transaction */ diff --git a/framework/db/QueryBuilder.php b/framework/db/QueryBuilder.php index ae4ec26cfa..992bb53d19 100644 --- a/framework/db/QueryBuilder.php +++ b/framework/db/QueryBuilder.php @@ -82,6 +82,7 @@ class QueryBuilder extends \yii\base\Object */ protected $likeEscapeCharacter; + /** * Constructor. * @param Connection $connection the database connection. diff --git a/framework/db/cubrid/QueryBuilder.php b/framework/db/cubrid/QueryBuilder.php index ce3ffce3e4..9656b78703 100644 --- a/framework/db/cubrid/QueryBuilder.php +++ b/framework/db/cubrid/QueryBuilder.php @@ -57,6 +57,7 @@ class QueryBuilder extends \yii\db\QueryBuilder '!' => '!!', ]; + /** * Creates a SQL statement for resetting the sequence value of a table's primary key. * The sequence will be reset such that the primary key of the next new row inserted diff --git a/framework/db/mssql/QueryBuilder.php b/framework/db/mssql/QueryBuilder.php index f8cfa33ea5..3cdb148594 100644 --- a/framework/db/mssql/QueryBuilder.php +++ b/framework/db/mssql/QueryBuilder.php @@ -56,6 +56,7 @@ class QueryBuilder extends \yii\db\QueryBuilder '\\' => '[\\]', ]; + /** * @inheritdoc */ diff --git a/framework/db/oci/QueryBuilder.php b/framework/db/oci/QueryBuilder.php index 57b31104f6..3a5c813081 100644 --- a/framework/db/oci/QueryBuilder.php +++ b/framework/db/oci/QueryBuilder.php @@ -61,6 +61,7 @@ class QueryBuilder extends \yii\db\QueryBuilder '!' => '!!', ]; + /** * @inheritdoc */ diff --git a/framework/db/pgsql/Schema.php b/framework/db/pgsql/Schema.php index 3eb4f72b4f..bc3a13cab2 100644 --- a/framework/db/pgsql/Schema.php +++ b/framework/db/pgsql/Schema.php @@ -16,8 +16,6 @@ use yii\db\ViewFinderTrait; * Schema is the class for retrieving metadata from a PostgreSQL database * (version 9.x and above). * - * @property string[] $viewNames All view names in the database. This property is read-only. - * * @author Gevik Babakhani * @since 2.0 */ diff --git a/framework/db/sqlite/QueryBuilder.php b/framework/db/sqlite/QueryBuilder.php index 3cdb28a671..89b6bfbdd5 100644 --- a/framework/db/sqlite/QueryBuilder.php +++ b/framework/db/sqlite/QueryBuilder.php @@ -53,6 +53,7 @@ class QueryBuilder extends \yii\db\QueryBuilder */ protected $likeEscapeCharacter = '\\'; + /** * Generates a batch INSERT SQL statement. * For example, diff --git a/framework/helpers/BaseHtml.php b/framework/helpers/BaseHtml.php index 52513e7cfb..a9bc4530f5 100644 --- a/framework/helpers/BaseHtml.php +++ b/framework/helpers/BaseHtml.php @@ -24,7 +24,6 @@ use yii\base\Model; */ class BaseHtml { - /** * @var string Regular expression used for attribute name validation. * @since 2.0.12 diff --git a/framework/rbac/BaseManager.php b/framework/rbac/BaseManager.php index 27e9c874cb..371c0fd9e2 100644 --- a/framework/rbac/BaseManager.php +++ b/framework/rbac/BaseManager.php @@ -16,6 +16,9 @@ use yii\base\InvalidParamException; * * For more details and usage information on DbManager, see the [guide article on security authorization](guide:security-authorization). * + * @property Role[] $defaultRoleInstances Default roles. The array is indexed by the role names. This property + * is read-only. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/validators/Validator.php b/framework/validators/Validator.php index 3fcc966ae8..02716874fd 100644 --- a/framework/validators/Validator.php +++ b/framework/validators/Validator.php @@ -47,8 +47,8 @@ use yii\base\NotSupportedException; * - `ip`: [[IpValidator]] * * For more details and usage information on Validator, see the [guide article on validators](guide:input-validation). - * - * @property array $attributeNames cleaned attribute names without the `!` character at the beginning. This property is read-only. + * + * @property array $attributeNames Attribute names. This property is read-only. * * @author Qiang Xue * @since 2.0 diff --git a/framework/web/CompositeUrlRule.php b/framework/web/CompositeUrlRule.php index 5f20a118f8..97d0bdc627 100644 --- a/framework/web/CompositeUrlRule.php +++ b/framework/web/CompositeUrlRule.php @@ -13,6 +13,9 @@ use yii\base\Object; /** * CompositeUrlRule is the base class for URL rule classes that consist of multiple simpler rules. * + * @property null|int $createUrlStatus Status of the URL creation after the last [[createUrl()]] call. `null` + * if rule does not provide info about create status. This property is read-only. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/web/Request.php b/framework/web/Request.php index af2edac1a3..e374f6b067 100644 --- a/framework/web/Request.php +++ b/framework/web/Request.php @@ -74,7 +74,8 @@ use yii\base\InvalidConfigException; * @property int $securePort Port number for secure requests. * @property string $serverName Server name, null if not available. This property is read-only. * @property int|null $serverPort Server port number, null if not available. This property is read-only. - * @property string $url The currently requested relative URL. Note that the URI returned may be URL-encoded depending on the client. + * @property string $url The currently requested relative URL. Note that the URI returned may be URL-encoded + * depending on the client. * @property string|null $userAgent User agent, null if not available. This property is read-only. * @property string|null $userHost User host name, null if not available. This property is read-only. * @property string|null $userIP User IP address, null if not available. This property is read-only. diff --git a/framework/web/Response.php b/framework/web/Response.php index 8348e4e76d..f643b7c53c 100644 --- a/framework/web/Response.php +++ b/framework/web/Response.php @@ -53,6 +53,7 @@ use yii\helpers\StringHelper; * @property bool $isServerError Whether this response indicates a server error. This property is read-only. * @property bool $isSuccessful Whether this response is successful. This property is read-only. * @property int $statusCode The HTTP status code to send with the response. + * @property \Exception|\Error $statusCodeByException The exception object. This property is write-only. * * @author Qiang Xue * @author Carsten Brandt diff --git a/framework/web/UrlRule.php b/framework/web/UrlRule.php index 988361d78d..4c3c510bbd 100644 --- a/framework/web/UrlRule.php +++ b/framework/web/UrlRule.php @@ -24,6 +24,9 @@ use yii\base\Object; * ] * ``` * + * @property null|int $createUrlStatus Status of the URL creation after the last [[createUrl()]] call. `null` + * if rule does not provide info about create status. This property is read-only. + * * @author Qiang Xue * @since 2.0 */ @@ -122,12 +125,12 @@ class UrlRule extends Object implements UrlRuleInterface * @since 2.0.10 */ public $normalizer; + /** * @var int|null status of the URL creation after the last [[createUrl()]] call. * @since 2.0.12 */ protected $createStatus; - /** * @var array list of placeholders for matching parameters names. Used in [[parseRequest()]], [[createUrl()]]. * On the rule initialization, the [[pattern]] parameters names will be replaced with placeholders. From d6bd627ac3dbe7055be9354b93d9bf850b3d0a89 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Mon, 5 Jun 2017 16:34:55 +0200 Subject: [PATCH 53/71] prepare for next release --- framework/BaseYii.php | 2 +- framework/CHANGELOG.md | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/framework/BaseYii.php b/framework/BaseYii.php index 5b71034f37..e13c295588 100644 --- a/framework/BaseYii.php +++ b/framework/BaseYii.php @@ -93,7 +93,7 @@ class BaseYii */ public static function getVersion() { - return '2.0.12'; + return '2.0.13-dev'; } /** diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 1a7f144ae7..02f9986b8a 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -1,6 +1,12 @@ Yii Framework 2 Change Log ========================== +2.0.13 under development +------------------------ + +- no changes in this release. + + 2.0.12 June 05, 2017 -------------------- From 38bf88df1a587be46c80ab1dce3c0e9351beeb0d Mon Sep 17 00:00:00 2001 From: Vasileios Lourdas Date: Mon, 5 Jun 2017 23:06:15 +0300 Subject: [PATCH 54/71] Greek translation update. --- framework/messages/el/yii.php | 1 + 1 file changed, 1 insertion(+) diff --git a/framework/messages/el/yii.php b/framework/messages/el/yii.php index 52916c6f80..93e2c1ba0d 100644 --- a/framework/messages/el/yii.php +++ b/framework/messages/el/yii.php @@ -17,6 +17,7 @@ * NOTE: this file must be saved in UTF-8 encoding. */ return [ + ' and ' => ' και ', '(not set)' => '(μη ορισμένο)', 'An internal server error occurred.' => 'Υπήρξε ένα εσωτερικό σφάλμα του διακομιστή.', 'Are you sure you want to delete this item?' => 'Είστε σίγουροι για τη διαγραφή του αντικειμένου;', From 981346cb1e36fb811613942254b234e96c44821b Mon Sep 17 00:00:00 2001 From: Brandon Kelly Date: Mon, 5 Jun 2017 14:07:03 -0700 Subject: [PATCH 55/71] Fixed Formatter::normalizeDatetimeValue() docs There was a reference to `$checkTimeInfo` that was leftover from 54278fc84262fc45e696ccccfd2258a6028bd9e3 --- framework/i18n/Formatter.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/i18n/Formatter.php b/framework/i18n/Formatter.php index 9beca866cb..6326a81bc8 100644 --- a/framework/i18n/Formatter.php +++ b/framework/i18n/Formatter.php @@ -656,7 +656,7 @@ class Formatter extends Component * whether the timestamp has date information. * This parameter is available since version 2.0.1. * @return DateTime|array the normalized datetime value. - * Since version 2.0.1 this may also return an array if `$checkTimeInfo` is true. + * Since version 2.0.1 this may also return an array if `$checkDateTimeInfo` is true. * The first element of the array is the normalized timestamp and the second is a boolean indicating whether * the timestamp has time information or it is just a date value. * Since version 2.0.12 the array has third boolean element indicating whether the timestamp has date information From b056dff031eaa87fc016712248db4ba9261ff6db Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Tue, 6 Jun 2017 11:43:34 +0200 Subject: [PATCH 56/71] improved formatter documentation --- framework/i18n/Formatter.php | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/framework/i18n/Formatter.php b/framework/i18n/Formatter.php index 6326a81bc8..a3db2ace30 100644 --- a/framework/i18n/Formatter.php +++ b/framework/i18n/Formatter.php @@ -86,6 +86,9 @@ class Formatter extends Component * * It defaults to `UTC` so you only have to adjust this value if you store datetime values in another time zone in your database. * + * Note that a UNIX timestamp is always in UTC by its definition. That means that specifying a default time zone different from + * UTC has no effect on date values given as UNIX timestamp. + * * @since 2.0.1 */ public $defaultTimeZone = 'UTC'; @@ -466,10 +469,15 @@ class Formatter extends Component * @param int|string|DateTime $value the value to be formatted. The following * types of value are supported: * - * - an integer representing a UNIX timestamp + * - an integer representing a UNIX timestamp. A UNIX timestamp is always in UTC by its definition. * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php). * The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given. - * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object + * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object. You may set the time zone + * for the DateTime object to specify the source time zone. + * + * The formatter will convert date values according to [[timeZone]] before formatting it. + * If no timezone conversion should be performed, you need to set [[defaultTimeZone]] and [[timeZone]] to the same value. + * Also no conversion will be performed on values that have no time information, e.g. `"2017-06-05"`. * * @param string $format the format used to convert the value into a date string. * If null, [[dateFormat]] will be used. @@ -498,10 +506,14 @@ class Formatter extends Component * @param int|string|DateTime $value the value to be formatted. The following * types of value are supported: * - * - an integer representing a UNIX timestamp + * - an integer representing a UNIX timestamp. A UNIX timestamp is always in UTC by its definition. * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php). * The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given. - * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object + * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object. You may set the time zone + * for the DateTime object to specify the source time zone. + * + * The formatter will convert date values according to [[timeZone]] before formatting it. + * If no timezone conversion should be performed, you need to set [[defaultTimeZone]] and [[timeZone]] to the same value. * * @param string $format the format used to convert the value into a date string. * If null, [[timeFormat]] will be used. @@ -530,10 +542,14 @@ class Formatter extends Component * @param int|string|DateTime $value the value to be formatted. The following * types of value are supported: * - * - an integer representing a UNIX timestamp + * - an integer representing a UNIX timestamp. A UNIX timestamp is always in UTC by its definition. * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php). * The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given. - * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object + * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object. You may set the time zone + * for the DateTime object to specify the source time zone. + * + * The formatter will convert date values according to [[timeZone]] before formatting it. + * If no timezone conversion should be performed, you need to set [[defaultTimeZone]] and [[timeZone]] to the same value. * * @param string $format the format used to convert the value into a date string. * If null, [[dateFormat]] will be used. From 3dc8f426d01ecbf23d2f1faade292bbe7762d999 Mon Sep 17 00:00:00 2001 From: PowerGamer1 Date: Sat, 3 Jun 2017 20:39:00 +0300 Subject: [PATCH 57/71] Fix MessageController color output on non-color termnials fixes #14248 close #14249 --- framework/CHANGELOG.md | 2 +- framework/console/controllers/MessageController.php | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 02f9986b8a..2df1c4973b 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -4,7 +4,7 @@ Yii Framework 2 Change Log 2.0.13 under development ------------------------ -- no changes in this release. +- Bug #14248: `yii\console\controllers\MessageController` no longer outputs colorized filenames when console does not support text colorization (PowerGamer1) 2.0.12 June 05, 2017 diff --git a/framework/console/controllers/MessageController.php b/framework/console/controllers/MessageController.php index b81405b19e..4729b69f22 100644 --- a/framework/console/controllers/MessageController.php +++ b/framework/console/controllers/MessageController.php @@ -482,8 +482,9 @@ EOD; */ protected function extractMessages($fileName, $translator, $ignoreCategories = []) { - $coloredFileName = Console::ansiFormat($fileName, [Console::FG_CYAN]); - $this->stdout("Extracting messages from $coloredFileName...\n"); + $this->stdout("Extracting messages from "); + $this->stdout($fileName, Console::FG_CYAN); + $this->stdout("...\n"); $subject = file_get_contents($fileName); $messages = []; From a3501ed831006722459106534bfd9678d0d204a0 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Wed, 7 Jun 2017 12:26:27 +0200 Subject: [PATCH 58/71] guide: note about param binding on strings, not arrays issue #14218 --- docs/guide/db-dao.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/guide/db-dao.md b/docs/guide/db-dao.md index 931fc8566c..c850717cc4 100644 --- a/docs/guide/db-dao.md +++ b/docs/guide/db-dao.md @@ -209,6 +209,11 @@ Notice that you bind the placeholder to the `$id` variable before the execution, before each subsequent execution (this is often done with loops). Executing queries in this manner can be vastly more efficient than running a new query for every different parameter value. +> Info: Parameter binding is only used in places where values need to be inserted into strings that contain plain SQL. +> In many places in higher abstraction layers like [query builder](db-query-builder.md) and [active record](db-active-record.md) +> you often specify an array of values which will be transformed into SQL. In these places parameter binding is done by Yii +> internally, so there is no need to specify params manually. + ### Executing Non-SELECT Queries @@ -381,7 +386,7 @@ Yii provides four constants for the most common isolation levels: - [[\yii\db\Transaction::SERIALIZABLE]] - the strongest level, avoids all of the above named problems. Besides using the above constants to specify isolation levels, you may also use strings with a valid syntax supported -by the DBMS that you are using. For example, in PostgreSQL, you may use `SERIALIZABLE READ ONLY DEFERRABLE`. +by the DBMS that you are using. For example, in PostgreSQL, you may use `"SERIALIZABLE READ ONLY DEFERRABLE"`. Note that some DBMS allow setting the isolation level only for the whole connection. Any subsequent transactions will get the same isolation level even if you do not specify any. When using this feature From fddb34b91ce65be04cc637aeb41ab5ef35b7f7ed Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Wed, 7 Jun 2017 23:19:47 +0200 Subject: [PATCH 59/71] added param binding examples for update() and delete() fixes #14218 --- framework/db/Command.php | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/framework/db/Command.php b/framework/db/Command.php index dc360e37fa..21ec2bf9ae 100644 --- a/framework/db/Command.php +++ b/framework/db/Command.php @@ -472,6 +472,13 @@ class Command extends Component * $connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute(); * ``` * + * or with using parameter binding for the condition: + * + * ```php + * $minAge = 30; + * $connection->createCommand()->update('user', ['status' => 1], 'age > :minAge', [':minAge' => $minAge])->execute(); + * ``` + * * The method will properly escape the column names and bind the values to be updated. * * Note that the created command is not executed until [[execute()]] is called. @@ -498,6 +505,13 @@ class Command extends Component * $connection->createCommand()->delete('user', 'status = 0')->execute(); * ``` * + * or with using parameter binding for the condition: + * + * ```php + * $status = 0; + * $connection->createCommand()->delete('user', 'status = :status', [':status' => $status])->execute(); + * ``` + * * The method will properly escape the table and column names. * * Note that the created command is not executed until [[execute()]] is called. From deea1829dbf0752ea83d46ad7ac534be8d0bfeaf Mon Sep 17 00:00:00 2001 From: Bizley Date: Thu, 8 Jun 2017 11:57:43 +0200 Subject: [PATCH 60/71] Fixes #14264: Fixed a bug where `yii\log\Logger::calculateTimings()` was not accepting messages with array tokens --- framework/CHANGELOG.md | 1 + framework/log/Logger.php | 2 +- tests/framework/log/LoggerTest.php | 22 ++++++++++++++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 2df1c4973b..f583fa7e1a 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -5,6 +5,7 @@ Yii Framework 2 Change Log ------------------------ - Bug #14248: `yii\console\controllers\MessageController` no longer outputs colorized filenames when console does not support text colorization (PowerGamer1) +- Bug #14264: Fixed a bug where `yii\log\Logger::calculateTimings()` was not accepting messages with array tokens (bizley) 2.0.12 June 05, 2017 diff --git a/framework/log/Logger.php b/framework/log/Logger.php index 8427223d10..87b48fc7b5 100644 --- a/framework/log/Logger.php +++ b/framework/log/Logger.php @@ -278,7 +278,7 @@ class Logger extends Component list($token, $level, $category, $timestamp, $traces) = $log; $memory = isset($log[5]) ? $log[5] : 0; $log[6] = $i; - $hash = md5($token); + $hash = md5(serialize($token)); if ($level == Logger::LEVEL_PROFILE_BEGIN) { $stack[$hash] = $log; } elseif ($level == Logger::LEVEL_PROFILE_END) { diff --git a/tests/framework/log/LoggerTest.php b/tests/framework/log/LoggerTest.php index b7d31b54e1..6725158088 100644 --- a/tests/framework/log/LoggerTest.php +++ b/tests/framework/log/LoggerTest.php @@ -174,12 +174,15 @@ class LoggerTest extends TestCase ['message2', Logger::LEVEL_PROFILE, 'category', 'time', 'trace', 1048576], ['message3', Logger::LEVEL_TRACE, 'category', 'time', 'trace', 1048576], ['message4', Logger::LEVEL_WARNING, 'category', 'time', 'trace', 1048576], + [['message5', 'message6'], Logger::LEVEL_ERROR, 'category', 'time', 'trace', 1048576], ]; $this->assertEmpty($this->logger->calculateTimings($messages)); } /** * @covers yii\log\Logger::calculateTimings() + * + * See https://github.com/yiisoft/yii2/issues/14264 */ public function testCalculateTimingsWithProfileBeginEnd() { @@ -201,6 +204,25 @@ class LoggerTest extends TestCase ], $this->logger->calculateTimings($messages) ); + + $messages = [ + 'anyKey' => [['a', 'b'], Logger::LEVEL_PROFILE_BEGIN, 'category', 10, 'trace', 1048576], + 'anyKey2' => [['a', 'b'], Logger::LEVEL_PROFILE_END, 'category', 15, 'trace', 2097152], + ]; + $this->assertEquals([ + [ + 'info' => ['a', 'b'], + 'category' => 'category', + 'timestamp' => 10, + 'trace' => 'trace', + 'level' => 0, + 'duration' => 5, + 'memory' => 2097152, + 'memoryDiff' => 1048576 + ] + ], + $this->logger->calculateTimings($messages) + ); } /** From fdc91f351b2c158001efb452f7b4b35864e2dbed Mon Sep 17 00:00:00 2001 From: Nikolay Oleynikov Date: Fri, 9 Jun 2017 11:36:03 +0300 Subject: [PATCH 61/71] Improved base migration controller documentation [skip ci] (#14253) --- .../console/controllers/BaseMigrateController.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/framework/console/controllers/BaseMigrateController.php b/framework/console/controllers/BaseMigrateController.php index c84d81f9a8..5f79c00187 100644 --- a/framework/console/controllers/BaseMigrateController.php +++ b/framework/console/controllers/BaseMigrateController.php @@ -204,8 +204,8 @@ abstract class BaseMigrateController extends Controller * yii migrate/down all # revert all migrations * ``` * - * @param int $limit the number of migrations to be reverted. Defaults to 1, - * meaning the last applied migration will be reverted. + * @param int|string $limit the number of migrations to be reverted. Defaults to 1, + * meaning the last applied migration will be reverted. When value is "all", all migrations will be reverted. * @throws Exception if the number of the steps specified is less than 1. * * @return int the status of the action execution. 0 means normal, other values mean abnormal. @@ -266,8 +266,8 @@ abstract class BaseMigrateController extends Controller * yii migrate/redo all # redo all migrations * ``` * - * @param int $limit the number of migrations to be redone. Defaults to 1, - * meaning the last applied migration will be redone. + * @param int|string $limit the number of migrations to be redone. Defaults to 1, + * meaning the last applied migration will be redone. When equals "all", all migrations will be redone. * @throws Exception if the number of the steps specified is less than 1. * * @return int the status of the action execution. 0 means normal, other values mean abnormal. @@ -463,7 +463,7 @@ abstract class BaseMigrateController extends Controller * yii migrate/history all # showing the whole history * ``` * - * @param int $limit the maximum number of migrations to be displayed. + * @param int|string $limit the maximum number of migrations to be displayed. * If it is "all", the whole migration history will be displayed. * @throws \yii\console\Exception if invalid limit value passed */ @@ -507,7 +507,7 @@ abstract class BaseMigrateController extends Controller * yii migrate/new all # showing all new migrations * ``` * - * @param int $limit the maximum number of new migrations to be displayed. + * @param int|string $limit the maximum number of new migrations to be displayed. * If it is `all`, all available new migrations will be displayed. * @throws \yii\console\Exception if invalid limit value passed */ From 2b9f0006d54241bebead0225ca694d5ecb8f7ce2 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Fri, 9 Jun 2017 12:07:02 +0200 Subject: [PATCH 62/71] added example for using unsupported PHP format in yii formatter fixes #14278 --- docs/guide/output-formatting.md | 14 ++++++++++++++ tests/framework/i18n/FormatterNumberTest.php | 14 ++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/docs/guide/output-formatting.md b/docs/guide/output-formatting.md index 07d31d3409..58134d617d 100644 --- a/docs/guide/output-formatting.md +++ b/docs/guide/output-formatting.md @@ -97,6 +97,20 @@ echo Yii::$app->formatter->asDate('now', 'yyyy-MM-dd'); // 2014-10-06 echo Yii::$app->formatter->asDate('now', 'php:Y-m-d'); // 2014-10-06 ``` +> Info: Some letters of the PHP format syntax are not supported by ICU and thus the PHP intl extension and can not be used +> in Yii formatter. Most of these (`w`, `t`, `L`, `B`, `u`, `I`, `Z`) are not really useful for formatting dates but rather +> used when doing date math. `S` and `U` however may be useful. Their behavior can be achived by doing the following: +> +> - for `S`, which is the English ordinal suffix for the day of the month (e.g. st, nd, rd or th.), the following replacement can be used: +> +> ```php +> $f = Yii::$app->formatter; +> $d = $f->asOrdinal($f->asDate('2017-05-15', 'php:j')); +> echo "On the $d day of the month."; // prints "On the 15th day of the month." +> ``` +> +> - for `U`, the Unix Epoch, you can use the [[yii\i18n\Formatter::asTimestamp()|timestamp]] format. + When working with applications that need to support multiple languages, you often need to specify different date and time formats for different locales. To simplify this task, you may use format shortcuts (e.g. `long`, `short`), instead. The formatter will turn a format shortcut into an appropriate format according to the currently active [[yii\i18n\Formatter::locale|locale]]. diff --git a/tests/framework/i18n/FormatterNumberTest.php b/tests/framework/i18n/FormatterNumberTest.php index bc8368631d..9be3016a29 100644 --- a/tests/framework/i18n/FormatterNumberTest.php +++ b/tests/framework/i18n/FormatterNumberTest.php @@ -456,6 +456,20 @@ class FormatterNumberTest extends TestCase $this->assertSame($this->formatter->nullDisplay, $this->formatter->asOrdinal(null)); } + /** + * https://github.com/yiisoft/yii2/issues/14278 + */ + public function testIntlAsOrdinalDate() + { + $f = $this->formatter; + $this->assertSame('15th', $f->asOrdinal($f->asDate('2017-05-15', 'php:j'))); + $this->assertSame('1st', $f->asOrdinal($f->asDate('2017-05-01', 'php:j'))); + + $f->locale = 'de_DE'; + $this->assertSame('15.', $f->asOrdinal($f->asDate('2017-05-15', 'php:j'))); + $this->assertSame('1.', $f->asOrdinal($f->asDate('2017-05-01', 'php:j'))); + } + public function testIntlAsShortSize() { $this->formatter->numberFormatterOptions = [ From 78ec17f13cb55c6803600579831acbbe432cacf4 Mon Sep 17 00:00:00 2001 From: Arthur Khachaturov Date: Wed, 24 May 2017 17:41:27 +0300 Subject: [PATCH 63/71] Fixes #14201: `yii\console\controllers\MessageController::extractMessagesFromTokens()` is now protected --- framework/CHANGELOG.md | 1 + framework/console/controllers/MessageController.php | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index f583fa7e1a..f74f314ff8 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -6,6 +6,7 @@ Yii Framework 2 Change Log - Bug #14248: `yii\console\controllers\MessageController` no longer outputs colorized filenames when console does not support text colorization (PowerGamer1) - Bug #14264: Fixed a bug where `yii\log\Logger::calculateTimings()` was not accepting messages with array tokens (bizley) +- Chg #14201: `yii\console\controllers\MessageController::extractMessagesFromTokens()` is now protected (faenir) 2.0.12 June 05, 2017 diff --git a/framework/console/controllers/MessageController.php b/framework/console/controllers/MessageController.php index 4729b69f22..4cd436a2bc 100644 --- a/framework/console/controllers/MessageController.php +++ b/framework/console/controllers/MessageController.php @@ -507,7 +507,7 @@ EOD; * @param array $ignoreCategories message categories to ignore. * @return array messages. */ - private function extractMessagesFromTokens(array $tokens, array $translatorTokens, array $ignoreCategories) + protected function extractMessagesFromTokens(array $tokens, array $translatorTokens, array $ignoreCategories) { $messages = []; $translatorTokensCount = count($translatorTokens); From 1d062100b640e035a49665217148c8ef06fd5df4 Mon Sep 17 00:00:00 2001 From: Thiago Talma Date: Wed, 5 Apr 2017 11:18:54 -0300 Subject: [PATCH 64/71] Fixes #13787: Added `yii\db\Migration::$maxSqlOutputLength` that allows limiting number of characters for outputting SQL --- framework/CHANGELOG.md | 2 +- framework/db/Migration.php | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index f74f314ff8..ab0d0ce7ac 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -7,7 +7,7 @@ Yii Framework 2 Change Log - Bug #14248: `yii\console\controllers\MessageController` no longer outputs colorized filenames when console does not support text colorization (PowerGamer1) - Bug #14264: Fixed a bug where `yii\log\Logger::calculateTimings()` was not accepting messages with array tokens (bizley) - Chg #14201: `yii\console\controllers\MessageController::extractMessagesFromTokens()` is now protected (faenir) - +- Enh #13787: Added `yii\db\Migration::$maxSqlOutputLength` that allows limiting number of characters for outputting SQL (thiagotalma) 2.0.12 June 05, 2017 -------------------- diff --git a/framework/db/Migration.php b/framework/db/Migration.php index 882aab6a47..aa31e7ee9b 100644 --- a/framework/db/Migration.php +++ b/framework/db/Migration.php @@ -9,6 +9,7 @@ namespace yii\db; use yii\base\Component; use yii\di\Instance; +use yii\helpers\StringHelper; /** * Migration is the base class for representing a database migration. @@ -65,6 +66,12 @@ class Migration extends Component implements MigrationInterface */ public $db = 'db'; + /** + * @var int max number of characters of the SQL outputted. Useful for reduction of long statements and making + * console output more compact. + * @since 2.0.13 + */ + public $maxSqlOutputLength; /** * Initializes the migration. @@ -198,7 +205,12 @@ class Migration extends Component implements MigrationInterface */ public function execute($sql, $params = []) { - echo " > execute SQL: $sql ..."; + $sqlOutput = $sql; + if ($this->maxSqlOutputLength !== null) { + $sqlOutput = StringHelper::truncate($sql, $this->maxSqlOutputLength, '[... hidden]'); + } + + echo " > execute SQL: $sqlOutput ..."; $time = microtime(true); $this->db->createCommand($sql)->bindValues($params)->execute(); echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n"; From b00c82c2a2aee4d4f41ca1397eee2c8834b4d2ac Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Sun, 11 Jun 2017 17:18:50 +0300 Subject: [PATCH 65/71] Adjusted RBAC docs to offer both migrations and command approaches [skip ci] --- docs/guide/security-authorization.md | 89 ++++++++++++++++++++++++++-- 1 file changed, 85 insertions(+), 4 deletions(-) diff --git a/docs/guide/security-authorization.md b/docs/guide/security-authorization.md index 55dc045893..cb8e06b300 100644 --- a/docs/guide/security-authorization.md +++ b/docs/guide/security-authorization.md @@ -262,9 +262,82 @@ Building authorization data is all about the following tasks: - assigning roles to users. Depending on authorization flexibility requirements the tasks above could be done in different ways. +If your permissions hierarchy is meant to be changed by developers only, you can use either migrations +or a console command. Migration pro is that it could be executed along with other migrations. Console +command pro is that you have a good overview of the hierarchy in the code rathe than it being scattered +among multiple migrations. + +Either way in the end you'll get the following RBAC hierarchy: + +![Simple RBAC hierarchy](images/rbac-hierarchy-1.png "Simple RBAC hierarchy") + +In case you need permissions hierarchy to be formed dynamically you need a UI or a console command. API used to +build the hierarchy itself won't be different. + +#### Using migrations + +You can use [migrations](db-migrations.md) +to initialize and modify hierarchy via APIs offered by `authManager`. + +Create new migration using `./yii migrate/create init_rbac` then impement creating a hierarchy: + +```php +authManager; + + // add "createPost" permission + $createPost = $auth->createPermission('createPost'); + $createPost->description = 'Create a post'; + $auth->add($createPost); + + // add "updatePost" permission + $updatePost = $auth->createPermission('updatePost'); + $updatePost->description = 'Update post'; + $auth->add($updatePost); + + // add "author" role and give this role the "createPost" permission + $author = $auth->createRole('author'); + $auth->add($author); + $auth->addChild($author, $createPost); + + // add "admin" role and give this role the "updatePost" permission + // as well as the permissions of the "author" role + $admin = $auth->createRole('admin'); + $auth->add($admin); + $auth->addChild($admin, $updatePost); + $auth->addChild($admin, $author); + + // Assign roles to users. 1 and 2 are IDs returned by IdentityInterface::getId() + // usually implemented in your User model. + $auth->assign($author, 2); + $auth->assign($admin, 1); + } + + public function down() + { + $auth = Yii::$app->authManager; + + $auth->removeAll(); + } +} +``` + +> If you don't want to hardcode which users have certain roles, don't put `->assign()` calls in migrations. Instead, + create either UI or console command to manage assignments. + +Migration could be applied by using `yii migrate`. + +### Using console command If your permissions hierarchy doesn't change at all and you have a fixed number of users you can create a -[console command](tutorial-console.md#create-command) that will initialize authorization data once via APIs offered by `authManager`: +-[console command](tutorial-console.md#create-command) that will initialize authorization data once via +APIs offered by `authManager`: ```php authManager; - + $auth->removeAll(); + // add "createPost" permission $createPost = $auth->createPermission('createPost'); $createPost->description = 'Create a post'; @@ -311,10 +385,17 @@ class RbacController extends Controller > Note: If you are using advanced template, you need to put your `RbacController` inside `console/controllers` directory and change namespace to `console\controllers`. + +The command above could be executed from console the following way: -After executing the command with `yii rbac/init` we'll get the following hierarchy: +``` +yii rbac/init +``` -![Simple RBAC hierarchy](images/rbac-hierarchy-1.png "Simple RBAC hierarchy") +> If you don't want to hardcode what users have certain roles, don't put `->assign()` calls into the command. Instead, + create either UI or console command to manage assignments. + +## Assigning roles to users Author can create post, admin can update post and do everything author can. From f6b54e1ac8c55c42a9d769790a9650821ebf849b Mon Sep 17 00:00:00 2001 From: vladis84 Date: Thu, 11 May 2017 20:56:01 +0500 Subject: [PATCH 66/71] Fixes #14089: Added tests for `yii\base\Theme` --- framework/CHANGELOG.md | 1 + framework/base/Theme.php | 7 +- tests/framework/base/ThemeTest.php | 165 ++++++++++++++++++ .../themes/basic/views/site/index.php | 1 + .../themes/christmas/views/site/index.php | 1 + .../themes/christmas/views/site/main.php | 1 + 6 files changed, 171 insertions(+), 5 deletions(-) create mode 100644 tests/framework/base/ThemeTest.php create mode 100644 tests/framework/base/fixtures/themes/basic/views/site/index.php create mode 100644 tests/framework/base/fixtures/themes/christmas/views/site/index.php create mode 100644 tests/framework/base/fixtures/themes/christmas/views/site/main.php diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index ab0d0ce7ac..088176747c 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -8,6 +8,7 @@ Yii Framework 2 Change Log - Bug #14264: Fixed a bug where `yii\log\Logger::calculateTimings()` was not accepting messages with array tokens (bizley) - Chg #14201: `yii\console\controllers\MessageController::extractMessagesFromTokens()` is now protected (faenir) - Enh #13787: Added `yii\db\Migration::$maxSqlOutputLength` that allows limiting number of characters for outputting SQL (thiagotalma) +- Enh #14089: Added tests for `yii\base\Theme` (vladis84) 2.0.12 June 05, 2017 -------------------- diff --git a/framework/base/Theme.php b/framework/base/Theme.php index 7ea7f247ba..32a0f4d7f5 100644 --- a/framework/base/Theme.php +++ b/framework/base/Theme.php @@ -99,7 +99,7 @@ class Theme extends Component */ public function setBaseUrl($url) { - $this->_baseUrl = rtrim(Yii::getAlias($url), '/'); + $this->_baseUrl = $url === null ? null : rtrim(Yii::getAlias($url), '/'); } private $_basePath; @@ -139,9 +139,7 @@ class Theme extends Component } $pathMap = [Yii::$app->getBasePath() => [$basePath]]; } - $path = FileHelper::normalizePath($path); - foreach ($pathMap as $from => $tos) { $from = FileHelper::normalizePath(Yii::getAlias($from)) . DIRECTORY_SEPARATOR; if (strpos($path, $from) === 0) { @@ -155,7 +153,6 @@ class Theme extends Component } } } - return $path; } @@ -178,7 +175,7 @@ class Theme extends Component * Converts a relative file path into an absolute one using [[basePath]]. * @param string $path the relative file path to be converted. * @return string the absolute file path - * @throws InvalidConfigException if [[baseUrl]] is not set + * @throws InvalidConfigException if [[basePath]] is not set */ public function getPath($path) { diff --git a/tests/framework/base/ThemeTest.php b/tests/framework/base/ThemeTest.php new file mode 100644 index 0000000000..942bd1649c --- /dev/null +++ b/tests/framework/base/ThemeTest.php @@ -0,0 +1,165 @@ + ['@web' => '']]; + $this->mockWebApplication($config); + } + + private function assertPathEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false) + { + $expected = str_replace('\\', '/', $expected); + $actual = str_replace('\\', '/', $actual); + $this->assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase); + } + + public function testSetBaseUrl() + { + $theme = new Theme(['baseUrl' => '@web/themes/basic']); + $expected = Yii::getAlias('@web/themes/basic'); + + $this->assertEquals($expected, $theme->baseUrl); + } + + public function testGetUrlFilledBaseUrl() + { + $theme = new Theme(['baseUrl' => '@web/themes/basic']); + $expected = Yii::getAlias('@web/themes/basic/js/test.js'); + + $actual = $theme->getUrl('/js/test.js'); + + $this->assertEquals($expected, $actual); + } + + public function testGetUrlNotFilledBaseUrl() + { + $theme = new Theme(['baseUrl' => null]); + + $this->expectException('yii\base\InvalidConfigException'); + + $theme->getUrl('/js/test.js'); + } + + public function testSetBasePath() + { + $theme = new Theme(['basePath' => '@app/framework/base/fixtures/themes/basic']); + $expected = Yii::getAlias('@app/framework/base/fixtures/themes/basic'); + + $this->assertEquals($expected, $theme->basePath); + } + + public function testGetPathFilledBasePath() + { + $theme = new Theme(['basePath' => '@app/framework/base/fixtures/themes/basic']); + $expected = Yii::getAlias('@app/framework/base/fixtures/themes/basic/img/logo.gif'); + + $actual = $theme->getPath('/img/logo.gif'); + + $this->assertPathEquals($expected, $actual); + } + + public function testGetPathNotFilledBasePath() + { + $theme = new Theme(['baseUrl' => null]); + + $this->expectException('yii\base\InvalidConfigException'); + + $theme->getPath('/img/logo.gif'); + } + + public function testApplyToEmptyBasePath() + { + $theme = new Theme(['basePath' => null]); + + $this->expectException('yii\base\InvalidConfigException'); + + $theme->applyTo(null); + } + + public function testApplyToEmptyPathMap() + { + $theme = new Theme(['basePath' => '@app/framework/base/fixtures/themes/basic']); + $expected = Yii::getAlias('@app/framework/base/fixtures/themes/basic/views/site/index.php'); + + $actual = $theme->applyTo(Yii::$app->basePath . '/views/site/index.php'); + + $this->assertPathEquals($expected, $actual); + } + + public function testApplyToFilledPathMap() + { + $config = [ + 'pathMap' => [ + '@app/views' => '@app/framework/base/fixtures/themes/basic/views', + ], + ]; + $theme = new Theme($config); + $expected = Yii::getAlias('@app/framework/base/fixtures/themes/basic/views/site/index.php'); + + $actual = $theme->applyTo(Yii::$app->basePath . '/views/site/index.php'); + + $this->assertPathEquals($expected, $actual); + } + + public function testApplyToFilledPathMapNotExistsViewInFirstTheme() + { + $config = [ + 'pathMap' => [ + '@app/views' => [ + '@app/framework/base/fixtures/themes/basic/views', + '@app/framework/base/fixtures/themes/christmas/views', + ], + ], + ]; + $theme = new Theme($config); + $expected = Yii::getAlias('@app/framework/base/fixtures/themes/christmas/views/site/main.php'); + + $actual = $theme->applyTo(Yii::$app->basePath . '/views/site/main.php'); + + $this->assertPathEquals($expected, $actual); + } + + public function testApplyToFilledPathMapAndInheritThemes() + { + $config = [ + 'pathMap' => [ + '@app/views' => [ + '@app/framework/base/fixtures/themes/christmas/views', + '@app/framework/base/fixtures/themes/basic/views', + ], + ], + ]; + $theme = new Theme($config); + $expected = Yii::getAlias('@app/framework/base/fixtures/themes/christmas/views/site/index.php'); + + $actual = $theme->applyTo(Yii::$app->basePath . '/views/site/index.php'); + + $this->assertPathEquals($expected, $actual); + } + + public function testApplyToFilledPathMapAndFileNotExists() + { + $config = [ + 'pathMap' => [ + '@app/views' => '@app/framework/base/fixtures/themes/christmas/views', + ], + ]; + $theme = new Theme($config); + $expected = Yii::getAlias(Yii::$app->basePath . '/views/main/index.php'); + + $actual = $theme->applyTo($expected); + + $this->assertPathEquals($expected, $actual); + } +} diff --git a/tests/framework/base/fixtures/themes/basic/views/site/index.php b/tests/framework/base/fixtures/themes/basic/views/site/index.php new file mode 100644 index 0000000000..b3d9bbc7f3 --- /dev/null +++ b/tests/framework/base/fixtures/themes/basic/views/site/index.php @@ -0,0 +1 @@ + Date: Wed, 15 Feb 2017 17:56:16 +0300 Subject: [PATCH 67/71] Fixes #13586: Added `$preserveNonEmptyValues` property to the `yii\behaviors\AttributeBehavior` --- framework/CHANGELOG.md | 1 + framework/behaviors/AttributeBehavior.php | 8 + .../behaviors/AttributeBehaviorTest.php | 155 ++++++++++++++++++ 3 files changed, 164 insertions(+) create mode 100644 tests/framework/behaviors/AttributeBehaviorTest.php diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 088176747c..19d0ab9542 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -9,6 +9,7 @@ Yii Framework 2 Change Log - Chg #14201: `yii\console\controllers\MessageController::extractMessagesFromTokens()` is now protected (faenir) - Enh #13787: Added `yii\db\Migration::$maxSqlOutputLength` that allows limiting number of characters for outputting SQL (thiagotalma) - Enh #14089: Added tests for `yii\base\Theme` (vladis84) +- Enh #13586: Added `$preserveNonEmptyValues` property to the `yii\behaviors\AttributeBehavior` (Kolyunya) 2.0.12 June 05, 2017 -------------------- diff --git a/framework/behaviors/AttributeBehavior.php b/framework/behaviors/AttributeBehavior.php index 0a4c430046..89c1ba3b4a 100644 --- a/framework/behaviors/AttributeBehavior.php +++ b/framework/behaviors/AttributeBehavior.php @@ -85,6 +85,11 @@ class AttributeBehavior extends Behavior * @since 2.0.8 */ public $skipUpdateOnClean = true; + /** + * @var bool whether to preserve non-empty attribute values. + * @since 2.0.13 + */ + public $preserveNonEmptyValues = false; /** @@ -117,6 +122,9 @@ class AttributeBehavior extends Behavior foreach ($attributes as $attribute) { // ignore attribute names which are not string (e.g. when set by TimestampBehavior::updatedAtAttribute) if (is_string($attribute)) { + if ($this->preserveNonEmptyValues && !empty($this->owner->$attribute)) { + continue; + } $this->owner->$attribute = $value; } } diff --git a/tests/framework/behaviors/AttributeBehaviorTest.php b/tests/framework/behaviors/AttributeBehaviorTest.php new file mode 100644 index 0000000000..a9fe367d7a --- /dev/null +++ b/tests/framework/behaviors/AttributeBehaviorTest.php @@ -0,0 +1,155 @@ +mockApplication([ + 'components' => [ + 'db' => [ + 'class' => '\yii\db\Connection', + 'dsn' => 'sqlite::memory:', + ] + ] + ]); + + $columns = [ + 'id' => 'pk', + 'name' => 'string', + 'alias' => 'string', + ]; + Yii::$app->getDb()->createCommand()->createTable('test_attribute', $columns)->execute(); + } + + public function tearDown() + { + Yii::$app->getDb()->close(); + parent::tearDown(); + } + + // Tests : + + /** + * @return array + */ + public function preserveNonEmptyValuesDataProvider() + { + return [ + [ + 'John Doe', + false, + 'John Doe', + null, + ], + [ + 'John Doe', + false, + 'John Doe', + 'Johnny', + ], + [ + 'John Doe', + true, + 'John Doe', + null, + ], + [ + 'Johnny', + true, + 'John Doe', + 'Johnny', + ], + ]; + } + + /** + * @dataProvider preserveNonEmptyValuesDataProvider + */ + public function testPreserveNonEmptyValues( + $aliasExpected, + $preserveNonEmptyValues, + $name, + $alias + ) + { + $model = new ActiveRecordWithAttributeBehavior(); + $model->attributeBehavior->preserveNonEmptyValues = $preserveNonEmptyValues; + $model->name = $name; + $model->alias = $alias; + $model->validate(); + + $this->assertEquals($aliasExpected, $model->alias); + } +} + +/** + * Test Active Record class with [[AttributeBehavior]] behavior attached. + * + * @property integer $id + * @property string $name + * @property string $alias + * + * @property AttributeBehavior $attributeBehavior + */ +class ActiveRecordWithAttributeBehavior extends ActiveRecord +{ + /** + * @inheritdoc + */ + public function behaviors() + { + return [ + 'attribute' => [ + 'class' => AttributeBehavior::className(), + 'attributes' => [ + self::EVENT_BEFORE_VALIDATE => 'alias', + ], + 'value' => function ($event) { + return $event->sender->name; + }, + ], + ]; + } + + /** + * @inheritdoc + */ + public static function tableName() + { + return 'test_attribute'; + } + + /** + * @return AttributeBehavior + */ + public function getAttributeBehavior() + { + return $this->getBehavior('attribute'); + } +} From 2b7e8be1e85e6c53772d0b8efa45152965d29033 Mon Sep 17 00:00:00 2001 From: Tigrov Date: Tue, 23 May 2017 18:02:48 +0300 Subject: [PATCH 68/71] Fixes #14192: Fixed wrong default null value for TIMESTAMP when using PostgreSQL --- framework/CHANGELOG.md | 1 + framework/db/pgsql/Schema.php | 6 +++--- tests/framework/db/pgsql/SchemaTest.php | 20 ++++++++++++++++++++ 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 19d0ab9542..0910f15ffe 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -10,6 +10,7 @@ Yii Framework 2 Change Log - Enh #13787: Added `yii\db\Migration::$maxSqlOutputLength` that allows limiting number of characters for outputting SQL (thiagotalma) - Enh #14089: Added tests for `yii\base\Theme` (vladis84) - Enh #13586: Added `$preserveNonEmptyValues` property to the `yii\behaviors\AttributeBehavior` (Kolyunya) +- Bug #14192: Fixed wrong default null value for TIMESTAMP when using PostgreSQL (Tigrov) 2.0.12 June 05, 2017 -------------------- diff --git a/framework/db/pgsql/Schema.php b/framework/db/pgsql/Schema.php index bc3a13cab2..4831198291 100644 --- a/framework/db/pgsql/Schema.php +++ b/framework/db/pgsql/Schema.php @@ -439,11 +439,11 @@ SQL; $column->defaultValue = bindec(trim($column->defaultValue, 'B\'')); } elseif (preg_match("/^'(.*?)'::/", $column->defaultValue, $matches)) { $column->defaultValue = $matches[1]; - } elseif (preg_match('/^(?:\()?(.*?)(?(1)\))(?:::.+)?$/', $column->defaultValue, $matches)) { - if ($matches[1] === 'NULL') { + } elseif (preg_match('/^(\()?(.*?)(?(1)\))(?:::.+)?$/', $column->defaultValue, $matches)) { + if ($matches[2] === 'NULL') { $column->defaultValue = null; } else { - $column->defaultValue = $column->phpTypecast($matches[1]); + $column->defaultValue = $column->phpTypecast($matches[2]); } } else { $column->defaultValue = $column->phpTypecast($column->defaultValue); diff --git a/tests/framework/db/pgsql/SchemaTest.php b/tests/framework/db/pgsql/SchemaTest.php index f4451dd4e8..a09b60e811 100644 --- a/tests/framework/db/pgsql/SchemaTest.php +++ b/tests/framework/db/pgsql/SchemaTest.php @@ -194,4 +194,24 @@ class SchemaTest extends \yiiunit\framework\db\SchemaTest $this->assertEquals('numeric', $column->dbType); $this->assertEquals(0, $column->defaultValue); } + + /** + * https://github.com/yiisoft/yii2/issues/14192 + */ + public function testTimestampNullDefaultValue() + { + $db = $this->getConnection(false); + if ($db->schema->getTableSchema('test_timestamp_default_null') !== null) { + $db->createCommand()->dropTable('test_timestamp_default_null')->execute(); + } + + $db->createCommand()->createTable('test_timestamp_default_null', [ + 'id' => 'pk', + 'timestamp' => 'timestamp DEFAULT NULL', + ])->execute(); + + $db->schema->refreshTableSchema('test_timestamp_default_null'); + $tableSchema = $db->schema->getTableSchema('test_timestamp_default_null'); + $this->assertNull($tableSchema->getColumn('timestamp')->defaultValue); + } } From cb53b2feec5f27ea9a32b10b7598991e11dedc69 Mon Sep 17 00:00:00 2001 From: SilverFire - Dmitry Naumenko Date: Mon, 1 May 2017 16:18:18 +0300 Subject: [PATCH 69/71] Fixes #14081: Added `yii\caching\CacheInterface` to make custom cache extensions adoption easier --- framework/CHANGELOG.md | 1 + framework/base/Application.php | 4 +- framework/caching/Cache.php | 2 +- framework/caching/CacheInterface.php | 187 ++++++++++++++++++ framework/caching/ChainedDependency.php | 4 +- framework/caching/DbDependency.php | 4 +- framework/caching/DbQueryDependency.php | 4 +- framework/caching/Dependency.php | 6 +- framework/caching/ExpressionDependency.php | 2 +- framework/caching/FileDependency.php | 2 +- framework/caching/TagDependency.php | 8 +- .../console/controllers/CacheController.php | 6 +- framework/db/Command.php | 2 +- framework/db/Connection.php | 14 +- framework/db/Schema.php | 14 +- framework/filters/PageCache.php | 6 +- framework/i18n/DbMessageSource.php | 6 +- framework/rbac/DbManager.php | 8 +- framework/web/CacheSession.php | 6 +- framework/web/UrlManager.php | 6 +- framework/widgets/FragmentCache.php | 12 +- tests/framework/caching/CacheTestCase.php | 6 +- 22 files changed, 249 insertions(+), 61 deletions(-) create mode 100644 framework/caching/CacheInterface.php diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 0910f15ffe..1ac1c69dcd 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -11,6 +11,7 @@ Yii Framework 2 Change Log - Enh #14089: Added tests for `yii\base\Theme` (vladis84) - Enh #13586: Added `$preserveNonEmptyValues` property to the `yii\behaviors\AttributeBehavior` (Kolyunya) - Bug #14192: Fixed wrong default null value for TIMESTAMP when using PostgreSQL (Tigrov) +- Enh #14081: Added `yii\caching\CacheInterface` to make custom cache extensions adoption easier (silverfire) 2.0.12 June 05, 2017 -------------------- diff --git a/framework/base/Application.php b/framework/base/Application.php index dee8fcbeec..0b99a4d31b 100644 --- a/framework/base/Application.php +++ b/framework/base/Application.php @@ -19,7 +19,7 @@ use Yii; * @property \yii\rbac\ManagerInterface $authManager The auth manager application component. Null is returned * if auth manager is not configured. This property is read-only. * @property string $basePath The root directory of the application. - * @property \yii\caching\Cache $cache The cache application component. Null if the component is not enabled. + * @property \yii\caching\CacheInterface $cache The cache application component. Null if the component is not enabled. * This property is read-only. * @property array $container Values given in terms of name-value pairs. This property is write-only. * @property \yii\db\Connection $db The database connection. This property is read-only. @@ -516,7 +516,7 @@ abstract class Application extends Module /** * Returns the cache component. - * @return \yii\caching\Cache the cache application component. Null if the component is not enabled. + * @return \yii\caching\CacheInterface the cache application component. Null if the component is not enabled. */ public function getCache() { diff --git a/framework/caching/Cache.php b/framework/caching/Cache.php index 1384189ec0..e54c981e26 100644 --- a/framework/caching/Cache.php +++ b/framework/caching/Cache.php @@ -51,7 +51,7 @@ use yii\helpers\StringHelper; * @author Qiang Xue * @since 2.0 */ -abstract class Cache extends Component implements \ArrayAccess +abstract class Cache extends Component implements CacheInterface { /** * @var string a string prefixed to every cache key so that it is unique globally in the whole cache storage. diff --git a/framework/caching/CacheInterface.php b/framework/caching/CacheInterface.php new file mode 100644 index 0000000000..ac35484dd0 --- /dev/null +++ b/framework/caching/CacheInterface.php @@ -0,0 +1,187 @@ +get($key); + * if ($data === false) { + * // ...generate $data here... + * $cache->set($key, $data, $duration, $dependency); + * } + * ``` + * + * Because CacheInterface extends the [[\ArrayAccess]] interface, it can be used like an array. For example, + * + * ```php + * $cache['foo'] = 'some data'; + * echo $cache['foo']; + * ``` + * + * For more details and usage information on Cache, see the [guide article on caching](guide:caching-overview). + * + * @author Qiang Xue + * @author Dmitry Naumenko + * @since 2.0.13. Previous framework versions used abstract class [[yii\caching\Cache]] as interface. + */ +interface CacheInterface extends \ArrayAccess +{ + /** + * Builds a normalized cache key from a given key. + * + * If the given key is a string containing alphanumeric characters only and no more than 32 characters, + * then the key will be returned back prefixed with [[keyPrefix]]. Otherwise, a normalized key + * is generated by serializing the given key, applying MD5 hashing, and prefixing with [[keyPrefix]]. + * + * @param mixed $key the key to be normalized + * @return string the generated cache key + */ + public function buildKey($key); + + /** + * Retrieves a value from cache with a specified key. + * @param mixed $key a key identifying the cached value. This can be a simple string or + * a complex data structure consisting of factors representing the key. + * @return mixed the value stored in cache, false if the value is not in the cache, expired, + * or the dependency associated with the cached data has changed. + */ + public function get($key); + + /** + * Checks whether a specified key exists in the cache. + * This can be faster than getting the value from the cache if the data is big. + * In case a cache does not support this feature natively, this method will try to simulate it + * but has no performance improvement over getting it. + * Note that this method does not check whether the dependency associated + * with the cached data, if there is any, has changed. So a call to [[get]] + * may return false while exists returns true. + * @param mixed $key a key identifying the cached value. This can be a simple string or + * a complex data structure consisting of factors representing the key. + * @return bool true if a value exists in cache, false if the value is not in the cache or expired. + */ + public function exists($key); + + /** + * Retrieves multiple values from cache with the specified keys. + * Some caches (such as memcache, apc) allow retrieving multiple cached values at the same time, + * which may improve the performance. In case a cache does not support this feature natively, + * this method will try to simulate it. + * @param string[] $keys list of string keys identifying the cached values + * @return array list of cached values corresponding to the specified keys. The array + * is returned in terms of (key, value) pairs. + * If a value is not cached or expired, the corresponding array value will be false. + */ + public function multiGet($keys); + + /** + * Stores a value identified by a key into cache. + * If the cache already contains such a key, the existing value and + * expiration time will be replaced with the new ones, respectively. + * + * @param mixed $key a key identifying the value to be cached. This can be a simple string or + * a complex data structure consisting of factors representing the key. + * @param mixed $value the value to be cached + * @param int $duration default duration in seconds before the cache will expire. If not set, + * default [[defaultDuration]] value is used. + * @param Dependency $dependency dependency of the cached item. If the dependency changes, + * the corresponding value in the cache will be invalidated when it is fetched via [[get()]]. + * This parameter is ignored if [[serializer]] is false. + * @return bool whether the value is successfully stored into cache + */ + public function set($key, $value, $duration = null, $dependency = null); + + /** + * Stores multiple items in cache. Each item contains a value identified by a key. + * If the cache already contains such a key, the existing value and + * expiration time will be replaced with the new ones, respectively. + * + * @param array $items the items to be cached, as key-value pairs. + * @param int $duration default number of seconds in which the cached values will expire. 0 means never expire. + * @param Dependency $dependency dependency of the cached items. If the dependency changes, + * the corresponding values in the cache will be invalidated when it is fetched via [[get()]]. + * This parameter is ignored if [[serializer]] is false. + * @return array array of failed keys + */ + public function multiSet($items, $duration = 0, $dependency = null); + + /** + * Stores a value identified by a key into cache if the cache does not contain this key. + * Nothing will be done if the cache already contains the key. + * @param mixed $key a key identifying the value to be cached. This can be a simple string or + * a complex data structure consisting of factors representing the key. + * @param mixed $value the value to be cached + * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire. + * @param Dependency $dependency dependency of the cached item. If the dependency changes, + * the corresponding value in the cache will be invalidated when it is fetched via [[get()]]. + * This parameter is ignored if [[serializer]] is false. + * @return bool whether the value is successfully stored into cache + */ + public function add($key, $value, $duration = 0, $dependency = null); + + /** + * Stores multiple items in cache. Each item contains a value identified by a key. + * If the cache already contains such a key, the existing value and expiration time will be preserved. + * + * @param array $items the items to be cached, as key-value pairs. + * @param int $duration default number of seconds in which the cached values will expire. 0 means never expire. + * @param Dependency $dependency dependency of the cached items. If the dependency changes, + * the corresponding values in the cache will be invalidated when it is fetched via [[get()]]. + * This parameter is ignored if [[serializer]] is false. + * @return array array of failed keys + */ + public function multiAdd($items, $duration = 0, $dependency = null); + + /** + * Deletes a value with the specified key from cache + * @param mixed $key a key identifying the value to be deleted from cache. This can be a simple string or + * a complex data structure consisting of factors representing the key. + * @return bool if no error happens during deletion + */ + public function delete($key); + + /** + * Deletes all values from cache. + * Be careful of performing this operation if the cache is shared among multiple applications. + * @return bool whether the flush operation was successful. + */ + public function flush(); + + /** + * Method combines both [[set()]] and [[get()]] methods to retrieve value identified by a $key, + * or to store the result of $callable execution if there is no cache available for the $key. + * + * Usage example: + * + * ```php + * public function getTopProducts($count = 10) { + * $cache = $this->cache; // Could be Yii::$app->cache + * return $cache->getOrSet(['top-n-products', 'n' => $count], function ($cache) use ($count) { + * return Products::find()->mostPopular()->limit(10)->all(); + * }, 1000); + * } + * ``` + * + * @param mixed $key a key identifying the value to be cached. This can be a simple string or + * a complex data structure consisting of factors representing the key. + * @param callable|\Closure $callable the callable or closure that will be used to generate a value to be cached. + * In case $callable returns `false`, the value will not be cached. + * @param int $duration default duration in seconds before the cache will expire. If not set, + * [[defaultDuration]] value will be used. + * @param Dependency $dependency dependency of the cached item. If the dependency changes, + * the corresponding value in the cache will be invalidated when it is fetched via [[get()]]. + * This parameter is ignored if [[serializer]] is `false`. + * @return mixed result of $callable execution + */ + public function getOrSet($key, $callable, $duration = null, $dependency = null); +} diff --git a/framework/caching/ChainedDependency.php b/framework/caching/ChainedDependency.php index 889d19dd07..ee233bff9c 100644 --- a/framework/caching/ChainedDependency.php +++ b/framework/caching/ChainedDependency.php @@ -37,7 +37,7 @@ class ChainedDependency extends Dependency /** * Evaluates the dependency by generating and saving the data related with dependency. - * @param Cache $cache the cache component that is currently evaluating this dependency + * @param CacheInterface $cache the cache component that is currently evaluating this dependency */ public function evaluateDependency($cache) { @@ -49,7 +49,7 @@ class ChainedDependency extends Dependency /** * Generates the data needed to determine if dependency has been changed. * This method does nothing in this class. - * @param Cache $cache the cache component that is currently evaluating this dependency + * @param CacheInterface $cache the cache component that is currently evaluating this dependency * @return mixed the data needed to determine if dependency has been changed. */ protected function generateDependencyData($cache) diff --git a/framework/caching/DbDependency.php b/framework/caching/DbDependency.php index 48ad14dfc8..f16ef4a1be 100644 --- a/framework/caching/DbDependency.php +++ b/framework/caching/DbDependency.php @@ -43,7 +43,7 @@ class DbDependency extends Dependency /** * Generates the data needed to determine if dependency has been changed. * This method returns the value of the global state. - * @param Cache $cache the cache component that is currently evaluating this dependency + * @param CacheInterface $cache the cache component that is currently evaluating this dependency * @return mixed the data needed to determine if dependency has been changed. * @throws InvalidConfigException if [[db]] is not a valid application component ID */ @@ -66,4 +66,4 @@ class DbDependency extends Dependency return $result; } -} \ No newline at end of file +} diff --git a/framework/caching/DbQueryDependency.php b/framework/caching/DbQueryDependency.php index 35017ff8ce..1865fb54a3 100644 --- a/framework/caching/DbQueryDependency.php +++ b/framework/caching/DbQueryDependency.php @@ -62,7 +62,7 @@ class DbQueryDependency extends Dependency /** * Generates the data needed to determine if dependency is changed. * This method returns the query result - * @param Cache $cache the cache component that is currently evaluating this dependency + * @param CacheInterface $cache the cache component that is currently evaluating this dependency * @return mixed the data needed to determine if dependency has been changed. * @throws InvalidConfigException on invalid configuration. */ @@ -106,4 +106,4 @@ class DbQueryDependency extends Dependency } return call_user_func($this->method, $query, $db); } -} \ No newline at end of file +} diff --git a/framework/caching/Dependency.php b/framework/caching/Dependency.php index 3a7e9a25fe..7039bfb50c 100644 --- a/framework/caching/Dependency.php +++ b/framework/caching/Dependency.php @@ -42,7 +42,7 @@ abstract class Dependency extends \yii\base\Object /** * Evaluates the dependency by generating and saving the data related with dependency. * This method is invoked by cache before writing data into it. - * @param Cache $cache the cache component that is currently evaluating this dependency + * @param CacheInterface $cache the cache component that is currently evaluating this dependency */ public function evaluateDependency($cache) { @@ -68,7 +68,7 @@ abstract class Dependency extends \yii\base\Object /** * Checks whether the dependency is changed - * @param Cache $cache the cache component that is currently evaluating this dependency + * @param CacheInterface $cache the cache component that is currently evaluating this dependency * @return bool whether the dependency has changed. * @since 2.0.11 */ @@ -111,7 +111,7 @@ abstract class Dependency extends \yii\base\Object /** * Generates the data needed to determine if dependency is changed. * Derived classes should override this method to generate the actual dependency data. - * @param Cache $cache the cache component that is currently evaluating this dependency + * @param CacheInterface $cache the cache component that is currently evaluating this dependency * @return mixed the data needed to determine if dependency has been changed. */ abstract protected function generateDependencyData($cache); diff --git a/framework/caching/ExpressionDependency.php b/framework/caching/ExpressionDependency.php index 33957fc79a..89c4a9fcf0 100644 --- a/framework/caching/ExpressionDependency.php +++ b/framework/caching/ExpressionDependency.php @@ -40,7 +40,7 @@ class ExpressionDependency extends Dependency /** * Generates the data needed to determine if dependency has been changed. * This method returns the result of the PHP expression. - * @param Cache $cache the cache component that is currently evaluating this dependency + * @param CacheInterface $cache the cache component that is currently evaluating this dependency * @return mixed the data needed to determine if dependency has been changed. */ protected function generateDependencyData($cache) diff --git a/framework/caching/FileDependency.php b/framework/caching/FileDependency.php index 4ab98588b8..b3e94fcc41 100644 --- a/framework/caching/FileDependency.php +++ b/framework/caching/FileDependency.php @@ -33,7 +33,7 @@ class FileDependency extends Dependency /** * Generates the data needed to determine if dependency has been changed. * This method returns the file's last modification time. - * @param Cache $cache the cache component that is currently evaluating this dependency + * @param CacheInterface $cache the cache component that is currently evaluating this dependency * @return mixed the data needed to determine if dependency has been changed. * @throws InvalidConfigException if [[fileName]] is not set */ diff --git a/framework/caching/TagDependency.php b/framework/caching/TagDependency.php index 213a11d7be..26b286c08f 100644 --- a/framework/caching/TagDependency.php +++ b/framework/caching/TagDependency.php @@ -37,7 +37,7 @@ class TagDependency extends Dependency /** * Generates the data needed to determine if dependency has been changed. * This method does nothing in this class. - * @param Cache $cache the cache component that is currently evaluating this dependency + * @param CacheInterface $cache the cache component that is currently evaluating this dependency * @return mixed the data needed to determine if dependency has been changed. */ protected function generateDependencyData($cache) @@ -68,7 +68,7 @@ class TagDependency extends Dependency /** * Invalidates all of the cached data items that are associated with any of the specified [[tags]]. - * @param Cache $cache the cache component that caches the data items + * @param CacheInterface $cache the cache component that caches the data items * @param string|array $tags */ public static function invalidate($cache, $tags) @@ -82,7 +82,7 @@ class TagDependency extends Dependency /** * Generates the timestamp for the specified cache keys. - * @param Cache $cache + * @param CacheInterface $cache * @param string[] $keys * @return array the timestamp indexed by cache keys */ @@ -99,7 +99,7 @@ class TagDependency extends Dependency /** * Returns the timestamps for the specified tags. - * @param Cache $cache + * @param CacheInterface $cache * @param string[] $tags * @return array the timestamps indexed by the specified tags. */ diff --git a/framework/console/controllers/CacheController.php b/framework/console/controllers/CacheController.php index 9d65f8d381..d5fc2b3e8d 100644 --- a/framework/console/controllers/CacheController.php +++ b/framework/console/controllers/CacheController.php @@ -9,8 +9,8 @@ namespace yii\console\controllers; use Yii; use yii\caching\ApcCache; +use yii\caching\CacheInterface; use yii\console\Controller; -use yii\caching\Cache; use yii\helpers\Console; use yii\console\Exception; @@ -265,7 +265,7 @@ class CacheController extends Controller continue; } - if ($component instanceof Cache) { + if ($component instanceof CacheInterface) { $caches[$name] = get_class($component); } elseif (is_array($component) && isset($component['class']) && $this->isCacheClass($component['class'])) { $caches[$name] = $component['class']; @@ -284,7 +284,7 @@ class CacheController extends Controller */ private function isCacheClass($className) { - return is_subclass_of($className, Cache::className()); + return is_subclass_of($className, 'yii\caching\CacheInterface'); } /** diff --git a/framework/db/Command.php b/framework/db/Command.php index 21ec2bf9ae..7c451de342 100644 --- a/framework/db/Command.php +++ b/framework/db/Command.php @@ -903,7 +903,7 @@ class Command extends Component if ($method !== '') { $info = $this->db->getQueryCacheInfo($this->queryCacheDuration, $this->queryCacheDependency); if (is_array($info)) { - /* @var $cache \yii\caching\Cache */ + /* @var $cache \yii\caching\CacheInterface */ $cache = $info[0]; $cacheKey = [ __CLASS__, diff --git a/framework/db/Connection.php b/framework/db/Connection.php index f00e08ecbf..57800b1a86 100644 --- a/framework/db/Connection.php +++ b/framework/db/Connection.php @@ -12,7 +12,7 @@ use Yii; use yii\base\Component; use yii\base\InvalidConfigException; use yii\base\NotSupportedException; -use yii\caching\Cache; +use yii\caching\CacheInterface; /** * Connection represents a connection to a database via [PDO](http://php.net/manual/en/book.pdo.php). @@ -207,7 +207,7 @@ class Connection extends Component */ public $schemaCacheExclude = []; /** - * @var Cache|string the cache object or the ID of the cache application component that + * @var CacheInterface|string the cache object or the ID of the cache application component that * is used to cache the table metadata. * @see enableSchemaCache */ @@ -231,7 +231,7 @@ class Connection extends Component */ public $queryCacheDuration = 3600; /** - * @var Cache|string the cache object or the ID of the cache application component + * @var CacheInterface|string the cache object or the ID of the cache application component * that is used for query caching. * @see enableQueryCache */ @@ -302,7 +302,7 @@ class Connection extends Component */ public $enableSavepoint = true; /** - * @var Cache|string the cache object or the ID of the cache application component that is used to store + * @var CacheInterface|string the cache object or the ID of the cache application component that is used to store * the health status of the DB servers specified in [[masters]] and [[slaves]]. * This is used only when read/write splitting is enabled or [[masters]] is not empty. */ @@ -540,7 +540,7 @@ class Connection extends Component } else { $cache = $this->queryCache; } - if ($cache instanceof Cache) { + if ($cache instanceof CacheInterface) { return [$cache, $duration, $dependency]; } } @@ -1049,7 +1049,7 @@ class Connection extends Component } $key = [__METHOD__, $config['dsn']]; - if ($cache instanceof Cache && $cache->get($key)) { + if ($cache instanceof CacheInterface && $cache->get($key)) { // should not try this dead server now continue; } @@ -1062,7 +1062,7 @@ class Connection extends Component return $db; } catch (\Exception $e) { Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__); - if ($cache instanceof Cache) { + if ($cache instanceof CacheInterface) { // mark this server as dead and only retry it after the specified interval $cache->set($key, 1, $this->serverRetryInterval); } diff --git a/framework/db/Schema.php b/framework/db/Schema.php index 155723544e..8b91241232 100644 --- a/framework/db/Schema.php +++ b/framework/db/Schema.php @@ -11,7 +11,7 @@ use Yii; use yii\base\Object; use yii\base\NotSupportedException; use yii\base\InvalidCallException; -use yii\caching\Cache; +use yii\caching\CacheInterface; use yii\caching\TagDependency; /** @@ -130,9 +130,9 @@ abstract class Schema extends Object $realName = $this->getRawTableName($name); if ($db->enableSchemaCache && !in_array($name, $db->schemaCacheExclude, true)) { - /* @var $cache Cache */ + /* @var $cache CacheInterface */ $cache = is_string($db->schemaCache) ? Yii::$app->get($db->schemaCache, false) : $db->schemaCache; - if ($cache instanceof Cache) { + if ($cache instanceof CacheInterface) { $key = $this->getCacheKey($name); if ($refresh || ($table = $cache->get($key)) === false) { $this->_tables[$name] = $table = $this->loadTableSchema($realName); @@ -277,9 +277,9 @@ abstract class Schema extends Object */ public function refresh() { - /* @var $cache Cache */ + /* @var $cache CacheInterface */ $cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache; - if ($this->db->enableSchemaCache && $cache instanceof Cache) { + if ($this->db->enableSchemaCache && $cache instanceof CacheInterface) { TagDependency::invalidate($cache, $this->getCacheTag()); } $this->_tableNames = []; @@ -297,9 +297,9 @@ abstract class Schema extends Object { unset($this->_tables[$name]); $this->_tableNames = []; - /* @var $cache Cache */ + /* @var $cache CacheInterface */ $cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache; - if ($this->db->enableSchemaCache && $cache instanceof Cache) { + if ($this->db->enableSchemaCache && $cache instanceof CacheInterface) { $cache->delete($this->getCacheKey($name)); } } diff --git a/framework/filters/PageCache.php b/framework/filters/PageCache.php index 8b02278118..605e10ab63 100644 --- a/framework/filters/PageCache.php +++ b/framework/filters/PageCache.php @@ -10,7 +10,7 @@ namespace yii\filters; use Yii; use yii\base\Action; use yii\base\ActionFilter; -use yii\caching\Cache; +use yii\caching\CacheInterface; use yii\caching\Dependency; use yii\di\Instance; use yii\web\Response; @@ -57,7 +57,7 @@ class PageCache extends ActionFilter */ public $varyByRoute = true; /** - * @var Cache|array|string the cache object or the application component ID of the cache object. + * @var CacheInterface|array|string the cache object or the application component ID of the cache object. * After the PageCache object is created, if you want to change this property, * you should only assign it with a cache object. * Starting from version 2.0.2, this can also be a configuration array for creating the object. @@ -156,7 +156,7 @@ class PageCache extends ActionFilter return true; } - $this->cache = Instance::ensure($this->cache, Cache::className()); + $this->cache = Instance::ensure($this->cache, 'yii\caching\CacheInterface'); if (is_array($this->dependency)) { $this->dependency = Yii::createObject($this->dependency); diff --git a/framework/i18n/DbMessageSource.php b/framework/i18n/DbMessageSource.php index 92d32a68bc..e2c9cd18ef 100644 --- a/framework/i18n/DbMessageSource.php +++ b/framework/i18n/DbMessageSource.php @@ -9,10 +9,10 @@ namespace yii\i18n; use Yii; use yii\base\InvalidConfigException; +use yii\caching\CacheInterface; use yii\db\Expression; use yii\di\Instance; use yii\helpers\ArrayHelper; -use yii\caching\Cache; use yii\db\Connection; use yii\db\Query; @@ -55,7 +55,7 @@ class DbMessageSource extends MessageSource */ public $db = 'db'; /** - * @var Cache|array|string the cache object or the application component ID of the cache object. + * @var CacheInterface|array|string the cache object or the application component ID of the cache object. * The messages data will be cached using this cache object. * Note, that to enable caching you have to set [[enableCaching]] to `true`, otherwise setting this property has no effect. * @@ -98,7 +98,7 @@ class DbMessageSource extends MessageSource parent::init(); $this->db = Instance::ensure($this->db, Connection::className()); if ($this->enableCaching) { - $this->cache = Instance::ensure($this->cache, Cache::className()); + $this->cache = Instance::ensure($this->cache, 'yii\caching\CacheInterface'); } } diff --git a/framework/rbac/DbManager.php b/framework/rbac/DbManager.php index a42176b62b..4bffc4f085 100644 --- a/framework/rbac/DbManager.php +++ b/framework/rbac/DbManager.php @@ -8,7 +8,7 @@ namespace yii\rbac; use Yii; -use yii\caching\Cache; +use yii\caching\CacheInterface; use yii\db\Connection; use yii\db\Query; use yii\db\Expression; @@ -62,7 +62,7 @@ class DbManager extends BaseManager */ public $ruleTable = '{{%auth_rule}}'; /** - * @var Cache|array|string the cache used to improve RBAC performance. This can be one of the following: + * @var CacheInterface|array|string the cache used to improve RBAC performance. This can be one of the following: * * - an application component ID (e.g. `cache`) * - a configuration array @@ -111,7 +111,7 @@ class DbManager extends BaseManager parent::init(); $this->db = Instance::ensure($this->db, Connection::className()); if ($this->cache !== null) { - $this->cache = Instance::ensure($this->cache, Cache::className()); + $this->cache = Instance::ensure($this->cache, 'yii\caching\CacheInterface'); } } @@ -968,7 +968,7 @@ class DbManager extends BaseManager public function loadFromCache() { - if ($this->items !== null || !$this->cache instanceof Cache) { + if ($this->items !== null || !$this->cache instanceof CacheInterface) { return; } diff --git a/framework/web/CacheSession.php b/framework/web/CacheSession.php index 77d360a581..918535973a 100644 --- a/framework/web/CacheSession.php +++ b/framework/web/CacheSession.php @@ -8,7 +8,7 @@ namespace yii\web; use Yii; -use yii\caching\Cache; +use yii\caching\CacheInterface; use yii\di\Instance; /** @@ -39,7 +39,7 @@ use yii\di\Instance; class CacheSession extends Session { /** - * @var Cache|array|string the cache object or the application component ID of the cache object. + * @var CacheInterface|array|string the cache object or the application component ID of the cache object. * The session data will be stored using this cache object. * * After the CacheSession object is created, if you want to change this property, @@ -56,7 +56,7 @@ class CacheSession extends Session public function init() { parent::init(); - $this->cache = Instance::ensure($this->cache, Cache::className()); + $this->cache = Instance::ensure($this->cache, 'yii\caching\CacheInterface'); } /** diff --git a/framework/web/UrlManager.php b/framework/web/UrlManager.php index 7c97561151..9633df7c05 100644 --- a/framework/web/UrlManager.php +++ b/framework/web/UrlManager.php @@ -10,7 +10,7 @@ namespace yii\web; use Yii; use yii\base\Component; use yii\base\InvalidConfigException; -use yii\caching\Cache; +use yii\caching\CacheInterface; use yii\helpers\Url; /** @@ -118,7 +118,7 @@ class UrlManager extends Component */ public $routeParam = 'r'; /** - * @var Cache|string the cache object or the application component ID of the cache object. + * @var CacheInterface|string the cache object or the application component ID of the cache object. * Compiled URL rules will be cached through this cache object, if it is available. * * After the UrlManager object is created, if you want to change this property, @@ -181,7 +181,7 @@ class UrlManager extends Component if (is_string($this->cache)) { $this->cache = Yii::$app->get($this->cache, false); } - if ($this->cache instanceof Cache) { + if ($this->cache instanceof CacheInterface) { $cacheKey = $this->cacheKey; $hash = md5(json_encode($this->rules)); if (($data = $this->cache->get($cacheKey)) !== false && isset($data[1]) && $data[1] === $hash) { diff --git a/framework/widgets/FragmentCache.php b/framework/widgets/FragmentCache.php index 29b22387b9..875ac43467 100644 --- a/framework/widgets/FragmentCache.php +++ b/framework/widgets/FragmentCache.php @@ -9,7 +9,7 @@ namespace yii\widgets; use Yii; use yii\base\Widget; -use yii\caching\Cache; +use yii\caching\CacheInterface; use yii\caching\Dependency; use yii\di\Instance; @@ -25,7 +25,7 @@ use yii\di\Instance; class FragmentCache extends Widget { /** - * @var Cache|array|string the cache object or the application component ID of the cache object. + * @var CacheInterface|array|string the cache object or the application component ID of the cache object. * After the FragmentCache object is created, if you want to change this property, * you should only assign it with a cache object. * Starting from version 2.0.2, this can also be a configuration array for creating the object. @@ -84,9 +84,9 @@ class FragmentCache extends Widget { parent::init(); - $this->cache = $this->enabled ? Instance::ensure($this->cache, Cache::className()) : null; + $this->cache = $this->enabled ? Instance::ensure($this->cache, 'yii\caching\CacheInterface') : null; - if ($this->cache instanceof Cache && $this->getCachedContent() === false) { + if ($this->cache instanceof CacheInterface && $this->getCachedContent() === false) { $this->getView()->cacheStack[] = $this; ob_start(); ob_implicit_flush(false); @@ -103,7 +103,7 @@ class FragmentCache extends Widget { if (($content = $this->getCachedContent()) !== false) { echo $content; - } elseif ($this->cache instanceof Cache) { + } elseif ($this->cache instanceof CacheInterface) { array_pop($this->getView()->cacheStack); $content = ob_get_clean(); @@ -140,7 +140,7 @@ class FragmentCache extends Widget $this->_content = false; - if (!($this->cache instanceof Cache)) { + if (!($this->cache instanceof CacheInterface)) { return $this->_content; } diff --git a/tests/framework/caching/CacheTestCase.php b/tests/framework/caching/CacheTestCase.php index 9d5c39975b..50914839b8 100644 --- a/tests/framework/caching/CacheTestCase.php +++ b/tests/framework/caching/CacheTestCase.php @@ -23,7 +23,7 @@ function microtime($float = false) namespace yiiunit\framework\caching; -use yii\caching\Cache; +use yii\caching\CacheInterface; use yii\caching\TagDependency; use yiiunit\TestCase; @@ -45,7 +45,7 @@ abstract class CacheTestCase extends TestCase /** - * @return Cache + * @return CacheInterface */ abstract protected function getCacheInstance(); @@ -62,7 +62,7 @@ abstract class CacheTestCase extends TestCase } /** - * @return Cache + * @return CacheInterface */ public function prepare() { From ab68caa867dbdb748cbbd5cbe701bd8c2b285c76 Mon Sep 17 00:00:00 2001 From: Robert Korulczyk Date: Sun, 11 Jun 2017 18:20:31 +0200 Subject: [PATCH 70/71] Removed unused local var in JS test (#14093) --- tests/js/tests/yii.test.js | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/js/tests/yii.test.js b/tests/js/tests/yii.test.js index 14ad2206e8..daaa1e1c16 100644 --- a/tests/js/tests/yii.test.js +++ b/tests/js/tests/yii.test.js @@ -945,7 +945,6 @@ describe('yii', function () { describe('with xhr defined', function () { var server; - var response = {result: 'OK'}; beforeEach(function () { server = sinon.fakeServer.create(); From ba0ab403b52124c941dbeb46fbd9efdc12252a5d Mon Sep 17 00:00:00 2001 From: Robert Korulczyk Date: Mon, 12 Jun 2017 11:25:45 +0200 Subject: [PATCH 71/71] Added php-cs-fixer coding standards validation to Travis CI (#14100) * php-cs-fixer: PSR2 rule. * php-cs-fixer: PSR2 rule - fix views. * Travis setup refactoring. * Add php-cs-fixer to travis cs tests. * Fix tests on hhvm-3.12 * improve travis config * composer update * revert composer update * improve travis config * Fix CS. * Extract config to separate classes. * Extract config to separate classes. * Add file header. * Force short array syntax. * binary_operator_spaces fixer * Fix broken tests * cast_spaces fixer * concat_space fixer * dir_constant fixer * ereg_to_preg fixer * function_typehint_space fixer * hash_to_slash_comment fixer * is_null fixer * linebreak_after_opening_tag fixer * lowercase_cast fixer * magic_constant_casing fixer * modernize_types_casting fixer * native_function_casing fixer * new_with_braces fixer * no_alias_functions fixer * no_blank_lines_after_class_opening fixer * no_blank_lines_after_phpdoc fixer * no_empty_comment fixer * no_empty_phpdoc fixer * no_empty_statement fixer * no_extra_consecutive_blank_lines fixer * no_leading_import_slash fixer * no_leading_namespace_whitespace fixer * no_mixed_echo_print fixer * no_multiline_whitespace_around_double_arrow fixer * no_multiline_whitespace_before_semicolons fixer * no_php4_constructor fixer * no_short_bool_cast fixer * no_singleline_whitespace_before_semicolons fixer * no_spaces_around_offset fixer * no_trailing_comma_in_list_call fixer * no_trailing_comma_in_singleline_array fixer * no_unneeded_control_parentheses fixer * no_unused_imports fixer * no_useless_return fixer * no_whitespace_before_comma_in_array fixer * no_whitespace_in_blank_line fixer * not_operator_with_successor_space fixer * object_operator_without_whitespace fixer * ordered_imports fixer * php_unit_construct fixer * php_unit_dedicate_assert fixer * php_unit_fqcn_annotation fixer * phpdoc_indent fixer * phpdoc_no_access fixer * phpdoc_no_empty_return fixer * phpdoc_no_package fixer * phpdoc_no_useless_inheritdoc fixer * Fix broken tests * phpdoc_return_self_reference fixer * phpdoc_single_line_var_spacing fixer * phpdoc_single_line_var_spacing fixer * phpdoc_to_comment fixer * phpdoc_trim fixer * phpdoc_var_without_name fixer * psr4 fixer * self_accessor fixer * short_scalar_cast fixer * single_blank_line_before_namespace fixer * single_quote fixer * standardize_not_equals fixer * ternary_operator_spaces fixer * trailing_comma_in_multiline_array fixer * trim_array_spaces fixer * protected_to_private fixer * unary_operator_spaces fixer * whitespace_after_comma_in_array fixer * `parent::setRules()` -> `$this->setRules()` * blank_line_after_opening_tag fixer * Update finder config. * Revert changes for YiiRequirementChecker. * Fix array formatting. * Add missing import. * Fix CS for new code merged from master. * Fix some indentation issues. --- .php_cs | 29 + .travis.yml | 241 ++-- build/controllers/PhpDocController.php | 57 +- build/controllers/ReleaseController.php | 102 +- build/controllers/TranslationController.php | 2 +- build/controllers/Utf8Controller.php | 34 +- composer.json | 6 +- composer.lock | 1056 ++++++++++++++++- cs/TODO.md | 1 + cs/src/YiiConfig.php | 174 +++ cs/src/YiisoftConfig.php | 39 + framework/BaseYii.php | 4 +- framework/Yii.php | 2 - framework/base/Application.php | 6 +- framework/base/Component.php | 2 +- framework/base/ErrorHandler.php | 3 +- framework/base/Event.php | 4 +- framework/base/Model.php | 10 +- framework/base/Module.php | 10 +- framework/base/Security.php | 6 +- framework/base/Widget.php | 2 +- framework/base/WidgetEvent.php | 2 +- .../behaviors/AttributeTypecastBehavior.php | 2 +- framework/behaviors/SluggableBehavior.php | 4 +- framework/caching/ArrayCache.php | 2 +- framework/caching/Cache.php | 2 +- framework/caching/CacheInterface.php | 5 + framework/caching/DbCache.php | 6 +- framework/caching/MemCache.php | 4 +- .../migrations/m150909_153426_cache_init.php | 1 - framework/captcha/Captcha.php | 2 +- framework/console/Application.php | 4 +- framework/console/Controller.php | 2 +- framework/console/ErrorHandler.php | 2 +- framework/console/UnknownCommandException.php | 4 +- .../console/controllers/AssetController.php | 6 +- .../controllers/BaseMigrateController.php | 19 +- .../console/controllers/CacheController.php | 8 +- .../console/controllers/FixtureController.php | 12 +- .../console/controllers/HelpController.php | 8 +- .../console/controllers/MessageController.php | 16 +- .../console/controllers/MigrateController.php | 2 +- framework/data/ActiveDataProvider.php | 4 +- framework/data/SqlDataProvider.php | 2 +- framework/db/ActiveQuery.php | 23 +- framework/db/ActiveQueryTrait.php | 2 +- framework/db/ActiveRelationTrait.php | 4 +- framework/db/BaseActiveRecord.php | 16 +- framework/db/ColumnSchema.php | 2 +- framework/db/Command.php | 2 +- framework/db/Query.php | 4 +- framework/db/QueryBuilder.php | 7 +- framework/db/QueryTrait.php | 2 +- framework/db/Schema.php | 7 +- framework/db/SchemaBuilderTrait.php | 2 +- framework/db/TableSchema.php | 2 +- framework/db/cubrid/Schema.php | 2 +- framework/db/mssql/PDO.php | 2 +- framework/db/mysql/Schema.php | 4 +- framework/db/oci/QueryBuilder.php | 1 - framework/db/oci/Schema.php | 9 +- framework/db/pgsql/Schema.php | 4 +- framework/db/sqlite/QueryBuilder.php | 5 +- framework/db/sqlite/Schema.php | 4 +- framework/di/Container.php | 5 +- framework/di/Instance.php | 2 +- framework/di/NotInstantiableException.php | 2 +- framework/di/ServiceLocator.php | 2 +- framework/filters/AccessControl.php | 2 +- framework/filters/AccessRule.php | 8 +- framework/filters/ContentNegotiator.php | 6 +- framework/filters/Cors.php | 4 +- framework/filters/HostControl.php | 2 +- framework/filters/HttpCache.php | 4 +- framework/filters/PageCache.php | 2 +- framework/filters/RateLimiter.php | 4 +- framework/filters/auth/AuthInterface.php | 4 +- framework/filters/auth/AuthMethod.php | 10 +- framework/filters/auth/CompositeAuth.php | 2 +- framework/grid/DataColumn.php | 4 +- framework/grid/GridView.php | 12 +- framework/helpers/BaseArrayHelper.php | 4 +- framework/helpers/BaseConsole.php | 105 +- framework/helpers/BaseFormatConverter.php | 32 +- framework/helpers/BaseHtml.php | 2 +- framework/helpers/BaseJson.php | 2 +- framework/helpers/BaseStringHelper.php | 4 +- framework/i18n/DbMessageSource.php | 6 +- framework/i18n/Formatter.php | 14 +- framework/i18n/GettextMoFile.php | 4 +- framework/i18n/GettextPoFile.php | 2 +- framework/log/DbTarget.php | 2 +- framework/log/Logger.php | 6 +- framework/mail/BaseMessage.php | 2 +- framework/messages/bs/yii.php | 2 +- framework/mutex/DbMutex.php | 2 +- framework/mutex/OracleMutex.php | 8 +- framework/rbac/DbManager.php | 53 +- framework/rbac/PhpManager.php | 5 +- framework/rbac/Role.php | 1 - .../migrations/m140506_102106_rbac_init.php | 8 +- framework/requirements/requirements.php | 10 +- .../requirements/views/console/index.php | 20 +- framework/rest/Controller.php | 2 +- framework/rest/Serializer.php | 4 +- framework/test/DbFixture.php | 2 +- framework/validators/DateValidator.php | 6 +- framework/validators/EachValidator.php | 2 +- framework/validators/EmailValidator.php | 4 +- framework/validators/ExistValidator.php | 4 +- framework/validators/FileValidator.php | 5 +- framework/validators/IpValidator.php | 1 - framework/validators/NumberValidator.php | 2 +- .../validators/RegularExpressionValidator.php | 2 +- framework/validators/UniqueValidator.php | 9 +- framework/validators/UrlValidator.php | 2 +- framework/validators/Validator.php | 2 +- .../views/errorHandler/callStackItem.php | 10 +- framework/views/errorHandler/error.php | 15 +- framework/views/errorHandler/exception.php | 18 +- .../views/errorHandler/previousException.php | 10 +- framework/web/Application.php | 4 +- framework/web/AssetBundle.php | 4 +- framework/web/AssetConverter.php | 2 +- framework/web/CompositeUrlRule.php | 2 +- framework/web/CookieCollection.php | 2 +- framework/web/DbSession.php | 4 +- framework/web/ErrorHandler.php | 8 +- framework/web/HeaderCollection.php | 2 +- framework/web/MultiFieldSession.php | 2 +- framework/web/MultipartFormDataParser.php | 8 +- framework/web/Request.php | 19 +- framework/web/Response.php | 12 +- framework/web/Session.php | 2 +- framework/web/UploadedFile.php | 2 +- framework/web/UrlNormalizer.php | 2 +- framework/web/UrlRule.php | 5 +- framework/web/User.php | 2 +- framework/web/View.php | 6 +- framework/web/ViewAction.php | 2 - framework/web/XmlResponseFormatter.php | 2 +- .../m160313_153426_session_init.php | 1 - framework/widgets/ActiveField.php | 6 +- framework/widgets/ActiveForm.php | 4 +- framework/widgets/BaseListView.php | 2 +- framework/widgets/Breadcrumbs.php | 3 +- framework/widgets/DetailView.php | 4 +- framework/widgets/FragmentCache.php | 2 +- framework/widgets/InputWidget.php | 4 +- framework/widgets/LinkPager.php | 2 +- framework/widgets/MaskedInput.php | 8 +- framework/widgets/MaskedInputAsset.php | 4 +- framework/widgets/Menu.php | 2 +- tests/IsOneOfAssert.php | 5 + tests/TestCase.php | 9 +- tests/bootstrap.php | 5 + tests/compatibility.php | 13 +- tests/data/ar/Animal.php | 5 +- tests/data/ar/BitValues.php | 1 - tests/data/ar/Cat.php | 3 - tests/data/ar/Customer.php | 6 + tests/data/ar/CustomerQuery.php | 5 + tests/data/ar/DefaultPk.php | 2 +- tests/data/ar/Document.php | 7 +- tests/data/ar/Dog.php | 3 - tests/data/ar/Item.php | 5 + tests/data/ar/NullValues.php | 5 + tests/data/ar/Order.php | 7 +- tests/data/ar/OrderItem.php | 9 +- tests/data/ar/OrderItemWithNullFK.php | 6 +- tests/data/ar/OrderWithNullFK.php | 7 +- tests/data/ar/Profile.php | 5 +- tests/data/ar/Type.php | 5 + tests/data/base/InvalidRulesModel.php | 6 + tests/data/base/RulesModel.php | 6 + tests/data/base/Singer.php | 8 +- tests/data/base/Speaker.php | 6 + tests/data/cache/MockDependency.php | 8 +- tests/data/config-docker.php | 16 +- tests/data/config.php | 16 +- .../controllers/fixtures/FirstFixture.php | 6 +- .../controllers/fixtures/FixtureStorage.php | 9 +- .../controllers/fixtures/GlobalFixture.php | 7 +- .../controllers/fixtures/SecondFixture.php | 6 +- .../fixtures/subdir/FirstFixture.php | 6 +- .../fixtures/subdir/SecondFixture.php | 6 +- .../console/migrate_create/add_columns_fk.php | 5 + .../migrate_create/add_columns_prefix.php | 5 + .../migrate_create/add_columns_test.php | 5 + .../console/migrate_create/create_fields.php | 5 + .../migrate_create/create_foreign_key.php | 5 + .../console/migrate_create/create_id_pk.php | 5 + .../console/migrate_create/create_prefix.php | 5 + .../create_products_from_store_table.php | 5 + .../console/migrate_create/create_test.php | 5 + .../migrate_create/create_title_pk.php | 5 + ...create_title_with_comma_default_values.php | 5 + .../migrate_create/create_unsigned_big_pk.php | 5 + .../migrate_create/create_unsigned_pk.php | 5 + tests/data/console/migrate_create/default.php | 5 + .../migrate_create/drop_columns_test.php | 5 + .../console/migrate_create/drop_fields.php | 5 + .../drop_products_from_store_table.php | 5 + .../data/console/migrate_create/drop_test.php | 5 + .../console/migrate_create/junction_test.php | 8 +- tests/data/helpers/CustomDebugInfo.php | 5 + tests/data/i18n/messages/de-DE/test.php | 6 + tests/data/i18n/messages/de/test.php | 6 + tests/data/i18n/messages/en-US/test.php | 6 + tests/data/i18n/messages/ru/test.php | 6 + tests/data/validators/TestValidator.php | 5 + .../models/FakedValidationModel.php | 7 +- .../models/ValidatorTestMainModel.php | 5 + .../models/ValidatorTestRefModel.php | 6 +- tests/data/views/error.php | 8 +- tests/data/views/errorHandler.php | 6 +- tests/data/views/widgets/ListView/item.php | 13 +- tests/framework/BaseYiiTest.php | 20 +- tests/framework/ar/ActiveRecordTestTrait.php | 24 +- tests/framework/base/ActionFilterTest.php | 3 +- tests/framework/base/ApplicationTest.php | 12 +- tests/framework/base/BehaviorTest.php | 5 + tests/framework/base/ComponentTest.php | 36 +- tests/framework/base/ControllerTest.php | 7 +- tests/framework/base/DynamicModelTest.php | 4 +- tests/framework/base/EventTest.php | 8 +- tests/framework/base/ExposedSecurity.php | 9 +- tests/framework/base/ModelTest.php | 20 +- tests/framework/base/ModuleTest.php | 11 +- tests/framework/base/ObjectTest.php | 17 +- tests/framework/base/SecurityTest.php | 112 +- tests/framework/base/ThemeTest.php | 7 +- tests/framework/base/ViewTest.php | 7 +- .../themes/basic/views/site/index.php | 5 + .../themes/christmas/views/site/index.php | 5 + .../themes/christmas/views/site/main.php | 5 + .../behaviors/AttributeBehaviorTest.php | 20 +- .../AttributeTypecastBehaviorTest.php | 13 +- .../behaviors/BlameableBehaviorTest.php | 18 +- .../behaviors/SluggableBehaviorTest.php | 19 +- .../behaviors/TimestampBehaviorTest.php | 27 +- tests/framework/caching/ApcCacheTest.php | 20 +- tests/framework/caching/ArrayCacheTest.php | 5 + tests/framework/caching/CacheTestCase.php | 5 + tests/framework/caching/DbCacheTest.php | 11 +- tests/framework/caching/DbDependencyTest.php | 7 +- .../caching/DbQueryDependencyTest.php | 7 +- tests/framework/caching/DependencyTest.php | 7 +- tests/framework/caching/FileCacheTest.php | 6 + tests/framework/caching/MemCacheTest.php | 10 +- tests/framework/caching/MemCachedTest.php | 10 +- tests/framework/caching/TagDependencyTest.php | 8 +- tests/framework/caching/WinCacheTest.php | 10 +- tests/framework/caching/XCacheTest.php | 10 +- tests/framework/caching/ZendDataCacheTest.php | 10 +- tests/framework/console/ControllerTest.php | 16 +- tests/framework/console/FakeController.php | 9 +- .../framework/console/FakeHelpController.php | 5 + tests/framework/console/RequestTest.php | 7 +- .../console/UnkownCommandExceptionTest.php | 1 - .../controllers/AssetControllerTest.php | 61 +- .../controllers/BaseMessageControllerTest.php | 8 +- .../controllers/CacheControllerTest.php | 22 +- .../controllers/DbMessageControllerTest.php | 16 +- .../controllers/EchoMigrateController.php | 8 +- .../controllers/FixtureControllerTest.php | 15 +- .../controllers/HelpControllerTest.php | 10 +- .../controllers/MigrateControllerTest.php | 19 +- .../MigrateControllerTestTrait.php | 31 +- .../controllers/PHPMessageControllerTest.php | 7 +- .../controllers/POMessageControllerTest.php | 7 +- .../controllers/SilencedCacheController.php | 10 +- .../StdOutBufferControllerTrait.php | 7 +- .../framework/data/ActiveDataProviderTest.php | 24 +- .../framework/data/ArrayDataProviderTest.php | 81 +- tests/framework/data/BaseDataProviderTest.php | 8 +- tests/framework/data/PaginationTest.php | 7 +- tests/framework/data/SortTest.php | 24 +- tests/framework/data/SqlDataProviderTest.php | 10 +- tests/framework/db/ActiveQueryTest.php | 25 +- tests/framework/db/ActiveRecordTest.php | 144 ++- tests/framework/db/BatchQueryResultTest.php | 9 +- .../framework/db/ColumnSchemaBuilderTest.php | 12 +- tests/framework/db/CommandTest.php | 20 +- tests/framework/db/ConnectionTest.php | 20 +- tests/framework/db/DatabaseTestCase.php | 11 +- tests/framework/db/QueryBuilderTest.php | 330 +++--- tests/framework/db/QueryTest.php | 67 +- tests/framework/db/SchemaTest.php | 9 +- tests/framework/db/UnqueryableQueryMock.php | 5 + .../db/cubrid/ActiveDataProviderTest.php | 5 + .../framework/db/cubrid/ActiveFixtureTest.php | 5 + tests/framework/db/cubrid/ActiveQueryTest.php | 5 + .../framework/db/cubrid/ActiveRecordTest.php | 5 + .../db/cubrid/BatchQueryResultTest.php | 5 + .../db/cubrid/ColumnSchemaBuilderTest.php | 7 +- tests/framework/db/cubrid/CommandTest.php | 5 + tests/framework/db/cubrid/ConnectionTest.php | 5 + .../db/cubrid/ExistValidatorTest.php | 5 + .../framework/db/cubrid/QueryBuilderTest.php | 7 +- tests/framework/db/cubrid/QueryTest.php | 5 + tests/framework/db/cubrid/SchemaTest.php | 5 + .../db/cubrid/UniqueValidatorTest.php | 5 + .../db/mssql/ActiveDataProviderTest.php | 5 + .../framework/db/mssql/ActiveFixtureTest.php | 5 + tests/framework/db/mssql/ActiveQueryTest.php | 5 + tests/framework/db/mssql/ActiveRecordTest.php | 5 + .../db/mssql/BatchQueryResultTest.php | 5 + .../db/mssql/ColumnSchemaBuilderTest.php | 6 +- tests/framework/db/mssql/CommandTest.php | 9 +- tests/framework/db/mssql/ConnectionTest.php | 5 + .../framework/db/mssql/ExistValidatorTest.php | 5 + tests/framework/db/mssql/QueryBuilderTest.php | 7 +- tests/framework/db/mssql/QueryTest.php | 5 + tests/framework/db/mssql/SchemaTest.php | 5 + .../db/mssql/UniqueValidatorTest.php | 5 + .../db/mysql/ActiveDataProviderTest.php | 5 + .../framework/db/mysql/ActiveFixtureTest.php | 5 + tests/framework/db/mysql/ActiveQueryTest.php | 5 + tests/framework/db/mysql/ActiveRecordTest.php | 5 + .../db/mysql/BatchQueryResultTest.php | 5 + .../db/mysql/ColumnSchemaBuilderTest.php | 7 +- tests/framework/db/mysql/CommandTest.php | 5 + tests/framework/db/mysql/ConnectionTest.php | 5 + .../framework/db/mysql/ExistValidatorTest.php | 5 + tests/framework/db/mysql/QueryBuilderTest.php | 19 +- tests/framework/db/mysql/QueryTest.php | 8 +- tests/framework/db/mysql/SchemaTest.php | 5 + .../db/mysql/UniqueValidatorTest.php | 5 + .../db/mysql/connection/DeadLockTest.php | 55 +- .../db/oci/ActiveDataProviderTest.php | 5 + tests/framework/db/oci/ActiveFixtureTest.php | 5 + tests/framework/db/oci/ActiveQueryTest.php | 5 + tests/framework/db/oci/ActiveRecordTest.php | 5 + .../framework/db/oci/BatchQueryResultTest.php | 5 + .../db/oci/ColumnSchemaBuilderTest.php | 5 + tests/framework/db/oci/CommandTest.php | 7 +- tests/framework/db/oci/ConnectionTest.php | 7 +- tests/framework/db/oci/ExistValidatorTest.php | 5 + tests/framework/db/oci/QueryBuilderTest.php | 26 +- tests/framework/db/oci/QueryTest.php | 9 +- tests/framework/db/oci/SchemaTest.php | 8 +- .../framework/db/oci/UniqueValidatorTest.php | 5 + .../db/pgsql/ActiveDataProviderTest.php | 5 + .../framework/db/pgsql/ActiveFixtureTest.php | 5 + tests/framework/db/pgsql/ActiveQueryTest.php | 5 + tests/framework/db/pgsql/ActiveRecordTest.php | 7 +- .../db/pgsql/BatchQueryResultTest.php | 5 + .../db/pgsql/ColumnSchemaBuilderTest.php | 5 + tests/framework/db/pgsql/CommandTest.php | 5 + tests/framework/db/pgsql/ConnectionTest.php | 7 +- .../framework/db/pgsql/ExistValidatorTest.php | 5 + tests/framework/db/pgsql/QueryBuilderTest.php | 47 +- tests/framework/db/pgsql/QueryTest.php | 6 +- tests/framework/db/pgsql/SchemaTest.php | 7 +- .../db/pgsql/UniqueValidatorTest.php | 5 + .../db/sqlite/ActiveDataProviderTest.php | 5 + .../framework/db/sqlite/ActiveFixtureTest.php | 5 + tests/framework/db/sqlite/ActiveQueryTest.php | 5 + .../framework/db/sqlite/ActiveRecordTest.php | 5 + .../db/sqlite/BatchQueryResultTest.php | 5 + .../db/sqlite/ColumnSchemaBuilderTest.php | 9 +- tests/framework/db/sqlite/CommandTest.php | 7 +- tests/framework/db/sqlite/ConnectionTest.php | 16 +- .../db/sqlite/ExistValidatorTest.php | 5 + .../framework/db/sqlite/QueryBuilderTest.php | 19 +- tests/framework/db/sqlite/QueryTest.php | 8 +- tests/framework/db/sqlite/SchemaTest.php | 5 + .../db/sqlite/UniqueValidatorTest.php | 5 + .../framework/db/testBatchInsertWithYield.php | 6 +- tests/framework/di/ContainerTest.php | 47 +- tests/framework/di/InstanceTest.php | 20 +- tests/framework/di/ServiceLocatorTest.php | 6 +- tests/framework/di/stubs/QuxInterface.php | 2 +- tests/framework/filters/AccessRuleTest.php | 30 +- tests/framework/filters/HostControlTest.php | 29 +- tests/framework/filters/HttpCacheTest.php | 21 +- tests/framework/filters/PageCacheTest.php | 59 +- tests/framework/filters/RateLimiterTest.php | 23 +- .../framework/filters/auth/AuthMethodTest.php | 11 +- tests/framework/filters/auth/AuthTest.php | 35 +- .../filters/auth/CompositeAuthTest.php | 25 +- .../filters/stubs/MockAuthManager.php | 13 +- tests/framework/filters/stubs/RateLimit.php | 8 +- .../framework/filters/stubs/UserIdentity.php | 7 +- tests/framework/grid/ActionColumnTest.php | 24 +- tests/framework/grid/CheckboxColumnTest.php | 8 +- tests/framework/grid/DataColumnTest.php | 25 +- tests/framework/grid/GridViewTest.php | 14 +- .../framework/grid/RadiobuttonColumnTest.php | 23 +- tests/framework/helpers/ArrayHelperTest.php | 107 +- tests/framework/helpers/ConsoleTest.php | 17 +- tests/framework/helpers/FallbackInflector.php | 9 +- tests/framework/helpers/FileHelperTest.php | 61 +- .../framework/helpers/FormatConverterTest.php | 5 + tests/framework/helpers/HtmlTest.php | 177 +-- tests/framework/helpers/InflectorTest.php | 25 +- tests/framework/helpers/JsonTest.php | 20 +- tests/framework/helpers/MarkdownTest.php | 8 +- tests/framework/helpers/StringHelperTest.php | 54 +- tests/framework/helpers/UrlTest.php | 10 +- tests/framework/helpers/VarDumperTest.php | 28 +- tests/framework/i18n/DbMessageSourceTest.php | 13 +- .../i18n/FallbackMessageFormatterTest.php | 72 +- tests/framework/i18n/FormatterDateTest.php | 75 +- tests/framework/i18n/FormatterNumberTest.php | 343 +++--- tests/framework/i18n/FormatterTest.php | 15 +- .../i18n/GettextMessageSourceTest.php | 5 + tests/framework/i18n/GettextMoFileTest.php | 11 +- tests/framework/i18n/GettextPoFileTest.php | 12 +- tests/framework/i18n/I18NTest.php | 18 +- tests/framework/i18n/IntlTestHelper.php | 8 +- tests/framework/i18n/MessageFormatterTest.php | 162 +-- tests/framework/log/DbTargetTest.php | 14 +- tests/framework/log/DispatcherTest.php | 44 +- tests/framework/log/EmailTargetTest.php | 35 +- tests/framework/log/FileTargetTest.php | 16 +- tests/framework/log/LoggerTest.php | 107 +- tests/framework/log/MySQLTargetTest.php | 8 +- tests/framework/log/PgSQLTargetTest.php | 9 +- tests/framework/log/SqliteTargetTest.php | 9 +- tests/framework/log/SyslogTargetTest.php | 29 +- tests/framework/log/TargetTest.php | 8 +- tests/framework/mail/BaseMailerTest.php | 35 +- tests/framework/mail/BaseMessageTest.php | 53 +- tests/framework/mutex/FileMutexTest.php | 7 +- tests/framework/mutex/MutexTestTrait.php | 9 +- tests/framework/mutex/MysqlMutexTest.php | 8 +- tests/framework/mutex/PgsqlMutexTest.php | 8 +- tests/framework/rbac/ActionRule.php | 5 + tests/framework/rbac/AuthorRule.php | 6 + tests/framework/rbac/DbManagerTestCase.php | 10 +- tests/framework/rbac/ExposedPhpManager.php | 8 +- tests/framework/rbac/ManagerTestCase.php | 11 +- .../framework/rbac/MySQLManagerCacheTest.php | 8 +- tests/framework/rbac/MySQLManagerTest.php | 7 +- .../framework/rbac/PgSQLManagerCacheTest.php | 9 +- tests/framework/rbac/PgSQLManagerTest.php | 6 + tests/framework/rbac/PhpManagerTest.php | 11 +- tests/framework/rbac/SqliteManagerTest.php | 6 + .../YiiRequirementCheckerTest.php | 19 +- tests/framework/rest/SerializerTest.php | 48 +- tests/framework/rest/UrlRuleTest.php | 200 ++-- tests/framework/test/ActiveFixtureTest.php | 12 +- tests/framework/test/ArrayFixtureTest.php | 4 +- tests/framework/test/data/array_fixture.php | 5 + tests/framework/test/data/customer.php | 9 +- tests/framework/test/data/profile.php | 5 + .../validators/BooleanValidatorTest.php | 23 +- .../validators/CompareValidatorTest.php | 29 +- .../validators/DateValidatorTest.php | 98 +- .../validators/DefaultValueValidatorTest.php | 9 +- .../validators/EachValidatorTest.php | 15 +- .../validators/EmailValidatorTest.php | 8 +- .../validators/ExistValidatorTest.php | 5 + .../validators/FileValidatorTest.php | 39 +- .../validators/FilterValidatorTest.php | 10 +- .../framework/validators/IpValidatorTest.php | 22 +- .../validators/NumberValidatorTest.php | 20 +- .../validators/RangeValidatorTest.php | 38 +- .../RegularExpressionValidatorTest.php | 7 +- .../validators/RequiredValidatorTest.php | 16 +- .../validators/StringValidatorTest.php | 11 +- .../validators/UniqueValidatorTest.php | 21 +- .../framework/validators/UrlValidatorTest.php | 21 +- tests/framework/validators/ValidatorTest.php | 5 + tests/framework/web/AssetBundleTest.php | 44 +- tests/framework/web/AssetConverterTest.php | 4 +- tests/framework/web/CacheSessionTest.php | 5 + tests/framework/web/ControllerTest.php | 7 +- tests/framework/web/DbSessionTest.php | 15 +- tests/framework/web/ErrorActionTest.php | 9 +- tests/framework/web/ErrorHandlerTest.php | 21 +- tests/framework/web/FakeController.php | 1 - tests/framework/web/FormatterTest.php | 10 +- tests/framework/web/GroupUrlRuleTest.php | 21 +- .../web/JsonResponseFormatterTest.php | 54 +- .../web/MultipartFormDataParserTest.php | 15 +- tests/framework/web/Post.php | 8 +- tests/framework/web/RequestTest.php | 8 +- tests/framework/web/ResponseTest.php | 24 +- tests/framework/web/SessionTest.php | 5 + tests/framework/web/UploadedFileTest.php | 13 +- .../framework/web/UrlManagerCreateUrlTest.php | 11 +- .../framework/web/UrlManagerParseUrlTest.php | 34 +- tests/framework/web/UrlManagerTest.php | 10 +- tests/framework/web/UrlRuleTest.php | 47 +- tests/framework/web/UserTest.php | 36 +- tests/framework/web/ViewTest.php | 22 +- .../web/XmlResponseFormatterTest.php | 10 +- tests/framework/web/stubs/CachedUrlRule.php | 5 + tests/framework/web/stubs/ModelStub.php | 5 + tests/framework/web/stubs/VendorImage.php | 8 +- tests/framework/widgets/ActiveFieldTest.php | 52 +- tests/framework/widgets/ActiveFormTest.php | 6 +- tests/framework/widgets/BreadcrumbsTest.php | 15 +- tests/framework/widgets/DetailViewTest.php | 22 +- tests/framework/widgets/FragmentCacheTest.php | 23 +- tests/framework/widgets/LinkPagerTest.php | 17 +- tests/framework/widgets/LinkSorterTest.php | 10 +- tests/framework/widgets/ListViewTest.php | 12 +- tests/framework/widgets/MenuTest.php | 75 +- tests/framework/widgets/PjaxTest.php | 6 +- tests/framework/widgets/SpacelessTest.php | 7 +- 504 files changed, 5840 insertions(+), 2940 deletions(-) create mode 100644 .php_cs create mode 100644 cs/TODO.md create mode 100644 cs/src/YiiConfig.php create mode 100644 cs/src/YiisoftConfig.php diff --git a/.php_cs b/.php_cs new file mode 100644 index 0000000000..d98e72f449 --- /dev/null +++ b/.php_cs @@ -0,0 +1,29 @@ +setCacheFile(__DIR__ . '/tests/runtime/php_cs.cache') + ->mergeRules([ + 'braces' => [ + 'allow_single_line_closure' => true, + ], + ]) + ->setFinder( + PhpCsFixer\Finder::create() + ->in(__DIR__) + ->exclude('docs') + ->exclude('apps') + ->exclude('extensions') + // requirement checker should work even on PHP 4.3, so it needs special treatment + ->exclude('framework/requirements') + ->notPath('framework/classes.php') + ->notPath('framework/helpers/mimeTypes.php') + ->notPath('framework/views/messageConfig.php') + // temporary disable messages processing - conflicts with header fixer + ->exclude('framework/messages') + ); diff --git a/.travis.yml b/.travis.yml index 47df824c47..9b1e881956 100644 --- a/.travis.yml +++ b/.travis.yml @@ -23,73 +23,13 @@ sudo: false language: php -php: - - 5.4 - - 5.5 - - 5.6 - - 7.0 - - 7.1 - - nightly - -matrix: - fast_finish: true - include: - # Test against HHVM 3.12 LTS version by using trusty - - php: hhvm-3.12 - sudo: true - dist: trusty - group: edge # Use edge image until the next travis CI image update - addons: - code_climate: - repo_token: 2935307212620b0e2228ab67eadd92c9f5501ddb60549d0d86007a354d56915b - apt: - packages: - - mysql-server-5.6 - - mysql-client-core-5.6 - - mysql-client-5.6 - services: - - mysql - # test against the latest HHVM version by using a newer image - - php: hhvm - sudo: true - dist: trusty - group: edge # Use edge image until the next travis CI image update - addons: - code_climate: - repo_token: 2935307212620b0e2228ab67eadd92c9f5501ddb60549d0d86007a354d56915b - postgresql: "9.3" - apt: - packages: - - mysql-server-5.6 - - mysql-client-core-5.6 - - mysql-client-5.6 - services: - - mysql - - postgresql - # have a separate branch for javascript tests - - language: node_js - node_js: 6 - dist: trusty - # overwrite php related settings - php: - services: - addons: - install: - - travis_retry npm install - # disable xdebug for performance in composer - - phpenv config-rm xdebug.ini || echo "xdebug is not installed" - - travis_retry composer self-update && composer --version - - travis_retry composer install --prefer-dist --no-interaction - before_script: - - node --version - - npm --version - - php --version - - composer --version - script: npm test - after_script: - - allow_failures: - - php: nightly +env: + global: + - DEFAULT_COMPOSER_FLAGS="--prefer-dist --no-interaction --no-progress --optimize-autoloader" + - TASK_TESTS_PHP=1 + - TASK_TESTS_JS=0 + - TASK_TESTS_CS=0 + - TASK_TESTS_COVERAGE=0 services: @@ -110,54 +50,165 @@ addons: code_climate: repo_token: 2935307212620b0e2228ab67eadd92c9f5501ddb60549d0d86007a354d56915b +matrix: + fast_finish: true + include: + # test coding standards + - php: 7.1 + env: TASK_TESTS_PHP=0 TASK_TESTS_CS=1 + # overwrite services used for PHP tests + services: + + # run tests coverage on PHP 7.1 + - php: 7.1 + env: TASK_TESTS_COVERAGE=1 + + - php: 7.0 + + - php: 5.6 + + - php: 5.5 + + - php: 5.4 + + # Test against HHVM 3.12 LTS version by using trusty + - php: hhvm-3.12 + sudo: true + dist: trusty + group: edge # Use edge image until the next travis CI image update + addons: + code_climate: + repo_token: 2935307212620b0e2228ab67eadd92c9f5501ddb60549d0d86007a354d56915b + apt: + packages: + - mysql-server-5.6 + - mysql-client-core-5.6 + - mysql-client-5.6 + services: + - mysql + + # test against the latest HHVM version by using a newer image + - php: hhvm + sudo: true + dist: trusty + group: edge # Use edge image until the next travis CI image update + addons: + code_climate: + repo_token: 2935307212620b0e2228ab67eadd92c9f5501ddb60549d0d86007a354d56915b + postgresql: "9.3" + apt: + packages: + - mysql-server-5.6 + - mysql-client-core-5.6 + - mysql-client-5.6 + services: + - mysql + - postgresql + + - php: nightly + + # have a separate branch for javascript tests + - language: node_js + node_js: 6 + env: TASK_TESTS_PHP=0 TASK_TESTS_JS=1 + dist: trusty + # overwrite services used for PHP tests + services: + + allow_failures: + - php: nightly + install: - | - if [[ $TRAVIS_PHP_VERSION != '7.1' && $TRAVIS_PHP_VERSION != hhv* ]]; then - # disable xdebug for performance reasons when code coverage is not needed. note: xdebug on hhvm is disabled by default - phpenv config-rm xdebug.ini || echo "xdebug is not installed" + if [[ $TASK_TESTS_COVERAGE != 1 && $TRAVIS_PHP_VERSION != hhv* ]]; then + # disable xdebug for performance reasons when code coverage is not needed. note: xdebug on hhvm is disabled by default + phpenv config-rm xdebug.ini || echo "xdebug is not installed" fi - - travis_retry composer self-update && composer --version + + # install composer dependencies + - travis_retry composer self-update - export PATH="$HOME/.composer/vendor/bin:$PATH" - # core framework: - - travis_retry composer install --prefer-dist --no-interaction - - tests/data/travis/apc-setup.sh - - tests/data/travis/memcache-setup.sh - - tests/data/travis/imagick-setup.sh + - | + if [[ $TRAVIS_PHP_VERSION == "hhvm-3.12" ]]; then + # remove php-cs-fixer from composer dependencies on hhvm-3.12 - php-cs-fixer requires at least hhvm-3.18 + composer remove friendsofphp/php-cs-fixer --dev + fi + - travis_retry composer install $DEFAULT_COMPOSER_FLAGS + + # setup PHP extension + - | + if [ $TASK_TESTS_PHP == 1 ]; then + tests/data/travis/apc-setup.sh + tests/data/travis/memcache-setup.sh + tests/data/travis/imagick-setup.sh + fi + + # setup JS test + - | + if [ $TASK_TESTS_JS == 1 ]; then + travis_retry npm install + fi before_script: # Disable the HHVM JIT for faster Unit Testing - if [[ $TRAVIS_PHP_VERSION = hhv* ]]; then echo 'hhvm.jit = 0' >> /etc/hhvm/php.ini; fi + # show some versions and env information - - php -r "echo INTL_ICU_VERSION . \"\n\";" - - php -r "echo INTL_ICU_DATA_VERSION . \"\n\";" - - mysql --version - - psql --version + - php --version + - composer --version + - | + if [ $TASK_TESTS_PHP == 1 ]; then + php -r "echo INTL_ICU_VERSION . \"\n\";" + php -r "echo INTL_ICU_DATA_VERSION . \"\n\";" + psql --version + mysql --version + fi + - | + if [ $TASK_TESTS_JS == 1 ]; then + node --version + npm --version + fi # initialize databases - - travis_retry mysql -e 'CREATE DATABASE `yiitest`;'; - - mysql -e "CREATE USER 'travis'@'localhost' IDENTIFIED WITH mysql_native_password;"; - - mysql -e "GRANT ALL PRIVILEGES ON *.* TO 'travis'@'localhost' WITH GRANT OPTION;"; - - psql -U postgres -c 'CREATE DATABASE yiitest;'; - - # enable code coverage on PHP 7.1, only one PHP version needs to generate coverage data - | - if [ $TRAVIS_PHP_VERSION = '7.1' ]; then + if [ $TASK_TESTS_PHP == 1 ]; then + travis_retry mysql -e 'CREATE DATABASE `yiitest`;'; + mysql -e "CREATE USER 'travis'@'localhost' IDENTIFIED WITH mysql_native_password;"; + mysql -e "GRANT ALL PRIVILEGES ON *.* TO 'travis'@'localhost' WITH GRANT OPTION;"; + psql -U postgres -c 'CREATE DATABASE yiitest;'; + fi + + # enable code coverage + - | + if [ $TASK_TESTS_COVERAGE == 1 ]; then PHPUNIT_FLAGS="--coverage-clover=coverage.clover" fi script: - # ensure no files contain UTF-8 byte order mark - - if ! grep -rlI $'\xEF\xBB\xBF' framework/ ; then echo "no utf8 BOM found"; else echo "found utf8 BOM in some files. See above."; exit 1; fi - # validate composer.json - - composer validate --no-check-lock - - cd framework && composer validate --no-check-lock && cd .. - # run PHPUnit - - vendor/bin/phpunit --verbose $PHPUNIT_FLAGS --exclude-group mssql,oci,wincache,xcache,zenddata,cubrid + # test coding standards + - | + if [ $TASK_TESTS_CS == 1 ]; then + composer validate --no-check-lock + cd framework && composer validate --no-check-lock && cd .. + vendor/bin/php-cs-fixer --diff --dry-run -v fix + fi + + # PHP tests + - | + if [ $TASK_TESTS_PHP == 1 ]; then + vendor/bin/phpunit --verbose $PHPUNIT_FLAGS --exclude-group mssql,oci,wincache,xcache,zenddata,cubrid + fi + + # JS tests + - | + if [ $TASK_TESTS_JS == 1 ]; then + npm test + fi after_script: - | - if [ $TRAVIS_PHP_VERSION = '7.1' ]; then + if [ $TASK_TESTS_COVERAGE == 1 ]; then travis_retry wget https://scrutinizer-ci.com/ocular.phar php ocular.phar code-coverage:upload --format=php-clover coverage.clover fi diff --git a/build/controllers/PhpDocController.php b/build/controllers/PhpDocController.php index bb01fa520b..d4284e8696 100644 --- a/build/controllers/PhpDocController.php +++ b/build/controllers/PhpDocController.php @@ -103,7 +103,6 @@ class PhpDocController extends Controller $this->stdout("\nParsed $nFilesTotal files.\n"); $this->stdout("Updated $nFilesUpdated files.\n"); - } /** @@ -173,7 +172,6 @@ class PhpDocController extends Controller } } } elseif (preg_match('~extensions/([\w-]+)[\\\\/]?$~', $root, $matches)) { - $extensionPath = dirname(rtrim($root, '\\/')); $this->setUpExtensionAliases($extensionPath); @@ -197,7 +195,6 @@ class PhpDocController extends Controller // return []; // } } elseif (preg_match('~apps/([\w-]+)[\\\\/]?$~', $root, $matches)) { - $extensionPath = dirname(dirname(rtrim($root, '\\/'))) . '/extensions'; $this->setUpExtensionAliases($extensionPath); @@ -211,20 +208,19 @@ class PhpDocController extends Controller $except[] = '/vendor/'; $except[] = '/tests/'; $except[] = '/docs/'; - } $root = FileHelper::normalizePath($root); $options = [ 'filter' => function ($path) { - if (is_file($path)) { - $file = basename($path); - if ($file[0] < 'A' || $file[0] > 'Z') { - return false; - } + if (is_file($path)) { + $file = basename($path); + if ($file[0] < 'A' || $file[0] > 'Z') { + return false; } + } - return null; - }, + return null; + }, 'only' => ['*.php'], 'except' => array_merge($except, [ '.git/', @@ -274,15 +270,15 @@ class PhpDocController extends Controller $contentAfterNamespace--; } $lines = array_merge([ - " $type) { switch ($type) { @@ -412,7 +408,7 @@ class PhpDocController extends Controller // check for multi line array if ($level > 0) { - ${'endof'.$property} = $i; + ${'endof' . $property} = $i; } $line = trim($line); @@ -448,8 +444,8 @@ class PhpDocController extends Controller $endofAll = false; foreach (['Private', 'Protected', 'Public', 'Const', 'Use'] as $var) { - if (${'endof'.$var} !== false) { - $endofAll = ${'endof'.$var}; + if (${'endof' . $var} !== false) { + $endofAll = ${'endof' . $var}; break; } } @@ -531,7 +527,6 @@ class PhpDocController extends Controller } if (trim($oldDoc) != trim($newDoc)) { - $fileContent = explode("\n", file_get_contents($file)); $start = $ref->getStartLine() - 2; $docStart = $start - count(explode("\n", $oldDoc)) + 1; @@ -621,8 +616,8 @@ class PhpDocController extends Controller protected function generateClassPropertyDocs($fileName) { - $phpdoc = ""; - $file = str_replace("\r", "", str_replace("\t", " ", file_get_contents($fileName, true))); + $phpdoc = ''; + $file = str_replace("\r", '', str_replace("\t", ' ', file_get_contents($fileName, true))); $ns = $this->match('#\nnamespace (?[\w\\\\]+);\n#', $file); $namespace = reset($ns); $namespace = $namespace['name']; @@ -655,7 +650,6 @@ class PhpDocController extends Controller $className = null; foreach ($classes as &$class) { - $className = $namespace . '\\' . $class['name']; $gets = $this->match( @@ -756,9 +750,11 @@ class PhpDocController extends Controller foreach ($parts as $part) { preg_match_all($pattern . 'suU', $part, $matches, PREG_SET_ORDER); foreach ($matches as &$set) { - foreach ($set as $i => $match) - if (is_numeric($i) /*&& $i != 0*/) + foreach ($set as $i => $match) { + if (is_numeric($i) /*&& $i != 0*/) { unset($set[$i]); + } + } $sets[] = $set; } @@ -769,8 +765,9 @@ class PhpDocController extends Controller protected function fixSentence($str) { // TODO fix word wrap - if ($str == '') + if ($str == '') { return ''; + } return strtoupper(substr($str, 0, 1)) . substr($str, 1) . ($str[strlen($str) - 1] != '.' ? '.' : ''); } diff --git a/build/controllers/ReleaseController.php b/build/controllers/ReleaseController.php index 06674a3d9f..7158d5cadf 100644 --- a/build/controllers/ReleaseController.php +++ b/build/controllers/ReleaseController.php @@ -127,10 +127,9 @@ class ReleaseController extends Controller $w = $this->minWidth(array_keys($versions)); $this->stdout(str_repeat(' ', $w + 2) . "Current Version Next Version\n", Console::BOLD); foreach ($versions as $ext => $version) { - $this->stdout($ext . str_repeat(' ', $w + 3 - mb_strlen($ext)) . $version . ""); + $this->stdout($ext . str_repeat(' ', $w + 3 - mb_strlen($ext)) . $version . ''); $this->stdout(str_repeat(' ', 17 - mb_strlen($version)) . $nextVersions[$ext] . "\n"); } - } private function minWidth($a) @@ -219,7 +218,7 @@ class ReleaseController extends Controller $this->stdout("- are all new `@since` tags for this release version?\n"); } $this->stdout("- other issues with code changes?\n\n git diff -w $gitVersion.. ${gitDir}\n\n"); - $travisUrl = reset($what) === 'framework' ? '' : '-'.reset($what); + $travisUrl = reset($what) === 'framework' ? '' : '-' . reset($what); $this->stdout("- are unit tests passing on travis? https://travis-ci.org/yiisoft/yii2$travisUrl/builds\n"); $this->stdout("- also make sure the milestone on github is complete and no issues or PRs are left open.\n\n"); $this->printWhatUrls($what, $versions); @@ -266,15 +265,15 @@ class ReleaseController extends Controller $this->stdout("You are about to generate packages for the following things:\n\n"); foreach ($what as $ext) { if (strncmp('app-', $ext, 4) === 0) { - $this->stdout(" - "); + $this->stdout(' - '); $this->stdout(substr($ext, 4), Console::FG_RED); - $this->stdout(" application version "); + $this->stdout(' application version '); } elseif ($ext === 'framework') { - $this->stdout(" - Yii Framework version "); + $this->stdout(' - Yii Framework version '); } else { - $this->stdout(" - "); + $this->stdout(' - '); $this->stdout($ext, Console::FG_RED); - $this->stdout(" extension version "); + $this->stdout(' extension version '); } $this->stdout($versions[$ext], Console::BOLD); $this->stdout("\n"); @@ -323,9 +322,9 @@ class ReleaseController extends Controller $version = array_values($this->getNextVersions($this->getCurrentVersions($what), self::PATCH))[0]; $this->stdout('sorting CHANGELOG of '); $this->stdout(reset($what), Console::BOLD); - $this->stdout(" for version "); + $this->stdout(' for version '); $this->stdout($version, Console::BOLD); - $this->stdout("..."); + $this->stdout('...'); $this->resortChangelogs($what, $version); @@ -336,15 +335,15 @@ class ReleaseController extends Controller { foreach ($what as $ext) { if (strncmp('app-', $ext, 4) === 0) { - $this->stdout(" - "); + $this->stdout(' - '); $this->stdout(substr($ext, 4), Console::FG_RED); - $this->stdout(" application version "); + $this->stdout(' application version '); } elseif ($ext === 'framework') { - $this->stdout(" - Yii Framework version "); + $this->stdout(' - Yii Framework version '); } else { - $this->stdout(" - "); + $this->stdout(' - '); $this->stdout($ext, Console::FG_RED); - $this->stdout(" extension version "); + $this->stdout(' extension version '); } $this->stdout($newVersions[$ext], Console::BOLD); $this->stdout(", last release was {$versions[$ext]}\n"); @@ -375,7 +374,7 @@ class ReleaseController extends Controller foreach ($what as $w) { if (strncmp('app-', $w, 4) === 0) { if (!empty($limit) && !in_array('app', $limit)) { - throw new Exception("Only the following types are allowed: ".implode(', ', $limit)."\n"); + throw new Exception('Only the following types are allowed: ' . implode(', ', $limit) . "\n"); } if (!is_dir($appPath = "{$this->basePath}/apps/" . substr($w, 4))) { throw new Exception("Application path does not exist: \"{$appPath}\"\n"); @@ -385,7 +384,7 @@ class ReleaseController extends Controller } } elseif ($w === 'framework') { if (!empty($limit) && !in_array('framework', $limit)) { - throw new Exception("Only the following types are allowed: ".implode(', ', $limit)."\n"); + throw new Exception('Only the following types are allowed: ' . implode(', ', $limit) . "\n"); } if (!is_dir($fwPath = "{$this->basePath}/framework")) { throw new Exception("Framework path does not exist: \"{$this->basePath}/framework\"\n"); @@ -395,7 +394,7 @@ class ReleaseController extends Controller } } else { if (!empty($limit) && !in_array('ext', $limit)) { - throw new Exception("Only the following types are allowed: ".implode(', ', $limit)."\n"); + throw new Exception('Only the following types are allowed: ' . implode(', ', $limit) . "\n"); } if (!is_dir($extPath = "{$this->basePath}/extensions/$w")) { throw new Exception("Extension path for \"$w\" does not exist: \"{$this->basePath}/extensions/$w\"\n"); @@ -457,10 +456,10 @@ class ReleaseController extends Controller $this->stdout("\nIn the following you can check the above changes using git diff.\n\n"); do { - $this->runGit("git diff --color", $frameworkPath); + $this->runGit('git diff --color', $frameworkPath); $this->stdout("\n\n\nCheck whether the above diff is okay, if not you may change things as needed before continuing.\n"); $this->stdout("You may abort the program with Ctrl + C and reset the changes by running `git checkout -- .` in the repo.\n\n"); - } while (!$this->confirm("Type `yes` to continue, `no` to view git diff again. Continue?")); + } while (!$this->confirm('Type `yes` to continue, `no` to view git diff again. Continue?')); $this->stdout("\n\n"); $this->stdout(" **** RELEASE TIME! ****\n", Console::FG_YELLOW, Console::BOLD); @@ -471,13 +470,13 @@ class ReleaseController extends Controller $this->runGit("git commit -S -a -m \"release version $version\"", $frameworkPath); $this->runGit("git tag -s $version -m \"version $version\"", $frameworkPath); - $this->runGit("git push", $frameworkPath); - $this->runGit("git push --tags", $frameworkPath); + $this->runGit('git push', $frameworkPath); + $this->runGit('git push --tags', $frameworkPath); $this->stdout("\n\n"); - $this->stdout("CONGRATULATIONS! You have just released ", Console::FG_YELLOW, Console::BOLD); + $this->stdout('CONGRATULATIONS! You have just released ', Console::FG_YELLOW, Console::BOLD); $this->stdout('framework', Console::FG_RED, Console::BOLD); - $this->stdout(" version ", Console::FG_YELLOW, Console::BOLD); + $this->stdout(' version ', Console::FG_YELLOW, Console::BOLD); $this->stdout($version, Console::BOLD); $this->stdout("!\n\n", Console::FG_YELLOW, Console::BOLD); @@ -519,10 +518,10 @@ class ReleaseController extends Controller $this->stdout("\n"); - $this->runGit("git diff --color", $frameworkPath); + $this->runGit('git diff --color', $frameworkPath); $this->stdout("\n\n"); - $this->runGit("git commit -a -m \"prepare for next release\"", $frameworkPath); - $this->runGit("git push", $frameworkPath); + $this->runGit('git commit -a -m "prepare for next release"', $frameworkPath); + $this->runGit('git push', $frameworkPath); $this->stdout("\n\nDONE!", Console::FG_YELLOW, Console::BOLD); @@ -544,7 +543,6 @@ class ReleaseController extends Controller $this->stdout("- release applications: ./build/build release app-advanced\n"); $this->stdout("\n"); - } protected function releaseApplication($name, $path, $version) @@ -578,10 +576,10 @@ class ReleaseController extends Controller $this->stdout("\nIn the following you can check the above changes using git diff.\n\n"); do { - $this->runGit("git diff --color", $path); + $this->runGit('git diff --color', $path); $this->stdout("\n\n\nCheck whether the above diff is okay, if not you may change things as needed before continuing.\n"); $this->stdout("You may abort the program with Ctrl + C and reset the changes by running `git checkout -- .` in the repo.\n\n"); - } while (!$this->confirm("Type `yes` to continue, `no` to view git diff again. Continue?")); + } while (!$this->confirm('Type `yes` to continue, `no` to view git diff again. Continue?')); $this->stdout("\n\n"); $this->stdout(" **** RELEASE TIME! ****\n", Console::FG_YELLOW, Console::BOLD); @@ -592,13 +590,13 @@ class ReleaseController extends Controller $this->runGit("git commit -S -a -m \"release version $version\"", $path); $this->runGit("git tag -s $version -m \"version $version\"", $path); - $this->runGit("git push", $path); - $this->runGit("git push --tags", $path); + $this->runGit('git push', $path); + $this->runGit('git push --tags', $path); $this->stdout("\n\n"); - $this->stdout("CONGRATULATIONS! You have just released application ", Console::FG_YELLOW, Console::BOLD); + $this->stdout('CONGRATULATIONS! You have just released application ', Console::FG_YELLOW, Console::BOLD); $this->stdout($name, Console::FG_RED, Console::BOLD); - $this->stdout(" version ", Console::FG_YELLOW, Console::BOLD); + $this->stdout(' version ', Console::FG_YELLOW, Console::BOLD); $this->stdout($version, Console::BOLD); $this->stdout("!\n\n", Console::FG_YELLOW, Console::BOLD); @@ -613,10 +611,10 @@ class ReleaseController extends Controller $nextVersion = $this->getNextVersions(["app-$name" => $version], self::PATCH); // TODO support other versions $this->stdout("\n"); - $this->runGit("git diff --color", $path); + $this->runGit('git diff --color', $path); $this->stdout("\n\n"); - $this->runGit("git commit -a -m \"prepare for next release\"", $path); - $this->runGit("git push", $path); + $this->runGit('git commit -a -m "prepare for next release"', $path); + $this->runGit('git push', $path); $this->stdout("\n\nDONE!", Console::FG_YELLOW, Console::BOLD); @@ -696,10 +694,10 @@ class ReleaseController extends Controller $this->stdout("\nIn the following you can check the above changes using git diff.\n\n"); do { - $this->runGit("git diff --color", $path); + $this->runGit('git diff --color', $path); $this->stdout("\n\n\nCheck whether the above diff is okay, if not you may change things as needed before continuing.\n"); $this->stdout("You may abort the program with Ctrl + C and reset the changes by running `git checkout -- .` in the repo.\n\n"); - } while (!$this->confirm("Type `yes` to continue, `no` to view git diff again. Continue?")); + } while (!$this->confirm('Type `yes` to continue, `no` to view git diff again. Continue?')); $this->stdout("\n\n"); $this->stdout(" **** RELEASE TIME! ****\n", Console::FG_YELLOW, Console::BOLD); @@ -710,13 +708,13 @@ class ReleaseController extends Controller $this->runGit("git commit -S -a -m \"release version $version\"", $path); $this->runGit("git tag -s $version -m \"version $version\"", $path); - $this->runGit("git push", $path); - $this->runGit("git push --tags", $path); + $this->runGit('git push', $path); + $this->runGit('git push --tags', $path); $this->stdout("\n\n"); - $this->stdout("CONGRATULATIONS! You have just released extension ", Console::FG_YELLOW, Console::BOLD); + $this->stdout('CONGRATULATIONS! You have just released extension ', Console::FG_YELLOW, Console::BOLD); $this->stdout($name, Console::FG_RED, Console::BOLD); - $this->stdout(" version ", Console::FG_YELLOW, Console::BOLD); + $this->stdout(' version ', Console::FG_YELLOW, Console::BOLD); $this->stdout($version, Console::BOLD); $this->stdout("!\n\n", Console::FG_YELLOW, Console::BOLD); @@ -730,10 +728,10 @@ class ReleaseController extends Controller $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD); $this->stdout("\n"); - $this->runGit("git diff --color", $path); + $this->runGit('git diff --color', $path); $this->stdout("\n\n"); - $this->runGit("git commit -a -m \"prepare for next release\"", $path); - $this->runGit("git push", $path); + $this->runGit('git commit -a -m "prepare for next release"', $path); + $this->runGit('git push', $path); $this->stdout("\n\nDONE!", Console::FG_YELLOW, Console::BOLD); @@ -815,7 +813,7 @@ class ReleaseController extends Controller $v = str_replace('\\-', '[\\- ]', preg_quote($version, '/')); $headline = $version . ' ' . date('F d, Y'); $this->sed( - '/'.$v.' under development\n(-+?)\n/', + '/' . $v . ' under development\n(-+?)\n/', $headline . "\n" . str_repeat('-', strlen($headline)) . "\n", $this->getChangelogs($what) ); @@ -862,11 +860,11 @@ class ReleaseController extends Controller $state = 'start'; foreach ($lines as $l => $line) { // starting from the changelogs headline - if (isset($lines[$l-2]) && strpos($lines[$l-2], $version) !== false && - isset($lines[$l-1]) && strncmp($lines[$l-1], '---', 3) === 0) { + if (isset($lines[$l - 2]) && strpos($lines[$l - 2], $version) !== false && + isset($lines[$l - 1]) && strncmp($lines[$l - 1], '---', 3) === 0) { $state = 'changelog'; } - if ($state === 'changelog' && isset($lines[$l+1]) && strncmp($lines[$l+1], '---', 3) === 0) { + if ($state === 'changelog' && isset($lines[$l + 1]) && strncmp($lines[$l + 1], '---', 3) === 0) { $state = 'end'; } // add continued lines to the last item to keep them together @@ -892,7 +890,7 @@ class ReleaseController extends Controller $changelog = array_filter($changelog); $i = 0; - ArrayHelper::multisort($changelog, function($line) use (&$i) { + ArrayHelper::multisort($changelog, function ($line) use (&$i) { if (preg_match('/^- (Chg|Enh|Bug|New)( #\d+(, #\d+)*)?: .+/', $line, $m)) { $o = ['Bug' => 'C', 'Enh' => 'D', 'Chg' => 'E', 'New' => 'F']; return $o[$m[1]] . ' ' . (!empty($m[2]) ? $m[2] : 'AAAA' . $i++); @@ -925,7 +923,7 @@ class ReleaseController extends Controller protected function getExtensionChangelogs($what) { - return array_filter(glob($this->basePath . '/extensions/*/CHANGELOG.md'), function($elem) use ($what) { + return array_filter(glob($this->basePath . '/extensions/*/CHANGELOG.md'), function ($elem) use ($what) { foreach ($what as $ext) { if (strpos($elem, "extensions/$ext/CHANGELOG.md") !== false) { return true; diff --git a/build/controllers/TranslationController.php b/build/controllers/TranslationController.php index 433c842621..9adc9c9680 100644 --- a/build/controllers/TranslationController.php +++ b/build/controllers/TranslationController.php @@ -113,7 +113,7 @@ class TranslationController extends Controller protected function getDiff($translatedFilePath, $sourceFilePath) { $lastTranslationHash = shell_exec('git log -1 --format=format:"%H" -- ' . $translatedFilePath); - return shell_exec('git diff ' . $lastTranslationHash.'..HEAD -- ' . $sourceFilePath); + return shell_exec('git diff ' . $lastTranslationHash . '..HEAD -- ' . $sourceFilePath); } /** diff --git a/build/controllers/Utf8Controller.php b/build/controllers/Utf8Controller.php index 4cf3cbd347..76d4d1870f 100644 --- a/build/controllers/Utf8Controller.php +++ b/build/controllers/Utf8Controller.php @@ -40,14 +40,12 @@ class Utf8Controller extends Controller } foreach ($files as $file) { - $content = file_get_contents($file); $chars = preg_split('//u', $content, null, PREG_SPLIT_NO_EMPTY); $line = 1; $pos = 0; foreach ($chars as $c) { - $ord = $this->unicodeOrd($c); $pos++; @@ -57,7 +55,7 @@ class Utf8Controller extends Controller } if ($ord === false) { - $this->found("BROKEN UTF8", $c, $line, $pos, $file); + $this->found('BROKEN UTF8', $c, $line, $pos, $file); continue; } @@ -66,22 +64,20 @@ class Utf8Controller extends Controller || 0x2028 <= $ord && $ord <= 0x202E || 0x205f <= $ord && $ord <= 0x206F ) { - $this->found("UNSUPPORTED SPACE CHARACTER", $c, $line, $pos, $file); + $this->found('UNSUPPORTED SPACE CHARACTER', $c, $line, $pos, $file); continue; } if ($ord < 0x0020 && $ord != 0x000A && $ord != 0x0009 || 0x0080 <= $ord && $ord < 0x009F) { - $this->found("CONTROL CHARARCTER", $c, $line, $pos, $file); + $this->found('CONTROL CHARARCTER', $c, $line, $pos, $file); continue; } // if ($ord > 0x009F) { // $this->found("NON ASCII CHARARCTER", $c, $line, $pos, $file); // continue; // } - } } - } private $_foundFiles = []; @@ -95,7 +91,7 @@ class Utf8Controller extends Controller $hexcode = dechex($this->unicodeOrd($char)); $hexcode = str_repeat('0', max(4 - strlen($hexcode), 0)) . $hexcode; - + $this->stdout(" at $line:$pos FOUND $what: 0x$hexcode '$char' http://unicode-table.com/en/$hexcode/\n"); } @@ -109,20 +105,20 @@ class Utf8Controller extends Controller */ private function unicodeOrd($c) { - $h = ord($c{0}); + $h = ord($c[0]); if ($h <= 0x7F) { return $h; - } else if ($h < 0xC2) { + } elseif ($h < 0xC2) { return false; - } else if ($h <= 0xDF) { - return ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F); - } else if ($h <= 0xEF) { - return ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6 - | (ord($c{2}) & 0x3F); - } else if ($h <= 0xF4) { - return ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12 - | (ord($c{2}) & 0x3F) << 6 - | (ord($c{3}) & 0x3F); + } elseif ($h <= 0xDF) { + return ($h & 0x1F) << 6 | (ord($c[1]) & 0x3F); + } elseif ($h <= 0xEF) { + return ($h & 0x0F) << 12 | (ord($c[1]) & 0x3F) << 6 + | (ord($c[2]) & 0x3F); + } elseif ($h <= 0xF4) { + return ($h & 0x0F) << 18 | (ord($c[1]) & 0x3F) << 12 + | (ord($c[2]) & 0x3F) << 6 + | (ord($c[3]) & 0x3F); } else { return false; } diff --git a/composer.json b/composer.json index 775c8623bc..39f30b876b 100644 --- a/composer.json +++ b/composer.json @@ -82,7 +82,8 @@ }, "require-dev": { "phpunit/phpunit": "~4.4", - "cebe/indent": "~1.0.2" + "cebe/indent": "~1.0.2", + "friendsofphp/php-cs-fixer": "~2.2.3" }, "repositories": [ { @@ -95,7 +96,8 @@ }, "autoload": { "psr-4": { - "yii\\": "framework/" + "yii\\": "framework/", + "yii\\cs\\": "cs/src/" } }, "config": { diff --git a/composer.lock b/composer.lock index 5e7bbfa61a..e1bd146d27 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "content-hash": "d33a8eeb49ce13a2e319e70d8d4a2f67", + "content-hash": "e53ec45854ce009b7bc979db8ebc24cc", "packages": [ { "name": "bower-asset/jquery", @@ -334,6 +334,74 @@ "description": "a small tool to convert text file indentation", "time": "2014-05-23T14:40:08+00:00" }, + { + "name": "doctrine/annotations", + "version": "v1.2.7", + "source": { + "type": "git", + "url": "https://github.com/doctrine/annotations.git", + "reference": "f25c8aab83e0c3e976fd7d19875f198ccf2f7535" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/annotations/zipball/f25c8aab83e0c3e976fd7d19875f198ccf2f7535", + "reference": "f25c8aab83e0c3e976fd7d19875f198ccf2f7535", + "shasum": "" + }, + "require": { + "doctrine/lexer": "1.*", + "php": ">=5.3.2" + }, + "require-dev": { + "doctrine/cache": "1.*", + "phpunit/phpunit": "4.*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3.x-dev" + } + }, + "autoload": { + "psr-0": { + "Doctrine\\Common\\Annotations\\": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Jonathan Wage", + "email": "jonwage@gmail.com" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "description": "Docblock Annotations Parser", + "homepage": "http://www.doctrine-project.org", + "keywords": [ + "annotations", + "docblock", + "parser" + ], + "time": "2015-08-31T12:32:49+00:00" + }, { "name": "doctrine/instantiator", "version": "1.0.5", @@ -388,6 +456,227 @@ ], "time": "2015-06-14T21:17:01+00:00" }, + { + "name": "doctrine/lexer", + "version": "v1.0.1", + "source": { + "type": "git", + "url": "https://github.com/doctrine/lexer.git", + "reference": "83893c552fd2045dd78aef794c31e694c37c0b8c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/lexer/zipball/83893c552fd2045dd78aef794c31e694c37c0b8c", + "reference": "83893c552fd2045dd78aef794c31e694c37c0b8c", + "shasum": "" + }, + "require": { + "php": ">=5.3.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-0": { + "Doctrine\\Common\\Lexer\\": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "description": "Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers.", + "homepage": "http://www.doctrine-project.org", + "keywords": [ + "lexer", + "parser" + ], + "time": "2014-09-09T13:34:57+00:00" + }, + { + "name": "friendsofphp/php-cs-fixer", + "version": "v2.2.3", + "source": { + "type": "git", + "url": "https://github.com/FriendsOfPHP/PHP-CS-Fixer.git", + "reference": "8f33cf3da0da94b67b9cd696b2b9dda81c928f72" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/FriendsOfPHP/PHP-CS-Fixer/zipball/8f33cf3da0da94b67b9cd696b2b9dda81c928f72", + "reference": "8f33cf3da0da94b67b9cd696b2b9dda81c928f72", + "shasum": "" + }, + "require": { + "doctrine/annotations": "^1.2", + "ext-tokenizer": "*", + "php": "^5.3.6 || >=7.0 <7.2", + "sebastian/diff": "^1.4", + "symfony/console": "^2.4 || ^3.0", + "symfony/event-dispatcher": "^2.1 || ^3.0", + "symfony/filesystem": "^2.4 || ^3.0", + "symfony/finder": "^2.2 || ^3.0", + "symfony/options-resolver": "^2.6 || ^3.0", + "symfony/polyfill-php54": "^1.0", + "symfony/polyfill-php55": "^1.3", + "symfony/polyfill-php70": "^1.0", + "symfony/polyfill-xml": "^1.3", + "symfony/process": "^2.3 || ^3.0", + "symfony/stopwatch": "^2.5 || ^3.0" + }, + "conflict": { + "hhvm": "<3.18" + }, + "require-dev": { + "gecko-packages/gecko-php-unit": "^2.0", + "justinrainbow/json-schema": "^5.0", + "phpunit/phpunit": "^4.5 || ^5.0", + "satooshi/php-coveralls": "^1.0", + "symfony/phpunit-bridge": "^3.2.2" + }, + "suggest": { + "ext-mbstring": "For handling non-UTF8 characters in cache signature.", + "ext-xml": "For better performance.", + "symfony/polyfill-mbstring": "When enabling `ext-mbstring` is not possible." + }, + "bin": [ + "php-cs-fixer" + ], + "type": "application", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev" + } + }, + "autoload": { + "psr-4": { + "PhpCsFixer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Dariusz Rumiński", + "email": "dariusz.ruminski@gmail.com" + }, + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + } + ], + "description": "A tool to automatically fix PHP code style", + "time": "2017-04-25T20:39:28+00:00" + }, + { + "name": "ircmaxell/password-compat", + "version": "v1.0.4", + "source": { + "type": "git", + "url": "https://github.com/ircmaxell/password_compat.git", + "reference": "5c5cde8822a69545767f7c7f3058cb15ff84614c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ircmaxell/password_compat/zipball/5c5cde8822a69545767f7c7f3058cb15ff84614c", + "reference": "5c5cde8822a69545767f7c7f3058cb15ff84614c", + "shasum": "" + }, + "require-dev": { + "phpunit/phpunit": "4.*" + }, + "type": "library", + "autoload": { + "files": [ + "lib/password.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Anthony Ferrara", + "email": "ircmaxell@php.net", + "homepage": "http://blog.ircmaxell.com" + } + ], + "description": "A compatibility library for the proposed simplified password hashing algorithm: https://wiki.php.net/rfc/password_hash", + "homepage": "https://github.com/ircmaxell/password_compat", + "keywords": [ + "hashing", + "password" + ], + "time": "2014-11-20T16:49:30+00:00" + }, + { + "name": "paragonie/random_compat", + "version": "v2.0.10", + "source": { + "type": "git", + "url": "https://github.com/paragonie/random_compat.git", + "reference": "634bae8e911eefa89c1abfbf1b66da679ac8f54d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/paragonie/random_compat/zipball/634bae8e911eefa89c1abfbf1b66da679ac8f54d", + "reference": "634bae8e911eefa89c1abfbf1b66da679ac8f54d", + "shasum": "" + }, + "require": { + "php": ">=5.2.0" + }, + "require-dev": { + "phpunit/phpunit": "4.*|5.*" + }, + "suggest": { + "ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes." + }, + "type": "library", + "autoload": { + "files": [ + "lib/random.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Paragon Initiative Enterprises", + "email": "security@paragonie.com", + "homepage": "https://paragonie.com" + } + ], + "description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7", + "keywords": [ + "csprng", + "pseudorandom", + "random" + ], + "time": "2017-03-13T16:27:32+00:00" + }, { "name": "phpdocumentor/reflection-docblock", "version": "2.0.4", @@ -871,6 +1160,53 @@ ], "time": "2015-10-02T06:51:40+00:00" }, + { + "name": "psr/log", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/4ebe3a8bf773a19edfe0a84b6585ba3d401b724d", + "reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "Psr/Log/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "time": "2016-10-10T12:19:37+00:00" + }, { "name": "sebastian/comparator", "version": "1.2.2", @@ -1243,6 +1579,724 @@ "homepage": "https://github.com/sebastianbergmann/version", "time": "2015-06-21T13:59:46+00:00" }, + { + "name": "symfony/console", + "version": "v2.8.20", + "source": { + "type": "git", + "url": "https://github.com/symfony/console.git", + "reference": "2cfcbced8e39e2313ed4da8896fc8c59a56c0d7e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/console/zipball/2cfcbced8e39e2313ed4da8896fc8c59a56c0d7e", + "reference": "2cfcbced8e39e2313ed4da8896fc8c59a56c0d7e", + "shasum": "" + }, + "require": { + "php": ">=5.3.9", + "symfony/debug": "^2.7.2|~3.0.0", + "symfony/polyfill-mbstring": "~1.0" + }, + "require-dev": { + "psr/log": "~1.0", + "symfony/event-dispatcher": "~2.1|~3.0.0", + "symfony/process": "~2.1|~3.0.0" + }, + "suggest": { + "psr/log": "For using the console logger", + "symfony/event-dispatcher": "", + "symfony/process": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Console\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Console Component", + "homepage": "https://symfony.com", + "time": "2017-04-26T01:38:53+00:00" + }, + { + "name": "symfony/debug", + "version": "v2.8.20", + "source": { + "type": "git", + "url": "https://github.com/symfony/debug.git", + "reference": "344f50ce827413b3640bfcb1e37386a67d06ea1f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/debug/zipball/344f50ce827413b3640bfcb1e37386a67d06ea1f", + "reference": "344f50ce827413b3640bfcb1e37386a67d06ea1f", + "shasum": "" + }, + "require": { + "php": ">=5.3.9", + "psr/log": "~1.0" + }, + "conflict": { + "symfony/http-kernel": ">=2.3,<2.3.24|~2.4.0|>=2.5,<2.5.9|>=2.6,<2.6.2" + }, + "require-dev": { + "symfony/class-loader": "~2.2|~3.0.0", + "symfony/http-kernel": "~2.3.24|~2.5.9|^2.6.2|~3.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Debug\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Debug Component", + "homepage": "https://symfony.com", + "time": "2017-04-19T19:56:30+00:00" + }, + { + "name": "symfony/event-dispatcher", + "version": "v2.8.20", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher.git", + "reference": "7fc8e2b4118ff316550596357325dfd92a51f531" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/7fc8e2b4118ff316550596357325dfd92a51f531", + "reference": "7fc8e2b4118ff316550596357325dfd92a51f531", + "shasum": "" + }, + "require": { + "php": ">=5.3.9" + }, + "require-dev": { + "psr/log": "~1.0", + "symfony/config": "^2.0.5|~3.0.0", + "symfony/dependency-injection": "~2.6|~3.0.0", + "symfony/expression-language": "~2.6|~3.0.0", + "symfony/stopwatch": "~2.3|~3.0.0" + }, + "suggest": { + "symfony/dependency-injection": "", + "symfony/http-kernel": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\EventDispatcher\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony EventDispatcher Component", + "homepage": "https://symfony.com", + "time": "2017-04-26T16:56:54+00:00" + }, + { + "name": "symfony/filesystem", + "version": "v2.8.20", + "source": { + "type": "git", + "url": "https://github.com/symfony/filesystem.git", + "reference": "dc40154e26a0116995e4f2f0c71cb9c2fe0775a3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/dc40154e26a0116995e4f2f0c71cb9c2fe0775a3", + "reference": "dc40154e26a0116995e4f2f0c71cb9c2fe0775a3", + "shasum": "" + }, + "require": { + "php": ">=5.3.9" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Filesystem\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Filesystem Component", + "homepage": "https://symfony.com", + "time": "2017-04-12T14:07:15+00:00" + }, + { + "name": "symfony/finder", + "version": "v2.8.20", + "source": { + "type": "git", + "url": "https://github.com/symfony/finder.git", + "reference": "16d55394b31547e4a8494551b85c9b9915545347" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/finder/zipball/16d55394b31547e4a8494551b85c9b9915545347", + "reference": "16d55394b31547e4a8494551b85c9b9915545347", + "shasum": "" + }, + "require": { + "php": ">=5.3.9" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Finder\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Finder Component", + "homepage": "https://symfony.com", + "time": "2017-04-12T14:07:15+00:00" + }, + { + "name": "symfony/options-resolver", + "version": "v2.8.20", + "source": { + "type": "git", + "url": "https://github.com/symfony/options-resolver.git", + "reference": "55bf349a3395afad81a369d57b3b99c373fbbdf5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/options-resolver/zipball/55bf349a3395afad81a369d57b3b99c373fbbdf5", + "reference": "55bf349a3395afad81a369d57b3b99c373fbbdf5", + "shasum": "" + }, + "require": { + "php": ">=5.3.9" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\OptionsResolver\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony OptionsResolver Component", + "homepage": "https://symfony.com", + "keywords": [ + "config", + "configuration", + "options" + ], + "time": "2017-04-12T14:07:15+00:00" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "e79d363049d1c2128f133a2667e4f4190904f7f4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/e79d363049d1c2128f133a2667e4f4190904f7f4", + "reference": "e79d363049d1c2128f133a2667e4f4190904f7f4", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "time": "2016-11-14T01:06:16+00:00" + }, + { + "name": "symfony/polyfill-php54", + "version": "v1.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php54.git", + "reference": "90e085822963fdcc9d1c5b73deb3d2e5783b16a0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php54/zipball/90e085822963fdcc9d1c5b73deb3d2e5783b16a0", + "reference": "90e085822963fdcc9d1c5b73deb3d2e5783b16a0", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Php54\\": "" + }, + "files": [ + "bootstrap.php" + ], + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 5.4+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "time": "2016-11-14T01:06:16+00:00" + }, + { + "name": "symfony/polyfill-php55", + "version": "v1.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php55.git", + "reference": "03e3f0350bca2220e3623a0e340eef194405fc67" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php55/zipball/03e3f0350bca2220e3623a0e340eef194405fc67", + "reference": "03e3f0350bca2220e3623a0e340eef194405fc67", + "shasum": "" + }, + "require": { + "ircmaxell/password-compat": "~1.0", + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Php55\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 5.5+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "time": "2016-11-14T01:06:16+00:00" + }, + { + "name": "symfony/polyfill-php70", + "version": "v1.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php70.git", + "reference": "13ce343935f0f91ca89605a2f6ca6f5c2f3faac2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php70/zipball/13ce343935f0f91ca89605a2f6ca6f5c2f3faac2", + "reference": "13ce343935f0f91ca89605a2f6ca6f5c2f3faac2", + "shasum": "" + }, + "require": { + "paragonie/random_compat": "~1.0|~2.0", + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Php70\\": "" + }, + "files": [ + "bootstrap.php" + ], + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 7.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "time": "2016-11-14T01:06:16+00:00" + }, + { + "name": "symfony/polyfill-xml", + "version": "v1.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-xml.git", + "reference": "64b6a864f18ab4fddad49f5025f805f6781dfabd" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-xml/zipball/64b6a864f18ab4fddad49f5025f805f6781dfabd", + "reference": "64b6a864f18ab4fddad49f5025f805f6781dfabd", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "ext-xml": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Xml\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for xml's utf8_encode and utf8_decode functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "time": "2016-11-14T01:06:16+00:00" + }, + { + "name": "symfony/process", + "version": "v2.8.20", + "source": { + "type": "git", + "url": "https://github.com/symfony/process.git", + "reference": "aff35fb3dee799c84a7313c576b72208b046ef8d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/process/zipball/aff35fb3dee799c84a7313c576b72208b046ef8d", + "reference": "aff35fb3dee799c84a7313c576b72208b046ef8d", + "shasum": "" + }, + "require": { + "php": ">=5.3.9" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Process\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Process Component", + "homepage": "https://symfony.com", + "time": "2017-04-12T14:07:15+00:00" + }, + { + "name": "symfony/stopwatch", + "version": "v2.8.20", + "source": { + "type": "git", + "url": "https://github.com/symfony/stopwatch.git", + "reference": "e02577b841394a78306d7b547701bb7bb705bad5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/stopwatch/zipball/e02577b841394a78306d7b547701bb7bb705bad5", + "reference": "e02577b841394a78306d7b547701bb7bb705bad5", + "shasum": "" + }, + "require": { + "php": ">=5.3.9" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Stopwatch\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Stopwatch Component", + "homepage": "https://symfony.com", + "time": "2017-04-12T14:07:15+00:00" + }, { "name": "symfony/yaml", "version": "v2.8.16", diff --git a/cs/TODO.md b/cs/TODO.md new file mode 100644 index 0000000000..7986205709 --- /dev/null +++ b/cs/TODO.md @@ -0,0 +1 @@ +This should be moved to separate package, like `yii\yii2-cs`. diff --git a/cs/src/YiiConfig.php b/cs/src/YiiConfig.php new file mode 100644 index 0000000000..477780589a --- /dev/null +++ b/cs/src/YiiConfig.php @@ -0,0 +1,174 @@ + + * @since 2.0.0 + */ +class YiiConfig extends Config +{ + /** + * {@inheritdoc} + */ + public function __construct($name = 'yii-cs-config') + { + parent::__construct($name); + + $this->setRiskyAllowed(true); + + $this->setRules([ + '@PSR2' => true, + 'array_syntax' => [ + 'syntax' => 'short', + ], + 'binary_operator_spaces' => [ + 'align_double_arrow' => false, + 'align_equals' => false, + ], + 'blank_line_after_opening_tag' => true, + 'cast_spaces' => true, + 'concat_space' => [ + 'spacing' => 'one', + ], + 'dir_constant' => true, + 'ereg_to_preg' => true, + 'function_typehint_space' => true, + 'hash_to_slash_comment' => true, +// 'heredoc_to_nowdoc' => true, // needs more discussion +// 'include' => true, // needs more discussion + 'is_null' => [ + 'use_yoda_style' => false, + ], + 'linebreak_after_opening_tag' => true, + 'lowercase_cast' => true, + 'magic_constant_casing' => true, +// 'mb_str_functions' => true, // needs more discussion +// 'method_separation' => true, // conflicts with current Yii style with double line between properties and methods + 'modernize_types_casting' => true, + 'native_function_casing' => true, + 'new_with_braces' => true, + 'no_alias_functions' => true, + 'no_blank_lines_after_class_opening' => true, + 'no_blank_lines_after_phpdoc' => true, + 'no_empty_comment' => true, + 'no_empty_phpdoc' => true, + 'no_empty_statement' => true, + 'no_extra_consecutive_blank_lines' => [ + 'tokens' => [ + 'break', + 'continue', +// 'extra', // conflicts with current Yii style with double line between properties and methods + 'return', + 'throw', + 'use', + 'use_trait', +// 'curly_brace_block', // breaks namespaces blocks + 'parenthesis_brace_block', + 'square_brace_block', + ], + ], + 'no_leading_import_slash' => true, + 'no_leading_namespace_whitespace' => true, + 'no_mixed_echo_print' => true, + 'no_multiline_whitespace_around_double_arrow' => true, + 'no_multiline_whitespace_before_semicolons' => true, + 'no_php4_constructor' => true, + 'no_short_bool_cast' => true, + 'no_singleline_whitespace_before_semicolons' => true, + 'no_spaces_around_offset' => true, + 'no_trailing_comma_in_list_call' => true, + 'no_trailing_comma_in_singleline_array' => true, + 'no_unneeded_control_parentheses' => true, + 'no_unused_imports' => true, +// 'no_useless_else' => true, // needs more discussion + 'no_useless_return' => true, + 'no_whitespace_before_comma_in_array' => true, + 'no_whitespace_in_blank_line' => true, +// 'non_printable_character' => true, // breaks Formatter::asCurrency() tests + 'normalize_index_brace' => true, + 'object_operator_without_whitespace' => true, +// 'ordered_class_elements' => [ // needs more discussion +// 'order' => [ +// 'use_trait', +// 'constant_public', +// 'constant_protected', +// 'constant_private', +// 'property_public', +// 'property_protected', +// 'property_private', +// 'construct', +// 'destruct', +// 'magic', +// ], +// ], + 'ordered_imports' => [ + 'sortAlgorithm' => 'alpha', + 'importsOrder' => [ + 'const', + 'function', + 'class', + ], + ], + 'php_unit_construct' => true, + 'php_unit_dedicate_assert' => true, + 'php_unit_fqcn_annotation' => true, +// 'php_unit_strict' => true, // needs more attention +// 'phpdoc_add_missing_param_annotation' => [ // needs more attention +// 'only_untyped' => false, +// ], + 'phpdoc_indent' => true, +// 'phpdoc_inline_tag' => true, // see https://github.com/yiisoft/yii2/issues/11635 + 'phpdoc_no_access' => true, + 'phpdoc_no_empty_return' => true, + 'phpdoc_no_package' => true, + 'phpdoc_no_useless_inheritdoc' => true, +// 'phpdoc_order', // may be useful, but should be configurable: https://github.com/FriendsOfPHP/PHP-CS-Fixer/issues/1602 + 'phpdoc_return_self_reference' => true, + 'phpdoc_scalar' => true, + 'phpdoc_single_line_var_spacing' => true, +// 'phpdoc_summary' => true, // needs more attention (summary should be separated by blank line from description) +// 'phpdoc_to_comment' => true, // breaks phpdoc for define('CONSTANT', $value); + 'phpdoc_trim' => true, +// 'phpdoc_types' => true, // conflicts with yii\base\Object typehits https://github.com/yiisoft/yii2/pull/12699 + 'phpdoc_var_without_name' => true, + 'protected_to_private' => true, + 'psr4' => true, + 'self_accessor' => true, + 'short_scalar_cast' => true, + 'single_blank_line_before_namespace' => true, + 'single_quote' => true, + 'standardize_not_equals' => true, + 'ternary_operator_spaces' => true, + 'trailing_comma_in_multiline_array' => true, + 'trim_array_spaces' => true, + 'unary_operator_spaces' => true, + 'whitespace_after_comma_in_array' => true, + ]); + } + + /** + * Merge current rules config with provided list of rules. + * + * @param array $rules + * @return $this + * @see setRules() + * @see ArrayHelper::merge() + */ + public function mergeRules(array $rules) + { + $this->setRules(ArrayHelper::merge($this->getRules(), $rules)); + + return $this; + } +} diff --git a/cs/src/YiisoftConfig.php b/cs/src/YiisoftConfig.php new file mode 100644 index 0000000000..077c970185 --- /dev/null +++ b/cs/src/YiisoftConfig.php @@ -0,0 +1,39 @@ + + * @since 2.0.0 + */ +final class YiisoftConfig extends YiiConfig +{ + /** + * {@inheritdoc} + */ + public function __construct() + { + parent::__construct('yiisoft-cs-config'); + + $header = <<
    mergeRules([ + 'header_comment' => [ + 'header' => $header, + 'commentType' => 'PHPDoc', + 'separate' => 'bottom', + ], + ]); + } +} diff --git a/framework/BaseYii.php b/framework/BaseYii.php index e13c295588..7e586f0ef6 100644 --- a/framework/BaseYii.php +++ b/framework/BaseYii.php @@ -10,8 +10,8 @@ namespace yii; use yii\base\InvalidConfigException; use yii\base\InvalidParamException; use yii\base\UnknownClassException; -use yii\log\Logger; use yii\di\Container; +use yii\log\Logger; /** * Gets the application start timestamp. @@ -474,7 +474,7 @@ class BaseYii { return \Yii::t('yii', 'Powered by {yii}', [ 'yii' => '' . \Yii::t('yii', - 'Yii Framework') . '' + 'Yii Framework') . '', ]); } diff --git a/framework/Yii.php b/framework/Yii.php index 83cd8586d0..6b787a6ddf 100644 --- a/framework/Yii.php +++ b/framework/Yii.php @@ -1,7 +1,5 @@ state = self::STATE_BEFORE_REQUEST; $this->trigger(self::EVENT_BEFORE_REQUEST); @@ -388,12 +387,9 @@ abstract class Application extends Module $this->state = self::STATE_END; return $response->exitStatus; - } catch (ExitException $e) { - $this->end($e->statusCode, isset($response) ? $response : null); return $e->statusCode; - } } @@ -649,7 +645,7 @@ abstract class Application extends Module if ($this->state !== self::STATE_SENDING_RESPONSE && $this->state !== self::STATE_END) { $this->state = self::STATE_END; - $response = $response ? : $this->getResponse(); + $response = $response ?: $this->getResponse(); $response->send(); } diff --git a/framework/base/Component.php b/framework/base/Component.php index 21880846fc..3b2db8d2e5 100644 --- a/framework/base/Component.php +++ b/framework/base/Component.php @@ -533,7 +533,7 @@ class Component extends Object $this->ensureBehaviors(); if (!empty($this->_events[$name])) { if ($event === null) { - $event = new Event; + $event = new Event(); } if ($event->sender === null) { $event->sender = $this; diff --git a/framework/base/ErrorHandler.php b/framework/base/ErrorHandler.php index 69e196a43f..8b74d56859 100644 --- a/framework/base/ErrorHandler.php +++ b/framework/base/ErrorHandler.php @@ -133,7 +133,8 @@ abstract class ErrorHandler extends Component * @param \Exception $previousException Main exception processed in [[handleException()]]. * @since 2.0.11 */ - protected function handleFallbackExceptionMessage($exception, $previousException) { + protected function handleFallbackExceptionMessage($exception, $previousException) + { $msg = "An Error occurred while handling another error:\n"; $msg .= (string) $exception; $msg .= "\nPrevious exception:\n"; diff --git a/framework/base/Event.php b/framework/base/Event.php index 99dfe4993f..c7d61e2ad5 100644 --- a/framework/base/Event.php +++ b/framework/base/Event.php @@ -190,7 +190,7 @@ class Event extends Object return; } if ($event === null) { - $event = new static; + $event = new static(); } $event->handled = false; $event->name = $name; @@ -214,7 +214,7 @@ class Event extends Object if (empty(self::$_events[$name][$class])) { continue; } - + foreach (self::$_events[$name][$class] as $handler) { $event->data = $handler[1]; call_user_func($handler[0], $event); diff --git a/framework/base/Model.php b/framework/base/Model.php index 621fddcd79..202e36709e 100644 --- a/framework/base/Model.php +++ b/framework/base/Model.php @@ -7,12 +7,12 @@ namespace yii\base; -use Yii; use ArrayAccess; -use ArrayObject; use ArrayIterator; -use ReflectionClass; +use ArrayObject; use IteratorAggregate; +use ReflectionClass; +use Yii; use yii\helpers\Inflector; use yii\validators\RequiredValidator; use yii\validators\Validator; @@ -372,7 +372,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab */ public function beforeValidate() { - $event = new ModelEvent; + $event = new ModelEvent(); $this->trigger(self::EVENT_BEFORE_VALIDATE, $event); return $event->isValid; @@ -439,7 +439,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab */ public function createValidators() { - $validators = new ArrayObject; + $validators = new ArrayObject(); foreach ($this->rules() as $rule) { if ($rule instanceof Validator) { $validators->append($rule); diff --git a/framework/base/Module.php b/framework/base/Module.php index 9820202d70..923e94d67f 100644 --- a/framework/base/Module.php +++ b/framework/base/Module.php @@ -415,7 +415,7 @@ class Module extends ServiceLocator } if (isset($this->_modules[$id])) { - if ($this->_modules[$id] instanceof Module) { + if ($this->_modules[$id] instanceof self) { return $this->_modules[$id]; } elseif ($load) { Yii::trace("Loading module: $id", __METHOD__); @@ -461,7 +461,7 @@ class Module extends ServiceLocator if ($loadedOnly) { $modules = []; foreach ($this->_modules as $module) { - if ($module instanceof Module) { + if ($module instanceof self) { $modules[] = $module; } } @@ -567,7 +567,7 @@ class Module extends ServiceLocator } if (strpos($route, '/') !== false) { - list ($id, $route) = explode('/', $route, 2); + list($id, $route) = explode('/', $route, 2); } else { $id = $route; $route = ''; @@ -629,7 +629,7 @@ class Module extends ServiceLocator } $className = str_replace(' ', '', ucwords(str_replace('-', ' ', $className))) . 'Controller'; - $className = ltrim($this->controllerNamespace . '\\' . str_replace('/', '\\', $prefix) . $className, '\\'); + $className = ltrim($this->controllerNamespace . '\\' . str_replace('/', '\\', $prefix) . $className, '\\'); if (strpos($className, '-') !== false || !class_exists($className)) { return null; } @@ -638,7 +638,7 @@ class Module extends ServiceLocator $controller = Yii::createObject($className, [$id, $this]); return get_class($controller) === $className ? $controller : null; } elseif (YII_DEBUG) { - throw new InvalidConfigException("Controller class must extend from \\yii\\base\\Controller."); + throw new InvalidConfigException('Controller class must extend from \\yii\\base\\Controller.'); } return null; } diff --git a/framework/base/Security.php b/framework/base/Security.php index 6f0568107c..48eda8e5b1 100644 --- a/framework/base/Security.php +++ b/framework/base/Security.php @@ -7,8 +7,8 @@ namespace yii\base; -use yii\helpers\StringHelper; use Yii; +use yii\helpers\StringHelper; /** * Security provides a set of methods to handle common security-related tasks. @@ -610,7 +610,7 @@ class Security extends Component } if (function_exists('password_hash')) { - /** @noinspection PhpUndefinedConstantInspection */ + /* @noinspection PhpUndefinedConstantInspection */ return password_hash($password, PASSWORD_DEFAULT, ['cost' => $cost]); } @@ -680,7 +680,7 @@ class Security extends Component // Get a 20-byte random string $rand = $this->generateRandomKey(20); // Form the prefix that specifies Blowfish (bcrypt) algorithm and cost parameter. - $salt = sprintf("$2y$%02d$", $cost); + $salt = sprintf('$2y$%02d$', $cost); // Append the random salt data in the required base64 format. $salt .= str_replace('+', '.', substr(base64_encode($rand), 0, 22)); diff --git a/framework/base/Widget.php b/framework/base/Widget.php index b791391a11..2ae908de9e 100644 --- a/framework/base/Widget.php +++ b/framework/base/Widget.php @@ -7,8 +7,8 @@ namespace yii\base; -use Yii; use ReflectionClass; +use Yii; /** * Widget is the base class for widgets. diff --git a/framework/base/WidgetEvent.php b/framework/base/WidgetEvent.php index d8582adc86..6ec5ae8b28 100644 --- a/framework/base/WidgetEvent.php +++ b/framework/base/WidgetEvent.php @@ -22,7 +22,7 @@ class WidgetEvent extends Event */ public $result; /** - * @var boolean whether to continue running the widget. Event handlers of + * @var bool whether to continue running the widget. Event handlers of * [[Widget::EVENT_BEFORE_RUN]] may set this property to decide whether * to continue running the current widget. */ diff --git a/framework/behaviors/AttributeTypecastBehavior.php b/framework/behaviors/AttributeTypecastBehavior.php index 0090e74833..d664da8386 100644 --- a/framework/behaviors/AttributeTypecastBehavior.php +++ b/framework/behaviors/AttributeTypecastBehavior.php @@ -280,7 +280,7 @@ class AttributeTypecastBehavior extends Behavior } if ($type !== null) { - foreach ((array)$validator->attributes as $attribute) { + foreach ((array) $validator->attributes as $attribute) { $attributeTypes[$attribute] = $type; } } diff --git a/framework/behaviors/SluggableBehavior.php b/framework/behaviors/SluggableBehavior.php index 57d35e392a..7625584e81 100644 --- a/framework/behaviors/SluggableBehavior.php +++ b/framework/behaviors/SluggableBehavior.php @@ -7,12 +7,12 @@ namespace yii\behaviors; +use Yii; use yii\base\InvalidConfigException; use yii\db\BaseActiveRecord; use yii\helpers\ArrayHelper; use yii\helpers\Inflector; use yii\validators\UniqueValidator; -use Yii; /** * SluggableBehavior automatically fills the specified attribute with a value that can be used a slug in a URL. @@ -177,7 +177,7 @@ class SluggableBehavior extends AttributeBehavior return true; } - foreach ((array)$this->attribute as $attribute) { + foreach ((array) $this->attribute as $attribute) { if ($this->owner->isAttributeChanged($attribute)) { return true; } diff --git a/framework/caching/ArrayCache.php b/framework/caching/ArrayCache.php index 76fcb7af66..e7de9d40da 100644 --- a/framework/caching/ArrayCache.php +++ b/framework/caching/ArrayCache.php @@ -85,4 +85,4 @@ class ArrayCache extends Cache $this->_cache = []; return true; } -} \ No newline at end of file +} diff --git a/framework/caching/Cache.php b/framework/caching/Cache.php index e54c981e26..42e7139453 100644 --- a/framework/caching/Cache.php +++ b/framework/caching/Cache.php @@ -73,7 +73,7 @@ abstract class Cache extends Component implements CacheInterface */ public $serializer; /** - * @var integer default duration in seconds before a cache entry will expire. Default value is 0, meaning infinity. + * @var int default duration in seconds before a cache entry will expire. Default value is 0, meaning infinity. * This value is used by [[set()]] if the duration is not explicitly given. * @since 2.0.11 */ diff --git a/framework/caching/CacheInterface.php b/framework/caching/CacheInterface.php index ac35484dd0..426724044a 100644 --- a/framework/caching/CacheInterface.php +++ b/framework/caching/CacheInterface.php @@ -1,4 +1,9 @@ buildKey($key); - $query = new Query; + $query = new Query(); $query->select(['COUNT(*)']) ->from($this->cacheTable) ->where('[[id]] = :id AND ([[expire]] = 0 OR [[expire]] >' . time() . ')', [':id' => $key]); @@ -125,7 +125,7 @@ class DbCache extends Cache */ protected function getValue($key) { - $query = new Query; + $query = new Query(); $query->select(['data']) ->from($this->cacheTable) ->where('[[id]] = :id AND ([[expire]] = 0 OR [[expire]] >' . time() . ')', [':id' => $key]); @@ -150,7 +150,7 @@ class DbCache extends Cache if (empty($keys)) { return []; } - $query = new Query; + $query = new Query(); $query->select(['id', 'data']) ->from($this->cacheTable) ->where(['id' => $keys]) diff --git a/framework/caching/MemCache.php b/framework/caching/MemCache.php index 6e69b40e72..7a5dac1bdc 100644 --- a/framework/caching/MemCache.php +++ b/framework/caching/MemCache.php @@ -221,7 +221,7 @@ class MemCache extends Cache } if ($this->useMemcached) { - $this->_cache = $this->persistentId !== null ? new \Memcached($this->persistentId) : new \Memcached; + $this->_cache = $this->persistentId !== null ? new \Memcached($this->persistentId) : new \Memcached(); if ($this->username !== null || $this->password !== null) { $this->_cache->setOption(\Memcached::OPT_BINARY_PROTOCOL, true); $this->_cache->setSaslAuthData($this->username, $this->password); @@ -230,7 +230,7 @@ class MemCache extends Cache $this->_cache->setOptions($this->options); } } else { - $this->_cache = new \Memcache; + $this->_cache = new \Memcache(); } } diff --git a/framework/caching/migrations/m150909_153426_cache_init.php b/framework/caching/migrations/m150909_153426_cache_init.php index 4be6cbeaff..359390faf6 100644 --- a/framework/caching/migrations/m150909_153426_cache_init.php +++ b/framework/caching/migrations/m150909_153426_cache_init.php @@ -17,7 +17,6 @@ use yii\db\Migration; */ class m150909_153426_cache_init extends Migration { - /** * @throws yii\base\InvalidConfigException * @return DbCache diff --git a/framework/captcha/Captcha.php b/framework/captcha/Captcha.php index ba75f65ed3..b1cc6e4853 100644 --- a/framework/captcha/Captcha.php +++ b/framework/captcha/Captcha.php @@ -9,9 +9,9 @@ namespace yii\captcha; use Yii; use yii\base\InvalidConfigException; -use yii\helpers\Url; use yii\helpers\Html; use yii\helpers\Json; +use yii\helpers\Url; use yii\widgets\InputWidget; /** diff --git a/framework/console/Application.php b/framework/console/Application.php index ab096f5c1c..758aafe31d 100644 --- a/framework/console/Application.php +++ b/framework/console/Application.php @@ -142,7 +142,7 @@ class Application extends \yii\base\Application */ public function handleRequest($request) { - list ($route, $params) = $request->resolve(); + list($route, $params) = $request->resolve(); $this->requestedRoute = $route; $result = $this->runAction($route, $params); if ($result instanceof Response) { @@ -178,7 +178,7 @@ class Application extends \yii\base\Application { try { $res = parent::runAction($route, $params); - return is_object($res) ? $res : (int)$res; + return is_object($res) ? $res : (int) $res; } catch (InvalidRouteException $e) { throw new UnknownCommandException($route, $this, 0, $e); } diff --git a/framework/console/Controller.php b/framework/console/Controller.php index 7cd4999ac6..ad6ea6a9b2 100644 --- a/framework/console/Controller.php +++ b/framework/console/Controller.php @@ -351,7 +351,7 @@ class Controller extends \yii\base\Controller public function optionAliases() { return [ - 'h' => 'help' + 'h' => 'help', ]; } diff --git a/framework/console/ErrorHandler.php b/framework/console/ErrorHandler.php index cf62613a99..c73c5a96c4 100644 --- a/framework/console/ErrorHandler.php +++ b/framework/console/ErrorHandler.php @@ -34,7 +34,7 @@ class ErrorHandler extends \yii\base\ErrorHandler $message = $this->formatMessage($exception->getName() . ': ') . $exception->command; $alternatives = $exception->getSuggestedAlternatives(); if (count($alternatives) === 1) { - $message .= "\n\nDid you mean \"" . reset($alternatives) . "\"?"; + $message .= "\n\nDid you mean \"" . reset($alternatives) . '"?'; } elseif (count($alternatives) > 1) { $message .= "\n\nDid you mean one of these?\n - " . implode("\n - ", $alternatives); } diff --git a/framework/console/UnknownCommandException.php b/framework/console/UnknownCommandException.php index c8ad38c492..eeb9d755f3 100644 --- a/framework/console/UnknownCommandException.php +++ b/framework/console/UnknownCommandException.php @@ -124,14 +124,14 @@ class UnknownCommandException extends Exception } // calculate the Levenshtein distance between the unknown command and all available commands. - $distances = array_map(function($action) use ($command) { + $distances = array_map(function ($action) use ($command) { $action = strlen($action) > 255 ? substr($action, 0, 255) : $action; $command = strlen($command) > 255 ? substr($command, 0, 255) : $command; return levenshtein($action, $command); }, array_combine($actions, $actions)); // we assume a typo if the levensthein distance is no more than 3, i.e. 3 replacements needed - $relevantTypos = array_filter($distances, function($distance) { + $relevantTypos = array_filter($distances, function ($distance) { return $distance <= 3; }); asort($relevantTypos); diff --git a/framework/console/controllers/AssetController.php b/framework/console/controllers/AssetController.php index d16220ad2a..dc63c7c409 100644 --- a/framework/console/controllers/AssetController.php +++ b/framework/console/controllers/AssetController.php @@ -8,8 +8,8 @@ namespace yii\console\controllers; use Yii; -use yii\console\Exception; use yii\console\Controller; +use yii\console\Exception; use yii\helpers\Console; use yii\helpers\FileHelper; use yii\helpers\VarDumper; @@ -612,7 +612,7 @@ EOD; $inputFilePathPartsCount = count($inputFilePathParts); $outputFilePathParts = explode('/', $outputFilePath); $outputFilePathPartsCount = count($outputFilePathParts); - for ($i =0; $i < $inputFilePathPartsCount && $i < $outputFilePathPartsCount; $i++) { + for ($i = 0; $i < $inputFilePathPartsCount && $i < $outputFilePathPartsCount; $i++) { if ($inputFilePathParts[$i] == $outputFilePathParts[$i]) { $sharedPathParts[] = $inputFilePathParts[$i]; } else { @@ -766,7 +766,7 @@ EOD; */ private function isBundleExternal($bundle) { - return (empty($bundle->sourcePath) && empty($bundle->basePath)); + return empty($bundle->sourcePath) && empty($bundle->basePath); } /** diff --git a/framework/console/controllers/BaseMigrateController.php b/framework/console/controllers/BaseMigrateController.php index 5f79c00187..25fec0bccc 100644 --- a/framework/console/controllers/BaseMigrateController.php +++ b/framework/console/controllers/BaseMigrateController.php @@ -9,11 +9,10 @@ namespace yii\console\controllers; use Yii; use yii\base\InvalidConfigException; -use yii\console\Exception; use yii\console\Controller; +use yii\console\Exception; use yii\helpers\Console; use yii\helpers\FileHelper; -use yii\helpers\StringHelper; /** * BaseMigrateController is the base class for migrate controllers. @@ -113,7 +112,7 @@ abstract class BaseMigrateController extends Controller } if (is_array($this->migrationPath)) { - foreach($this->migrationPath as $i => $path) { + foreach ($this->migrationPath as $i => $path) { $this->migrationPath[$i] = Yii::getAlias($path); } } elseif ($this->migrationPath !== null) { @@ -181,7 +180,7 @@ abstract class BaseMigrateController extends Controller if ($this->confirm('Apply the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) { foreach ($migrations as $migration) { if (!$this->migrateUp($migration)) { - $this->stdout("\n$applied from $n " . ($applied === 1 ? 'migration was' : 'migrations were') ." applied.\n", Console::FG_RED); + $this->stdout("\n$applied from $n " . ($applied === 1 ? 'migration was' : 'migrations were') . " applied.\n", Console::FG_RED); $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED); return self::EXIT_CODE_ERROR; @@ -189,7 +188,7 @@ abstract class BaseMigrateController extends Controller $applied++; } - $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') ." applied.\n", Console::FG_GREEN); + $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " applied.\n", Console::FG_GREEN); $this->stdout("\nMigrated up successfully.\n", Console::FG_GREEN); } } @@ -242,14 +241,14 @@ abstract class BaseMigrateController extends Controller if ($this->confirm('Revert the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) { foreach ($migrations as $migration) { if (!$this->migrateDown($migration)) { - $this->stdout("\n$reverted from $n " . ($reverted === 1 ? 'migration was' : 'migrations were') ." reverted.\n", Console::FG_RED); + $this->stdout("\n$reverted from $n " . ($reverted === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_RED); $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED); return self::EXIT_CODE_ERROR; } $reverted++; } - $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') ." reverted.\n", Console::FG_GREEN); + $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_GREEN); $this->stdout("\nMigrated down successfully.\n", Console::FG_GREEN); } } @@ -315,7 +314,7 @@ abstract class BaseMigrateController extends Controller return self::EXIT_CODE_ERROR; } } - $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') ." redone.\n", Console::FG_GREEN); + $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " redone.\n", Console::FG_GREEN); $this->stdout("\nMigration redone successfully.\n", Console::FG_GREEN); } } @@ -735,7 +734,7 @@ abstract class BaseMigrateController extends Controller $class = trim($class, '\\'); if (strpos($class, '\\') === false) { if (is_array($this->migrationPath)) { - foreach($this->migrationPath as $path) { + foreach ($this->migrationPath as $path) { $file = $path . DIRECTORY_SEPARATOR . $class . '.php'; if (is_file($file)) { require_once($file); @@ -817,7 +816,7 @@ abstract class BaseMigrateController extends Controller $migrationPaths = []; if (is_array($this->migrationPath)) { - foreach($this->migrationPath as $path) { + foreach ($this->migrationPath as $path) { $migrationPaths[] = [$path, '']; } } elseif (!empty($this->migrationPath)) { diff --git a/framework/console/controllers/CacheController.php b/framework/console/controllers/CacheController.php index d5fc2b3e8d..31d5383a8b 100644 --- a/framework/console/controllers/CacheController.php +++ b/framework/console/controllers/CacheController.php @@ -11,8 +11,8 @@ use Yii; use yii\caching\ApcCache; use yii\caching\CacheInterface; use yii\console\Controller; -use yii\helpers\Console; use yii\console\Exception; +use yii\helpers\Console; /** * Allows you to flush cache. @@ -67,7 +67,6 @@ class CacheController extends Controller * # flushes caches specified by their id: "first", "second", "third" * yii cache/flush first second third * ``` - * */ public function actionFlush() { @@ -213,7 +212,6 @@ class CacheController extends Controller } /** - * * @param array $caches */ private function notifyFlushed($caches) @@ -221,7 +219,7 @@ class CacheController extends Controller $this->stdout("The following cache components were processed:\n\n", Console::FG_YELLOW); foreach ($caches as $cache) { - $this->stdout("\t* " . $cache['name'] .' (' . $cache['class'] . ')', Console::FG_GREEN); + $this->stdout("\t* " . $cache['name'] . ' (' . $cache['class'] . ')', Console::FG_GREEN); if (!$cache['is_flushed']) { $this->stdout(" - not flushed\n", Console::FG_RED); @@ -294,6 +292,6 @@ class CacheController extends Controller */ private function canBeFlushed($className) { - return !is_a($className, ApcCache::className(), true) || php_sapi_name() !== "cli"; + return !is_a($className, ApcCache::className(), true) || php_sapi_name() !== 'cli'; } } diff --git a/framework/console/controllers/FixtureController.php b/framework/console/controllers/FixtureController.php index 8355900fc6..9ebfee63b3 100644 --- a/framework/console/controllers/FixtureController.php +++ b/framework/console/controllers/FixtureController.php @@ -68,7 +68,7 @@ class FixtureController extends Controller public function options($actionID) { return array_merge(parent::options($actionID), [ - 'namespace', 'globalFixtures' + 'namespace', 'globalFixtures', ]); } @@ -135,8 +135,8 @@ class FixtureController extends Controller if (!$foundFixtures) { throw new Exception( - "No files were found for: \"" . implode(', ', $fixturesInput) . "\".\n" . - "Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . "\"." + 'No files were found for: "' . implode(', ', $fixturesInput) . "\".\n" . + "Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . '".' ); } @@ -205,8 +205,8 @@ class FixtureController extends Controller if (!$foundFixtures) { throw new Exception( - "No files were found for: \"" . implode(', ', $fixturesInput) . "\".\n" . - "Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . "\"." + 'No files were found for: "' . implode(', ', $fixturesInput) . "\".\n" . + "Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . '".' ); } @@ -433,7 +433,7 @@ class FixtureController extends Controller $fixturesPath = FileHelper::normalizePath($this->getFixturePath()); $fullFixturePath = FileHelper::normalizePath($fullFixturePath); - $relativeName = substr($fullFixturePath, strlen($fixturesPath)+1); + $relativeName = substr($fullFixturePath, strlen($fixturesPath) + 1); $relativeDir = dirname($relativeName) === '.' ? '' : dirname($relativeName) . DIRECTORY_SEPARATOR; return $relativeDir . basename($fullFixturePath, 'Fixture.php'); diff --git a/framework/console/controllers/HelpController.php b/framework/console/controllers/HelpController.php index 6e8f6fb58d..e6649df5fa 100644 --- a/framework/console/controllers/HelpController.php +++ b/framework/console/controllers/HelpController.php @@ -168,8 +168,6 @@ class HelpController extends Controller } $this->stdout("\n"); - - return; } /** @@ -372,14 +370,14 @@ class HelpController extends Controller $maxlen = 5; foreach ($actions as $action) { - $len = strlen($prefix.'/'.$action) + 2 + ($action === $controller->defaultAction ? 10 : 0); + $len = strlen($prefix . '/' . $action) + 2 + ($action === $controller->defaultAction ? 10 : 0); if ($maxlen < $len) { $maxlen = $len; } } foreach ($actions as $action) { - $this->stdout('- ' . $this->ansiFormat($prefix.'/'.$action, Console::FG_YELLOW)); - $len = strlen($prefix.'/'.$action) + 2; + $this->stdout('- ' . $this->ansiFormat($prefix . '/' . $action, Console::FG_YELLOW)); + $len = strlen($prefix . '/' . $action) + 2; if ($action === $controller->defaultAction) { $this->stdout(' (default)', Console::FG_GREEN); $len += 10; diff --git a/framework/console/controllers/MessageController.php b/framework/console/controllers/MessageController.php index 4cd436a2bc..74b9192182 100644 --- a/framework/console/controllers/MessageController.php +++ b/framework/console/controllers/MessageController.php @@ -363,13 +363,13 @@ EOD; protected function saveMessagesToDb($messages, $db, $sourceMessageTable, $messageTable, $removeUnused, $languages, $markUnused) { $currentMessages = []; - $rows = (new Query)->select(['id', 'category', 'message'])->from($sourceMessageTable)->all($db); + $rows = (new Query())->select(['id', 'category', 'message'])->from($sourceMessageTable)->all($db); foreach ($rows as $row) { $currentMessages[$row['category']][$row['id']] = $row['message']; } $currentLanguages = []; - $rows = (new Query)->select(['language'])->from($messageTable)->groupBy('language')->all($db); + $rows = (new Query())->select(['language'])->from($messageTable)->groupBy('language')->all($db); foreach ($rows as $row) { $currentLanguages[] = $row['language']; } @@ -422,7 +422,7 @@ EOD; if (!empty($missingLanguages)) { $updatedMessages = []; - $rows = (new Query)->select(['id', 'category', 'message'])->from($sourceMessageTable)->all($db); + $rows = (new Query())->select(['id', 'category', 'message'])->from($sourceMessageTable)->all($db); foreach ($rows as $row) { $updatedMessages[$row['category']][$row['id']] = $row['message']; } @@ -452,7 +452,7 @@ EOD; ->execute(); $this->stdout("deleted.\n"); } elseif ($markUnused) { - $rows = (new Query) + $rows = (new Query()) ->select(['id', 'message']) ->from($sourceMessageTable) ->where(['in', 'id', $obsolete]) @@ -482,7 +482,7 @@ EOD; */ protected function extractMessages($fileName, $translator, $ignoreCategories = []) { - $this->stdout("Extracting messages from "); + $this->stdout('Extracting messages from '); $this->stdout($fileName, Console::FG_CYAN); $this->stdout("...\n"); @@ -656,7 +656,7 @@ EOD; protected function saveMessagesToPHP($messages, $dirName, $overwrite, $removeUnused, $sort, $markUnused) { foreach ($messages as $category => $msgs) { - $file = str_replace("\\", '/', "$dirName/$category.php"); + $file = str_replace('\\', '/', "$dirName/$category.php"); $path = dirname($file); FileHelper::createDirectory($path); $msgs = array_values(array_unique($msgs)); @@ -777,7 +777,7 @@ EOD; */ protected function saveMessagesToPO($messages, $dirName, $overwrite, $removeUnused, $sort, $catalog, $markUnused) { - $file = str_replace("\\", '/', "$dirName/$catalog.po"); + $file = str_replace('\\', '/', "$dirName/$catalog.po"); FileHelper::createDirectory(dirname($file)); $this->stdout("Saving messages to $file...\n"); @@ -870,7 +870,7 @@ EOD; */ protected function saveMessagesToPOT($messages, $dirName, $catalog) { - $file = str_replace("\\", '/', "$dirName/$catalog.pot"); + $file = str_replace('\\', '/', "$dirName/$catalog.pot"); FileHelper::createDirectory(dirname($file)); $this->stdout("Saving messages to $file...\n"); diff --git a/framework/console/controllers/MigrateController.php b/framework/console/controllers/MigrateController.php index c6c9315295..c234e350d7 100644 --- a/framework/console/controllers/MigrateController.php +++ b/framework/console/controllers/MigrateController.php @@ -220,7 +220,7 @@ class MigrateController extends BaseMigrateController } else { $row['canonicalVersion'] = $row['version']; } - $row['apply_time'] = (int)$row['apply_time']; + $row['apply_time'] = (int) $row['apply_time']; $history[] = $row; } diff --git a/framework/data/ActiveDataProvider.php b/framework/data/ActiveDataProvider.php index c971a481a6..6fd1b4420c 100644 --- a/framework/data/ActiveDataProvider.php +++ b/framework/data/ActiveDataProvider.php @@ -7,9 +7,9 @@ namespace yii\data; -use yii\db\ActiveQueryInterface; use yii\base\InvalidConfigException; use yii\base\Model; +use yii\db\ActiveQueryInterface; use yii\db\Connection; use yii\db\QueryInterface; use yii\di\Instance; @@ -177,7 +177,7 @@ class ActiveDataProvider extends BaseDataProvider parent::setSort($value); if (($sort = $this->getSort()) !== false && $this->query instanceof ActiveQueryInterface) { /* @var $model Model */ - $model = new $this->query->modelClass; + $model = new $this->query->modelClass(); if (empty($sort->attributes)) { foreach ($model->attributes() as $attribute) { $sort->attributes[$attribute] = [ diff --git a/framework/data/SqlDataProvider.php b/framework/data/SqlDataProvider.php index 0b894d355e..a54bf5b47d 100644 --- a/framework/data/SqlDataProvider.php +++ b/framework/data/SqlDataProvider.php @@ -165,7 +165,7 @@ class SqlDataProvider extends BaseDataProvider { return (new Query([ 'from' => ['sub' => "({$this->sql})"], - 'params' => $this->params + 'params' => $this->params, ]))->count('*', $this->db); } } diff --git a/framework/db/ActiveQuery.php b/framework/db/ActiveQuery.php index d6dbb105ad..03f6ed28a9 100644 --- a/framework/db/ActiveQuery.php +++ b/framework/db/ActiveQuery.php @@ -315,7 +315,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface } if ($this->sql === null) { - list ($sql, $params) = $db->getQueryBuilder()->build($this); + list($sql, $params) = $db->getQueryBuilder()->build($this); } else { $sql = $this->sql; $params = $this->params; @@ -339,7 +339,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface return parent::queryScalar($selectExpression, $db); } - return (new Query)->select([$selectExpression]) + return (new Query())->select([$selectExpression]) ->from(['c' => "({$this->sql})"]) ->params($this->params) ->createCommand($db) @@ -412,7 +412,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface list(, $relation, $alias) = $matches; $name = $relation; $callback = function ($query) use ($callback, $alias) { - /** @var $query ActiveQuery */ + /* @var $query ActiveQuery */ $query->alias($alias); if ($callback !== null) { call_user_func($callback, $query); @@ -435,9 +435,9 @@ class ActiveQuery extends Query implements ActiveQueryInterface $join = $this->join; $this->join = []; - $model = new $this->modelClass; + $model = new $this->modelClass(); foreach ($this->joinWith as $config) { - list ($with, $eagerLoading, $joinType) = $config; + list($with, $eagerLoading, $joinType) = $config; $this->joinWithRelations($model, $with, $joinType); if (is_array($eagerLoading)) { @@ -515,7 +515,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface } else { $relation = $relations[$fullName]; } - $primaryModel = new $relation->modelClass; + $primaryModel = new $relation->modelClass(); $parent = $relation; $prefix = $fullName; $name = $childName; @@ -590,7 +590,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface { $via = $child->via; $child->via = null; - if ($via instanceof ActiveQuery) { + if ($via instanceof self) { // via table $this->joinWithRelation($parent, $via, $joinType); $this->joinWithRelation($via, $child, $joinType); @@ -602,11 +602,10 @@ class ActiveQuery extends Query implements ActiveQueryInterface return; } - list ($parentTable, $parentAlias) = $parent->getTableNameAndAlias(); - list ($childTable, $childAlias) = $child->getTableNameAndAlias(); + list($parentTable, $parentAlias) = $parent->getTableNameAndAlias(); + list($childTable, $childAlias) = $child->getTableNameAndAlias(); if (!empty($child->link)) { - if (strpos($parentAlias, '{{') === false) { $parentAlias = '{{' . $parentAlias . '}}'; } @@ -750,7 +749,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface */ public function viaTable($tableName, $link, callable $callable = null) { - $relation = new ActiveQuery(get_class($this->primaryModel), [ + $relation = new self(get_class($this->primaryModel), [ 'from' => [$tableName], 'link' => $link, 'multiple' => true, @@ -777,7 +776,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface public function alias($alias) { if (empty($this->from) || count($this->from) < 2) { - list($tableName, ) = $this->getTableNameAndAlias(); + list($tableName) = $this->getTableNameAndAlias(); $this->from = [$alias => $tableName]; } else { $tableName = $this->getPrimaryTableName(); diff --git a/framework/db/ActiveQueryTrait.php b/framework/db/ActiveQueryTrait.php index d4046a30d6..7880deac53 100644 --- a/framework/db/ActiveQueryTrait.php +++ b/framework/db/ActiveQueryTrait.php @@ -162,7 +162,7 @@ trait ActiveQueryTrait { $primaryModel = reset($models); if (!$primaryModel instanceof ActiveRecordInterface) { - $primaryModel = new $this->modelClass; + $primaryModel = new $this->modelClass(); } $relations = $this->normalizeRelations($primaryModel, $with); /* @var $relation ActiveQuery */ diff --git a/framework/db/ActiveRelationTrait.php b/framework/db/ActiveRelationTrait.php index 3a7ce71187..dfe3a55669 100644 --- a/framework/db/ActiveRelationTrait.php +++ b/framework/db/ActiveRelationTrait.php @@ -177,7 +177,7 @@ trait ActiveRelationTrait $relatedModel->populateRelation($this->inverseOf, $inverseRelation->multiple ? [$this->primaryModel] : $this->primaryModel); } else { if (!isset($inverseRelation)) { - $inverseRelation = (new $this->modelClass)->getRelation($this->inverseOf); + $inverseRelation = (new $this->modelClass())->getRelation($this->inverseOf); } $result[$i][$this->inverseOf] = $inverseRelation->multiple ? [$this->primaryModel] : $this->primaryModel; } @@ -298,7 +298,7 @@ trait ActiveRelationTrait } $model = reset($models); /* @var $relation ActiveQueryInterface|ActiveQuery */ - $relation = $model instanceof ActiveRecordInterface ? $model->getRelation($name) : (new $this->modelClass)->getRelation($name); + $relation = $model instanceof ActiveRecordInterface ? $model->getRelation($name) : (new $this->modelClass())->getRelation($name); if ($relation->multiple) { $buckets = $this->buildBuckets($primaryModels, $relation->link, null, null, false); diff --git a/framework/db/BaseActiveRecord.php b/framework/db/BaseActiveRecord.php index 05b95ab3c6..9dcb5a9c52 100644 --- a/framework/db/BaseActiveRecord.php +++ b/framework/db/BaseActiveRecord.php @@ -7,14 +7,14 @@ namespace yii\db; -use yii\base\InvalidConfigException; use yii\base\Event; -use yii\base\Model; +use yii\base\InvalidCallException; +use yii\base\InvalidConfigException; use yii\base\InvalidParamException; +use yii\base\Model; use yii\base\ModelEvent; use yii\base\NotSupportedException; use yii\base\UnknownMethodException; -use yii\base\InvalidCallException; use yii\helpers\ArrayHelper; /** @@ -934,7 +934,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface */ public function beforeSave($insert) { - $event = new ModelEvent; + $event = new ModelEvent(); $this->trigger($insert ? self::EVENT_BEFORE_INSERT : self::EVENT_BEFORE_UPDATE, $event); return $event->isValid; @@ -986,7 +986,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface */ public function beforeDelete() { - $event = new ModelEvent; + $event = new ModelEvent(); $this->trigger(self::EVENT_BEFORE_DELETE, $event); return $event->isValid; @@ -1160,7 +1160,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface */ public static function instantiate($row) { - return new static; + return new static(); } /** @@ -1566,7 +1566,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface } catch (InvalidParamException $e) { return $this->generateAttributeLabel($attribute); } - $relatedModel = new $relation->modelClass; + $relatedModel = new $relation->modelClass(); } } @@ -1606,7 +1606,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface } catch (InvalidParamException $e) { return ''; } - $relatedModel = new $relation->modelClass; + $relatedModel = new $relation->modelClass(); } } diff --git a/framework/db/ColumnSchema.php b/framework/db/ColumnSchema.php index b2d0f19c59..dbec75ed51 100644 --- a/framework/db/ColumnSchema.php +++ b/framework/db/ColumnSchema.php @@ -137,7 +137,7 @@ class ColumnSchema extends Object // https://github.com/yiisoft/yii2/issues/9006 return (bool) $value && $value !== "\0"; case 'double': - return (double) $value; + return (float) $value; } return $value; diff --git a/framework/db/Command.php b/framework/db/Command.php index 7c451de342..6034fa8c3d 100644 --- a/framework/db/Command.php +++ b/framework/db/Command.php @@ -267,7 +267,7 @@ class Command extends Component } else { $this->pdoStatement->bindParam($name, $value, $dataType, $length, $driverOptions); } - $this->params[$name] =& $value; + $this->params[$name] = &$value; return $this; } diff --git a/framework/db/Query.php b/framework/db/Query.php index a97b655669..832c21ec1d 100644 --- a/framework/db/Query.php +++ b/framework/db/Query.php @@ -123,7 +123,7 @@ class Query extends Component implements QueryInterface if ($db === null) { $db = Yii::$app->getDb(); } - list ($sql, $params) = $db->getQueryBuilder()->build($this); + list($sql, $params) = $db->getQueryBuilder()->build($this); return $db->createCommand($sql, $params); } @@ -432,7 +432,7 @@ class Query extends Component implements QueryInterface return $command->queryScalar(); } else { - return (new Query)->select([$selectExpression]) + return (new self())->select([$selectExpression]) ->from(['c' => $this]) ->createCommand($db) ->queryScalar(); diff --git a/framework/db/QueryBuilder.php b/framework/db/QueryBuilder.php index 992bb53d19..9e7cfd1f6f 100644 --- a/framework/db/QueryBuilder.php +++ b/framework/db/QueryBuilder.php @@ -225,7 +225,7 @@ class QueryBuilder extends \yii\base\Object foreach ($columns->select as $title => $field) { if (is_string($title)) { $names[] = $schema->quoteColumnName($title); - } else if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $field, $matches)) { + } elseif (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $field, $matches)) { $names[] = $schema->quoteColumnName($matches[2]); } else { $names[] = $schema->quoteColumnName($field); @@ -452,7 +452,7 @@ class QueryBuilder extends \yii\base\Object return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name) . ' PRIMARY KEY (' - . implode(', ', $columns). ' )'; + . implode(', ', $columns) . ' )'; } /** @@ -648,7 +648,6 @@ class QueryBuilder extends \yii\base\Object */ public function addCommentOnColumn($table, $column, $comment) { - return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . ' IS ' . $this->db->quoteValue($comment); } @@ -829,7 +828,7 @@ class QueryBuilder extends \yii\base\Object throw new Exception('A join clause must be specified as an array of join type, join table, and optionally join condition.'); } // 0:join type, 1:join table, 2:on-condition (optional) - list ($joinType, $table) = $join; + list($joinType, $table) = $join; $tables = $this->quoteTableNames((array) $table, $params); $table = reset($tables); $joins[$i] = "$joinType $table"; diff --git a/framework/db/QueryTrait.php b/framework/db/QueryTrait.php index 932d28c508..c5e1ecfae9 100644 --- a/framework/db/QueryTrait.php +++ b/framework/db/QueryTrait.php @@ -52,7 +52,7 @@ trait QueryTrait */ public $indexBy; /** - * @var boolean whether to emulate the actual query execution, returning empty or false results. + * @var bool whether to emulate the actual query execution, returning empty or false results. * @see emulateExecution() * @since 2.0.11 */ diff --git a/framework/db/Schema.php b/framework/db/Schema.php index 8b91241232..5c71af8dd7 100644 --- a/framework/db/Schema.php +++ b/framework/db/Schema.php @@ -8,9 +8,9 @@ namespace yii\db; use Yii; -use yii\base\Object; -use yii\base\NotSupportedException; use yii\base\InvalidCallException; +use yii\base\NotSupportedException; +use yii\base\Object; use yii\caching\CacheInterface; use yii\caching\TagDependency; @@ -511,7 +511,6 @@ abstract class Schema extends Object } return implode('.', $parts); - } /** @@ -631,7 +630,7 @@ abstract class Schema extends Object $exceptionClass = $class; } } - $message = $e->getMessage() . "\nThe SQL being executed was: $rawSql"; + $message = $e->getMessage() . "\nThe SQL being executed was: $rawSql"; $errorInfo = $e instanceof \PDOException ? $e->errorInfo : null; return new $exceptionClass($message, $errorInfo, (int) $e->getCode(), $e); } diff --git a/framework/db/SchemaBuilderTrait.php b/framework/db/SchemaBuilderTrait.php index 5b03c32666..e7ff966f3e 100644 --- a/framework/db/SchemaBuilderTrait.php +++ b/framework/db/SchemaBuilderTrait.php @@ -37,7 +37,7 @@ trait SchemaBuilderTrait /** * @return Connection the database connection to be used for schema building. */ - protected abstract function getDb(); + abstract protected function getDb(); /** * Creates a primary key column. diff --git a/framework/db/TableSchema.php b/framework/db/TableSchema.php index e13daabef8..e78e7be002 100644 --- a/framework/db/TableSchema.php +++ b/framework/db/TableSchema.php @@ -7,8 +7,8 @@ namespace yii\db; -use yii\base\Object; use yii\base\InvalidParamException; +use yii\base\Object; /** * TableSchema represents the metadata of a database table. diff --git a/framework/db/cubrid/Schema.php b/framework/db/cubrid/Schema.php index dfea42ebf1..39a9be2bac 100644 --- a/framework/db/cubrid/Schema.php +++ b/framework/db/cubrid/Schema.php @@ -7,9 +7,9 @@ namespace yii\db\cubrid; +use yii\db\ColumnSchema; use yii\db\Expression; use yii\db\TableSchema; -use yii\db\ColumnSchema; use yii\db\Transaction; /** diff --git a/framework/db/mssql/PDO.php b/framework/db/mssql/PDO.php index 6a776b227a..196eaf563b 100644 --- a/framework/db/mssql/PDO.php +++ b/framework/db/mssql/PDO.php @@ -76,7 +76,7 @@ class PDO extends \PDO return parent::getAttribute($attribute); } catch (\PDOException $e) { switch ($attribute) { - case PDO::ATTR_SERVER_VERSION: + case self::ATTR_SERVER_VERSION: return $this->query("SELECT CAST(SERVERPROPERTY('productversion') AS VARCHAR)")->fetchColumn(); default: throw $e; diff --git a/framework/db/mysql/Schema.php b/framework/db/mysql/Schema.php index 4ea23fab4f..b41ed37823 100644 --- a/framework/db/mysql/Schema.php +++ b/framework/db/mysql/Schema.php @@ -7,9 +7,9 @@ namespace yii\db\mysql; +use yii\db\ColumnSchema; use yii\db\Expression; use yii\db\TableSchema; -use yii\db\ColumnSchema; /** * Schema is the class for retrieving metadata from a MySQL database (version 4.1.x and 5.x). @@ -92,7 +92,7 @@ class Schema extends \yii\db\Schema */ protected function loadTableSchema($name) { - $table = new TableSchema; + $table = new TableSchema(); $this->resolveTableNames($table, $name); if ($this->findColumns($table)) { diff --git a/framework/db/oci/QueryBuilder.php b/framework/db/oci/QueryBuilder.php index 3a5c813081..d39696f5d3 100644 --- a/framework/db/oci/QueryBuilder.php +++ b/framework/db/oci/QueryBuilder.php @@ -386,5 +386,4 @@ EOD; return $this->buildCondition(['AND', $condition], $params); } - } diff --git a/framework/db/oci/Schema.php b/framework/db/oci/Schema.php index 28d2b2f96e..7ab9c4c40a 100644 --- a/framework/db/oci/Schema.php +++ b/framework/db/oci/Schema.php @@ -172,7 +172,6 @@ SQL; */ protected function getTableSequenceName($tableName) { - $sequenceNameSql = <<size = trim($length) === '' ? null : (int)$length; - $column->precision = trim($precision) === '' ? null : (int)$precision; - $column->scale = trim($scale) === '' ? null : (int)$scale; + $column->size = trim($length) === '' ? null : (int) $length; + $column->precision = trim($precision) === '' ? null : (int) $precision; + $column->scale = trim($scale) === '' ? null : (int) $scale; } /** @@ -488,7 +487,7 @@ SQL; if (!empty($returnColumns)) { $columnSchemas = $tableSchema->columns; $returning = []; - foreach ((array)$returnColumns as $name) { + foreach ((array) $returnColumns as $name) { $phName = QueryBuilder::PARAM_PREFIX . (count($params) + count($returnParams)); $returnParams[$phName] = [ 'column' => $name, diff --git a/framework/db/pgsql/Schema.php b/framework/db/pgsql/Schema.php index 4831198291..57f38f5b86 100644 --- a/framework/db/pgsql/Schema.php +++ b/framework/db/pgsql/Schema.php @@ -7,9 +7,9 @@ namespace yii\db\pgsql; +use yii\db\ColumnSchema; use yii\db\Expression; use yii\db\TableSchema; -use yii\db\ColumnSchema; use yii\db\ViewFinderTrait; /** @@ -434,7 +434,7 @@ SQL; if ($column->type === 'timestamp' && $column->defaultValue === 'now()') { $column->defaultValue = new Expression($column->defaultValue); } elseif ($column->type === 'boolean') { - $column->defaultValue = ($column->defaultValue === 'true'); + $column->defaultValue = ($column->defaultValue === 'true'); } elseif (stripos($column->dbType, 'bit') === 0 || stripos($column->dbType, 'varbit') === 0) { $column->defaultValue = bindec(trim($column->defaultValue, 'B\'')); } elseif (preg_match("/^'(.*?)'::/", $column->defaultValue, $matches)) { diff --git a/framework/db/sqlite/QueryBuilder.php b/framework/db/sqlite/QueryBuilder.php index 89b6bfbdd5..491aeacbc4 100644 --- a/framework/db/sqlite/QueryBuilder.php +++ b/framework/db/sqlite/QueryBuilder.php @@ -7,10 +7,9 @@ namespace yii\db\sqlite; -use yii\db\Connection; -use yii\db\Exception; use yii\base\InvalidParamException; use yii\base\NotSupportedException; +use yii\db\Connection; use yii\db\Expression; use yii\db\Query; @@ -166,7 +165,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; } /** diff --git a/framework/db/sqlite/Schema.php b/framework/db/sqlite/Schema.php index 1b58c339fe..bd8299a94e 100644 --- a/framework/db/sqlite/Schema.php +++ b/framework/db/sqlite/Schema.php @@ -8,9 +8,9 @@ namespace yii\db\sqlite; use yii\base\NotSupportedException; +use yii\db\ColumnSchema; use yii\db\Expression; use yii\db\TableSchema; -use yii\db\ColumnSchema; use yii\db\Transaction; /** @@ -119,7 +119,7 @@ class Schema extends \yii\db\Schema */ protected function loadTableSchema($name) { - $table = new TableSchema; + $table = new TableSchema(); $table->name = $name; $table->fullName = $name; diff --git a/framework/di/Container.php b/framework/di/Container.php index 7726c93efb..2346fd50ba 100644 --- a/framework/di/Container.php +++ b/framework/di/Container.php @@ -330,7 +330,7 @@ class Container extends Component if (strpos($class, '\\') !== false) { $definition['class'] = $class; } else { - throw new InvalidConfigException("A class definition requires a \"class\" member."); + throw new InvalidConfigException('A class definition requires a "class" member.'); } } return $definition; @@ -361,7 +361,7 @@ class Container extends Component protected function build($class, $params, $config) { /* @var $reflection ReflectionClass */ - list ($reflection, $dependencies) = $this->getDependencies($class); + list($reflection, $dependencies) = $this->getDependencies($class); foreach ($params as $index => $param) { $dependencies[$index] = $param; @@ -546,7 +546,6 @@ class Container extends Component throw $e; } } - } } elseif ($associative && isset($params[$name])) { $args[] = $params[$name]; diff --git a/framework/di/Instance.php b/framework/di/Instance.php index 2300cc4e94..6b0823b630 100644 --- a/framework/di/Instance.php +++ b/framework/di/Instance.php @@ -120,7 +120,7 @@ class Instance if ($type === null || $component instanceof $type) { return $component; } else { - throw new InvalidConfigException('Invalid data type: ' . $class .'. ' . $type . ' is expected.'); + throw new InvalidConfigException('Invalid data type: ' . $class . '. ' . $type . ' is expected.'); } } elseif (empty($reference)) { throw new InvalidConfigException('The required component is not specified.'); diff --git a/framework/di/NotInstantiableException.php b/framework/di/NotInstantiableException.php index 70898dd23e..e6f3e8187a 100644 --- a/framework/di/NotInstantiableException.php +++ b/framework/di/NotInstantiableException.php @@ -7,7 +7,7 @@ namespace yii\di; -use \yii\base\InvalidConfigException; +use yii\base\InvalidConfigException; /** * NotInstantiableException represents an exception caused by incorrect dependency injection container diff --git a/framework/di/ServiceLocator.php b/framework/di/ServiceLocator.php index 3bc8982ae4..6fd064aa56 100644 --- a/framework/di/ServiceLocator.php +++ b/framework/di/ServiceLocator.php @@ -7,8 +7,8 @@ namespace yii\di; -use Yii; use Closure; +use Yii; use yii\base\Component; use yii\base\InvalidConfigException; diff --git a/framework/filters/AccessControl.php b/framework/filters/AccessControl.php index c228d66b8f..eb02604266 100644 --- a/framework/filters/AccessControl.php +++ b/framework/filters/AccessControl.php @@ -11,8 +11,8 @@ use Yii; use yii\base\Action; use yii\base\ActionFilter; use yii\di\Instance; -use yii\web\User; use yii\web\ForbiddenHttpException; +use yii\web\User; /** * AccessControl provides simple access control based on a set of rules. diff --git a/framework/filters/AccessRule.php b/framework/filters/AccessRule.php index 513a7039f1..78b585eab7 100644 --- a/framework/filters/AccessRule.php +++ b/framework/filters/AccessRule.php @@ -8,12 +8,12 @@ namespace yii\filters; use Closure; -use yii\base\Component; use yii\base\Action; -use yii\base\InvalidConfigException; -use yii\web\User; -use yii\web\Request; +use yii\base\Component; use yii\base\Controller; +use yii\base\InvalidConfigException; +use yii\web\Request; +use yii\web\User; /** * This class represents an access rule defined by the [[AccessControl]] action filter diff --git a/framework/filters/ContentNegotiator.php b/framework/filters/ContentNegotiator.php index 86140bc149..987ad554aa 100644 --- a/framework/filters/ContentNegotiator.php +++ b/framework/filters/ContentNegotiator.php @@ -11,8 +11,8 @@ use Yii; use yii\base\ActionFilter; use yii\base\BootstrapInterface; use yii\base\InvalidConfigException; -use yii\web\Response; use yii\web\Request; +use yii\web\Response; use yii\web\UnsupportedMediaTypeHttpException; /** @@ -151,8 +151,8 @@ class ContentNegotiator extends ActionFilter implements BootstrapInterface */ public function negotiate() { - $request = $this->request ? : Yii::$app->getRequest(); - $response = $this->response ? : Yii::$app->getResponse(); + $request = $this->request ?: Yii::$app->getRequest(); + $response = $this->response ?: Yii::$app->getResponse(); if (!empty($this->formats)) { $this->negotiateContentType($request, $response); } diff --git a/framework/filters/Cors.php b/framework/filters/Cors.php index d374f89d67..ce7b25ea6a 100644 --- a/framework/filters/Cors.php +++ b/framework/filters/Cors.php @@ -196,7 +196,7 @@ class Cors extends ActionFilter if (in_array('*', $this->cors[$requestHeaderField])) { $responseHeaders[$responseHeaderField] = $this->headerize($requestHeaders[$requestHeaderField]); } else { - $requestedData = preg_split("/[\\s,]+/", $requestHeaders[$requestHeaderField], -1, PREG_SPLIT_NO_EMPTY); + $requestedData = preg_split('/[\\s,]+/', $requestHeaders[$requestHeaderField], -1, PREG_SPLIT_NO_EMPTY); $acceptedData = array_uintersect($requestedData, $this->cors[$requestHeaderField], 'strcasecmp'); if (!empty($acceptedData)) { $responseHeaders[$responseHeaderField] = implode(', ', $acceptedData); @@ -228,7 +228,7 @@ class Cors extends ActionFilter */ protected function headerize($string) { - $headers = preg_split("/[\\s,]+/", $string, -1, PREG_SPLIT_NO_EMPTY); + $headers = preg_split('/[\\s,]+/', $string, -1, PREG_SPLIT_NO_EMPTY); $headers = array_map(function ($element) { return str_replace(' ', '-', ucwords(strtolower(str_replace(['_', '-'], [' ', ' '], $element)))); }, $headers); diff --git a/framework/filters/HostControl.php b/framework/filters/HostControl.php index bbc9402e73..2d7a423f88 100644 --- a/framework/filters/HostControl.php +++ b/framework/filters/HostControl.php @@ -129,7 +129,7 @@ class HostControl extends ActionFilter } if (!is_array($allowedHosts) && !$allowedHosts instanceof \Traversable) { - $allowedHosts = (array)$allowedHosts; + $allowedHosts = (array) $allowedHosts; } $currentHost = Yii::$app->getRequest()->getHostName(); diff --git a/framework/filters/HttpCache.php b/framework/filters/HttpCache.php index 7732b204be..00f384ae24 100644 --- a/framework/filters/HttpCache.php +++ b/framework/filters/HttpCache.php @@ -8,8 +8,8 @@ namespace yii\filters; use Yii; -use yii\base\ActionFilter; use yii\base\Action; +use yii\base\ActionFilter; /** * HttpCache implements client-side caching by utilizing the `Last-Modified` and `ETag` HTTP headers. @@ -206,7 +206,7 @@ class HttpCache extends ActionFilter */ protected function generateEtag($seed) { - $etag = '"' . rtrim(base64_encode(sha1($seed, true)), '=') . '"'; + $etag = '"' . rtrim(base64_encode(sha1($seed, true)), '=') . '"'; return $this->weakEtag ? 'W/' . $etag : $etag; } } diff --git a/framework/filters/PageCache.php b/framework/filters/PageCache.php index 605e10ab63..cff555f741 100644 --- a/framework/filters/PageCache.php +++ b/framework/filters/PageCache.php @@ -249,7 +249,7 @@ class PageCache extends ActionFilter $data = [ 'cacheVersion' => 1, 'cacheData' => is_array($beforeCacheResponseResult) ? $beforeCacheResponseResult : null, - 'content' => ob_get_clean() + 'content' => ob_get_clean(), ]; if ($data['content'] === false || $data['content'] === '') { return; diff --git a/framework/filters/RateLimiter.php b/framework/filters/RateLimiter.php index 4feaff20b4..8e6f4fa6c2 100644 --- a/framework/filters/RateLimiter.php +++ b/framework/filters/RateLimiter.php @@ -108,8 +108,8 @@ class RateLimiter extends ActionFilter { $current = time(); - list ($limit, $window) = $user->getRateLimit($request, $action); - list ($allowance, $timestamp) = $user->loadAllowance($request, $action); + list($limit, $window) = $user->getRateLimit($request, $action); + list($allowance, $timestamp) = $user->loadAllowance($request, $action); $allowance += (int) (($current - $timestamp) * $limit / $window); if ($allowance > $limit) { diff --git a/framework/filters/auth/AuthInterface.php b/framework/filters/auth/AuthInterface.php index f12518cb3d..492d314ca3 100644 --- a/framework/filters/auth/AuthInterface.php +++ b/framework/filters/auth/AuthInterface.php @@ -7,11 +7,11 @@ namespace yii\filters\auth; -use yii\web\User; +use yii\web\IdentityInterface; use yii\web\Request; use yii\web\Response; -use yii\web\IdentityInterface; use yii\web\UnauthorizedHttpException; +use yii\web\User; /** * AuthInterface is the interface that should be implemented by auth method classes. diff --git a/framework/filters/auth/AuthMethod.php b/framework/filters/auth/AuthMethod.php index b13f02ef04..fe8f25c391 100644 --- a/framework/filters/auth/AuthMethod.php +++ b/framework/filters/auth/AuthMethod.php @@ -10,10 +10,10 @@ namespace yii\filters\auth; use Yii; use yii\base\Action; use yii\base\ActionFilter; -use yii\web\UnauthorizedHttpException; -use yii\web\User; use yii\web\Request; use yii\web\Response; +use yii\web\UnauthorizedHttpException; +use yii\web\User; /** * AuthMethod is a base class implementing the [[AuthInterface]] interface. @@ -51,12 +51,12 @@ abstract class AuthMethod extends ActionFilter implements AuthInterface */ public function beforeAction($action) { - $response = $this->response ? : Yii::$app->getResponse(); + $response = $this->response ?: Yii::$app->getResponse(); try { $identity = $this->authenticate( - $this->user ? : Yii::$app->getUser(), - $this->request ? : Yii::$app->getRequest(), + $this->user ?: Yii::$app->getUser(), + $this->request ?: Yii::$app->getRequest(), $response ); } catch (UnauthorizedHttpException $e) { diff --git a/framework/filters/auth/CompositeAuth.php b/framework/filters/auth/CompositeAuth.php index 0465723bd8..3a532a4efb 100644 --- a/framework/filters/auth/CompositeAuth.php +++ b/framework/filters/auth/CompositeAuth.php @@ -85,7 +85,7 @@ class CompositeAuth extends AuthMethod public function challenge($response) { foreach ($this->authMethods as $method) { - /** @var $method AuthInterface */ + /* @var $method AuthInterface */ $method->challenge($response); } } diff --git a/framework/grid/DataColumn.php b/framework/grid/DataColumn.php index f3749e2348..1466dbc8db 100644 --- a/framework/grid/DataColumn.php +++ b/framework/grid/DataColumn.php @@ -144,11 +144,11 @@ class DataColumn extends Column if ($this->label === null) { if ($provider instanceof ActiveDataProvider && $provider->query instanceof ActiveQueryInterface) { /* @var $model Model */ - $model = new $provider->query->modelClass; + $model = new $provider->query->modelClass(); $label = $model->getAttributeLabel($this->attribute); } elseif ($provider instanceof ArrayDataProvider && $provider->modelClass !== null) { /* @var $model Model */ - $model = new $provider->modelClass; + $model = new $provider->modelClass(); $label = $model->getAttributeLabel($this->attribute); } elseif ($this->grid->filterModel !== null && $this->grid->filterModel instanceof Model) { $label = $this->grid->filterModel->getAttributeLabel($this->attribute); diff --git a/framework/grid/GridView.php b/framework/grid/GridView.php index c6e0175157..3e9d47a1da 100644 --- a/framework/grid/GridView.php +++ b/framework/grid/GridView.php @@ -7,15 +7,15 @@ namespace yii\grid; -use Yii; use Closure; -use yii\i18n\Formatter; +use Yii; use yii\base\InvalidConfigException; -use yii\helpers\Url; +use yii\base\Model; use yii\helpers\Html; use yii\helpers\Json; +use yii\helpers\Url; +use yii\i18n\Formatter; use yii\widgets\BaseListView; -use yii\base\Model; /** * The GridView widget is used to display data in a grid. @@ -529,7 +529,7 @@ class GridView extends BaseListView $column = $this->createDataColumn($column); } else { $column = Yii::createObject(array_merge([ - 'class' => $this->dataColumnClass ? : DataColumn::className(), + 'class' => $this->dataColumnClass ?: DataColumn::className(), 'grid' => $this, ], $column)); } @@ -554,7 +554,7 @@ class GridView extends BaseListView } return Yii::createObject([ - 'class' => $this->dataColumnClass ? : DataColumn::className(), + 'class' => $this->dataColumnClass ?: DataColumn::className(), 'grid' => $this, 'attribute' => $matches[1], 'format' => isset($matches[3]) ? $matches[3] : 'text', diff --git a/framework/helpers/BaseArrayHelper.php b/framework/helpers/BaseArrayHelper.php index 6b5186b89b..54ee6c4eee 100644 --- a/framework/helpers/BaseArrayHelper.php +++ b/framework/helpers/BaseArrayHelper.php @@ -194,7 +194,7 @@ class BaseArrayHelper $key = $lastKey; } - if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array)) ) { + if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) { return $array[$key]; } @@ -380,7 +380,7 @@ class BaseArrayHelper public static function index($array, $key, $groups = []) { $result = []; - $groups = (array)$groups; + $groups = (array) $groups; foreach ($array as $element) { $lastArray = &$result; diff --git a/framework/helpers/BaseConsole.php b/framework/helpers/BaseConsole.php index b42678ed71..626a544d8d 100644 --- a/framework/helpers/BaseConsole.php +++ b/framework/helpers/BaseConsole.php @@ -20,36 +20,36 @@ use yii\console\Markdown as ConsoleMarkdown; class BaseConsole { // foreground color control codes - const FG_BLACK = 30; - const FG_RED = 31; - const FG_GREEN = 32; + const FG_BLACK = 30; + const FG_RED = 31; + const FG_GREEN = 32; const FG_YELLOW = 33; - const FG_BLUE = 34; + const FG_BLUE = 34; const FG_PURPLE = 35; - const FG_CYAN = 36; - const FG_GREY = 37; + const FG_CYAN = 36; + const FG_GREY = 37; // background color control codes - const BG_BLACK = 40; - const BG_RED = 41; - const BG_GREEN = 42; + const BG_BLACK = 40; + const BG_RED = 41; + const BG_GREEN = 42; const BG_YELLOW = 43; - const BG_BLUE = 44; + const BG_BLUE = 44; const BG_PURPLE = 45; - const BG_CYAN = 46; - const BG_GREY = 47; + const BG_CYAN = 46; + const BG_GREY = 47; // fonts style control codes - const RESET = 0; - const NORMAL = 0; - const BOLD = 1; - const ITALIC = 3; - const UNDERLINE = 4; - const BLINK = 5; - const NEGATIVE = 7; - const CONCEALED = 8; + const RESET = 0; + const NORMAL = 0; + const BOLD = 1; + const ITALIC = 3; + const UNDERLINE = 4; + const BLINK = 5; + const NEGATIVE = 7; + const CONCEALED = 8; const CROSSED_OUT = 9; - const FRAMED = 51; - const ENCIRCLED = 52; - const OVERLINED = 53; + const FRAMED = 51; + const ENCIRCLED = 52; + const OVERLINED = 53; /** @@ -357,31 +357,31 @@ class BaseConsole { $styleMap = [ // http://www.w3.org/TR/CSS2/syndata.html#value-def-color - self::FG_BLACK => ['color' => 'black'], - self::FG_BLUE => ['color' => 'blue'], - self::FG_CYAN => ['color' => 'aqua'], - self::FG_GREEN => ['color' => 'lime'], - self::FG_GREY => ['color' => 'silver'], + self::FG_BLACK => ['color' => 'black'], + self::FG_BLUE => ['color' => 'blue'], + self::FG_CYAN => ['color' => 'aqua'], + self::FG_GREEN => ['color' => 'lime'], + self::FG_GREY => ['color' => 'silver'], // http://meyerweb.com/eric/thoughts/2014/06/19/rebeccapurple/ // http://dev.w3.org/csswg/css-color/#valuedef-rebeccapurple - self::FG_PURPLE => ['color' => 'rebeccapurple'], - self::FG_RED => ['color' => 'red'], - self::FG_YELLOW => ['color' => 'yellow'], - self::BG_BLACK => ['background-color' => 'black'], - self::BG_BLUE => ['background-color' => 'blue'], - self::BG_CYAN => ['background-color' => 'aqua'], - self::BG_GREEN => ['background-color' => 'lime'], - self::BG_GREY => ['background-color' => 'silver'], - self::BG_PURPLE => ['background-color' => 'rebeccapurple'], - self::BG_RED => ['background-color' => 'red'], - self::BG_YELLOW => ['background-color' => 'yellow'], - self::BOLD => ['font-weight' => 'bold'], - self::ITALIC => ['font-style' => 'italic'], - self::UNDERLINE => ['text-decoration' => ['underline']], - self::OVERLINED => ['text-decoration' => ['overline']], + self::FG_PURPLE => ['color' => 'rebeccapurple'], + self::FG_RED => ['color' => 'red'], + self::FG_YELLOW => ['color' => 'yellow'], + self::BG_BLACK => ['background-color' => 'black'], + self::BG_BLUE => ['background-color' => 'blue'], + self::BG_CYAN => ['background-color' => 'aqua'], + self::BG_GREEN => ['background-color' => 'lime'], + self::BG_GREY => ['background-color' => 'silver'], + self::BG_PURPLE => ['background-color' => 'rebeccapurple'], + self::BG_RED => ['background-color' => 'red'], + self::BG_YELLOW => ['background-color' => 'yellow'], + self::BOLD => ['font-weight' => 'bold'], + self::ITALIC => ['font-style' => 'italic'], + self::UNDERLINE => ['text-decoration' => ['underline']], + self::OVERLINED => ['text-decoration' => ['overline']], self::CROSSED_OUT => ['text-decoration' => ['line-through']], - self::BLINK => ['text-decoration' => ['blink']], - self::CONCEALED => ['visibility' => 'hidden'], + self::BLINK => ['text-decoration' => ['blink']], + self::CONCEALED => ['visibility' => 'hidden'], ] + $styleMap; $tags = 0; @@ -561,7 +561,6 @@ class BaseConsole * * @param string $string String to escape * - * @access public * @return string */ public static function escape($string) @@ -624,12 +623,12 @@ class BaseConsole // Linux stty output if (preg_match('/rows\s+(\d+);\s*columns\s+(\d+);/mi', $stty, $matches)) { - return $size = [(int)$matches[2], (int)$matches[1]]; + return $size = [(int) $matches[2], (int) $matches[1]]; } // MacOS stty output if (preg_match('/(\d+)\s+rows;\s*(\d+)\s+columns;/mi', $stty, $matches)) { - return $size = [(int)$matches[2], (int)$matches[1]]; + return $size = [(int) $matches[2], (int) $matches[1]]; } } @@ -777,15 +776,15 @@ class BaseConsole { $options = ArrayHelper::merge( [ - 'required' => false, - 'default' => null, - 'pattern' => null, + 'required' => false, + 'default' => null, + 'pattern' => null, 'validator' => null, - 'error' => 'Invalid input.', + 'error' => 'Invalid input.', ], $options ); - $error = null; + $error = null; top: $input = $options['default'] diff --git a/framework/helpers/BaseFormatConverter.php b/framework/helpers/BaseFormatConverter.php index 0c1a6ca879..32f1664f4c 100644 --- a/framework/helpers/BaseFormatConverter.php +++ b/framework/helpers/BaseFormatConverter.php @@ -75,10 +75,10 @@ class BaseFormatConverter ]; private static $_icuShortFormats = [ - 'short' => 3, // IntlDateFormatter::SHORT, + 'short' => 3, // IntlDateFormatter::SHORT, 'medium' => 2, // IntlDateFormatter::MEDIUM, - 'long' => 1, // IntlDateFormatter::LONG, - 'full' => 0, // IntlDateFormatter::FULL, + 'long' => 1, // IntlDateFormatter::LONG, + 'full' => 0, // IntlDateFormatter::FULL, ]; @@ -125,19 +125,19 @@ class BaseFormatConverter if (preg_match_all('/(? '\\\'', // two single quotes produce one - 'G' => '', // era designator like (Anno Domini) + 'G' => '', // era designator like (Anno Domini) 'Y' => 'o', // 4digit year of "Week of Year" 'y' => 'Y', // 4digit year e.g. 2014 'yyyy' => 'Y', // 4digit year e.g. 2014 'yy' => 'y', // 2digit year number eg. 14 'u' => '', // extended year e.g. 4601 'U' => '', // cyclic year name, as in Chinese lunar calendar - 'r' => '', // related Gregorian year e.g. 1996 + 'r' => '', // related Gregorian year e.g. 1996 'Q' => '', // number of quarter 'QQ' => '', // number of quarter '02' 'QQQ' => '', // quarter 'Q2' @@ -152,7 +152,7 @@ class BaseFormatConverter 'MM' => 'm', // Numeric representation of a month, with leading zeros 'MMM' => 'M', // A short textual representation of a month, three letters 'MMMM' => 'F', // A full textual representation of a month, such as January or March - 'MMMMM' => '', // + 'MMMMM' => '', 'L' => 'n', // Stand alone month in year 'LL' => 'm', // Stand alone month in year 'LLL' => 'M', // Stand alone month in year @@ -205,7 +205,7 @@ class BaseFormatConverter 'z' => 'T', // Timezone abbreviation 'zz' => 'T', // Timezone abbreviation 'zzz' => 'T', // Timezone abbreviation - 'zzzz' => 'T', // Timzone full name, not supported by php but we fallback + 'zzzz' => 'T', // Timezone full name, not supported by php but we fallback 'Z' => 'O', // Difference to Greenwich time (GMT) in hours 'ZZ' => 'O', // Difference to Greenwich time (GMT) in hours 'ZZZ' => 'O', // Difference to Greenwich time (GMT) in hours @@ -225,8 +225,8 @@ class BaseFormatConverter 'XXXX' => '', // Time Zone: ISO8601 basic hms?, with Z, e.g. -0800, -075258, Z 'XXXXX' => '', // Time Zone: ISO8601 extended hms?, with Z, e.g. -08:00, -07:52:58, Z 'x' => '', // Time Zone: ISO8601 basic hm?, without Z for 0, e.g. -08, +0530 - 'xx' => 'O', // Time Zone: ISO8601 basic hm, without Z, e.g. -0800 - 'xxx' => 'P', // Time Zone: ISO8601 extended hm, without Z, e.g. -08:00 + 'xx' => 'O', // Time Zone: ISO8601 basic hm, without Z, e.g. -0800 + 'xxx' => 'P', // Time Zone: ISO8601 extended hm, without Z, e.g. -08:00 'xxxx' => '', // Time Zone: ISO8601 basic hms?, without Z, e.g. -0800, -075258 'xxxxx' => '', // Time Zone: ISO8601 extended hms?, without Z, e.g. -08:00, -07:52:58 ])); @@ -290,7 +290,7 @@ class BaseFormatConverter 'O' => 'xx', // Difference to Greenwich time (GMT) in hours, Example: +0200 'P' => 'xxx', // Difference to Greenwich time (GMT) with colon between hours and minutes, Example: +02:00 'T' => 'zzz', // Timezone abbreviation, Examples: EST, MDT ... - 'Z' => '', // Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 50400 + 'Z' => '', // Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 50400 // Full Date/Time 'c' => 'yyyy-MM-dd\'T\'HH:mm:ssxxx', // ISO 8601 date, e.g. 2004-02-12T15:19:21+00:00 'r' => 'eee, dd MMM yyyy HH:mm:ss xx', // RFC 2822 formatted date, Example: Thu, 21 Dec 2000 16:01:07 +0200 @@ -358,11 +358,11 @@ class BaseFormatConverter 'qqq' => '', // Stand Alone quarter 'Q2' 'qqqq' => '', // Stand Alone quarter '2nd quarter' 'qqqqq' => '', // number of Stand Alone quarter '2' - 'M' => 'm', // Numeric representation of a month, without leading zeros + 'M' => 'm', // Numeric representation of a month, without leading zeros 'MM' => 'mm', // Numeric representation of a month, with leading zeros 'MMM' => 'M', // A short textual representation of a month, three letters 'MMMM' => 'MM', // A full textual representation of a month, such as January or March - 'MMMMM' => '', // + 'MMMMM' => '', 'L' => 'm', // Stand alone month in year 'LL' => 'mm', // Stand alone month in year 'LLL' => 'M', // Stand alone month in year @@ -415,14 +415,14 @@ class BaseFormatConverter 'z' => '', // Timezone abbreviation 'zz' => '', // Timezone abbreviation 'zzz' => '', // Timezone abbreviation - 'zzzz' => '', // Timzone full name, not supported by php but we fallback + 'zzzz' => '', // Timezone full name, not supported by php but we fallback 'Z' => '', // Difference to Greenwich time (GMT) in hours 'ZZ' => '', // Difference to Greenwich time (GMT) in hours 'ZZZ' => '', // Difference to Greenwich time (GMT) in hours 'ZZZZ' => '', // Time Zone: long localized GMT (=OOOO) e.g. GMT-08:00 - 'ZZZZZ' => '', // TIme Zone: ISO8601 extended hms? (=XXXXX) + 'ZZZZZ' => '', // Time Zone: ISO8601 extended hms? (=XXXXX) 'O' => '', // Time Zone: short localized GMT e.g. GMT-8 - 'OOOO' => '', // Time Zone: long localized GMT (=ZZZZ) e.g. GMT-08:00 + 'OOOO' => '', // Time Zone: long localized GMT (=ZZZZ) e.g. GMT-08:00 'v' => '', // Time Zone: generic non-location (falls back first to VVVV and then to OOOO) using the ICU defined fallback here 'vvvv' => '', // Time Zone: generic non-location (falls back first to VVVV and then to OOOO) using the ICU defined fallback here 'V' => '', // Time Zone: short time zone ID diff --git a/framework/helpers/BaseHtml.php b/framework/helpers/BaseHtml.php index a9bc4530f5..c5914b9c71 100644 --- a/framework/helpers/BaseHtml.php +++ b/framework/helpers/BaseHtml.php @@ -9,10 +9,10 @@ namespace yii\helpers; use Yii; use yii\base\InvalidParamException; +use yii\base\Model; use yii\db\ActiveRecordInterface; use yii\validators\StringValidator; use yii\web\Request; -use yii\base\Model; /** * BaseHtml provides concrete implementation for [[Html]]. diff --git a/framework/helpers/BaseJson.php b/framework/helpers/BaseJson.php index 28b2af34f7..eef9d0b405 100644 --- a/framework/helpers/BaseJson.php +++ b/framework/helpers/BaseJson.php @@ -7,8 +7,8 @@ namespace yii\helpers; -use yii\base\InvalidParamException; use yii\base\Arrayable; +use yii\base\InvalidParamException; use yii\web\JsExpression; /** diff --git a/framework/helpers/BaseStringHelper.php b/framework/helpers/BaseStringHelper.php index 6e5eae30d7..12c934384a 100644 --- a/framework/helpers/BaseStringHelper.php +++ b/framework/helpers/BaseStringHelper.php @@ -166,7 +166,7 @@ class BaseStringHelper ++$depth; } elseif ($token instanceof \HTMLPurifier_Token_Text && $totalCount <= $count) { //Text if (false === $encoding) { - preg_match('/^(\s*)/um', $token->data, $prefixSpace) ?: $prefixSpace = ['','']; + preg_match('/^(\s*)/um', $token->data, $prefixSpace) ?: $prefixSpace = ['', '']; $token->data = $prefixSpace[1] . self::truncateWords(ltrim($token->data), $count - $totalCount, ''); $currentCount = self::countWords($token->data); } else { @@ -176,7 +176,7 @@ class BaseStringHelper $totalCount += $currentCount; $truncated[] = $token; } elseif ($token instanceof \HTMLPurifier_Token_End) { //Tag ends - if ($token->name === $openTokens[$depth-1]) { + if ($token->name === $openTokens[$depth - 1]) { --$depth; unset($openTokens[$depth]); $truncated[] = $token; diff --git a/framework/i18n/DbMessageSource.php b/framework/i18n/DbMessageSource.php index e2c9cd18ef..5bfaecebe9 100644 --- a/framework/i18n/DbMessageSource.php +++ b/framework/i18n/DbMessageSource.php @@ -10,11 +10,11 @@ namespace yii\i18n; use Yii; use yii\base\InvalidConfigException; use yii\caching\CacheInterface; +use yii\db\Connection; use yii\db\Expression; +use yii\db\Query; use yii\di\Instance; use yii\helpers\ArrayHelper; -use yii\db\Connection; -use yii\db\Query; /** * DbMessageSource extends [[MessageSource]] and represents a message source that stores translated @@ -183,7 +183,7 @@ class DbMessageSource extends MessageSource 't1.category' => $category, 't2.language' => $fallbackLanguage, ])->andWhere([ - 'NOT IN', 't2.id', (new Query())->select('[[id]]')->from($this->messageTable)->where(['language' => $language]) + 'NOT IN', 't2.id', (new Query())->select('[[id]]')->from($this->messageTable)->where(['language' => $language]), ]); } } diff --git a/framework/i18n/Formatter.php b/framework/i18n/Formatter.php index a3db2ace30..11b6c0bd68 100644 --- a/framework/i18n/Formatter.php +++ b/framework/i18n/Formatter.php @@ -18,8 +18,8 @@ use yii\base\Component; use yii\base\InvalidConfigException; use yii\base\InvalidParamException; use yii\helpers\FormatConverter; -use yii\helpers\HtmlPurifier; use yii\helpers\Html; +use yii\helpers\HtmlPurifier; /** * Formatter provides a set of commonly used data formatting methods. @@ -577,10 +577,10 @@ class Formatter extends Component * @var array map of short format names to IntlDateFormatter constant values. */ private $_dateFormats = [ - 'short' => 3, // IntlDateFormatter::SHORT, + 'short' => 3, // IntlDateFormatter::SHORT, 'medium' => 2, // IntlDateFormatter::MEDIUM, - 'long' => 1, // IntlDateFormatter::LONG, - 'full' => 0, // IntlDateFormatter::FULL, + 'long' => 1, // IntlDateFormatter::LONG, + 'full' => 0, // IntlDateFormatter::FULL, ]; /** @@ -691,7 +691,7 @@ class Formatter extends Component } try { if (is_numeric($value)) { // process as unix timestamp, which is always in UTC - $timestamp = new DateTime('@' . (int)$value, new DateTimeZone('UTC')); + $timestamp = new DateTime('@' . (int) $value, new DateTimeZone('UTC')); return $checkDateTimeInfo ? [$timestamp, true, true] : $timestamp; } elseif (($timestamp = DateTime::createFromFormat('Y-m-d', $value, new DateTimeZone($this->defaultTimeZone))) !== false) { // try Y-m-d format (support invalid dates like 2012-13-01) return $checkDateTimeInfo ? [$timestamp, false, true] : $timestamp; @@ -705,7 +705,7 @@ class Formatter extends Component return [ $timestamp, !($info['hour'] === false && $info['minute'] === false && $info['second'] === false), - !($info['year'] === false && $info['month'] === false && $info['day'] === false) + !($info['year'] === false && $info['month'] === false && $info['day'] === false), ]; } else { return new DateTime($value, new DateTimeZone($this->defaultTimeZone)); @@ -872,7 +872,7 @@ class Formatter extends Component $valueDateTime = (new DateTime())->setTimestamp(abs($value)); $interval = $valueDateTime->diff($zeroDateTime); } elseif (strpos($value, 'P-') === 0) { - $interval = new DateInterval('P'.substr($value, 2)); + $interval = new DateInterval('P' . substr($value, 2)); $isNegative = true; } else { $interval = new DateInterval($value); diff --git a/framework/i18n/GettextMoFile.php b/framework/i18n/GettextMoFile.php index 4692bda6e1..8aaf6be20c 100644 --- a/framework/i18n/GettextMoFile.php +++ b/framework/i18n/GettextMoFile.php @@ -111,7 +111,7 @@ class GettextMoFile extends GettextFile if ((!$context && $separatorPosition === false) || ($context && $separatorPosition !== false && strncmp($id, $context, $separatorPosition) === 0)) { if ($separatorPosition !== false) { - $id = substr($id, $separatorPosition+1); + $id = substr($id, $separatorPosition + 1); } $message = $this->readString($fileHandle, $targetLengths[$i], $targetOffsets[$i]); @@ -270,6 +270,6 @@ class GettextMoFile extends GettextFile */ protected function writeString($fileHandle, $string) { - return $this->writeBytes($fileHandle, $string. "\0"); + return $this->writeBytes($fileHandle, $string . "\0"); } } diff --git a/framework/i18n/GettextPoFile.php b/framework/i18n/GettextPoFile.php index 55770eca06..d3473e252c 100644 --- a/framework/i18n/GettextPoFile.php +++ b/framework/i18n/GettextPoFile.php @@ -66,7 +66,7 @@ class GettextPoFile extends GettextFile '"Language: ' . $language . '\n"', '"MIME-Version: 1.0\n"', '"Content-Type: text/plain; charset=' . Yii::$app->charset . '\n"', - '"Content-Transfer-Encoding: 8bit\n"' + '"Content-Transfer-Encoding: 8bit\n"', ]; $content = implode("\n", $headers) . "\n\n"; foreach ($messages as $id => $message) { diff --git a/framework/log/DbTarget.php b/framework/log/DbTarget.php index 0392f5e402..95288157d6 100644 --- a/framework/log/DbTarget.php +++ b/framework/log/DbTarget.php @@ -8,8 +8,8 @@ namespace yii\log; use Yii; -use yii\db\Connection; use yii\base\InvalidConfigException; +use yii\db\Connection; use yii\di\Instance; use yii\helpers\VarDumper; diff --git a/framework/log/Logger.php b/framework/log/Logger.php index 87b48fc7b5..7124b2f03b 100644 --- a/framework/log/Logger.php +++ b/framework/log/Logger.php @@ -279,9 +279,9 @@ class Logger extends Component $memory = isset($log[5]) ? $log[5] : 0; $log[6] = $i; $hash = md5(serialize($token)); - if ($level == Logger::LEVEL_PROFILE_BEGIN) { + if ($level == self::LEVEL_PROFILE_BEGIN) { $stack[$hash] = $log; - } elseif ($level == Logger::LEVEL_PROFILE_END) { + } elseif ($level == self::LEVEL_PROFILE_END) { if (isset($stack[$hash])) { $timings[$stack[$hash][6]] = [ 'info' => $stack[$hash][0], @@ -318,7 +318,7 @@ class Logger extends Component self::LEVEL_TRACE => 'trace', self::LEVEL_PROFILE_BEGIN => 'profile begin', self::LEVEL_PROFILE_END => 'profile end', - self::LEVEL_PROFILE => 'profile' + self::LEVEL_PROFILE => 'profile', ]; return isset($levels[$level]) ? $levels[$level] : 'unknown'; diff --git a/framework/mail/BaseMessage.php b/framework/mail/BaseMessage.php index 1a0c73e582..973ba63648 100644 --- a/framework/mail/BaseMessage.php +++ b/framework/mail/BaseMessage.php @@ -7,9 +7,9 @@ namespace yii\mail; +use Yii; use yii\base\ErrorHandler; use yii\base\Object; -use Yii; /** * BaseMessage serves as a base class that implements the [[send()]] method required by [[MessageInterface]]. diff --git a/framework/messages/bs/yii.php b/framework/messages/bs/yii.php index 695a595b05..810f89fff3 100644 --- a/framework/messages/bs/yii.php +++ b/framework/messages/bs/yii.php @@ -111,4 +111,4 @@ return [ '{nFormatted} {n, plural, =1{petabyte} other{petabytes}}' => '{nFormatted} {n, plural, =1{petabajt} other{petabajta}}', '{nFormatted} {n, plural, =1{tebibyte} other{tebibytes}}' => '{nFormatted} {n, plural, =1{tebibajt} other{tebibajta}}', '{nFormatted} {n, plural, =1{terabyte} other{terabytes}}' => '{nFormatted} {n, plural, =1{terabajt} other{terabajta}}', -]; \ No newline at end of file +]; diff --git a/framework/mutex/DbMutex.php b/framework/mutex/DbMutex.php index aa27005a45..b47188f8a5 100644 --- a/framework/mutex/DbMutex.php +++ b/framework/mutex/DbMutex.php @@ -7,8 +7,8 @@ namespace yii\mutex; -use yii\db\Connection; use yii\base\InvalidConfigException; +use yii\db\Connection; use yii\di\Instance; /** diff --git a/framework/mutex/OracleMutex.php b/framework/mutex/OracleMutex.php index bf78add365..52d5cf56f6 100644 --- a/framework/mutex/OracleMutex.php +++ b/framework/mutex/OracleMutex.php @@ -85,9 +85,9 @@ class OracleMutex extends DbMutex /** clean vars before using */ $releaseOnCommit = $this->releaseOnCommit ? 'TRUE' : 'FALSE'; - $timeout = abs((int)$timeout); + $timeout = abs((int) $timeout); - /** inside pl/sql scopes pdo binding not working correctly :( */ + // inside pl/sql scopes pdo binding not working correctly :( $this->db->createCommand( 'DECLARE handle VARCHAR2(128); @@ -100,7 +100,7 @@ END;', ->bindParam(':lockStatus', $lockStatus, PDO::PARAM_INT, 1) ->execute(); - return ($lockStatus === 0 || $lockStatus === '0'); + return $lockStatus === 0 || $lockStatus === '0'; } /** @@ -124,6 +124,6 @@ END;', ->bindParam(':result', $releaseStatus, PDO::PARAM_INT, 1) ->execute(); - return ($releaseStatus === 0 || $releaseStatus === '0'); + return $releaseStatus === 0 || $releaseStatus === '0'; } } diff --git a/framework/rbac/DbManager.php b/framework/rbac/DbManager.php index 4bffc4f085..8a07a2222c 100644 --- a/framework/rbac/DbManager.php +++ b/framework/rbac/DbManager.php @@ -8,12 +8,12 @@ namespace yii\rbac; use Yii; -use yii\caching\CacheInterface; -use yii\db\Connection; -use yii\db\Query; -use yii\db\Expression; use yii\base\InvalidCallException; use yii\base\InvalidParamException; +use yii\caching\CacheInterface; +use yii\db\Connection; +use yii\db\Expression; +use yii\db\Query; use yii\di\Instance; /** @@ -204,7 +204,7 @@ class DbManager extends BaseManager return true; } - $query = new Query; + $query = new Query(); $parents = $query->select(['parent']) ->from($this->itemChildTable) ->where(['child' => $itemName]) @@ -231,7 +231,7 @@ class DbManager extends BaseManager return $this->items[$name]; } - $row = (new Query)->from($this->itemTable) + $row = (new Query())->from($this->itemTable) ->where(['name' => $name]) ->one($this->db); @@ -415,7 +415,7 @@ class DbManager extends BaseManager */ protected function getItems($type) { - $query = (new Query) + $query = (new Query()) ->from($this->itemTable) ->where(['type' => $type]); @@ -460,7 +460,7 @@ class DbManager extends BaseManager return []; } - $query = (new Query)->select('b.*') + $query = (new Query())->select('b.*') ->from(['a' => $this->assignmentTable, 'b' => $this->itemTable]) ->where('{{a}}.[[item_name]]={{b}}.[[name]]') ->andWhere(['a.user_id' => (string) $userId]) @@ -507,7 +507,7 @@ class DbManager extends BaseManager if (empty($result)) { return []; } - $query = (new Query)->from($this->itemTable)->where([ + $query = (new Query())->from($this->itemTable)->where([ 'type' => Item::TYPE_PERMISSION, 'name' => array_keys($result), ]); @@ -541,7 +541,7 @@ class DbManager extends BaseManager */ protected function getDirectPermissionsByUser($userId) { - $query = (new Query)->select('b.*') + $query = (new Query())->select('b.*') ->from(['a' => $this->assignmentTable, 'b' => $this->itemTable]) ->where('{{a}}.[[item_name]]={{b}}.[[name]]') ->andWhere(['a.user_id' => (string) $userId]) @@ -562,7 +562,7 @@ class DbManager extends BaseManager */ protected function getInheritedPermissionsByUser($userId) { - $query = (new Query)->select('item_name') + $query = (new Query())->select('item_name') ->from($this->assignmentTable) ->where(['user_id' => (string) $userId]); @@ -576,7 +576,7 @@ class DbManager extends BaseManager return []; } - $query = (new Query)->from($this->itemTable)->where([ + $query = (new Query())->from($this->itemTable)->where([ 'type' => Item::TYPE_PERMISSION, 'name' => array_keys($result), ]); @@ -594,7 +594,7 @@ class DbManager extends BaseManager */ protected function getChildrenList() { - $query = (new Query)->from($this->itemChildTable); + $query = (new Query())->from($this->itemChildTable); $parents = []; foreach ($query->all($this->db) as $row) { $parents[$row['parent']][] = $row['child']; @@ -627,7 +627,7 @@ class DbManager extends BaseManager return isset($this->rules[$name]) ? $this->rules[$name] : null; } - $row = (new Query)->select(['data']) + $row = (new Query())->select(['data']) ->from($this->ruleTable) ->where(['name' => $name]) ->one($this->db); @@ -639,7 +639,6 @@ class DbManager extends BaseManager $data = stream_get_contents($data); } return unserialize($data); - } /** @@ -651,13 +650,13 @@ class DbManager extends BaseManager return $this->rules; } - $query = (new Query)->from($this->ruleTable); + $query = (new Query())->from($this->ruleTable); $rules = []; foreach ($query->all($this->db) as $row) { $data = $row['data']; if (is_resource($data)) { - $data = stream_get_contents($data); + $data = stream_get_contents($data); } $rules[$row['name']] = unserialize($data); } @@ -674,7 +673,7 @@ class DbManager extends BaseManager return null; } - $row = (new Query)->from($this->assignmentTable) + $row = (new Query())->from($this->assignmentTable) ->where(['user_id' => (string) $userId, 'item_name' => $roleName]) ->one($this->db); @@ -698,7 +697,7 @@ class DbManager extends BaseManager return []; } - $query = (new Query) + $query = (new Query()) ->from($this->assignmentTable) ->where(['user_id' => (string) $userId]); @@ -782,7 +781,7 @@ class DbManager extends BaseManager */ public function hasChild($parent, $child) { - return (new Query) + return (new Query()) ->from($this->itemChildTable) ->where(['parent' => $parent->name, 'child' => $child->name]) ->one($this->db) !== false; @@ -793,7 +792,7 @@ class DbManager extends BaseManager */ public function getChildren($name) { - $query = (new Query) + $query = (new Query()) ->select(['name', 'type', 'description', 'rule_name', 'data', 'created_at', 'updated_at']) ->from([$this->itemTable, $this->itemChildTable]) ->where(['parent' => $name, 'name' => new Expression('[[child]]')]); @@ -909,7 +908,7 @@ class DbManager extends BaseManager protected function removeAllItems($type) { if (!$this->supportsCascadeUpdate()) { - $names = (new Query) + $names = (new Query()) ->select(['name']) ->from($this->itemTable) ->where(['type' => $type]) @@ -974,17 +973,17 @@ class DbManager extends BaseManager $data = $this->cache->get($this->cacheKey); if (is_array($data) && isset($data[0], $data[1], $data[2])) { - list ($this->items, $this->rules, $this->parents) = $data; + list($this->items, $this->rules, $this->parents) = $data; return; } - $query = (new Query)->from($this->itemTable); + $query = (new Query())->from($this->itemTable); $this->items = []; foreach ($query->all($this->db) as $row) { $this->items[$row['name']] = $this->populateItem($row); } - $query = (new Query)->from($this->ruleTable); + $query = (new Query())->from($this->ruleTable); $this->rules = []; foreach ($query->all($this->db) as $row) { $data = $row['data']; @@ -994,7 +993,7 @@ class DbManager extends BaseManager $this->rules[$row['name']] = unserialize($data); } - $query = (new Query)->from($this->itemChildTable); + $query = (new Query())->from($this->itemChildTable); $this->parents = []; foreach ($query->all($this->db) as $row) { if (isset($this->items[$row['child']])) { @@ -1018,7 +1017,7 @@ class DbManager extends BaseManager return []; } - return (new Query)->select('[[user_id]]') + return (new Query())->select('[[user_id]]') ->from($this->assignmentTable) ->where(['item_name' => $roleName])->column($this->db); } diff --git a/framework/rbac/PhpManager.php b/framework/rbac/PhpManager.php index 6b6b5aed89..06bf0ef7eb 100644 --- a/framework/rbac/PhpManager.php +++ b/framework/rbac/PhpManager.php @@ -7,9 +7,9 @@ namespace yii\rbac; +use Yii; use yii\base\InvalidCallException; use yii\base\InvalidParamException; -use Yii; use yii\helpers\VarDumper; /** @@ -701,7 +701,6 @@ class PhpManager extends BaseManager $this->saveItems(); return true; - } /** @@ -875,7 +874,7 @@ class PhpManager extends BaseManager foreach ($this->assignments as $userID => $assignments) { foreach ($assignments as $userAssignment) { if ($userAssignment->roleName === $roleName && $userAssignment->userId == $userID) { - $result[] = (string)$userID; + $result[] = (string) $userID; } } } diff --git a/framework/rbac/Role.php b/framework/rbac/Role.php index 233d1d6468..ed084e98fa 100644 --- a/framework/rbac/Role.php +++ b/framework/rbac/Role.php @@ -8,7 +8,6 @@ namespace yii\rbac; /** - * * For more details and usage information on Role, see the [guide article on security authorization](guide:security-authorization). * * @author Qiang Xue diff --git a/framework/rbac/migrations/m140506_102106_rbac_init.php b/framework/rbac/migrations/m140506_102106_rbac_init.php index 9f9dff6111..9c6d604e24 100644 --- a/framework/rbac/migrations/m140506_102106_rbac_init.php +++ b/framework/rbac/migrations/m140506_102106_rbac_init.php @@ -73,8 +73,8 @@ class m140506_102106_rbac_init extends \yii\db\Migration 'created_at' => $this->integer(), 'updated_at' => $this->integer(), 'PRIMARY KEY ([[name]])', - 'FOREIGN KEY ([[rule_name]]) REFERENCES ' . $authManager->ruleTable . ' ([[name]])'. - $this->buildFkClause('ON DELETE SET NULL', 'ON UPDATE CASCADE') + 'FOREIGN KEY ([[rule_name]]) REFERENCES ' . $authManager->ruleTable . ' ([[name]])' . + $this->buildFkClause('ON DELETE SET NULL', 'ON UPDATE CASCADE'), ], $tableOptions); $this->createIndex('idx-auth_item-type', $authManager->itemTable, 'type'); @@ -82,9 +82,9 @@ class m140506_102106_rbac_init extends \yii\db\Migration 'parent' => $this->string(64)->notNull(), 'child' => $this->string(64)->notNull(), 'PRIMARY KEY ([[parent]], [[child]])', - 'FOREIGN KEY ([[parent]]) REFERENCES ' . $authManager->itemTable . ' ([[name]])'. + 'FOREIGN KEY ([[parent]]) REFERENCES ' . $authManager->itemTable . ' ([[name]])' . $this->buildFkClause('ON DELETE CASCADE', 'ON UPDATE CASCADE'), - 'FOREIGN KEY ([[child]]) REFERENCES ' . $authManager->itemTable . ' ([[name]])'. + 'FOREIGN KEY ([[child]]) REFERENCES ' . $authManager->itemTable . ' ([[name]])' . $this->buildFkClause('ON DELETE CASCADE', 'ON UPDATE CASCADE'), ], $tableOptions); diff --git a/framework/requirements/requirements.php b/framework/requirements/requirements.php index cb14ec35f1..d515af77fe 100644 --- a/framework/requirements/requirements.php +++ b/framework/requirements/requirements.php @@ -1,10 +1,16 @@ 'PHP version', diff --git a/framework/requirements/views/console/index.php b/framework/requirements/views/console/index.php index 4bb042e61b..d1559b68bc 100644 --- a/framework/requirements/views/console/index.php +++ b/framework/requirements/views/console/index.php @@ -1,4 +1,10 @@ $requirement) { if ($requirement['condition']) { - echo $requirement['name'].": OK\n"; + echo $requirement['name'] . ": OK\n"; echo "\n"; } else { - echo $requirement['name'].': '.($requirement['mandatory'] ? 'FAILED!!!' : 'WARNING!!!')."\n"; - echo 'Required by: '.strip_tags($requirement['by'])."\n"; + echo $requirement['name'] . ': ' . ($requirement['mandatory'] ? 'FAILED!!!' : 'WARNING!!!') . "\n"; + echo 'Required by: ' . strip_tags($requirement['by']) . "\n"; $memo = strip_tags($requirement['memo']); if (!empty($memo)) { - echo 'Memo: '.strip_tags($requirement['memo'])."\n"; + echo 'Memo: ' . strip_tags($requirement['memo']) . "\n"; } echo "\n"; } } -$summaryString = 'Errors: '.$summary['errors'].' Warnings: '.$summary['warnings'].' Total checks: '.$summary['total']; -echo str_pad('', strlen($summaryString), '-')."\n"; +$summaryString = 'Errors: ' . $summary['errors'] . ' Warnings: ' . $summary['warnings'] . ' Total checks: ' . $summary['total']; +echo str_pad('', strlen($summaryString), '-') . "\n"; echo $summaryString; echo "\n\n"; diff --git a/framework/rest/Controller.php b/framework/rest/Controller.php index 92a0514dcb..734b34429b 100644 --- a/framework/rest/Controller.php +++ b/framework/rest/Controller.php @@ -11,8 +11,8 @@ use Yii; use yii\filters\auth\CompositeAuth; use yii\filters\ContentNegotiator; use yii\filters\RateLimiter; -use yii\web\Response; use yii\filters\VerbFilter; +use yii\web\Response; /** * Controller is the base class for RESTful API controller classes. diff --git a/framework/rest/Serializer.php b/framework/rest/Serializer.php index 1602156e07..33e5637c8b 100644 --- a/framework/rest/Serializer.php +++ b/framework/rest/Serializer.php @@ -255,7 +255,7 @@ class Serializer extends Component if ($this->request->getIsHead()) { return null; } else { - list ($fields, $expand) = $this->getRequestedFields(); + list($fields, $expand) = $this->getRequestedFields(); return $model->toArray($fields, $expand); } } @@ -286,7 +286,7 @@ class Serializer extends Component */ protected function serializeModels(array $models) { - list ($fields, $expand) = $this->getRequestedFields(); + list($fields, $expand) = $this->getRequestedFields(); foreach ($models as $i => $model) { if ($model instanceof Arrayable) { $models[$i] = $model->toArray($fields, $expand); diff --git a/framework/test/DbFixture.php b/framework/test/DbFixture.php index 7648acd84b..9de4d71de8 100644 --- a/framework/test/DbFixture.php +++ b/framework/test/DbFixture.php @@ -8,9 +8,9 @@ namespace yii\test; use Yii; +use yii\base\Object; use yii\db\Connection; use yii\di\Instance; -use yii\base\Object; /** * DbFixture is the base class for DB-related fixtures. diff --git a/framework/validators/DateValidator.php b/framework/validators/DateValidator.php index 871f522285..04c1ac7fca 100644 --- a/framework/validators/DateValidator.php +++ b/framework/validators/DateValidator.php @@ -199,10 +199,10 @@ class DateValidator extends Validator * @var array map of short format names to IntlDateFormatter constant values. */ private $_dateFormats = [ - 'short' => 3, // IntlDateFormatter::SHORT, + 'short' => 3, // IntlDateFormatter::SHORT, 'medium' => 2, // IntlDateFormatter::MEDIUM, - 'long' => 1, // IntlDateFormatter::LONG, - 'full' => 0, // IntlDateFormatter::FULL, + 'long' => 1, // IntlDateFormatter::LONG, + 'full' => 0, // IntlDateFormatter::FULL, ]; diff --git a/framework/validators/EachValidator.php b/framework/validators/EachValidator.php index 15dd9f798e..385e4f2d23 100644 --- a/framework/validators/EachValidator.php +++ b/framework/validators/EachValidator.php @@ -7,8 +7,8 @@ namespace yii\validators; -use yii\base\InvalidConfigException; use Yii; +use yii\base\InvalidConfigException; use yii\base\Model; /** diff --git a/framework/validators/EmailValidator.php b/framework/validators/EmailValidator.php index bf72754705..bd613f6162 100644 --- a/framework/validators/EmailValidator.php +++ b/framework/validators/EmailValidator.php @@ -9,8 +9,8 @@ namespace yii\validators; use Yii; use yii\base\InvalidConfigException; -use yii\web\JsExpression; use yii\helpers\Json; +use yii\web\JsExpression; /** * EmailValidator validates that the attribute value is a valid email address. @@ -130,7 +130,7 @@ class EmailValidator extends Validator 'message' => $this->formatMessage($this->message, [ 'attribute' => $model->getAttributeLabel($attribute), ]), - 'enableIDN' => (bool)$this->enableIDN, + 'enableIDN' => (bool) $this->enableIDN, ]; if ($this->skipOnEmpty) { $options['skipOnEmpty'] = 1; diff --git a/framework/validators/ExistValidator.php b/framework/validators/ExistValidator.php index 6e561fd1ca..91b78b33dc 100644 --- a/framework/validators/ExistValidator.php +++ b/framework/validators/ExistValidator.php @@ -223,8 +223,8 @@ class ExistValidator extends Validator foreach ($conditions as $columnName => $columnValue) { $prefixedColumn = "{$alias}.[[" . preg_replace( '/^' . preg_quote($alias) . '\.(.*)$/', - "$1", - $columnName) . "]]"; + '$1', + $columnName) . ']]'; $prefixedConditions[$prefixedColumn] = $columnValue; } return $prefixedConditions; diff --git a/framework/validators/FileValidator.php b/framework/validators/FileValidator.php index 80183600d7..b679bdf7f3 100644 --- a/framework/validators/FileValidator.php +++ b/framework/validators/FileValidator.php @@ -8,11 +8,11 @@ namespace yii\validators; use Yii; +use yii\helpers\FileHelper; use yii\helpers\Html; use yii\helpers\Json; use yii\web\JsExpression; use yii\web\UploadedFile; -use yii\helpers\FileHelper; /** * FileValidator verifies if an attribute is receiving a valid uploaded file. @@ -250,7 +250,7 @@ class FileValidator extends Validator ]; } elseif (!empty($this->extensions) && !$this->validateExtension($value)) { return [$this->wrongExtension, ['file' => $value->name, 'extensions' => implode(', ', $this->extensions)]]; - } elseif (!empty($this->mimeTypes) && !$this->validateMimeType($value)) { + } elseif (!empty($this->mimeTypes) && !$this->validateMimeType($value)) { return [$this->wrongMimeType, ['file' => $value->name, 'mimeTypes' => implode(', ', $this->mimeTypes)]]; } return null; @@ -353,7 +353,6 @@ class FileValidator extends Validator $extension = mb_strtolower($file->extension, 'UTF-8'); if ($this->checkExtensionByMimeType) { - $mimeType = FileHelper::getMimeType($file->tempName, null, false); if ($mimeType === null) { return false; diff --git a/framework/validators/IpValidator.php b/framework/validators/IpValidator.php index bfe84f79bd..89800b2bf2 100644 --- a/framework/validators/IpValidator.php +++ b/framework/validators/IpValidator.php @@ -71,7 +71,6 @@ class IpValidator extends Validator * - `localhost`: `127.0.0.0/8', ::1` * - `documentation`: `192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32` * - `system`: `multicast, linklocal, localhost, documentation` - * */ public $networks = [ '*' => ['any'], diff --git a/framework/validators/NumberValidator.php b/framework/validators/NumberValidator.php index d5b4fb9216..ca18d59e04 100644 --- a/framework/validators/NumberValidator.php +++ b/framework/validators/NumberValidator.php @@ -8,9 +8,9 @@ namespace yii\validators; use Yii; +use yii\helpers\Json; use yii\helpers\StringHelper; use yii\web\JsExpression; -use yii\helpers\Json; /** * NumberValidator validates that the attribute value is a number. diff --git a/framework/validators/RegularExpressionValidator.php b/framework/validators/RegularExpressionValidator.php index 7f174329fc..fab5c51b45 100644 --- a/framework/validators/RegularExpressionValidator.php +++ b/framework/validators/RegularExpressionValidator.php @@ -10,8 +10,8 @@ namespace yii\validators; use Yii; use yii\base\InvalidConfigException; use yii\helpers\Html; -use yii\web\JsExpression; use yii\helpers\Json; +use yii\web\JsExpression; /** * RegularExpressionValidator validates that the attribute value matches the specified [[pattern]]. diff --git a/framework/validators/UniqueValidator.php b/framework/validators/UniqueValidator.php index b834d6dfa2..d4d1b61ba7 100644 --- a/framework/validators/UniqueValidator.php +++ b/framework/validators/UniqueValidator.php @@ -10,8 +10,8 @@ namespace yii\validators; use Yii; use yii\base\Model; use yii\db\ActiveQuery; -use yii\db\ActiveRecord; use yii\db\ActiveQueryInterface; +use yii\db\ActiveRecord; use yii\db\ActiveRecordInterface; use yii\helpers\Inflector; @@ -75,7 +75,6 @@ class UniqueValidator extends Validator * * - `{attributes}`: the labels of the attributes being validated. * - `{values}`: the values of the attributes being validated. - * */ public $message; /** @@ -271,7 +270,7 @@ class UniqueValidator extends Validator } $this->addError($model, $attribute, $this->message, [ 'attributes' => Inflector::sentence($attributeCombo), - 'values' => implode('-', $valueCombo) + 'values' => implode('-', $valueCombo), ]); } @@ -291,8 +290,8 @@ class UniqueValidator extends Validator foreach ($conditions as $columnName => $columnValue) { $prefixedColumn = "{$alias}.[[" . preg_replace( '/^' . preg_quote($alias) . '\.(.*)$/', - "$1", - $columnName) . "]]"; + '$1', + $columnName) . ']]'; $prefixedConditions[$prefixedColumn] = $columnValue; } return $prefixedConditions; diff --git a/framework/validators/UrlValidator.php b/framework/validators/UrlValidator.php index 0c2151e63c..6f237a2155 100644 --- a/framework/validators/UrlValidator.php +++ b/framework/validators/UrlValidator.php @@ -9,8 +9,8 @@ namespace yii\validators; use Yii; use yii\base\InvalidConfigException; -use yii\web\JsExpression; use yii\helpers\Json; +use yii\web\JsExpression; /** * UrlValidator validates that the attribute value is a valid http or https URL. diff --git a/framework/validators/Validator.php b/framework/validators/Validator.php index 02716874fd..b7f4458e6a 100644 --- a/framework/validators/Validator.php +++ b/framework/validators/Validator.php @@ -460,7 +460,7 @@ class Validator extends Component */ public function getAttributeNames() { - return array_map(function($attribute) { + return array_map(function ($attribute) { return ltrim($attribute, '!'); }, $this->attributes); } diff --git a/framework/views/errorHandler/callStackItem.php b/framework/views/errorHandler/callStackItem.php index 6701ee44db..04f8c88eba 100644 --- a/framework/views/errorHandler/callStackItem.php +++ b/framework/views/errorHandler/callStackItem.php @@ -10,19 +10,19 @@ /* @var $args array */ /* @var $handler \yii\web\ErrorHandler */ ?> -
  • . - htmlEncode($file); ?> + htmlEncode($file) : '' ?> - - + + - + addTypeLinks("$class::$method") : $handler->htmlEncode($method)) . '(' . $handler->argumentsToString($args) . ')' ?> diff --git a/framework/views/errorHandler/error.php b/framework/views/errorHandler/error.php index e85f09cd85..dc88e6bc20 100644 --- a/framework/views/errorHandler/error.php +++ b/framework/views/errorHandler/error.php @@ -80,14 +80,11 @@ if (method_exists($this, 'beginPage')) {
    - endBody(); // to allow injecting code into body (mostly by Yii Debug Toolbar) - } - ?> + + endBody() // to allow injecting code into body (mostly by Yii Debug Toolbar)?> + -endPage(); -} + + endPage() ?> + diff --git a/framework/views/errorHandler/exception.php b/framework/views/errorHandler/exception.php index 3eae788ad5..6de99047ed 100644 --- a/framework/views/errorHandler/exception.php +++ b/framework/views/errorHandler/exception.php @@ -3,7 +3,9 @@ /* @var $exception \Exception */ /* @var $handler \yii\web\ErrorHandler */ ?> -beginPage(); ?> + + beginPage() ?> + @@ -370,9 +372,9 @@ body.mousedown pre {

    htmlEncode($exception->getMessage())) ?>

    - errorInfo)) { - echo '
    Error Info: ' . print_r($exception->errorInfo, true) . '
    '; - } ?> + errorInfo)): ?> +
    Error Info: errorInfo, true) ?>
    + renderPreviousExceptions($exception) ?>
    @@ -448,8 +450,12 @@ window.onload = function() { document.onmousedown = function() { document.getElementsByTagName('body')[0].classList.add('mousedown'); } document.onmouseup = function() { document.getElementsByTagName('body')[0].classList.remove('mousedown'); } - endBody(); // to allow injecting code into body (mostly by Yii Debug Toolbar) ?> + + endBody() // to allow injecting code into body (mostly by Yii Debug Toolbar)?> + -endPage(); ?> + + endPage() ?> + diff --git a/framework/views/errorHandler/previousException.php b/framework/views/errorHandler/previousException.php index 882246da7f..59e1451fa7 100644 --- a/framework/views/errorHandler/previousException.php +++ b/framework/views/errorHandler/previousException.php @@ -6,8 +6,8 @@

    Caused by: - getExceptionName($exception); - if ($name !== null): ?> + getExceptionName($exception) ?> + htmlEncode($name) ?>addTypeLinks(get_class($exception)) ?> @@ -16,8 +16,8 @@

    htmlEncode($exception->getMessage())) ?>

    in getFile() ?> at line getLine() ?>

    - errorInfo)) { - echo '
    Error Info: ' . print_r($exception->errorInfo, true) . '
    '; - } ?> + errorInfo)): ?> +
    Error Info: errorInfo, true) ?>
    + renderPreviousExceptions($exception) ?>
    diff --git a/framework/web/Application.php b/framework/web/Application.php index 89728f17bc..a43090b045 100644 --- a/framework/web/Application.php +++ b/framework/web/Application.php @@ -8,8 +8,8 @@ namespace yii\web; use Yii; -use yii\helpers\Url; use yii\base\InvalidRouteException; +use yii\helpers\Url; /** * Application is the base class for all web application classes. @@ -79,7 +79,7 @@ class Application extends \yii\base\Application { if (empty($this->catchAll)) { try { - list ($route, $params) = $request->resolve(); + list($route, $params) = $request->resolve(); } catch (UrlNormalizerRedirectException $e) { $url = $e->url; if (is_array($url)) { diff --git a/framework/web/AssetBundle.php b/framework/web/AssetBundle.php index 7d391e11cc..ce395bf9c2 100644 --- a/framework/web/AssetBundle.php +++ b/framework/web/AssetBundle.php @@ -7,10 +7,10 @@ namespace yii\web; +use Yii; use yii\base\Object; use yii\helpers\ArrayHelper; use yii\helpers\Url; -use Yii; /** * AssetBundle represents a collection of asset files, such as CSS, JS, images. @@ -182,7 +182,7 @@ class AssetBundle extends Object public function publish($am) { if ($this->sourcePath !== null && !isset($this->basePath, $this->baseUrl)) { - list ($this->basePath, $this->baseUrl) = $am->publish($this->sourcePath, $this->publishOptions); + list($this->basePath, $this->baseUrl) = $am->publish($this->sourcePath, $this->publishOptions); } if (isset($this->basePath, $this->baseUrl) && ($converter = $am->getConverter()) !== null) { diff --git a/framework/web/AssetConverter.php b/framework/web/AssetConverter.php index 55e67d1276..ad1e949182 100644 --- a/framework/web/AssetConverter.php +++ b/framework/web/AssetConverter.php @@ -63,7 +63,7 @@ class AssetConverter extends Component implements AssetConverterInterface if ($pos !== false) { $ext = substr($asset, $pos + 1); if (isset($this->commands[$ext])) { - list ($ext, $command) = $this->commands[$ext]; + list($ext, $command) = $this->commands[$ext]; $result = substr($asset, 0, $pos + 1) . $ext; if ($this->forceConvert || @filemtime("$basePath/$result") < @filemtime("$basePath/$asset")) { $this->runCommand($command, $basePath, $asset, $result); diff --git a/framework/web/CompositeUrlRule.php b/framework/web/CompositeUrlRule.php index 97d0bdc627..080e1a5b5d 100644 --- a/framework/web/CompositeUrlRule.php +++ b/framework/web/CompositeUrlRule.php @@ -60,7 +60,7 @@ abstract class CompositeUrlRule extends Object implements UrlRuleInterface Yii::trace([ 'rule' => method_exists($rule, '__toString') ? $rule->__toString() : get_class($rule), 'match' => $result !== false, - 'parent' => self::className() + 'parent' => self::className(), ], __METHOD__); } if ($result !== false) { diff --git a/framework/web/CookieCollection.php b/framework/web/CookieCollection.php index 6a3dea3585..bb2b7390cc 100644 --- a/framework/web/CookieCollection.php +++ b/framework/web/CookieCollection.php @@ -7,8 +7,8 @@ namespace yii\web; -use Yii; use ArrayIterator; +use Yii; use yii\base\InvalidCallException; use yii\base\Object; diff --git a/framework/web/DbSession.php b/framework/web/DbSession.php index 072aca3ee5..28cf074765 100644 --- a/framework/web/DbSession.php +++ b/framework/web/DbSession.php @@ -8,9 +8,9 @@ namespace yii\web; use Yii; +use yii\base\InvalidConfigException; use yii\db\Connection; use yii\db\Query; -use yii\base\InvalidConfigException; use yii\di\Instance; /** @@ -165,7 +165,7 @@ class DbSession extends MultiFieldSession // exception must be caught in session write handler // http://us.php.net/manual/en/function.session-set-save-handler.php#refsect1-function.session-set-save-handler-notes try { - $query = new Query; + $query = new Query(); $exists = $query->select(['id']) ->from($this->sessionTable) ->where(['id' => $id]) diff --git a/framework/web/ErrorHandler.php b/framework/web/ErrorHandler.php index f01d6d083d..c3dea6a513 100644 --- a/framework/web/ErrorHandler.php +++ b/framework/web/ErrorHandler.php @@ -8,8 +8,8 @@ namespace yii\web; use Yii; -use yii\base\Exception; use yii\base\ErrorException; +use yii\base\Exception; use yii\base\UserException; use yii\helpers\VarDumper; @@ -191,7 +191,7 @@ class ErrorHandler extends \yii\base\ErrorHandler $url = null; $shouldGenerateLink = true; - if ($method !== null && substr_compare($method, '{closure}', -9) !== 0) { + if ($method !== null && substr_compare($method, '{closure}', -9) !== 0) { $reflection = new \ReflectionMethod($class, $method); $shouldGenerateLink = $reflection->isPublic() || $reflection->isProtected(); } @@ -419,8 +419,8 @@ class ErrorHandler extends \yii\base\ErrorHandler foreach ($args as $key => $value) { $count++; - if ($count>=5) { - if ($count>5) { + if ($count >= 5) { + if ($count > 5) { unset($args[$key]); } else { $args[$key] = '...'; diff --git a/framework/web/HeaderCollection.php b/framework/web/HeaderCollection.php index 163c408184..2a616ef60b 100644 --- a/framework/web/HeaderCollection.php +++ b/framework/web/HeaderCollection.php @@ -7,9 +7,9 @@ namespace yii\web; +use ArrayIterator; use Yii; use yii\base\Object; -use ArrayIterator; /** * HeaderCollection is used by [[Response]] to maintain the currently registered HTTP headers. diff --git a/framework/web/MultiFieldSession.php b/framework/web/MultiFieldSession.php index c4083e4213..dcb0d6d7af 100644 --- a/framework/web/MultiFieldSession.php +++ b/framework/web/MultiFieldSession.php @@ -130,7 +130,7 @@ abstract class MultiFieldSession extends Session $extraData = call_user_func($this->readCallback, $fields); if (!empty($extraData)) { session_decode($fields['data']); - $_SESSION = array_merge((array)$_SESSION, (array)$extraData); + $_SESSION = array_merge((array) $_SESSION, (array) $extraData); return session_encode(); } return $fields['data']; diff --git a/framework/web/MultipartFormDataParser.php b/framework/web/MultipartFormDataParser.php index 6fae328d9b..ac1ffd8f84 100644 --- a/framework/web/MultipartFormDataParser.php +++ b/framework/web/MultipartFormDataParser.php @@ -141,7 +141,7 @@ class MultipartFormDataParser extends Object implements RequestParserInterface if (empty($bodyPart)) { continue; } - list($headers, $value) = preg_split("/\\R\\R/", $bodyPart, 2); + list($headers, $value) = preg_split('/\\R\\R/', $bodyPart, 2); $headers = $this->parseHeaders($headers); if (!isset($headers['content-disposition']['name'])) { @@ -202,7 +202,7 @@ class MultipartFormDataParser extends Object implements RequestParserInterface private function parseHeaders($headerContent) { $headers = []; - $headerParts = preg_split("/\\R/s", $headerContent, -1, PREG_SPLIT_NO_EMPTY); + $headerParts = preg_split('/\\R/s', $headerContent, -1, PREG_SPLIT_NO_EMPTY); foreach ($headerParts as $headerPart) { if (($separatorPos = strpos($headerPart, ':')) === false) { continue; @@ -278,7 +278,7 @@ class MultipartFormDataParser extends Object implements RequestParserInterface 'size', 'error', 'tmp_name', - 'tmp_resource' + 'tmp_resource', ]; $nameParts = preg_split('/\\]\\[|\\[/s', $name); @@ -290,7 +290,7 @@ class MultipartFormDataParser extends Object implements RequestParserInterface } } else { foreach ($fileInfoAttributes as $attribute) { - $files[$baseName][$attribute] = (array)$files[$baseName][$attribute]; + $files[$baseName][$attribute] = (array) $files[$baseName][$attribute]; } } diff --git a/framework/web/Request.php b/framework/web/Request.php index e374f6b067..c6ce4575c3 100644 --- a/framework/web/Request.php +++ b/framework/web/Request.php @@ -183,7 +183,7 @@ class Request extends \yii\base\Request { $result = Yii::$app->getUrlManager()->parseRequest($this); if ($result !== false) { - list ($route, $params) = $result; + list($route, $params) = $result; if ($this->_queryParams === null) { $_GET = $params + $_GET; // preserve numeric keys } else { @@ -203,7 +203,7 @@ class Request extends \yii\base\Request public function getHeaders() { if ($this->_headers === null) { - $this->_headers = new HeaderCollection; + $this->_headers = new HeaderCollection(); if (function_exists('getallheaders')) { $headers = getallheaders(); } elseif (function_exists('http_get_request_headers')) { @@ -407,7 +407,7 @@ class Request extends \yii\base\Request } elseif (isset($this->parsers['*'])) { $parser = Yii::createObject($this->parsers['*']); if (!($parser instanceof RequestParserInterface)) { - throw new InvalidConfigException("The fallback request parser is invalid. It must implement the yii\\web\\RequestParserInterface."); + throw new InvalidConfigException('The fallback request parser is invalid. It must implement the yii\\web\\RequestParserInterface.'); } $this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType); } elseif ($this->getMethod() === 'POST') { @@ -1153,9 +1153,9 @@ class Request extends \yii\base\Request ]; foreach ($params as $param) { if (strpos($param, '=') !== false) { - list ($key, $value) = explode('=', $param, 2); + list($key, $value) = explode('=', $param, 2); if ($key === 'q') { - $values['q'][2] = (double) $value; + $values['q'][2] = (float) $value; } else { $values[$key] = $value; } @@ -1226,10 +1226,11 @@ class Request extends \yii\base\Request foreach ($languages as $language) { $normalizedLanguage = str_replace('_', '-', strtolower($language)); - if ($normalizedLanguage === $acceptableLanguage || // en-us==en-us - strpos($acceptableLanguage, $normalizedLanguage . '-') === 0 || // en==en-us - strpos($normalizedLanguage, $acceptableLanguage . '-') === 0) { // en-us==en - + if ( + $normalizedLanguage === $acceptableLanguage // en-us==en-us + || strpos($acceptableLanguage, $normalizedLanguage . '-') === 0 // en==en-us + || strpos($normalizedLanguage, $acceptableLanguage . '-') === 0 // en-us==en + ) { return $language; } } diff --git a/framework/web/Response.php b/framework/web/Response.php index f643b7c53c..40deeade43 100644 --- a/framework/web/Response.php +++ b/framework/web/Response.php @@ -10,10 +10,10 @@ namespace yii\web; use Yii; use yii\base\InvalidConfigException; use yii\base\InvalidParamException; -use yii\helpers\Inflector; -use yii\helpers\Url; use yii\helpers\FileHelper; +use yii\helpers\Inflector; use yii\helpers\StringHelper; +use yii\helpers\Url; /** * The web Response class represents an HTTP response @@ -317,7 +317,7 @@ class Response extends \yii\base\Response public function getHeaders() { if ($this->_headers === null) { - $this->_headers = new HeaderCollection; + $this->_headers = new HeaderCollection(); } return $this->_headers; } @@ -396,7 +396,7 @@ class Response extends \yii\base\Response } foreach ($this->getCookies() as $cookie) { $value = $cookie->value; - if ($cookie->expire != 1 && isset($validationKey)) { + if ($cookie->expire != 1 && isset($validationKey)) { $value = Yii::$app->getSecurity()->hashData(serialize([$cookie->name, $value]), $validationKey); } setcookie($cookie->name, $value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly); @@ -418,7 +418,7 @@ class Response extends \yii\base\Response $chunkSize = 8 * 1024 * 1024; // 8MB per chunk if (is_array($this->stream)) { - list ($handle, $begin, $end) = $this->stream; + list($handle, $begin, $end) = $this->stream; fseek($handle, $begin); while (!feof($handle) && ($pos = ftell($handle)) <= $end) { if ($pos + $chunkSize > $end) { @@ -907,7 +907,7 @@ class Response extends \yii\base\Response public function getCookies() { if ($this->_cookies === null) { - $this->_cookies = new CookieCollection; + $this->_cookies = new CookieCollection(); } return $this->_cookies; } diff --git a/framework/web/Session.php b/framework/web/Session.php index 99c7fb3ee6..2455888ce8 100644 --- a/framework/web/Session.php +++ b/framework/web/Session.php @@ -561,7 +561,7 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co public function getIterator() { $this->open(); - return new SessionIterator; + return new SessionIterator(); } /** diff --git a/framework/web/UploadedFile.php b/framework/web/UploadedFile.php index b3613e2f7c..9ad19823f8 100644 --- a/framework/web/UploadedFile.php +++ b/framework/web/UploadedFile.php @@ -227,7 +227,7 @@ class UploadedFile extends Object foreach ($names as $i => $name) { self::loadFilesRecursive($key . '[' . $i . ']', $name, $tempNames[$i], $types[$i], $sizes[$i], $errors[$i]); } - } elseif ((int)$errors !== UPLOAD_ERR_NO_FILE) { + } elseif ((int) $errors !== UPLOAD_ERR_NO_FILE) { self::$_files[$key] = [ 'name' => $names, 'tempName' => $tempNames, diff --git a/framework/web/UrlNormalizer.php b/framework/web/UrlNormalizer.php index 712d3560c0..739c0d6da6 100644 --- a/framework/web/UrlNormalizer.php +++ b/framework/web/UrlNormalizer.php @@ -8,8 +8,8 @@ namespace yii\web; use Yii; -use yii\base\Object; use yii\base\InvalidConfigException; +use yii\base\Object; /** * UrlNormalizer normalizes URLs for [[UrlManager]] and [[UrlRule]]. diff --git a/framework/web/UrlRule.php b/framework/web/UrlRule.php index 4c3c510bbd..d66595bf21 100644 --- a/framework/web/UrlRule.php +++ b/framework/web/UrlRule.php @@ -385,7 +385,7 @@ class UrlRule extends Object implements UrlRuleInterface return false; } - $suffix = (string)($this->suffix === null ? $manager->suffix : $this->suffix); + $suffix = (string) ($this->suffix === null ? $manager->suffix : $this->suffix); $pathInfo = $request->getPathInfo(); $normalized = false; if ($this->hasNormalizer($manager)) { @@ -545,7 +545,8 @@ class UrlRule extends Object implements UrlRuleInterface * @see $createStatus * @since 2.0.12 */ - public function getCreateUrlStatus() { + public function getCreateUrlStatus() + { return $this->createStatus; } diff --git a/framework/web/User.php b/framework/web/User.php index d671d3808d..c483e81fee 100644 --- a/framework/web/User.php +++ b/framework/web/User.php @@ -558,7 +558,7 @@ class User extends Component } $data = json_decode($value, true); if (count($data) == 3) { - list ($id, $authKey, $duration) = $data; + list($id, $authKey, $duration) = $data; /* @var $class IdentityInterface */ $class = $this->identityClass; $identity = $class::findIdentity($id); diff --git a/framework/web/View.php b/framework/web/View.php index 3f09d09d81..ed8a9a1bb2 100644 --- a/framework/web/View.php +++ b/framework/web/View.php @@ -8,9 +8,9 @@ namespace yii\web; use Yii; +use yii\base\InvalidConfigException; use yii\helpers\ArrayHelper; use yii\helpers\Html; -use yii\base\InvalidConfigException; /** * View represents a view object in the MVC pattern. @@ -411,7 +411,7 @@ class View extends \yii\base\View 'baseUrl' => '', 'css' => [strncmp($url, '//', 2) === 0 ? $url : ltrim($url, '/')], 'cssOptions' => $options, - 'depends' => (array)$depends, + 'depends' => (array) $depends, ]); $this->registerAssetBundle($key); } @@ -479,7 +479,7 @@ class View extends \yii\base\View 'baseUrl' => '', 'js' => [strncmp($url, '//', 2) === 0 ? $url : ltrim($url, '/')], 'jsOptions' => $options, - 'depends' => (array)$depends, + 'depends' => (array) $depends, ]); $this->registerAssetBundle($key); } diff --git a/framework/web/ViewAction.php b/framework/web/ViewAction.php index d4d28987b8..9a45954d09 100644 --- a/framework/web/ViewAction.php +++ b/framework/web/ViewAction.php @@ -80,9 +80,7 @@ class ViewAction extends Action if ($controllerLayout) { $this->controller->layout = $controllerLayout; } - } catch (ViewNotFoundException $e) { - if ($controllerLayout) { $this->controller->layout = $controllerLayout; } diff --git a/framework/web/XmlResponseFormatter.php b/framework/web/XmlResponseFormatter.php index c76b27dfb3..326e6496e0 100644 --- a/framework/web/XmlResponseFormatter.php +++ b/framework/web/XmlResponseFormatter.php @@ -9,8 +9,8 @@ namespace yii\web; use DOMDocument; use DOMElement; -use DOMText; use DOMException; +use DOMText; use yii\base\Arrayable; use yii\base\Component; use yii\helpers\StringHelper; diff --git a/framework/web/migrations/m160313_153426_session_init.php b/framework/web/migrations/m160313_153426_session_init.php index accbbf398a..279ebf9c59 100644 --- a/framework/web/migrations/m160313_153426_session_init.php +++ b/framework/web/migrations/m160313_153426_session_init.php @@ -15,7 +15,6 @@ use yii\db\Migration; */ class m160313_153426_session_init extends Migration { - /** * @inheritdoc */ diff --git a/framework/widgets/ActiveField.php b/framework/widgets/ActiveField.php index 3030a2ddf5..68d634c1a0 100644 --- a/framework/widgets/ActiveField.php +++ b/framework/widgets/ActiveField.php @@ -10,9 +10,9 @@ namespace yii\widgets; use Yii; use yii\base\Component; use yii\base\ErrorHandler; +use yii\base\Model; use yii\helpers\ArrayHelper; use yii\helpers\Html; -use yii\base\Model; use yii\web\JsExpression; /** @@ -799,7 +799,7 @@ class ActiveField extends Component } if (!empty($validators)) { - $options['validate'] = new JsExpression("function (attribute, value, messages, deferred, \$form) {" . implode('', $validators) . '}'); + $options['validate'] = new JsExpression('function (attribute, value, messages, deferred, $form) {' . implode('', $validators) . '}'); } if ($this->addAriaAttributes === false) { @@ -857,7 +857,7 @@ class ActiveField extends Component { if ($this->addAriaAttributes) { if (!isset($options['aria-required']) && $this->model->isAttributeRequired($this->attribute)) { - $options['aria-required'] = 'true'; + $options['aria-required'] = 'true'; } if (!isset($options['aria-invalid'])) { if ($this->model->hasErrors($this->attribute)) { diff --git a/framework/widgets/ActiveForm.php b/framework/widgets/ActiveForm.php index a03e48747f..a65f04f086 100644 --- a/framework/widgets/ActiveForm.php +++ b/framework/widgets/ActiveForm.php @@ -9,12 +9,12 @@ namespace yii\widgets; use Yii; use yii\base\InvalidCallException; -use yii\base\Widget; use yii\base\Model; +use yii\base\Widget; use yii\helpers\ArrayHelper; -use yii\helpers\Url; use yii\helpers\Html; use yii\helpers\Json; +use yii\helpers\Url; /** * ActiveForm is a widget that builds an interactive HTML form for one or multiple data models. diff --git a/framework/widgets/BaseListView.php b/framework/widgets/BaseListView.php index 4abff649b0..f300220665 100644 --- a/framework/widgets/BaseListView.php +++ b/framework/widgets/BaseListView.php @@ -130,7 +130,7 @@ abstract class BaseListView extends Widget public function run() { if ($this->showOnEmpty || $this->dataProvider->getCount() > 0) { - $content = preg_replace_callback("/{\\w+}/", function ($matches) { + $content = preg_replace_callback('/{\\w+}/', function ($matches) { $content = $this->renderSection($matches[0]); return $content === false ? $matches[0] : $content; diff --git a/framework/widgets/Breadcrumbs.php b/framework/widgets/Breadcrumbs.php index 2dfe1d427b..c26f6c6b1a 100644 --- a/framework/widgets/Breadcrumbs.php +++ b/framework/widgets/Breadcrumbs.php @@ -8,8 +8,8 @@ namespace yii\widgets; use Yii; -use yii\base\Widget; use yii\base\InvalidConfigException; +use yii\base\Widget; use yii\helpers\ArrayHelper; use yii\helpers\Html; @@ -110,7 +110,6 @@ class Breadcrumbs extends Widget * 'encode' => false, * ] * ``` - * */ public $links = []; /** diff --git a/framework/widgets/DetailView.php b/framework/widgets/DetailView.php index 4cf8ad1180..30dfa9e85b 100644 --- a/framework/widgets/DetailView.php +++ b/framework/widgets/DetailView.php @@ -9,13 +9,13 @@ namespace yii\widgets; use Yii; use yii\base\Arrayable; -use yii\i18n\Formatter; use yii\base\InvalidConfigException; use yii\base\Model; use yii\base\Widget; use yii\helpers\ArrayHelper; use yii\helpers\Html; use yii\helpers\Inflector; +use yii\i18n\Formatter; /** * DetailView displays the detail of a single data [[model]]. @@ -177,7 +177,7 @@ class DetailView extends Widget '{label}' => $attribute['label'], '{value}' => $this->formatter->format($attribute['value'], $attribute['format']), '{captionOptions}' => $captionOptions, - '{contentOptions}' => $contentOptions, + '{contentOptions}' => $contentOptions, ]); } else { return call_user_func($this->template, $attribute, $index, $this); diff --git a/framework/widgets/FragmentCache.php b/framework/widgets/FragmentCache.php index 875ac43467..e7cd5d5e01 100644 --- a/framework/widgets/FragmentCache.php +++ b/framework/widgets/FragmentCache.php @@ -150,7 +150,7 @@ class FragmentCache extends Widget return $this->_content; } - list ($this->_content, $placeholders) = $data; + list($this->_content, $placeholders) = $data; if (!is_array($placeholders) || count($placeholders) === 0) { return $this->_content; } diff --git a/framework/widgets/InputWidget.php b/framework/widgets/InputWidget.php index f067502e2a..f59b4ec52a 100644 --- a/framework/widgets/InputWidget.php +++ b/framework/widgets/InputWidget.php @@ -8,9 +8,9 @@ namespace yii\widgets; use Yii; -use yii\base\Widget; -use yii\base\Model; use yii\base\InvalidConfigException; +use yii\base\Model; +use yii\base\Widget; use yii\helpers\Html; /** diff --git a/framework/widgets/LinkPager.php b/framework/widgets/LinkPager.php index 52270d119d..a7e5a2c1f6 100644 --- a/framework/widgets/LinkPager.php +++ b/framework/widgets/LinkPager.php @@ -9,10 +9,10 @@ namespace yii\widgets; use Yii; use yii\base\InvalidConfigException; -use yii\helpers\Html; use yii\base\Widget; use yii\data\Pagination; use yii\helpers\ArrayHelper; +use yii\helpers\Html; /** * LinkPager displays a list of hyperlinks that lead to different pages of target. diff --git a/framework/widgets/MaskedInput.php b/framework/widgets/MaskedInput.php index 7fa7a2f5cd..9c4bd40c9c 100644 --- a/framework/widgets/MaskedInput.php +++ b/framework/widgets/MaskedInput.php @@ -156,8 +156,12 @@ class MaskedInput extends InputWidget { $options = $this->clientOptions; foreach ($options as $key => $value) { - if (!$value instanceof JsExpression && in_array($key, ['oncomplete', 'onincomplete', 'oncleared', 'onKeyUp', - 'onKeyDown', 'onBeforeMask', 'onBeforePaste', 'onUnMask', 'isComplete', 'determineActiveMasksetIndex'], true) + if ( + !$value instanceof JsExpression + && in_array($key, [ + 'oncomplete', 'onincomplete', 'oncleared', 'onKeyUp', 'onKeyDown', 'onBeforeMask', + 'onBeforePaste', 'onUnMask', 'isComplete', 'determineActiveMasksetIndex', + ], true) ) { $options[$key] = new JsExpression($value); } diff --git a/framework/widgets/MaskedInputAsset.php b/framework/widgets/MaskedInputAsset.php index 2325571a52..357c5e7a9f 100644 --- a/framework/widgets/MaskedInputAsset.php +++ b/framework/widgets/MaskedInputAsset.php @@ -21,9 +21,9 @@ class MaskedInputAsset extends AssetBundle { public $sourcePath = '@bower/jquery.inputmask/dist'; public $js = [ - 'jquery.inputmask.bundle.js' + 'jquery.inputmask.bundle.js', ]; public $depends = [ - 'yii\web\YiiAsset' + 'yii\web\YiiAsset', ]; } diff --git a/framework/widgets/Menu.php b/framework/widgets/Menu.php index db678d46d4..9869650b76 100644 --- a/framework/widgets/Menu.php +++ b/framework/widgets/Menu.php @@ -11,8 +11,8 @@ use Closure; use Yii; use yii\base\Widget; use yii\helpers\ArrayHelper; -use yii\helpers\Url; use yii\helpers\Html; +use yii\helpers\Url; /** * Menu displays a multi-level menu using nested HTML lists. diff --git a/tests/IsOneOfAssert.php b/tests/IsOneOfAssert.php index 3ca85d24d6..3bd7ce0356 100644 --- a/tests/IsOneOfAssert.php +++ b/tests/IsOneOfAssert.php @@ -1,4 +1,9 @@ $this->getVendorPath(), 'aliases' => [ '@bower' => '@vendor/bower-asset', - '@npm' => '@vendor/npm-asset', + '@npm' => '@vendor/npm-asset', ], 'components' => [ 'request' => [ @@ -78,7 +83,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase 'scriptFile' => __DIR__ . '/index.php', 'scriptUrl' => '/index.php', ], - ] + ], ], $config)); } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index a1aebe79b7..db6bb10537 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -1,4 +1,9 @@ does = 'meow'; } - } diff --git a/tests/data/ar/Customer.php b/tests/data/ar/Customer.php index a451dc3440..216d6e197e 100644 --- a/tests/data/ar/Customer.php +++ b/tests/data/ar/Customer.php @@ -1,4 +1,10 @@ does = 'bark'; } - } diff --git a/tests/data/ar/Item.php b/tests/data/ar/Item.php index 4b4977a096..f2447c365e 100644 --- a/tests/data/ar/Item.php +++ b/tests/data/ar/Item.php @@ -1,4 +1,9 @@ 'customer_id' + 0 => 'customer_id', ]; } } diff --git a/tests/data/ar/OrderItem.php b/tests/data/ar/OrderItem.php index 5a1492f2bc..117abbe984 100644 --- a/tests/data/ar/OrderItem.php +++ b/tests/data/ar/OrderItem.php @@ -1,4 +1,9 @@ hasOne(OrderItem::className(), ['item_id' => 'item_id', 'order_id' => 'order_id' ]) + return $this->hasOne(self::className(), ['item_id' => 'item_id', 'order_id' => 'order_id']) ->joinWith('item'); } public function getOrderItemCompositeNoJoin() { - return $this->hasOne(OrderItem::className(), ['item_id' => 'item_id', 'order_id' => 'order_id' ]); + return $this->hasOne(self::className(), ['item_id' => 'item_id', 'order_id' => 'order_id']); } } diff --git a/tests/data/ar/OrderItemWithNullFK.php b/tests/data/ar/OrderItemWithNullFK.php index 52cbc445fd..09c34946e9 100644 --- a/tests/data/ar/OrderItemWithNullFK.php +++ b/tests/data/ar/OrderItemWithNullFK.php @@ -1,4 +1,9 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\data\ar; @@ -10,7 +12,6 @@ namespace yiiunit\data\ar; * * @property int $id * @property string $description - * */ class Profile extends ActiveRecord { diff --git a/tests/data/ar/Type.php b/tests/data/ar/Type.php index 0c5c69fe05..0b86110aeb 100644 --- a/tests/data/ar/Type.php +++ b/tests/data/ar/Type.php @@ -1,4 +1,9 @@ 'Lennon'], [['lastName'], 'required'], [['underscore_style'], 'yii\captcha\CaptchaValidator'], - [['test'], 'required', 'when' => function($model) { return $model->firstName === 'cebe'; }], + [['test'], 'required', 'when' => function ($model) { return $model->firstName === 'cebe'; }], ]; } } diff --git a/tests/data/base/Speaker.php b/tests/data/base/Speaker.php index 5e801110e9..2bd3a65aaa 100644 --- a/tests/data/base/Speaker.php +++ b/tests/data/base/Speaker.php @@ -1,4 +1,10 @@ * @since 2.0.11 @@ -17,4 +21,4 @@ class MockDependency extends Dependency { return $this->data; } -} \ No newline at end of file +} diff --git a/tests/data/config-docker.php b/tests/data/config-docker.php index 606f984e0e..cef8189f9c 100644 --- a/tests/data/config-docker.php +++ b/tests/data/config-docker.php @@ -1,4 +1,9 @@ [ 'cubrid' => [ @@ -56,4 +58,4 @@ if (is_file(__DIR__ . '/config.local.php')) { include(__DIR__ . '/config.local.php'); } -return $config; \ No newline at end of file +return $config; diff --git a/tests/data/config.php b/tests/data/config.php index 107258621f..60cddd1774 100644 --- a/tests/data/config.php +++ b/tests/data/config.php @@ -1,4 +1,9 @@ [ 'cubrid' => [ @@ -56,4 +58,4 @@ if (is_file(__DIR__ . '/config.local.php')) { include(__DIR__ . '/config.local.php'); } -return $config; \ No newline at end of file +return $config; diff --git a/tests/data/console/controllers/fixtures/FirstFixture.php b/tests/data/console/controllers/fixtures/FirstFixture.php index d97b542dde..49e3f68da0 100644 --- a/tests/data/console/controllers/fixtures/FirstFixture.php +++ b/tests/data/console/controllers/fixtures/FirstFixture.php @@ -1,4 +1,9 @@ 3, 'extensions' => ['png'], 'on' => 'validateMultipleFiles', 'checkExtensionByMimeType' => false], ['attr_image', 'file', 'extensions' => ['png'], 'on' => 'validateFile', 'checkExtensionByMimeType' => false], - ['!safe_attr', 'integer'] + ['!safe_attr', 'integer'], ]; } diff --git a/tests/data/validators/models/ValidatorTestMainModel.php b/tests/data/validators/models/ValidatorTestMainModel.php index 7031e3fb9b..141fed28c1 100644 --- a/tests/data/validators/models/ValidatorTestMainModel.php +++ b/tests/data/validators/models/ValidatorTestMainModel.php @@ -1,4 +1,9 @@ Name: diff --git a/tests/data/views/errorHandler.php b/tests/data/views/errorHandler.php index 79e5566bf4..0e34d618fd 100644 --- a/tests/data/views/errorHandler.php +++ b/tests/data/views/errorHandler.php @@ -1,12 +1,10 @@ Code: response->statusCode ?> Message: getMessage() ?> -Exception: \ No newline at end of file +Exception: diff --git a/tests/data/views/widgets/ListView/item.php b/tests/data/views/widgets/ListView/item.php index 5ac7564996..f543715af5 100644 --- a/tests/data/views/widgets/ListView/item.php +++ b/tests/data/views/widgets/ListView/item.php @@ -1,10 +1,13 @@ className(); diff --git a/tests/framework/BaseYiiTest.php b/tests/framework/BaseYiiTest.php index 38df4fb6af..8216ed57ee 100644 --- a/tests/framework/BaseYiiTest.php +++ b/tests/framework/BaseYiiTest.php @@ -1,4 +1,10 @@ assertTrue(is_string(Yii::powered())); + $this->assertInternalType('string', Yii::powered()); } public function testCreateObjectCallable() @@ -70,19 +76,19 @@ class BaseYiiTest extends TestCase Yii::$container = new Container(); // Test passing in of normal params combined with DI params. - $this->assertTrue(Yii::createObject(function(Singer $singer, $a) { + $this->assertTrue(Yii::createObject(function (Singer $singer, $a) { return $a === 'a'; }, ['a'])); $singer = new Singer(); $singer->firstName = 'Bob'; - $this->assertTrue(Yii::createObject(function(Singer $singer, $a) { + $this->assertTrue(Yii::createObject(function (Singer $singer, $a) { return $singer->firstName === 'Bob'; }, [$singer, 'a'])); - $this->assertTrue(Yii::createObject(function(Singer $singer, $a = 3) { + $this->assertTrue(Yii::createObject(function (Singer $singer, $a = 3) { return true; })); } @@ -125,19 +131,19 @@ class BaseYiiTest extends TestCase [ $this->equalTo('warning message'), $this->equalTo(Logger::LEVEL_WARNING), - $this->equalTo('warning category') + $this->equalTo('warning category'), ], [$this->equalTo('trace message'), $this->equalTo(Logger::LEVEL_TRACE), $this->equalTo('trace category')], [$this->equalTo('error message'), $this->equalTo(Logger::LEVEL_ERROR), $this->equalTo('error category')], [ $this->equalTo('beginProfile message'), $this->equalTo(Logger::LEVEL_PROFILE_BEGIN), - $this->equalTo('beginProfile category') + $this->equalTo('beginProfile category'), ], [ $this->equalTo('endProfile message'), $this->equalTo(Logger::LEVEL_PROFILE_END), - $this->equalTo('endProfile category') + $this->equalTo('endProfile category'), ] ); diff --git a/tests/framework/ar/ActiveRecordTestTrait.php b/tests/framework/ar/ActiveRecordTestTrait.php index af014f46f0..2e76ba5977 100644 --- a/tests/framework/ar/ActiveRecordTestTrait.php +++ b/tests/framework/ar/ActiveRecordTestTrait.php @@ -1,17 +1,17 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\framework\ar; use yii\base\Event; use yii\db\BaseActiveRecord; -use yiiunit\TestCase; use yiiunit\data\ar\Customer; use yiiunit\data\ar\Order; +use yiiunit\TestCase; /** * This trait provides unit tests shared by the different AR implementations. @@ -151,7 +151,7 @@ trait ActiveRecordTestTrait /* @var $customerClass \yii\db\ActiveRecordInterface */ $customerClass = $this->getCustomerClass(); - $customer = new $customerClass; + $customer = new $customerClass(); $this->assertTrue($customer->hasAttribute('id')); $this->assertTrue($customer->hasAttribute('email')); $this->assertFalse($customer->hasAttribute(0)); @@ -369,7 +369,6 @@ trait ActiveRecordTestTrait $customer = $customerClass::find()->offset(3)->one(); $this->assertNull($customer); - } public function testFindComplexCondition() @@ -671,7 +670,7 @@ trait ActiveRecordTestTrait $this->assertCount(2, $customer->orders); // has many - $order = new $orderClass; + $order = new $orderClass(); $order->total = 100; $this->assertTrue($order->isNewRecord); $customer->link('orders', $order); @@ -682,7 +681,7 @@ trait ActiveRecordTestTrait $this->assertEquals(2, $order->customer_id); // belongs to - $order = new $orderClass; + $order = new $orderClass(); $order->total = 100; $this->assertTrue($order->isNewRecord); $customer = $customerClass::findOne(1); @@ -818,7 +817,7 @@ trait ActiveRecordTestTrait $this->assertCount(2, $order->booksWithNullFK); $orderItemCount = $orderItemsWithNullFKClass::find()->count(); $this->assertEquals(5, $itemClass::find()->count()); - $order->unlinkAll('booksWithNullFK',false); + $order->unlinkAll('booksWithNullFK', false); $this->afterSave(); $this->assertCount(0, $order->booksWithNullFK); $this->assertEquals(2, $orderItemsWithNullFKClass::find()->where(['AND', ['item_id' => [1, 2]], ['order_id' => null]])->count()); @@ -888,7 +887,7 @@ trait ActiveRecordTestTrait /* @var $customerClass \yii\db\ActiveRecordInterface */ $customerClass = $this->getCustomerClass(); /* @var $this TestCase|ActiveRecordTestTrait */ - $customer = new $customerClass; + $customer = new $customerClass(); $customer->email = 'user4@example.com'; $customer->name = 'user4'; $customer->address = 'address4'; @@ -912,7 +911,7 @@ trait ActiveRecordTestTrait /* @var $customerClass \yii\db\ActiveRecordInterface */ $customerClass = $this->getCustomerClass(); /* @var $this TestCase|ActiveRecordTestTrait */ - $customer = new $customerClass; + $customer = new $customerClass(); $customer->id = 1337; $customer->email = 'user1337@example.com'; $customer->name = 'user1337'; @@ -1261,12 +1260,10 @@ trait ActiveRecordTestTrait $this->assertFalse($customer->canSetProperty('orderItems')); try { - /* @var $itemClass \yii\db\ActiveRecordInterface */ $itemClass = $this->getItemClass(); $customer->orderItems = [new $itemClass()]; $this->fail('setter call above MUST throw Exception'); - } catch (\Exception $e) { // catch exception "Setting read-only property" $this->assertInstanceOf('yii\base\InvalidCallException', $e); @@ -1278,5 +1275,4 @@ trait ActiveRecordTestTrait $this->assertFalse($customer->canGetProperty('non_existing_property')); $this->assertFalse($customer->canSetProperty('non_existing_property')); } - } diff --git a/tests/framework/base/ActionFilterTest.php b/tests/framework/base/ActionFilterTest.php index 0b81ae3728..0f86d9f6db 100644 --- a/tests/framework/base/ActionFilterTest.php +++ b/tests/framework/base/ActionFilterTest.php @@ -14,7 +14,6 @@ use yii\base\Controller; use yii\web\User; use yiiunit\TestCase; - /** * @group base */ @@ -243,4 +242,4 @@ class MockUser extends User { // do not call parent to avoid the need to mock configuration } -} \ No newline at end of file +} diff --git a/tests/framework/base/ApplicationTest.php b/tests/framework/base/ApplicationTest.php index 6071705ab7..f3ce06cabb 100644 --- a/tests/framework/base/ApplicationTest.php +++ b/tests/framework/base/ApplicationTest.php @@ -1,4 +1,9 @@ mockApplication([ 'container' => [ 'definitions' => [ - Dispatcher::className() => DispatcherMock::className() - ] + Dispatcher::className() => DispatcherMock::className(), + ], ], - 'bootstrap' => ['log'] + 'bootstrap' => ['log'], ]); $this->assertInstanceOf(DispatcherMock::className(), Yii::$app->log); @@ -28,5 +33,4 @@ class ApplicationTest extends TestCase class DispatcherMock extends Dispatcher { - } diff --git a/tests/framework/base/BehaviorTest.php b/tests/framework/base/BehaviorTest.php index d923184e4d..ecfeb2330d 100644 --- a/tests/framework/base/BehaviorTest.php +++ b/tests/framework/base/BehaviorTest.php @@ -1,4 +1,9 @@ on('click', 'yiiunit\framework\base\globalEventHandler2'); $component->on('click', [$this->component, 'myEventHandler']); $component->raiseEvent(); @@ -232,12 +238,12 @@ class ComponentTest extends TestCase public function testAttachBehavior() { - $component = new NewComponent; + $component = new NewComponent(); $this->assertFalse($component->hasProperty('p')); $this->assertFalse($component->behaviorCalled); $this->assertNull($component->getBehavior('a')); - $behavior = new NewBehavior; + $behavior = new NewBehavior(); $component->attachBehavior('a', $behavior); $this->assertSame($behavior, $component->getBehavior('a')); $this->assertTrue($component->hasProperty('p')); @@ -250,7 +256,7 @@ class ComponentTest extends TestCase $component->test(); $p = 'as b'; - $component = new NewComponent; + $component = new NewComponent(); $component->$p = ['class' => 'NewBehavior']; $this->assertSame($behavior, $component->getBehavior('a')); $this->assertTrue($component->hasProperty('p')); @@ -260,11 +266,11 @@ class ComponentTest extends TestCase public function testAttachBehaviors() { - $component = new NewComponent; + $component = new NewComponent(); $this->assertNull($component->getBehavior('a')); $this->assertNull($component->getBehavior('b')); - $behavior = new NewBehavior; + $behavior = new NewBehavior(); $component->attachBehaviors([ 'a' => $behavior, @@ -276,8 +282,8 @@ class ComponentTest extends TestCase public function testDetachBehavior() { - $component = new NewComponent; - $behavior = new NewBehavior; + $component = new NewComponent(); + $behavior = new NewBehavior(); $component->attachBehavior('a', $behavior); $this->assertSame($behavior, $component->getBehavior('a')); @@ -292,8 +298,8 @@ class ComponentTest extends TestCase public function testDetachBehaviors() { - $component = new NewComponent; - $behavior = new NewBehavior; + $component = new NewComponent(); + $behavior = new NewBehavior(); $component->attachBehavior('a', $behavior); $this->assertSame($behavior, $component->getBehavior('a')); @@ -316,7 +322,7 @@ class ComponentTest extends TestCase { $this->assertNull($this->component->getBehavior('a')); - $behavior = new NewBehavior; + $behavior = new NewBehavior(); $this->component->attachBehaviors([ 'a' => $behavior, ]); @@ -330,8 +336,8 @@ class ComponentTest extends TestCase $behaviorName = 'foo'; $this->assertNull($this->component->getBehavior($behaviorName)); $p = 'as ' . $behaviorName; - $this->component->$p = __NAMESPACE__ . '\NewBehavior'; - $this->assertSame(__NAMESPACE__ . '\NewBehavior', get_class($this->component->getBehavior($behaviorName))); + $this->component->$p = __NAMESPACE__ . '\NewBehavior'; + $this->assertSame(__NAMESPACE__ . '\NewBehavior', get_class($this->component->getBehavior($behaviorName))); } public function testWriteOnlyProperty() @@ -373,7 +379,7 @@ class NewComponent extends Component public function getObject() { if (!$this->_object) { - $this->_object = new self; + $this->_object = new self(); $this->_object->_text = 'object text'; } @@ -404,7 +410,7 @@ class NewComponent extends Component public function raiseEvent() { - $this->trigger('click', new Event); + $this->trigger('click', new Event()); } public function setWriteOnly() diff --git a/tests/framework/base/ControllerTest.php b/tests/framework/base/ControllerTest.php index fdf742ecaf..9a6db5400c 100644 --- a/tests/framework/base/ControllerTest.php +++ b/tests/framework/base/ControllerTest.php @@ -1,4 +1,9 @@ action->uniqueId; return 'test2'; } -} \ No newline at end of file +} diff --git a/tests/framework/base/DynamicModelTest.php b/tests/framework/base/DynamicModelTest.php index d4ca3397f5..8f03625d6b 100644 --- a/tests/framework/base/DynamicModelTest.php +++ b/tests/framework/base/DynamicModelTest.php @@ -83,13 +83,13 @@ class DynamicModelTest extends TestCase $dynamic->defineAttribute('name'); $dynamic->defineAttribute('mobile'); // define rule - $dynamic->addRule(['name','mobile'], 'required'); + $dynamic->addRule(['name', 'mobile'], 'required'); // define your sample data $data = [ 'DynamicModel' => [ 'name' => $name = 'your name 2', 'mobile' => $mobile = 'my number mobile', - ] + ], ]; // load data $this->assertFalse($dynamic->load([])); diff --git a/tests/framework/base/EventTest.php b/tests/framework/base/EventTest.php index 3d9abcf223..0f876ed338 100644 --- a/tests/framework/base/EventTest.php +++ b/tests/framework/base/EventTest.php @@ -42,10 +42,10 @@ class EventTest extends TestCase $this->counter += 5; }); $this->assertEquals(0, $this->counter); - $post = new Post; + $post = new Post(); $post->save(); $this->assertEquals(4, $this->counter); - $user = new User; + $user = new User(); $user->save(); $this->assertEquals(7, $this->counter); $someClass = new SomeClass(); @@ -59,7 +59,7 @@ class EventTest extends TestCase public function testOff() { $handler = function ($event) { - $this->counter ++; + $this->counter++; }; $this->assertFalse(Event::hasHandlers(Post::className(), 'save')); Event::on(Post::className(), 'save', $handler); @@ -77,7 +77,7 @@ class EventTest extends TestCase $this->counter += 1; }); Event::on('yiiunit\framework\base\SomeInterface', SomeInterface::EVENT_SUPER_EVENT, function ($event) { - $this->counter ++; + $this->counter++; }); $this->assertTrue(Event::hasHandlers(Post::className(), 'save')); $this->assertFalse(Event::hasHandlers(ActiveRecord::className(), 'save')); diff --git a/tests/framework/base/ExposedSecurity.php b/tests/framework/base/ExposedSecurity.php index 431e123924..db4408f14c 100644 --- a/tests/framework/base/ExposedSecurity.php +++ b/tests/framework/base/ExposedSecurity.php @@ -1,6 +1,11 @@ setScenario('test'); $this->assertTrue($speaker->isAttributeSafe('firstName')); - } public function testSafeScenarios() @@ -180,7 +184,7 @@ class ModelTest extends TestCase [['account_id', 'user_id'], 'required'], // only in create and update scenario [['user_id'], 'number', 'on' => ['create', 'update']], - [['email', 'name'], 'required', 'on' => 'create'] + [['email', 'name'], 'required', 'on' => 'create'], ]; $model->scenario = Model::SCENARIO_DEFAULT; $this->assertEquals(['account_id', 'user_id'], $model->safeAttributes()); @@ -236,7 +240,7 @@ class ModelTest extends TestCase $model = new RulesModel(); $model->rules = [ [['name', 'email'], 'required'], - [['!email'], 'safe'] + [['!email'], 'safe'], ]; $this->assertEquals(['name'], $model->safeAttributes()); $model->attributes = ['name' => 'mdmunir', 'email' => 'm2792684@mdm.com']; @@ -246,7 +250,7 @@ class ModelTest extends TestCase $model->rules = [ [['name', 'email'], 'required'], [['email'], 'email'], - [['!email'], 'safe', 'on' => 'update'] + [['!email'], 'safe', 'on' => 'update'], ]; $model->setScenario(RulesModel::SCENARIO_DEFAULT); $this->assertEquals(['name', 'email'], $model->safeAttributes()); @@ -325,7 +329,7 @@ class ModelTest extends TestCase $singer->clearErrors(); $errors = [ 'firstName' => ['Something is wrong!'], - 'lastName' => ['Another one!'] + 'lastName' => ['Another one!'], ]; $singer->addErrors($errors); $this->assertEquals($singer->getErrors(), $errors); @@ -333,7 +337,7 @@ class ModelTest extends TestCase $singer->clearErrors(); $errors = [ 'firstName' => ['Something is wrong!', 'Totally wrong!'], - 'lastName' => ['Another one!'] + 'lastName' => ['Another one!'], ]; $singer->addErrors($errors); $this->assertEquals($singer->getErrors(), $errors); @@ -341,7 +345,7 @@ class ModelTest extends TestCase $singer->clearErrors(); $errors = [ 'firstName' => ['Something is wrong!', 'Totally wrong!'], - 'lastName' => ['Another one!', 'Totally wrong!'] + 'lastName' => ['Another one!', 'Totally wrong!'], ]; $singer->addErrors($errors); $this->assertEquals($singer->getErrors(), $errors); @@ -488,4 +492,4 @@ class WriteOnlyModel extends Model { $this->passwordHash = $pw; } -} \ No newline at end of file +} diff --git a/tests/framework/base/ModuleTest.php b/tests/framework/base/ModuleTest.php index c2348c1450..d00988e969 100644 --- a/tests/framework/base/ModuleTest.php +++ b/tests/framework/base/ModuleTest.php @@ -1,4 +1,9 @@ assertEquals('yiiunit\framework\base\controllers', $module->controllerNamespace); - $this->assertEquals(__DIR__ . DIRECTORY_SEPARATOR . 'controllers', str_replace(['/','\\'], DIRECTORY_SEPARATOR , $module->controllerPath)); + $this->assertEquals(__DIR__ . DIRECTORY_SEPARATOR . 'controllers', str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $module->controllerPath)); } public function testSetupVersion() @@ -32,7 +37,7 @@ class ModuleTest extends TestCase $module->setVersion($version); $this->assertEquals($version, $module->getVersion()); - $module->setVersion(function($module) { + $module->setVersion(function ($module) { /* @var $module TestModule */ return 'version.' . $module->getUniqueId(); }); @@ -99,4 +104,4 @@ class ModuleTestController extends Controller { ModuleTest::$actionRuns[] = $this->action->uniqueId; } -} \ No newline at end of file +} diff --git a/tests/framework/base/ObjectTest.php b/tests/framework/base/ObjectTest.php index 10320f96eb..d02acae182 100644 --- a/tests/framework/base/ObjectTest.php +++ b/tests/framework/base/ObjectTest.php @@ -1,4 +1,10 @@ mockApplication(); - $this->object = new NewObject; + $this->object = new NewObject(); } protected function tearDown() @@ -94,7 +100,8 @@ class ObjectTest extends TestCase $this->assertEmpty($this->object->Text); $this->assertFalse(isset($this->object->unknownProperty)); - $this->assertTrue(empty($this->object->unknownProperty)); + $isEmpty = empty($this->object->unknownProperty); + $this->assertTrue($isEmpty); } public function testUnset() @@ -175,7 +182,7 @@ class NewObject extends Object public function getObject() { if (!$this->_object) { - $this->_object = new self; + $this->_object = new self(); $this->_object->_text = 'object text'; } @@ -194,5 +201,7 @@ class NewObject extends Object return $this->_items; } - public function setWriteOnly() {} + public function setWriteOnly() + { + } } diff --git a/tests/framework/base/SecurityTest.php b/tests/framework/base/SecurityTest.php index c872f4387d..0c18514e7b 100644 --- a/tests/framework/base/SecurityTest.php +++ b/tests/framework/base/SecurityTest.php @@ -13,8 +13,8 @@ namespace yii\base { * * This function overrides function_exists from the root namespace in yii\base. */ - function function_exists($name) { - + function function_exists($name) + { if (isset(\yiiunit\framework\base\SecurityTest::$functions[$name])) { return \yiiunit\framework\base\SecurityTest::$functions[$name]; } @@ -26,13 +26,15 @@ namespace yii\base { * * This function overrides fopen and fread from the root namespace in yii\base. */ - function fopen($filename, $mode) { + function fopen($filename, $mode) + { if (\yiiunit\framework\base\SecurityTest::$fopen !== null) { return \yiiunit\framework\base\SecurityTest::$fopen; } return \fopen($filename, $mode); } - function fread($handle, $length) { + function fread($handle, $length) + { if (\yiiunit\framework\base\SecurityTest::$fread !== null) { return \yiiunit\framework\base\SecurityTest::$fread; } @@ -41,7 +43,6 @@ namespace yii\base { } return \fread($handle, $length); } - } // closing namespace yii\base; namespace yiiunit\framework\base { @@ -863,11 +864,11 @@ TEXT; public function randomKeyInvalidInputs() { return [ - [ 0 ], - [ -1 ], - [ '0' ], - [ '34' ], - [ [] ], + [0], + [-1], + ['0'], + ['34'], + [[]], ]; } @@ -885,7 +886,7 @@ TEXT; */ public function testRandomKeyNoOptions() { - static::$functions = ['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false ]; + static::$functions = ['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false]; static::$fopen = false; $this->expectException('yii\base\Exception'); $this->expectExceptionMessage('Unable to generate a random key'); @@ -898,7 +899,7 @@ TEXT; */ public function testRandomKeyFreadFailure() { - static::$functions = ['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false ]; + static::$functions = ['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false]; static::$fread = false; $this->expectException('yii\base\Exception'); $this->expectExceptionMessage('Unable to generate a random key'); @@ -912,14 +913,14 @@ TEXT; public function randomKeyVariants() { return [ - [ ['random_bytes' => true, 'openssl_random_pseudo_bytes' => true, 'mcrypt_create_iv' => true ] ], - [ ['random_bytes' => true, 'openssl_random_pseudo_bytes' => true, 'mcrypt_create_iv' => false ] ], - [ ['random_bytes' => true, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => true ] ], - [ ['random_bytes' => true, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false ] ], - [ ['random_bytes' => false, 'openssl_random_pseudo_bytes' => true, 'mcrypt_create_iv' => true ] ], - [ ['random_bytes' => false, 'openssl_random_pseudo_bytes' => true, 'mcrypt_create_iv' => false ] ], - [ ['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => true ] ], - [ ['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false ] ], + [['random_bytes' => true, 'openssl_random_pseudo_bytes' => true, 'mcrypt_create_iv' => true]], + [['random_bytes' => true, 'openssl_random_pseudo_bytes' => true, 'mcrypt_create_iv' => false]], + [['random_bytes' => true, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => true]], + [['random_bytes' => true, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false]], + [['random_bytes' => false, 'openssl_random_pseudo_bytes' => true, 'mcrypt_create_iv' => true]], + [['random_bytes' => false, 'openssl_random_pseudo_bytes' => true, 'mcrypt_create_iv' => false]], + [['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => true]], + [['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false]], ]; } @@ -934,7 +935,7 @@ TEXT; } } // there is no /dev/urandom on windows so we expect this to fail - if (DIRECTORY_SEPARATOR === '\\' && $functions['random_bytes'] === false && $functions['openssl_random_pseudo_bytes'] === false && $functions['mcrypt_create_iv'] === false ) { + if (DIRECTORY_SEPARATOR === '\\' && $functions['random_bytes'] === false && $functions['openssl_random_pseudo_bytes'] === false && $functions['mcrypt_create_iv'] === false) { $this->expectException('yii\base\Exception'); $this->expectExceptionMessage('Unable to generate a random key'); } @@ -998,10 +999,10 @@ TEXT; $tests = [ "function_exists('random_bytes')", "defined('OPENSSL_VERSION_TEXT') ? OPENSSL_VERSION_TEXT : null", - "PHP_VERSION_ID", - "PHP_OS", + 'PHP_VERSION_ID', + 'PHP_OS', "function_exists('mcrypt_create_iv') ? bin2hex(mcrypt_create_iv(4, MCRYPT_DEV_URANDOM)) : null", - "DIRECTORY_SEPARATOR", + 'DIRECTORY_SEPARATOR', "ini_get('open_basedir')", ]; if (DIRECTORY_SEPARATOR === '/') { @@ -1045,7 +1046,7 @@ TEXT; 'salt', 1, 20, - '0c60c80f961f0e71f3a9b524af6012062fe037a6' + '0c60c80f961f0e71f3a9b524af6012062fe037a6', ], [ 'sha1', @@ -1053,7 +1054,7 @@ TEXT; 'salt', 2, 20, - 'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957' + 'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957', ], [ 'sha1', @@ -1061,7 +1062,7 @@ TEXT; 'salt', 4096, 20, - '4b007901b765489abead49d926f721d065a429c1' + '4b007901b765489abead49d926f721d065a429c1', ], [ 'sha1', @@ -1069,7 +1070,7 @@ TEXT; 'salt', 16777216, 20, - 'eefe3d61cd4da4e4e9945b3d6ba2158c2634e984' + 'eefe3d61cd4da4e4e9945b3d6ba2158c2634e984', ], [ 'sha1', @@ -1077,7 +1078,7 @@ TEXT; 'saltSALTsaltSALTsaltSALTsaltSALTsalt', 4096, 25, - '3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038' + '3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038', ], [ 'sha1', @@ -1085,7 +1086,7 @@ TEXT; "sa\0lt", 4096, 16, - '56fa6aa75548099dcc37d7f03425e0c3' + '56fa6aa75548099dcc37d7f03425e0c3', ], [ 'sha256', @@ -1093,7 +1094,7 @@ TEXT; 'salt', 1, 20, - '120fb6cffcf8b32c43e7225256c4f837a86548c9' + '120fb6cffcf8b32c43e7225256c4f837a86548c9', ], [ 'sha256', @@ -1101,7 +1102,7 @@ TEXT; "sa\0lt", 4096, 32, - '89b69d0516f829893c696226650a86878c029ac13ee276509d5ae58b6466a724' + '89b69d0516f829893c696226650a86878c029ac13ee276509d5ae58b6466a724', ], [ 'sha256', @@ -1109,7 +1110,7 @@ TEXT; 'saltSALTsaltSALTsaltSALTsaltSALTsalt', 4096, 40, - '348c89dbcbd32b2f32d814b8116e84cf2b17347ebc1800181c4e2a1fb8dd53e1c635518c7dac47e9' + '348c89dbcbd32b2f32d814b8116e84cf2b17347ebc1800181c4e2a1fb8dd53e1c635518c7dac47e9', ], ]; } @@ -1197,7 +1198,7 @@ TEXT; 'L' => 42, 'PRK' => '2adccada18779e7c2077ad2eb19d3f3e731385dd', 'OKM' => '2c91117204d745f3500d636a62f64f0ab3bae548aa53d423b0d1f27ebba6f5e5673a081d70cce7acfc48', - ] + ], ]; } @@ -1221,26 +1222,26 @@ TEXT; public function dataProviderCompareStrings() { return [ - ["", ""], - [false, ""], - [null, ""], - [0, ""], - [0.00, ""], - ["", null], - ["", false], - ["", 0], - ["", "\0"], - ["\0", ""], + ['', ''], + [false, ''], + [null, ''], + [0, ''], + [0.00, ''], + ['', null], + ['', false], + ['', 0], + ['', "\0"], + ["\0", ''], ["\0", "\0"], - ["0", "\0"], + ['0', "\0"], [0, "\0"], - ["user", "User"], - ["password", "password"], - ["password", "passwordpassword"], - ["password1", "password"], - ["password", "password2"], - ["", "password"], - ["password", ""], + ['user', 'User'], + ['password', 'password'], + ['password', 'passwordpassword'], + ['password1', 'password'], + ['password', 'password2'], + ['', 'password'], + ['password', ''], ]; } @@ -1282,15 +1283,14 @@ TEXT; /** * @return array */ - public function maskProvider() { + public function maskProvider() + { return [ ['1'], ['SimpleToken'], ['Token with special characters: %d1 5"'], - ['Token with UTF8 character: †'] + ['Token with UTF8 character: †'], ]; } } - } // closing namespace yiiunit\framework\base; - diff --git a/tests/framework/base/ThemeTest.php b/tests/framework/base/ThemeTest.php index 942bd1649c..006f516008 100644 --- a/tests/framework/base/ThemeTest.php +++ b/tests/framework/base/ThemeTest.php @@ -1,10 +1,15 @@ assertEquals($obInitialLevel, ob_get_level()); } -} \ No newline at end of file +} diff --git a/tests/framework/base/fixtures/themes/basic/views/site/index.php b/tests/framework/base/fixtures/themes/basic/views/site/index.php index b3d9bbc7f3..d63e9ec967 100644 --- a/tests/framework/base/fixtures/themes/basic/views/site/index.php +++ b/tests/framework/base/fixtures/themes/basic/views/site/index.php @@ -1 +1,6 @@ [ 'class' => '\yii\db\Connection', 'dsn' => 'sqlite::memory:', - ] - ] + ], + ], ]); $columns = [ @@ -96,8 +101,7 @@ class AttributeBehaviorTest extends TestCase $preserveNonEmptyValues, $name, $alias - ) - { + ) { $model = new ActiveRecordWithAttributeBehavior(); $model->attributeBehavior->preserveNonEmptyValues = $preserveNonEmptyValues; $model->name = $name; @@ -111,7 +115,7 @@ class AttributeBehaviorTest extends TestCase /** * Test Active Record class with [[AttributeBehavior]] behavior attached. * - * @property integer $id + * @property int $id * @property string $name * @property string $alias * diff --git a/tests/framework/behaviors/AttributeTypecastBehaviorTest.php b/tests/framework/behaviors/AttributeTypecastBehaviorTest.php index 2de622fa91..4c57d60d33 100644 --- a/tests/framework/behaviors/AttributeTypecastBehaviorTest.php +++ b/tests/framework/behaviors/AttributeTypecastBehaviorTest.php @@ -1,12 +1,17 @@ [ 'class' => '\yii\db\Connection', 'dsn' => 'sqlite::memory:', - ] - ] + ], + ], ]); $columns = [ diff --git a/tests/framework/behaviors/BlameableBehaviorTest.php b/tests/framework/behaviors/BlameableBehaviorTest.php index f69fc054d1..b049d5d75c 100644 --- a/tests/framework/behaviors/BlameableBehaviorTest.php +++ b/tests/framework/behaviors/BlameableBehaviorTest.php @@ -1,13 +1,18 @@ [ 'class' => 'yiiunit\framework\behaviors\UserMock', - ] - ] + ], + ], ]); $columns = [ @@ -131,9 +136,9 @@ class BlameableBehaviorTest extends TestCase 'class' => BlameableBehavior::className(), 'attributes' => [ BaseActiveRecord::EVENT_BEFORE_VALIDATE => 'created_by', - BaseActiveRecord::EVENT_BEFORE_INSERT => ['created_by', 'updated_by'] - ] - ] + BaseActiveRecord::EVENT_BEFORE_INSERT => ['created_by', 'updated_by'], + ], + ], ]); $model->name = __METHOD__; @@ -149,7 +154,6 @@ class BlameableBehaviorTest extends TestCase $this->assertEquals(20, $model->created_by); $this->assertEquals(20, $model->updated_by); } - } /** diff --git a/tests/framework/behaviors/SluggableBehaviorTest.php b/tests/framework/behaviors/SluggableBehaviorTest.php index b119e37e02..6fae292fb1 100644 --- a/tests/framework/behaviors/SluggableBehaviorTest.php +++ b/tests/framework/behaviors/SluggableBehaviorTest.php @@ -1,12 +1,17 @@ [ 'class' => '\yii\db\Connection', 'dsn' => 'sqlite::memory:', - ] - ] + ], + ], ]); $columns = [ @@ -139,7 +144,7 @@ class SluggableBehaviorTest extends TestCase $model->save(); $model = new ActiveRecordSluggableUnique(); - $model->sluggable->uniqueSlugGenerator = function($baseSlug, $iteration) {return $baseSlug . '-callback';}; + $model->sluggable->uniqueSlugGenerator = function ($baseSlug, $iteration) {return $baseSlug . '-callback';}; $model->name = $name; $model->save(); @@ -269,4 +274,4 @@ class ActiveRecordSluggableUnique extends ActiveRecordSluggable ], ]; } -} \ No newline at end of file +} diff --git a/tests/framework/behaviors/TimestampBehaviorTest.php b/tests/framework/behaviors/TimestampBehaviorTest.php index 5732a1f8c9..0afdfc75d2 100644 --- a/tests/framework/behaviors/TimestampBehaviorTest.php +++ b/tests/framework/behaviors/TimestampBehaviorTest.php @@ -1,13 +1,18 @@ [ 'class' => '\yii\db\Connection', 'dsn' => 'sqlite::memory:', - ] - ] + ], + ], ]); $columns = [ @@ -188,7 +193,7 @@ class TimestampBehaviorTest extends TestCase $this->assertEquals($enforcedTime, $model->created_at, 'Create time has been set on update!'); $this->assertEquals(date('Y'), $model->updated_at); } - + public function testTouchingNewRecordGeneratesException() { ActiveRecordTimestamp::$behaviors = [ @@ -196,14 +201,14 @@ class TimestampBehaviorTest extends TestCase 'class' => TimestampBehavior::className(), 'value' => new Expression("strftime('%Y')"), ], - ]; + ]; $model = new ActiveRecordTimestamp(); - + $this->expectException('yii\base\InvalidCallException'); - + $model->touch('created_at'); } - + public function testTouchingNotNewRecord() { ActiveRecordTimestamp::$behaviors = [ @@ -218,7 +223,7 @@ class TimestampBehaviorTest extends TestCase $model->updated_at = $enforcedTime; $model->save(false); $expectedCreatedAt = new Expression("strftime('%Y')"); - + $model->touch('created_at'); $this->assertEquals($expectedCreatedAt, $model->created_at); diff --git a/tests/framework/caching/ApcCacheTest.php b/tests/framework/caching/ApcCacheTest.php index 126471c5e6..80b5dfbafc 100644 --- a/tests/framework/caching/ApcCacheTest.php +++ b/tests/framework/caching/ApcCacheTest.php @@ -1,4 +1,10 @@ markTestSkipped("APC not installed. Skipping."); + if (!extension_loaded('apc')) { + $this->markTestSkipped('APC not installed. Skipping.'); } elseif ('cli' === PHP_SAPI && !ini_get('apc.enable_cli')) { - $this->markTestSkipped("APC cli is not enabled. Skipping."); + $this->markTestSkipped('APC cli is not enabled. Skipping.'); } - if (!ini_get("apc.enabled") || !ini_get("apc.enable_cli")) { - $this->markTestSkipped("APC is installed but not enabled. Skipping."); + if (!ini_get('apc.enabled') || !ini_get('apc.enable_cli')) { + $this->markTestSkipped('APC is installed but not enabled. Skipping.'); } if ($this->_cacheInstance === null) { @@ -36,11 +42,11 @@ class ApcCacheTest extends CacheTestCase public function testExpire() { - $this->markTestSkipped("APC keys are expiring only on the next request."); + $this->markTestSkipped('APC keys are expiring only on the next request.'); } public function testExpireAdd() { - $this->markTestSkipped("APC keys are expiring only on the next request."); + $this->markTestSkipped('APC keys are expiring only on the next request.'); } } diff --git a/tests/framework/caching/ArrayCacheTest.php b/tests/framework/caching/ArrayCacheTest.php index 5ec7d731b9..e6359e5b36 100644 --- a/tests/framework/caching/ArrayCacheTest.php +++ b/tests/framework/caching/ArrayCacheTest.php @@ -1,4 +1,9 @@ getConnection()->createCommand(" + $this->getConnection()->createCommand(' CREATE TABLE IF NOT EXISTS cache ( id char(128) NOT NULL, expire int(11) DEFAULT NULL, @@ -30,7 +35,7 @@ class DbCacheTest extends CacheTestCase PRIMARY KEY (id), KEY expire (expire) ); - ")->execute(); + ')->execute(); } /** @@ -42,7 +47,7 @@ class DbCacheTest extends CacheTestCase if ($this->_connection === null) { $databases = self::getParam('databases'); $params = $databases['mysql']; - $db = new \yii\db\Connection; + $db = new \yii\db\Connection(); $db->dsn = $params['dsn']; $db->username = $params['username']; $db->password = $params['password']; diff --git a/tests/framework/caching/DbDependencyTest.php b/tests/framework/caching/DbDependencyTest.php index 8dd1868ed3..95c1cf9d01 100644 --- a/tests/framework/caching/DbDependencyTest.php +++ b/tests/framework/caching/DbDependencyTest.php @@ -1,4 +1,9 @@ assertTrue($dependency->isChanged($cache)); } -} \ No newline at end of file +} diff --git a/tests/framework/caching/DbQueryDependencyTest.php b/tests/framework/caching/DbQueryDependencyTest.php index 4f8a323961..c66aa3168a 100644 --- a/tests/framework/caching/DbQueryDependencyTest.php +++ b/tests/framework/caching/DbQueryDependencyTest.php @@ -1,4 +1,9 @@ assertTrue($dependency->isChanged($cache)); } -} \ No newline at end of file +} diff --git a/tests/framework/caching/DependencyTest.php b/tests/framework/caching/DependencyTest.php index 48c749182b..255c80428a 100644 --- a/tests/framework/caching/DependencyTest.php +++ b/tests/framework/caching/DependencyTest.php @@ -1,4 +1,9 @@ isChanged($cache); $this->assertTrue($result); } -} \ No newline at end of file +} diff --git a/tests/framework/caching/FileCacheTest.php b/tests/framework/caching/FileCacheTest.php index 1c7e183f80..7129c880bf 100644 --- a/tests/framework/caching/FileCacheTest.php +++ b/tests/framework/caching/FileCacheTest.php @@ -1,4 +1,10 @@ markTestSkipped("memcache not installed. Skipping."); + if (!extension_loaded('memcache')) { + $this->markTestSkipped('memcache not installed. Skipping.'); } // check whether memcached is running and skip tests if not. diff --git a/tests/framework/caching/MemCachedTest.php b/tests/framework/caching/MemCachedTest.php index 56a5570355..05682f333a 100644 --- a/tests/framework/caching/MemCachedTest.php +++ b/tests/framework/caching/MemCachedTest.php @@ -1,4 +1,10 @@ markTestSkipped("memcached not installed. Skipping."); + if (!extension_loaded('memcached')) { + $this->markTestSkipped('memcached not installed. Skipping.'); } // check whether memcached is running and skip tests if not. diff --git a/tests/framework/caching/TagDependencyTest.php b/tests/framework/caching/TagDependencyTest.php index 8b61b275ed..b56c91b995 100644 --- a/tests/framework/caching/TagDependencyTest.php +++ b/tests/framework/caching/TagDependencyTest.php @@ -1,9 +1,15 @@ markTestSkipped("Wincache not installed. Skipping."); + $this->markTestSkipped('Wincache not installed. Skipping.'); } if (!ini_get('wincache.ucenabled')) { - $this->markTestSkipped("Wincache user cache disabled. Skipping."); + $this->markTestSkipped('Wincache user cache disabled. Skipping.'); } if ($this->_cacheInstance === null) { diff --git a/tests/framework/caching/XCacheTest.php b/tests/framework/caching/XCacheTest.php index ca2b79c8b4..670282938c 100644 --- a/tests/framework/caching/XCacheTest.php +++ b/tests/framework/caching/XCacheTest.php @@ -1,4 +1,10 @@ markTestSkipped("XCache not installed. Skipping."); + if (!function_exists('xcache_isset')) { + $this->markTestSkipped('XCache not installed. Skipping.'); } if ($this->_cacheInstance === null) { diff --git a/tests/framework/caching/ZendDataCacheTest.php b/tests/framework/caching/ZendDataCacheTest.php index 63c0d10f0f..86b5bf1dd0 100644 --- a/tests/framework/caching/ZendDataCacheTest.php +++ b/tests/framework/caching/ZendDataCacheTest.php @@ -1,4 +1,10 @@ markTestSkipped("Zend Data cache not installed. Skipping."); + if (!function_exists('zend_shm_cache_store')) { + $this->markTestSkipped('Zend Data cache not installed. Skipping.'); } if ($this->_cacheInstance === null) { diff --git a/tests/framework/console/ControllerTest.php b/tests/framework/console/ControllerTest.php index cc6a698c43..f9855f6d8f 100644 --- a/tests/framework/console/ControllerTest.php +++ b/tests/framework/console/ControllerTest.php @@ -85,13 +85,13 @@ class ControllerTest extends TestCase $response = $this->runRequest('fake/status'); $this->assertResponseStatus(0, $response); - $response = $this->runRequest('fake/status', (string)$status); + $response = $this->runRequest('fake/status', (string) $status); $this->assertResponseStatus($status, $response); $response = $this->runRequest('fake/response'); $this->assertResponseStatus(0, $response); - $response = $this->runRequest('fake/response', (string)$status); + $response = $this->runRequest('fake/response', (string) $status); $this->assertResponseStatus($status, $response); } @@ -139,11 +139,11 @@ class ControllerTest extends TestCase * @see #10372 */ public function testHelpSkipsTypeHintedArguments() - { - $controller = new FakeController('fake', Yii::$app); - $help = $controller->getActionArgsHelp($controller->createAction('with-complex-type-hint')); + { + $controller = new FakeController('fake', Yii::$app); + $help = $controller->getActionArgsHelp($controller->createAction('with-complex-type-hint')); - $this->assertArrayNotHasKey('typedArgument', $help); - $this->assertArrayHasKey('simpleArgument', $help); - } + $this->assertArrayNotHasKey('typedArgument', $help); + $this->assertArrayHasKey('simpleArgument', $help); + } } diff --git a/tests/framework/console/FakeController.php b/tests/framework/console/FakeController.php index 2fc6ab18c8..7ca0d55d66 100644 --- a/tests/framework/console/FakeController.php +++ b/tests/framework/console/FakeController.php @@ -37,7 +37,7 @@ class FakeController extends Controller return array_merge(parent::options($actionID), [ 'test', 'testArray', - 'alias' + 'alias', ]); } @@ -46,7 +46,7 @@ class FakeController extends Controller return [ 't' => 'test', 'ta' => 'testArray', - 'a' => 'alias' + 'a' => 'alias', ]; } @@ -84,7 +84,8 @@ class FakeController extends Controller return $this->testArray; } - public function actionWithComplexTypeHint(self $typedArgument, $simpleArgument) { + public function actionWithComplexTypeHint(self $typedArgument, $simpleArgument) + { return $simpleArgument; } @@ -96,7 +97,7 @@ class FakeController extends Controller public function actionResponse($status = 0) { $response = new Response(); - $response->exitStatus = (int)$status; + $response->exitStatus = (int) $status; return $response; } } diff --git a/tests/framework/console/FakeHelpController.php b/tests/framework/console/FakeHelpController.php index 32876d6fc8..9b0ea50b89 100644 --- a/tests/framework/console/FakeHelpController.php +++ b/tests/framework/console/FakeHelpController.php @@ -1,4 +1,9 @@ [], 'exception' => [ '\yii\console\Exception', - 'Parameter "0" is not valid' + 'Parameter "0" is not valid', ], ], ]; diff --git a/tests/framework/console/UnkownCommandExceptionTest.php b/tests/framework/console/UnkownCommandExceptionTest.php index 88897ede55..6d743eca8a 100644 --- a/tests/framework/console/UnkownCommandExceptionTest.php +++ b/tests/framework/console/UnkownCommandExceptionTest.php @@ -8,7 +8,6 @@ namespace yiiunit\framework\console; use Yii; -use yii\console\Application; use yii\console\UnknownCommandException; use yiiunit\TestCase; diff --git a/tests/framework/console/controllers/AssetControllerTest.php b/tests/framework/console/controllers/AssetControllerTest.php index 9e3026b949..15aa565f65 100644 --- a/tests/framework/console/controllers/AssetControllerTest.php +++ b/tests/framework/console/controllers/AssetControllerTest.php @@ -1,14 +1,19 @@ runAssetControllerAction('template', [$configFileName]); $this->assertFileExists($configFileName, 'Unable to create config file template!'); $config = require($configFileName); - $this->assertTrue(is_array($config), 'Invalid config created!'); + $this->assertInternalType('array', $config, 'Invalid config created!'); } public function testActionCompress() @@ -275,9 +280,9 @@ EOL; 'js/test_alert.js' => "function test() { alert('Test message'); }", - 'js/test_sum_ab.js' => "function sumAB(a, b) { + 'js/test_sum_ab.js' => 'function sumAB(a, b) { return a + b; - }", + }', ]; $this->createAssetSourceFiles($jsFiles); $assetBundleClassName = $this->declareAssetBundleClass([ @@ -286,7 +291,7 @@ EOL; ]); $bundles = [ - $assetBundleClassName + $assetBundleClassName, ]; $bundleFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'bundle.php'; @@ -299,7 +304,7 @@ EOL; // Then : $this->assertFileExists($bundleFile, 'Unable to create output bundle file!'); $compressedBundleConfig = require($bundleFile); - $this->assertTrue(is_array($compressedBundleConfig), 'Output bundle file has incorrect format!'); + $this->assertInternalType('array', $compressedBundleConfig, 'Output bundle file has incorrect format!'); $this->assertCount(2, $compressedBundleConfig, 'Output bundle config contains wrong bundle count!'); $this->assertArrayHasKey($assetBundleClassName, $compressedBundleConfig, 'Source bundle is lost!'); @@ -339,7 +344,7 @@ EOL; '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js', ], 'css' => [ - '//ajax.googleapis.com/css/libs/jquery/2.1.1/jquery.ui.min.css' + '//ajax.googleapis.com/css/libs/jquery/2.1.1/jquery.ui.min.css', ], ]; $externalAssetBundleClassName = $this->declareAssetBundleClass($externalAssetConfig); @@ -362,11 +367,11 @@ EOL; 'css' => array_keys($cssFiles), 'js' => array_keys($jsFiles), 'depends' => [ - $externalAssetBundleClassName + $externalAssetBundleClassName, ], ]); $bundles = [ - $regularAssetBundleClassName + $regularAssetBundleClassName, ]; $bundleFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'bundle.php'; @@ -379,7 +384,7 @@ EOL; // Then : $this->assertFileExists($bundleFile, 'Unable to create output bundle file!'); $compressedBundleConfig = require($bundleFile); - $this->assertTrue(is_array($compressedBundleConfig), 'Output bundle file has incorrect format!'); + $this->assertInternalType('array', $compressedBundleConfig, 'Output bundle file has incorrect format!'); $this->assertArrayHasKey($externalAssetBundleClassName, $compressedBundleConfig, 'External bundle is lost!'); $compressedExternalAssetConfig = $compressedBundleConfig[$externalAssetBundleClassName]; @@ -404,33 +409,33 @@ EOL; 'namespace' => $namespace, 'class' => 'AssetStart', 'depends' => [ - $namespace . '\AssetA' + $namespace . '\AssetA', ], ]); $this->declareAssetBundleClass([ 'namespace' => $namespace, 'class' => 'AssetA', 'depends' => [ - $namespace . '\AssetB' + $namespace . '\AssetB', ], ]); $this->declareAssetBundleClass([ 'namespace' => $namespace, 'class' => 'AssetB', 'depends' => [ - $namespace . '\AssetC' + $namespace . '\AssetC', ], ]); $this->declareAssetBundleClass([ 'namespace' => $namespace, 'class' => 'AssetC', 'depends' => [ - $namespace . '\AssetA' + $namespace . '\AssetA', ], ]); $bundles = [ - $namespace . '\AssetStart' + $namespace . '\AssetStart', ]; $bundleFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'bundle.php'; @@ -542,10 +547,10 @@ EOL; '.published-relative-dir-class {background-image: url(../img/same_relative_dir.png);}', ], [ - "img {clip-path: url(#xxx)}", + 'img {clip-path: url(#xxx)}', '/test/base/path/css', '/test/base/path/assets/output', - "img {clip-path: url(#xxx)}", + 'img {clip-path: url(#xxx)}', ], ]; } @@ -645,14 +650,14 @@ EOL; ]); $bundles = [ - $assetBundleClassName + $assetBundleClassName, ]; $bundleFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'bundle.php'; // Keep source : $configFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'config_no_source_delete.php'; $this->createCompressConfigFile($configFile, $bundles, [ - 'deleteSource' => false + 'deleteSource' => false, ]); $this->runAssetControllerAction('compress', [$configFile, $bundleFile]); @@ -660,7 +665,7 @@ EOL; $files = FileHelper::findFiles($this->testAssetsBasePath, [ 'only' => [ 'test_body.css', - 'test_alert.js' + 'test_alert.js', ], ]); $this->assertNotEmpty($files); @@ -668,7 +673,7 @@ EOL; // Delete source : $configFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'config_source_delete.php'; $this->createCompressConfigFile($configFile, $bundles, [ - 'deleteSource' => true + 'deleteSource' => true, ]); $this->runAssetControllerAction('compress', [$configFile, $bundleFile]); @@ -676,7 +681,7 @@ EOL; $files = FileHelper::findFiles($this->testAssetsBasePath, [ 'only' => [ 'test_body.css', - 'test_alert.js' + 'test_alert.js', ], ]); $this->assertEmpty($files); @@ -712,7 +717,7 @@ EOL; ]); $bundles = [ - $assetBundleClassName + $assetBundleClassName, ]; $bundleFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'bundle_override_as_external.php'; @@ -723,10 +728,10 @@ EOL; 'basePath' => null, 'baseUrl' => null, 'css' => [ - '//some.cdn.com/js/override_external.css' + '//some.cdn.com/js/override_external.css', ], 'js' => [ - '//some.cdn.com/js/override_external.js' + '//some.cdn.com/js/override_external.js', ], ]; $this->createCompressConfigFile($configFile, $bundles, [ @@ -734,7 +739,7 @@ EOL; 'bundles' => [ $assetBundleClassName => $assetBundleOverrideConfig, ], - ] + ], ]); $this->runAssetControllerAction('compress', [$configFile, $bundleFile]); @@ -752,4 +757,4 @@ EOL; class AssetControllerMock extends AssetController { use StdOutBufferControllerTrait; -} \ No newline at end of file +} diff --git a/tests/framework/console/controllers/BaseMessageControllerTest.php b/tests/framework/console/controllers/BaseMessageControllerTest.php index 1b7251dfd3..417e36c64a 100644 --- a/tests/framework/console/controllers/BaseMessageControllerTest.php +++ b/tests/framework/console/controllers/BaseMessageControllerTest.php @@ -1,11 +1,17 @@ _cacheController = Yii::createObject([ 'class' => 'yiiunit\framework\console\controllers\SilencedCacheController', 'interactive' => false, - ],[null, null]); //id and module are null + ], [null, null]); //id and module are null $databases = self::getParam('databases'); $config = $databases[$this->driverName]; @@ -77,8 +81,8 @@ class CacheControllerTest extends TestCase $this->_cacheController->actionFlush('firstCache'); - $this->assertFalse(Yii::$app->firstCache->get('firstKey'),'first cache data should be flushed'); - $this->assertFalse(Yii::$app->firstCache->get('secondKey'),'first cache data should be flushed'); + $this->assertFalse(Yii::$app->firstCache->get('firstKey'), 'first cache data should be flushed'); + $this->assertFalse(Yii::$app->firstCache->get('secondKey'), 'first cache data should be flushed'); $this->assertEquals('thirdValue', Yii::$app->secondCache->get('thirdKey'), 'second cache data should not be flushed'); } @@ -98,7 +102,6 @@ class CacheControllerTest extends TestCase $this->_cacheController->actionFlushSchema('db'); $cacheSchema = $schema->getTableSchemas('', false); $this->assertEquals($noCacheSchemas, $cacheSchema, 'Schema cache should be flushed.'); - } public function testFlushBoth() @@ -109,8 +112,8 @@ class CacheControllerTest extends TestCase $this->_cacheController->actionFlush('firstCache', 'secondCache'); - $this->assertFalse(Yii::$app->firstCache->get('firstKey'),'first cache data should be flushed'); - $this->assertFalse(Yii::$app->firstCache->get('secondKey'),'first cache data should be flushed'); + $this->assertFalse(Yii::$app->firstCache->get('firstKey'), 'first cache data should be flushed'); + $this->assertFalse(Yii::$app->firstCache->get('secondKey'), 'first cache data should be flushed'); $this->assertFalse(Yii::$app->secondCache->get('thirdKey'), 'second cache data should be flushed'); } @@ -138,8 +141,7 @@ class CacheControllerTest extends TestCase $this->_cacheController->actionFlushAll(); - $this->assertFalse(Yii::$app->firstCache->get('firstKey'),'first cache data should be flushed'); + $this->assertFalse(Yii::$app->firstCache->get('firstKey'), 'first cache data should be flushed'); $this->assertFalse(Yii::$app->secondCache->get('thirdKey'), 'second cache data should be flushed'); } - } diff --git a/tests/framework/console/controllers/DbMessageControllerTest.php b/tests/framework/console/controllers/DbMessageControllerTest.php index f99959802b..c2a4665d75 100644 --- a/tests/framework/console/controllers/DbMessageControllerTest.php +++ b/tests/framework/console/controllers/DbMessageControllerTest.php @@ -1,4 +1,10 @@ runAction($route, $params); - echo "Result is " . $result; + echo 'Result is ' . $result; if ($result !== \yii\console\Controller::EXIT_CODE_NORMAL) { ob_end_flush(); } else { @@ -84,7 +90,7 @@ class DbMessageControllerTest extends BaseMessageControllerTest public static function getConnection() { if (static::$db == null) { - $db = new Connection; + $db = new Connection(); $db->dsn = static::$database['dsn']; if (isset(static::$database['username'])) { $db->username = static::$database['username']; @@ -111,7 +117,7 @@ class DbMessageControllerTest extends BaseMessageControllerTest 'languages' => [$this->language], 'sourcePath' => $this->sourcePath, 'overwrite' => true, - 'db' => static::$db + 'db' => static::$db, ]; } @@ -127,12 +133,12 @@ class DbMessageControllerTest extends BaseMessageControllerTest foreach ($messages as $source => $translation) { $lastPk = static::$db->schema->insert('source_message', [ 'category' => $category, - 'message' => $source + 'message' => $source, ]); static::$db->createCommand()->insert('message', [ 'id' => $lastPk['id'], 'language' => $this->language, - 'translation' => $translation + 'translation' => $translation, ])->execute(); } } diff --git a/tests/framework/console/controllers/EchoMigrateController.php b/tests/framework/console/controllers/EchoMigrateController.php index 9e362bd80b..eec267f278 100644 --- a/tests/framework/console/controllers/EchoMigrateController.php +++ b/tests/framework/console/controllers/EchoMigrateController.php @@ -1,4 +1,10 @@ _fixtureController->globalFixtures = [ - '\yiiunit\data\console\controllers\fixtures\Global' + '\yiiunit\data\console\controllers\fixtures\Global', ]; $this->_fixtureController->actionLoad(['First']); @@ -56,7 +60,7 @@ class FixtureControllerTest extends TestCase public function testUnloadGlobalFixture() { $this->_fixtureController->globalFixtures = [ - '\yiiunit\data\console\controllers\fixtures\Global' + '\yiiunit\data\console\controllers\fixtures\Global', ]; FixtureStorage::$globalFixturesData[] = 'some seeded global fixture data'; @@ -209,7 +213,6 @@ class FixtureControllerTest extends TestCase class FixtureConsoledController extends FixtureController { - public function stdout($string) { } diff --git a/tests/framework/console/controllers/HelpControllerTest.php b/tests/framework/console/controllers/HelpControllerTest.php index b175b90fa5..4d4ea40dd0 100644 --- a/tests/framework/console/controllers/HelpControllerTest.php +++ b/tests/framework/console/controllers/HelpControllerTest.php @@ -1,8 +1,14 @@ assertContains('--port, -p: int (defaults to 8080)', $result); $this->assertContains('--router, -r: string', $result); } - - } diff --git a/tests/framework/console/controllers/MigrateControllerTest.php b/tests/framework/console/controllers/MigrateControllerTest.php index f22f5a1a54..ef054589ff 100644 --- a/tests/framework/console/controllers/MigrateControllerTest.php +++ b/tests/framework/console/controllers/MigrateControllerTest.php @@ -1,4 +1,9 @@ 'title:string(10):notNull:unique:defaultValue("test"), body:text:notNull, price:money(11,2):notNull, - parenthesis_in_comment:string(255):notNull:comment(\'Name of set (RU)\')' + parenthesis_in_comment:string(255):notNull:comment(\'Name of set (RU)\')', ]); $this->assertCommandCreatedFile('create_title_pk', $migrationName, $table, [ @@ -132,7 +137,7 @@ class MigrateControllerTest extends TestCase $this->assertCommandCreatedFile('drop_products_from_store_table', 'drop_' . $table . '_table', $table); } // @see https://github.com/yiisoft/yii2/issues/11461 - $this->assertCommandCreatedFile('create_title_with_comma_default_values', 'create_test_table', 'test', [ + $this->assertCommandCreatedFile('create_title_with_comma_default_values', 'create_test_table', 'test', [ 'fields' => 'title:string(10):notNull:unique:defaultValue(",te,st"), body:text:notNull:defaultValue(",test"), test:custom(11,2,"s"):notNull', @@ -151,7 +156,7 @@ class MigrateControllerTest extends TestCase $this->assertCommandCreatedFile('drop_test', $migrationName, $table); $this->assertCommandCreatedFile('drop_fields', $migrationName, $table, [ - 'fields' => 'body:text:notNull,price:money(11,2)' + 'fields' => 'body:text:notNull,price:money(11,2)', ]); } @@ -174,7 +179,7 @@ class MigrateControllerTest extends TestCase 'fields' => 'title:string(10):notNull, body:text:notNull, price:money(11,2):notNull, - created_at:dateTime' + created_at:dateTime', ]); $this->assertCommandCreatedFile('add_columns_fk', $migrationName, $table, [ @@ -209,7 +214,7 @@ class MigrateControllerTest extends TestCase $this->assertCommandCreatedFile('drop_columns_test', $migrationName, $table, [ 'fields' => 'title:string(10):notNull,body:text:notNull, price:money(11,2):notNull, - created_at:dateTime' + created_at:dateTime', ]); } } @@ -235,7 +240,7 @@ class MigrateControllerTest extends TestCase { $controllerConfig = [ 'migrationPath' => null, - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]; $this->runMigrateControllerAction('history', [], $controllerConfig); @@ -283,4 +288,4 @@ class MigrateControllerTest extends TestCase array_keys($rows) ); } -} \ No newline at end of file +} diff --git a/tests/framework/console/controllers/MigrateControllerTestTrait.php b/tests/framework/console/controllers/MigrateControllerTestTrait.php index 39fef0cf17..b95160f0bc 100644 --- a/tests/framework/console/controllers/MigrateControllerTestTrait.php +++ b/tests/framework/console/controllers/MigrateControllerTestTrait.php @@ -1,4 +1,9 @@ assertTrue($success, $message); } @@ -341,7 +346,7 @@ CODE; $migrationName = 'testDefaultNamespace'; $this->runMigrateControllerAction('create', [$migrationName], [ 'migrationPath' => null, - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]); $files = FileHelper::findFiles($this->migrationPath); $fileContent = file_get_contents($files[0]); @@ -353,7 +358,7 @@ CODE; $migrationName = 'test_namespace_specify'; $this->runMigrateControllerAction('create', [$this->migrationNamespace . '\\' . $migrationName], [ 'migrationPath' => $this->migrationPath, - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]); $files = FileHelper::findFiles($this->migrationPath); $fileContent = file_get_contents($files[0]); @@ -364,7 +369,7 @@ CODE; $migrationName = 'test_no_namespace'; $this->runMigrateControllerAction('create', [$migrationName], [ 'migrationPath' => $this->migrationPath, - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]); $files = FileHelper::findFiles($this->migrationPath); $fileContent = file_get_contents($files[0]); @@ -381,7 +386,7 @@ CODE; $this->runMigrateControllerAction('up', [], [ 'migrationPath' => null, - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]); $this->assertMigrationHistory([ @@ -402,7 +407,7 @@ CODE; $controllerConfig = [ 'migrationPath' => null, - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]; $this->runMigrateControllerAction('up', [], $controllerConfig); $this->runMigrateControllerAction('down', [1], $controllerConfig); @@ -421,7 +426,7 @@ CODE; { $controllerConfig = [ 'migrationPath' => null, - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]; $output = $this->runMigrateControllerAction('history', [], $controllerConfig); @@ -443,7 +448,7 @@ CODE; { $controllerConfig = [ 'migrationPath' => null, - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]; $version = '010101000001'; @@ -461,7 +466,7 @@ CODE; { $controllerConfig = [ 'migrationPath' => null, - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]; $version = '020202000020'; @@ -481,7 +486,7 @@ CODE; FileHelper::createDirectory(Yii::getAlias('@yiiunit/runtime/extension_migrations')); $controllerConfig = [ 'migrationPath' => [$appPath = '@yiiunit/runtime/app_migrations', $extensionPath = '@yiiunit/runtime/extension_migrations'], - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]; $this->createMigration('app_migration1', '010101_000001', $appPath); @@ -579,8 +584,8 @@ CODE; 'm010101_000002_ext_migration1', 'm010101_000003_app_migration2', $this->migrationNamespace . '\\M010101000004NsMigration', - 'm*_app_migration3' + 'm*_app_migration3', ]); - $this->assertCount(1, FileHelper::findFiles(Yii::getAlias($appPath), ['only'=> ['m*_app_migration3.php']])); + $this->assertCount(1, FileHelper::findFiles(Yii::getAlias($appPath), ['only' => ['m*_app_migration3.php']])); } } diff --git a/tests/framework/console/controllers/PHPMessageControllerTest.php b/tests/framework/console/controllers/PHPMessageControllerTest.php index 36c43572c6..4c74d606bc 100644 --- a/tests/framework/console/controllers/PHPMessageControllerTest.php +++ b/tests/framework/console/controllers/PHPMessageControllerTest.php @@ -1,6 +1,11 @@ stdOutBuffer = ''; return $result; } -} \ No newline at end of file +} diff --git a/tests/framework/data/ActiveDataProviderTest.php b/tests/framework/data/ActiveDataProviderTest.php index 024ef3937d..b496dcb96b 100644 --- a/tests/framework/data/ActiveDataProviderTest.php +++ b/tests/framework/data/ActiveDataProviderTest.php @@ -13,9 +13,9 @@ use yii\db\Query; use yiiunit\data\ar\ActiveRecord; use yiiunit\data\ar\Customer; use yiiunit\data\ar\Item; +use yiiunit\data\ar\Order; use yiiunit\framework\db\DatabaseTestCase; use yiiunit\framework\db\UnqueryableQueryMock; -use yiiunit\data\ar\Order; /** * @author Qiang Xue @@ -48,7 +48,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase 'query' => Order::find(), 'pagination' => [ 'pageSize' => 2, - ] + ], ]); $orders = $provider->getModels(); $this->assertCount(2, $orders); @@ -71,7 +71,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase 'query' => $customer->getOrders(), 'pagination' => [ 'pageSize' => 1, - ] + ], ]); $orders = $provider->getModels(); $this->assertCount(1, $orders); @@ -95,7 +95,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase 'query' => $order->getItems(), 'pagination' => [ 'pageSize' => 2, - ] + ], ]); $items = $provider->getModels(); $this->assertCount(2, $items); @@ -117,7 +117,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase 'query' => $order->getBooks(), 'pagination' => [ 'pageSize' => 1, - ] + ], ]); $items = $provider->getModels(); $this->assertCount(1, $items); @@ -125,23 +125,23 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase public function testQuery() { - $query = new Query; + $query = new Query(); $provider = new ActiveDataProvider([ 'db' => $this->getConnection(), 'query' => $query->from('order')->orderBy('id'), ]); $orders = $provider->getModels(); $this->assertCount(3, $orders); - $this->assertTrue(is_array($orders[0])); + $this->assertInternalType('array', $orders[0]); $this->assertEquals([0, 1, 2], $provider->getKeys()); - $query = new Query; + $query = new Query(); $provider = new ActiveDataProvider([ 'db' => $this->getConnection(), 'query' => $query->from('order'), 'pagination' => [ 'pageSize' => 2, - ] + ], ]); $orders = $provider->getModels(); $this->assertCount(2, $orders); @@ -149,7 +149,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase public function testRefresh() { - $query = new Query; + $query = new Query(); $provider = new ActiveDataProvider([ 'db' => $this->getConnection(), 'query' => $query->from('order')->orderBy('id'), @@ -164,7 +164,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase public function testPaginationBeforeModels() { - $query = new Query; + $query = new Query(); $provider = new ActiveDataProvider([ 'db' => $this->getConnection(), 'query' => $query->from('order')->orderBy('id'), @@ -182,7 +182,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase public function testDoesNotPerformQueryWhenHasNoModels() { - $query = new UnqueryableQueryMock; + $query = new UnqueryableQueryMock(); $provider = new ActiveDataProvider([ 'db' => $this->getConnection(), 'query' => $query->from('order')->where('0=1'), diff --git a/tests/framework/data/ArrayDataProviderTest.php b/tests/framework/data/ArrayDataProviderTest.php index e8837844f3..3d74535613 100644 --- a/tests/framework/data/ArrayDataProviderTest.php +++ b/tests/framework/data/ArrayDataProviderTest.php @@ -1,4 +1,9 @@ 'zero'], - ['name' => 'one'] + ['name' => 'one'], ]; $dataProvider = new ArrayDataProvider(['allModels' => $simpleArray]); $this->assertEquals($simpleArray, $dataProvider->getModels()); @@ -43,7 +48,7 @@ class ArrayDataProviderTest extends TestCase ], 'defaultOrder' => [ 'sort' => SORT_ASC, - ] + ], ], ] ); @@ -55,7 +60,7 @@ class ArrayDataProviderTest extends TestCase { $simpleArray = [ ['innerArray' => ['sortField' => 1]], - ['innerArray' => ['sortField' => 0]] + ['innerArray' => ['sortField' => 0]], ]; $dataProvider = new ArrayDataProvider( [ @@ -71,13 +76,13 @@ class ArrayDataProviderTest extends TestCase ], 'defaultOrder' => [ 'sort' => SORT_ASC, - ] + ], ], ] ); $sortedArray = [ ['innerArray' => ['sortField' => 0]], - ['innerArray' => ['sortField' => 1]] + ['innerArray' => ['sortField' => 1]], ]; $this->assertEquals($sortedArray, $dataProvider->getModels()); } @@ -86,44 +91,44 @@ class ArrayDataProviderTest extends TestCase { // source data $unsortedProjects = [ - ['title'=>'Zabbix', 'license'=>'GPL'], - ['title'=>'munin', 'license'=>'GPL'], - ['title'=>'Arch Linux', 'license'=>'GPL'], - ['title'=>'Nagios', 'license'=>'GPL'], - ['title'=>'zend framework', 'license'=>'BSD'], - ['title'=>'Zope', 'license'=>'ZPL'], - ['title'=>'active-record', 'license'=>false], - ['title'=>'ActiveState', 'license'=>false], - ['title'=>'mach', 'license'=>false], - ['title'=>'MySQL', 'license'=>'GPL'], - ['title'=>'mssql', 'license'=>'EULA'], - ['title'=>'Master-Master', 'license'=>false], - ['title'=>'Zend Engine', 'license'=>false], - ['title'=>'Mageia Linux', 'license'=>'GNU GPL'], - ['title'=>'nginx', 'license'=>'BSD'], - ['title'=>'Mozilla Firefox', 'license'=>'MPL'], + ['title' => 'Zabbix', 'license' => 'GPL'], + ['title' => 'munin', 'license' => 'GPL'], + ['title' => 'Arch Linux', 'license' => 'GPL'], + ['title' => 'Nagios', 'license' => 'GPL'], + ['title' => 'zend framework', 'license' => 'BSD'], + ['title' => 'Zope', 'license' => 'ZPL'], + ['title' => 'active-record', 'license' => false], + ['title' => 'ActiveState', 'license' => false], + ['title' => 'mach', 'license' => false], + ['title' => 'MySQL', 'license' => 'GPL'], + ['title' => 'mssql', 'license' => 'EULA'], + ['title' => 'Master-Master', 'license' => false], + ['title' => 'Zend Engine', 'license' => false], + ['title' => 'Mageia Linux', 'license' => 'GNU GPL'], + ['title' => 'nginx', 'license' => 'BSD'], + ['title' => 'Mozilla Firefox', 'license' => 'MPL'], ]; // expected data $sortedProjects = [ // upper cased titles - ['title'=>'ActiveState', 'license'=>false], - ['title'=>'Arch Linux', 'license'=>'GPL'], - ['title'=>'Mageia Linux', 'license'=>'GNU GPL'], - ['title'=>'Master-Master', 'license'=>false], - ['title'=>'Mozilla Firefox', 'license'=>'MPL'], - ['title'=>'MySQL', 'license'=>'GPL'], - ['title'=>'Nagios', 'license'=>'GPL'], - ['title'=>'Zabbix', 'license'=>'GPL'], - ['title'=>'Zend Engine', 'license'=>false], - ['title'=>'Zope', 'license'=>'ZPL'], + ['title' => 'ActiveState', 'license' => false], + ['title' => 'Arch Linux', 'license' => 'GPL'], + ['title' => 'Mageia Linux', 'license' => 'GNU GPL'], + ['title' => 'Master-Master', 'license' => false], + ['title' => 'Mozilla Firefox', 'license' => 'MPL'], + ['title' => 'MySQL', 'license' => 'GPL'], + ['title' => 'Nagios', 'license' => 'GPL'], + ['title' => 'Zabbix', 'license' => 'GPL'], + ['title' => 'Zend Engine', 'license' => false], + ['title' => 'Zope', 'license' => 'ZPL'], // lower cased titles - ['title'=>'active-record', 'license'=>false], - ['title'=>'mach', 'license'=>false], - ['title'=>'mssql', 'license'=>'EULA'], - ['title'=>'munin', 'license'=>'GPL'], - ['title'=>'nginx', 'license'=>'BSD'], - ['title'=>'zend framework', 'license'=>'BSD'], + ['title' => 'active-record', 'license' => false], + ['title' => 'mach', 'license' => false], + ['title' => 'mssql', 'license' => 'EULA'], + ['title' => 'munin', 'license' => 'GPL'], + ['title' => 'nginx', 'license' => 'BSD'], + ['title' => 'zend framework', 'license' => 'BSD'], ]; $dataProvider = new ArrayDataProvider( @@ -140,7 +145,7 @@ class ArrayDataProviderTest extends TestCase ], 'defaultOrder' => [ 'sort' => SORT_ASC, - ] + ], ], 'pagination' => [ 'pageSize' => 100500, diff --git a/tests/framework/data/BaseDataProviderTest.php b/tests/framework/data/BaseDataProviderTest.php index 2c1827e5f2..d59b5e0e0f 100644 --- a/tests/framework/data/BaseDataProviderTest.php +++ b/tests/framework/data/BaseDataProviderTest.php @@ -1,9 +1,14 @@ assertNull((new ConcreteDataProvider())->id); $this->assertNotNull((new ConcreteDataProvider())->id); } - } /** diff --git a/tests/framework/data/PaginationTest.php b/tests/framework/data/PaginationTest.php index a410b389e2..85951ff0c8 100644 --- a/tests/framework/data/PaginationTest.php +++ b/tests/framework/data/PaginationTest.php @@ -1,4 +1,9 @@ mockWebApplication([ 'components' => [ 'urlManager' => [ - 'scriptUrl' => '/index.php' + 'scriptUrl' => '/index.php', ], ], ]); diff --git a/tests/framework/data/SortTest.php b/tests/framework/data/SortTest.php index 8b68ddb0de..426b6b5cac 100644 --- a/tests/framework/data/SortTest.php +++ b/tests/framework/data/SortTest.php @@ -7,9 +7,9 @@ namespace yiiunit\framework\data; +use yii\data\Sort; use yii\web\UrlManager; use yiiunit\TestCase; -use yii\data\Sort; /** * @author Qiang Xue @@ -36,7 +36,7 @@ class SortTest extends TestCase ], ], 'params' => [ - 'sort' => 'age,-name' + 'sort' => 'age,-name', ], 'enableMultiSort' => true, ]); @@ -67,7 +67,7 @@ class SortTest extends TestCase ], ], 'params' => [ - 'sort' => 'age,-name' + 'sort' => 'age,-name', ], 'enableMultiSort' => true, ]); @@ -97,7 +97,7 @@ class SortTest extends TestCase ], ], 'params' => [ - 'sort' => 'age,-name' + 'sort' => 'age,-name', ], 'enableMultiSort' => true, ]); @@ -121,7 +121,7 @@ class SortTest extends TestCase ], ], 'params' => [ - 'sort' => 'age,-name' + 'sort' => 'age,-name', ], 'enableMultiSort' => true, ]); @@ -157,7 +157,7 @@ class SortTest extends TestCase ], ], 'params' => [ - 'sort' => 'age,-name' + 'sort' => 'age,-name', ], 'enableMultiSort' => true, 'route' => 'site/index', @@ -184,7 +184,7 @@ class SortTest extends TestCase ], ], 'params' => [ - 'sort' => 'age,-name' + 'sort' => 'age,-name', ], 'enableMultiSort' => true, 'urlManager' => $manager, @@ -216,7 +216,7 @@ class SortTest extends TestCase ], ], 'params' => [ - 'sort' => 'age,-name' + 'sort' => 'age,-name', ], 'enableMultiSort' => true, 'urlManager' => $manager, @@ -231,15 +231,15 @@ class SortTest extends TestCase $sort = new CustomSort([ 'attributes' => [ 'age', - 'name' + 'name', ], 'params' => [ 'sort' => [ ['field' => 'age', 'dir' => 'asc'], - ['field' => 'name', 'dir' => 'desc'] - ] + ['field' => 'name', 'dir' => 'desc'], + ], ], - 'enableMultiSort' => true + 'enableMultiSort' => true, ]); $this->assertEquals(SORT_ASC, $sort->getAttributeOrder('age')); diff --git a/tests/framework/data/SqlDataProviderTest.php b/tests/framework/data/SqlDataProviderTest.php index d5edc47341..3ccb408412 100644 --- a/tests/framework/data/SqlDataProviderTest.php +++ b/tests/framework/data/SqlDataProviderTest.php @@ -1,12 +1,14 @@ 'select * from `customer` where id > :minimum', 'params' => [ - ':minimum' => -1 + ':minimum' => -1, ], 'db' => $this->getConnection(), ]); diff --git a/tests/framework/db/ActiveQueryTest.php b/tests/framework/db/ActiveQueryTest.php index 792f896439..230ec45eaa 100644 --- a/tests/framework/db/ActiveQueryTest.php +++ b/tests/framework/db/ActiveQueryTest.php @@ -1,4 +1,9 @@ joinWith('profile'); $this->assertEquals([ - [['profile'], true, 'LEFT JOIN'] + [['profile'], true, 'LEFT JOIN'], ], $result->joinWith); } @@ -125,7 +130,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase $query = new ActiveQuery(Customer::className()); $result = $query->innerJoinWith('profile'); $this->assertEquals([ - [['profile'], true, 'INNER JOIN'] + [['profile'], true, 'INNER JOIN'], ], $result->joinWith); } @@ -135,16 +140,16 @@ abstract class ActiveQueryTest extends DatabaseTestCase public function testGetQueryTableName_from_not_set() { $query = new ActiveQuery(Customer::className()); - $result = $this->invokeMethod($query,'getTableNameAndAlias'); - $this->assertEquals(['customer','customer'], $result); + $result = $this->invokeMethod($query, 'getTableNameAndAlias'); + $this->assertEquals(['customer', 'customer'], $result); } public function testGetQueryTableName_from_set() { - $options = ['from' => ['alias'=>'customer']]; + $options = ['from' => ['alias' => 'customer']]; $query = new ActiveQuery(Customer::className(), $options); - $result = $this->invokeMethod($query,'getTableNameAndAlias'); - $this->assertEquals(['customer','alias'], $result); + $result = $this->invokeMethod($query, 'getTableNameAndAlias'); + $this->assertEquals(['customer', 'alias'], $result); } public function testOnCondition() @@ -280,7 +285,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase public function testGetTableNames_isFromObject_generateException() { $query = new ActiveQuery(null); - $query->from = new \stdClass; + $query->from = new \stdClass(); $this->setExpectedException('\yii\base\InvalidConfigException'); @@ -329,14 +334,14 @@ abstract class ActiveQueryTest extends DatabaseTestCase '{{srv}}' => '{{service}}', '{{order}}' => '{{order}}', '{{c d}}' => '{{a b}}', - '{{myalias}}' => '{{something}}' + '{{myalias}}' => '{{something}}', ], $tables); } public function testGetTablesAlias_isFromObject_generateException() { $query = new ActiveQuery(null); - $query->from = new \stdClass; + $query->from = new \stdClass(); $this->setExpectedException('\yii\base\InvalidConfigException'); diff --git a/tests/framework/db/ActiveRecordTest.php b/tests/framework/db/ActiveRecordTest.php index 8c5b105958..6f607ebb9b 100644 --- a/tests/framework/db/ActiveRecordTest.php +++ b/tests/framework/db/ActiveRecordTest.php @@ -1,26 +1,31 @@ assertCount(0, $order->books); $order = Order::find()->where(['id' => 1])->asArray()->one(); - $this->assertTrue(is_array($order)); + $this->assertInternalType('array', $order); } public function testFindEagerViaTable() @@ -207,10 +212,10 @@ abstract class ActiveRecordTest extends DatabaseTestCase // https://github.com/yiisoft/yii2/issues/1402 $orders = Order::find()->with('books')->orderBy('id')->asArray()->all(); $this->assertCount(3, $orders); - $this->assertTrue(is_array($orders[0]['orderItems'][0])); + $this->assertInternalType('array', $orders[0]['orderItems'][0]); $order = $orders[0]; - $this->assertTrue(is_array($order)); + $this->assertInternalType('array', $order); $this->assertEquals(1, $order['id']); $this->assertCount(2, $order['books']); $this->assertEquals(1, $order['books'][0]['id']); @@ -258,7 +263,6 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertCount(1, $orders); $this->assertInstanceOf(Order::className(), $orders[0]); $this->assertEquals(2, $orders[0]->id); - } public function testStoreNull() @@ -393,7 +397,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase // inner join filtering without eager loading, conditions on both primary and relation $orders = Order::find()->innerJoinWith([ 'customer' => function ($query) { - $query->where(['customer.id' => 2]); + $query->where(['customer.id' => 2]); }, ], false)->where(['order.id' => [1, 2]])->orderBy('order.id')->all(); $this->assertCount(1, $orders); @@ -430,7 +434,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $orders = Order::find()->joinWith([ 'customer' => function ($q) { $q->from('customer c'); - } + }, ])->orderBy('c.id DESC, order.id')->all(); $this->assertCount(3, $orders); $this->assertEquals(2, $orders[0]->id); @@ -509,9 +513,13 @@ abstract class ActiveRecordTest extends DatabaseTestCase // https://github.com/yiisoft/yii2/issues/2880 $query = Order::findOne(1); - $customer = $query->getCustomer()->joinWith([ - 'orders' => function ($q) { $q->orderBy([]); } - ])->one(); + $customer = $query->getCustomer() + ->joinWith([ + 'orders' => function ($q) { + $q->orderBy([]); + }, + ]) + ->one(); $this->assertEquals(1, $customer->id); $order = Order::find()->joinWith([ 'items' => function ($q) { @@ -521,16 +529,19 @@ abstract class ActiveRecordTest extends DatabaseTestCase ])->orderBy('order.id')->one(); // join with sub-relation called inside Closure - $orders = Order::find()->joinWith([ + $orders = Order::find() + ->joinWith([ 'items' => function ($q) { $q->orderBy('item.id'); $q->joinWith([ - 'category'=> function ($q) { - $q->where('{{category}}.[[id]] = 2'); - } - ]); + 'category' => function ($q) { + $q->where('{{category}}.[[id]] = 2'); + }, + ]); }, - ])->orderBy('order.id')->all(); + ]) + ->orderBy('order.id') + ->all(); $this->assertCount(1, $orders); $this->assertTrue($orders[0]->isRelationPopulated('items')); $this->assertEquals(2, $orders[0]->id); @@ -561,7 +572,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $customers = Customer::find()->active()->joinWith([ 'orders' => function ($q) { $q->orderBy('order.id'); - } + }, ])->orderBy('customer.id DESC, order.id')->all(); $this->assertCount(2, $customers); $this->assertEquals(2, $customers[0]->id); @@ -667,11 +678,10 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertCount(2, $orders[0]->books); $this->assertCount(1, $orders[1]->books); - // joining sub relations $query = Order::find()->innerJoinWith([ 'items i' => function ($q) use ($aliasMethod) { - /** @var $q ActiveQuery */ + /* @var $q ActiveQuery */ if ($aliasMethod === 'explicit') { $q->orderBy('{{i}}.[[id]]'); } elseif ($aliasMethod === 'querysyntax') { @@ -681,15 +691,15 @@ abstract class ActiveRecordTest extends DatabaseTestCase } }, 'items.category c' => function ($q) use ($aliasMethod) { - /** @var $q ActiveQuery */ - if ($aliasMethod === 'explicit') { - $q->where('{{c}}.[[id]] = 2'); - } elseif ($aliasMethod === 'querysyntax') { - $q->where('{{@category}}.[[id]] = 2'); - } elseif ($aliasMethod === 'applyAlias') { - $q->where([$q->applyAlias('category', 'id') => 2]); - } - }, + /* @var $q ActiveQuery */ + if ($aliasMethod === 'explicit') { + $q->where('{{c}}.[[id]] = 2'); + } elseif ($aliasMethod === 'querysyntax') { + $q->where('{{@category}}.[[id]] = 2'); + } elseif ($aliasMethod === 'applyAlias') { + $q->where([$q->applyAlias('category', 'id') => 2]); + } + }, ]); if ($aliasMethod === 'explicit') { $orders = $query->orderBy('{{i}}.id')->all(); @@ -768,7 +778,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase // join with sub-relation called inside Closure $orders = Order::find()->joinWith([ 'items' => function ($q) use ($aliasMethod) { - /** @var $q ActiveQuery */ + /* @var $q ActiveQuery */ $q->orderBy('item.id'); $q->joinWith(['category c']); if ($aliasMethod === 'explicit') { @@ -786,7 +796,6 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertCount(3, $orders[0]->items); $this->assertTrue($orders[0]->items[0]->isRelationPopulated('category')); $this->assertEquals(2, $orders[0]->items[0]->category->id); - } public function testJoinWithSameTable() @@ -820,8 +829,16 @@ abstract class ActiveRecordTest extends DatabaseTestCase // alias is defined in the call to joinWith() // without eager loading $query = Order::find() - ->joinWith(['itemsIndexed books' => function($q) { $q->onCondition('books.category_id = 1'); }], false) - ->joinWith(['itemsIndexed movies' => function($q) { $q->onCondition('movies.category_id = 2'); }], false) + ->joinWith([ + 'itemsIndexed books' => function ($q) { + $q->onCondition('books.category_id = 1'); + }, + ], false) + ->joinWith([ + 'itemsIndexed movies' => function ($q) { + $q->onCondition('movies.category_id = 2'); + }, + ], false) ->where(['movies.name' => 'Toy Story']); $orders = $query->all(); $this->assertCount(1, $orders, $query->createCommand()->rawSql . print_r($orders, true)); @@ -829,8 +846,16 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertFalse($orders[0]->isRelationPopulated('itemsIndexed')); // with eager loading, only for one relation as it would be overwritten otherwise. $query = Order::find() - ->joinWith(['itemsIndexed books' => function($q) { $q->onCondition('books.category_id = 1'); }], false) - ->joinWith(['itemsIndexed movies' => function($q) { $q->onCondition('movies.category_id = 2'); }], true) + ->joinWith([ + 'itemsIndexed books' => function ($q) { + $q->onCondition('books.category_id = 1'); + }, + ], false) + ->joinWith([ + 'itemsIndexed movies' => function ($q) { + $q->onCondition('movies.category_id = 2'); + }, + ], true) ->where(['movies.name' => 'Toy Story']); $orders = $query->all(); $this->assertCount(1, $orders, $query->createCommand()->rawSql . print_r($orders, true)); @@ -839,8 +864,16 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertCount(3, $orders[0]->itemsIndexed); // with eager loading, and the other relation $query = Order::find() - ->joinWith(['itemsIndexed books' => function($q) { $q->onCondition('books.category_id = 1'); }], true) - ->joinWith(['itemsIndexed movies' => function($q) { $q->onCondition('movies.category_id = 2'); }], false) + ->joinWith([ + 'itemsIndexed books' => function ($q) { + $q->onCondition('books.category_id = 1'); + }, + ], true) + ->joinWith([ + 'itemsIndexed movies' => function ($q) { + $q->onCondition('movies.category_id = 2'); + }, + ], false) ->where(['movies.name' => 'Toy Story']); $orders = $query->all(); $this->assertCount(1, $orders, $query->createCommand()->rawSql . print_r($orders, true)); @@ -877,7 +910,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertInstanceOf('yiiunit\data\ar\Customer', $customerWithJoin); $customerWithJoinIndexOrdered = $order->customerJoinedWithProfileIndexOrdered; - $this->assertTrue(is_array($customerWithJoinIndexOrdered)); + $this->assertInternalType('array', $customerWithJoinIndexOrdered); $this->assertArrayHasKey('user1', $customerWithJoinIndexOrdered); $this->assertInstanceOf('yiiunit\data\ar\Customer', $customerWithJoinIndexOrdered['user1']); } @@ -905,12 +938,12 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** @var $order Order */ $order = Order::findOne(1); $itemsSQL = $order->getOrderitems()->createCommand()->rawSql; - $expectedSQL = $this->replaceQuotes("SELECT * FROM [[order_item]] WHERE [[order_id]]=1"); + $expectedSQL = $this->replaceQuotes('SELECT * FROM [[order_item]] WHERE [[order_id]]=1'); $this->assertEquals($expectedSQL, $itemsSQL); $order = Order::findOne(1); $itemsSQL = $order->getOrderItems()->joinWith('item')->createCommand()->rawSql; - $expectedSQL = $this->replaceQuotes("SELECT [[order_item]].* FROM [[order_item]] LEFT JOIN [[item]] ON [[order_item]].[[item_id]] = [[item]].[[id]] WHERE [[order_item]].[[order_id]]=1"); + $expectedSQL = $this->replaceQuotes('SELECT [[order_item]].* FROM [[order_item]] LEFT JOIN [[item]] ON [[order_item]].[[item_id]] = [[item]].[[id]] WHERE [[order_item]].[[order_id]]=1'); $this->assertEquals($expectedSQL, $itemsSQL); Order::$tableName = null; @@ -1127,7 +1160,14 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertCount(2, $orders[0]->orderItems); $this->assertCount(3, $orders[1]->orderItems); $this->assertCount(1, $orders[2]->orderItems); - $orders = Order::find()->with(['orderItems' => function ($q) { $q->indexBy('item_id'); }])->orderBy('id')->all(); + $orders = Order::find() + ->with([ + 'orderItems' => function ($q) { + $q->indexBy('item_id'); + }, + ]) + ->orderBy('id') + ->all(); $this->assertCount(3, $orders); $this->assertCount(2, $orders[0]->orderItems); $this->assertCount(3, $orders[1]->orderItems); @@ -1156,7 +1196,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase public function testSaveEmpty() { - $record = new NullValues; + $record = new NullValues(); $this->assertTrue($record->save(false)); $this->assertEquals(1, $record->id); } @@ -1276,9 +1316,9 @@ abstract class ActiveRecordTest extends DatabaseTestCase public function testLinkWhenRelationIsIndexed2() { $order = Order::find() - ->with('orderItems2') - ->where(['id' => 1]) - ->one(); + ->with('orderItems2') + ->where(['id' => 1]) + ->one(); $orderItem = new OrderItem([ 'order_id' => $order->id, 'item_id' => 3, @@ -1292,9 +1332,9 @@ abstract class ActiveRecordTest extends DatabaseTestCase public function testLinkWhenRelationIsIndexed3() { $order = Order::find() - ->with('orderItems3') - ->where(['id' => 1]) - ->one(); + ->with('orderItems3') + ->where(['id' => 1]) + ->one(); $orderItem = new OrderItem([ 'order_id' => $order->id, 'item_id' => 3, diff --git a/tests/framework/db/BatchQueryResultTest.php b/tests/framework/db/BatchQueryResultTest.php index 5fab5ce3c7..0936cddbba 100644 --- a/tests/framework/db/BatchQueryResultTest.php +++ b/tests/framework/db/BatchQueryResultTest.php @@ -1,11 +1,16 @@ createCommand(); - $this->assertEquals(null, $command->sql); + $this->assertNull($command->sql); // string $sql = 'SELECT * FROM customer'; @@ -43,7 +48,7 @@ abstract class CommandTest extends DatabaseTestCase $sql = 'SELECT [[id]], [[t.name]] FROM {{customer}} t'; $command = $db->createCommand($sql); - $this->assertEquals("SELECT `id`, `t`.`name` FROM `customer` t", $command->sql); + $this->assertEquals('SELECT `id`, `t`.`name` FROM `customer` t', $command->sql); } public function testPrepareCancel() @@ -53,7 +58,7 @@ abstract class CommandTest extends DatabaseTestCase $command = $db->createCommand('SELECT * FROM {{customer}}'); $this->assertEquals(null, $command->pdoStatement); $command->prepare(); - $this->assertNotEquals(null, $command->pdoStatement); + $this->assertNotNull($command->pdoStatement); $command->cancel(); $this->assertEquals(null, $command->pdoStatement); } @@ -202,7 +207,7 @@ SQL; } elseif (defined('HHVM_VERSION') && $this->driverName === 'pgsql') { // HHVMs pgsql implementation does not seem to support blob columns correctly. } else { - $this->assertTrue(is_resource($row['blob_col'])); + $this->assertInternalType('resource', $row['blob_col']); $this->assertEquals($blobCol, stream_get_contents($row['blob_col'])); } $this->assertEquals($numericCol, $row['numeric_col']); @@ -266,7 +271,7 @@ SQL; $command = $db->createCommand($sql); $command->fetchMode = \PDO::FETCH_OBJ; $result = $command->queryOne(); - $this->assertTrue(is_object($result)); + $this->assertInternalType('object', $result); // FETCH_NUM, customized in query method $sql = 'SELECT * FROM {{customer}}'; @@ -442,7 +447,8 @@ SQL; * Data provider for testInsertSelectFailed * @return array */ - public function invalidSelectColumns() { + public function invalidSelectColumns() + { return [ [[]], ['*'], @@ -481,7 +487,7 @@ SQL; break; case 'cubrid': case 'mysql': - $expression = "YEAR(NOW())"; + $expression = 'YEAR(NOW())'; break; case 'sqlite': $expression = "strftime('%Y')"; diff --git a/tests/framework/db/ConnectionTest.php b/tests/framework/db/ConnectionTest.php index 772ce0949a..3562e0e1e8 100644 --- a/tests/framework/db/ConnectionTest.php +++ b/tests/framework/db/ConnectionTest.php @@ -1,4 +1,9 @@ getConnection(false); @@ -33,7 +37,7 @@ abstract class ConnectionTest extends DatabaseTestCase $this->assertFalse($connection->isActive); $this->assertEquals(null, $connection->pdo); - $connection = new Connection; + $connection = new Connection(); $connection->dsn = 'unknown::memory:'; $this->expectException('yii\db\Exception'); $connection->open(); @@ -47,7 +51,7 @@ abstract class ConnectionTest extends DatabaseTestCase $unserialized = unserialize($serialized); $this->assertInstanceOf('yii\db\Connection', $unserialized); - $this->assertEquals(123, $unserialized->createCommand("SELECT 123")->queryScalar()); + $this->assertEquals(123, $unserialized->createCommand('SELECT 123')->queryScalar()); } public function testGetDriverName() @@ -208,9 +212,9 @@ abstract class ConnectionTest extends DatabaseTestCase { /** @var Connection $connection */ $connection = $this->getConnection(true); - $connection->transaction(function(Connection $db) { + $connection->transaction(function (Connection $db) { $this->assertNotNull($db->transaction); - $db->transaction(function(Connection $db) { + $db->transaction(function (Connection $db) { $this->assertNotNull($db->transaction); $db->transaction->rollBack(); }); @@ -221,7 +225,7 @@ abstract class ConnectionTest extends DatabaseTestCase public function testEnableQueryLog() { $connection = $this->getConnection(); - foreach(['qlog1', 'qlog2', 'qlog3', 'qlog4'] as $table) { + foreach (['qlog1', 'qlog2', 'qlog3', 'qlog4'] as $table) { if ($connection->getTableSchema($table, true) !== null) { $connection->createCommand()->dropTable($table)->execute(); } @@ -317,7 +321,7 @@ abstract class ConnectionTest extends DatabaseTestCase try { $connection->createCommand('INSERT INTO qlog1(a) VALUES(:a);', [':a' => 1])->execute(); } catch (\yii\db\Exception $e) { - $this->assertContains('INSERT INTO qlog1(a) VALUES(1);', $e->getMessage(), 'Exception message should contain raw SQL query: ' . (string)$e); + $this->assertContains('INSERT INTO qlog1(a) VALUES(1);', $e->getMessage(), 'Exception message should contain raw SQL query: ' . (string) $e); $thrown = true; } $this->assertTrue($thrown, 'An exception should have been thrown by the command.'); @@ -326,7 +330,7 @@ abstract class ConnectionTest extends DatabaseTestCase try { $connection->createCommand('SELECT * FROM qlog1 WHERE id=:a ORDER BY nonexistingcolumn;', [':a' => 1])->queryAll(); } catch (\yii\db\Exception $e) { - $this->assertContains('SELECT * FROM qlog1 WHERE id=1 ORDER BY nonexistingcolumn;', $e->getMessage(), 'Exception message should contain raw SQL query: ' . (string)$e); + $this->assertContains('SELECT * FROM qlog1 WHERE id=1 ORDER BY nonexistingcolumn;', $e->getMessage(), 'Exception message should contain raw SQL query: ' . (string) $e); $thrown = true; } $this->assertTrue($thrown, 'An exception should have been thrown by the command.'); diff --git a/tests/framework/db/DatabaseTestCase.php b/tests/framework/db/DatabaseTestCase.php index 7d6de14d87..eb8e935007 100644 --- a/tests/framework/db/DatabaseTestCase.php +++ b/tests/framework/db/DatabaseTestCase.php @@ -1,4 +1,9 @@ database = $databases[$this->driverName]; - $pdo_database = 'pdo_'.$this->driverName; + $pdo_database = 'pdo_' . $this->driverName; if ($this->driverName === 'oci') { $pdo_database = 'oci8'; } if (!extension_loaded('pdo') || !extension_loaded($pdo_database)) { - $this->markTestSkipped('pdo and '.$pdo_database.' extension are required.'); + $this->markTestSkipped('pdo and ' . $pdo_database . ' extension are required.'); } $this->mockApplication(); } @@ -66,7 +71,7 @@ abstract class DatabaseTestCase extends TestCase try { $this->_db = $this->prepareDatabase($config, $fixture, $open); } catch (\Exception $e) { - $this->markTestSkipped("Something wrong when preparing database: " . $e->getMessage()); + $this->markTestSkipped('Something wrong when preparing database: ' . $e->getMessage()); } return $this->_db; } diff --git a/tests/framework/db/QueryBuilderTest.php b/tests/framework/db/QueryBuilderTest.php index 34d6b06576..464b8f2fd0 100644 --- a/tests/framework/db/QueryBuilderTest.php +++ b/tests/framework/db/QueryBuilderTest.php @@ -1,18 +1,23 @@ primaryKey()->first(), [ - 'mysql' => "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST", + 'mysql' => 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST', 'postgres' => 'serial NOT NULL PRIMARY KEY', 'oci' => 'NUMBER(10) NOT NULL PRIMARY KEY', 'sqlsrv' => 'int IDENTITY PRIMARY KEY', - 'cubrid' => "int NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST", + 'cubrid' => 'int NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST', ], ], [ - Schema::TYPE_INTEGER . " FIRST", + Schema::TYPE_INTEGER . ' FIRST', $this->integer()->first(), [ - 'mysql' => "int(11) FIRST", + 'mysql' => 'int(11) FIRST', 'postgres' => 'integer', - 'oci' => "NUMBER(10)", + 'oci' => 'NUMBER(10)', 'sqlsrv' => 'int', - 'cubrid' => "int FIRST", + 'cubrid' => 'int FIRST', ], ], [ @@ -966,14 +971,14 @@ abstract class QueryBuilderTest extends DatabaseTestCase ], ], [ - Schema::TYPE_INTEGER . " NOT NULL FIRST", + Schema::TYPE_INTEGER . ' NOT NULL FIRST', $this->integer()->append('NOT NULL')->first(), [ - 'mysql' => "int(11) NOT NULL FIRST", + 'mysql' => 'int(11) NOT NULL FIRST', 'postgres' => 'integer NOT NULL', - 'oci' => "NUMBER(10) NOT NULL", + 'oci' => 'NUMBER(10) NOT NULL', 'sqlsrv' => 'int NOT NULL', - 'cubrid' => "int NOT NULL FIRST", + 'cubrid' => 'int NOT NULL FIRST', ], ], [ @@ -993,8 +998,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase if (array_key_exists($this->driverName, $item[2])) { $item[2] = $item[2][$this->driverName]; $items[$i] = $item; - } - else { + } else { unset($items[$i]); } } @@ -1007,7 +1011,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $qb = $this->getQueryBuilder(); foreach ($this->columnTypes() as $item) { - list ($column, $builder, $expected) = $item; + list($column, $builder, $expected) = $item; $expectedColumnSchemaBuilder = isset($item[3]) ? $item[3] : $column; $this->assertEquals($expected, $qb->getColumnType($column)); @@ -1025,7 +1029,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $columns = []; $i = 0; foreach ($this->columnTypes() as $item) { - list ($column, $builder, $expected) = $item; + list($column, $builder, $expected) = $item; if (!(strncmp($column, Schema::TYPE_PK, 2) === 0 || strncmp($column, Schema::TYPE_UPK, 3) === 0 || strncmp($column, Schema::TYPE_BIGPK, 5) === 0 || @@ -1043,52 +1047,52 @@ abstract class QueryBuilderTest extends DatabaseTestCase { $conditions = [ // empty values - [ ['like', 'name', []], '0=1', [] ], - [ ['not like', 'name', []], '', [] ], - [ ['or like', 'name', []], '0=1', [] ], - [ ['or not like', 'name', []], '', [] ], + [['like', 'name', []], '0=1', []], + [['not like', 'name', []], '', []], + [['or like', 'name', []], '0=1', []], + [['or not like', 'name', []], '', []], // not - [ ['not', 'name'], 'NOT (name)', [] ], + [['not', 'name'], 'NOT (name)', []], // and - [ ['and', 'id=1', 'id=2'], '(id=1) AND (id=2)', [] ], - [ ['and', 'type=1', ['or', 'id=1', 'id=2']], '(type=1) AND ((id=1) OR (id=2))', [] ], - [ ['and', 'id=1', new Expression('id=:qp0', [':qp0' => 2])], '(id=1) AND (id=:qp0)', [':qp0' => 2] ], + [['and', 'id=1', 'id=2'], '(id=1) AND (id=2)', []], + [['and', 'type=1', ['or', 'id=1', 'id=2']], '(type=1) AND ((id=1) OR (id=2))', []], + [['and', 'id=1', new Expression('id=:qp0', [':qp0' => 2])], '(id=1) AND (id=:qp0)', [':qp0' => 2]], // or - [ ['or', 'id=1', 'id=2'], '(id=1) OR (id=2)', [] ], - [ ['or', 'type=1', ['or', 'id=1', 'id=2']], '(type=1) OR ((id=1) OR (id=2))', [] ], - [ ['or', 'type=1', new Expression('id=:qp0', [':qp0' => 1])], '(type=1) OR (id=:qp0)', [':qp0' => 1] ], + [['or', 'id=1', 'id=2'], '(id=1) OR (id=2)', []], + [['or', 'type=1', ['or', 'id=1', 'id=2']], '(type=1) OR ((id=1) OR (id=2))', []], + [['or', 'type=1', new Expression('id=:qp0', [':qp0' => 1])], '(type=1) OR (id=:qp0)', [':qp0' => 1]], // between - [ ['between', 'id', 1, 10], '[[id]] BETWEEN :qp0 AND :qp1', [':qp0' => 1, ':qp1' => 10] ], - [ ['not between', 'id', 1, 10], '[[id]] NOT BETWEEN :qp0 AND :qp1', [':qp0' => 1, ':qp1' => 10] ], - [ ['between', 'date', new Expression('(NOW() - INTERVAL 1 MONTH)'), new Expression('NOW()')], '[[date]] BETWEEN (NOW() - INTERVAL 1 MONTH) AND NOW()', [] ], - [ ['between', 'date', new Expression('(NOW() - INTERVAL 1 MONTH)'), 123], '[[date]] BETWEEN (NOW() - INTERVAL 1 MONTH) AND :qp0', [':qp0' => 123] ], - [ ['not between', 'date', new Expression('(NOW() - INTERVAL 1 MONTH)'), new Expression('NOW()')], '[[date]] NOT BETWEEN (NOW() - INTERVAL 1 MONTH) AND NOW()', [] ], - [ ['not between', 'date', new Expression('(NOW() - INTERVAL 1 MONTH)'), 123], '[[date]] NOT BETWEEN (NOW() - INTERVAL 1 MONTH) AND :qp0', [':qp0' => 123] ], + [['between', 'id', 1, 10], '[[id]] BETWEEN :qp0 AND :qp1', [':qp0' => 1, ':qp1' => 10]], + [['not between', 'id', 1, 10], '[[id]] NOT BETWEEN :qp0 AND :qp1', [':qp0' => 1, ':qp1' => 10]], + [['between', 'date', new Expression('(NOW() - INTERVAL 1 MONTH)'), new Expression('NOW()')], '[[date]] BETWEEN (NOW() - INTERVAL 1 MONTH) AND NOW()', []], + [['between', 'date', new Expression('(NOW() - INTERVAL 1 MONTH)'), 123], '[[date]] BETWEEN (NOW() - INTERVAL 1 MONTH) AND :qp0', [':qp0' => 123]], + [['not between', 'date', new Expression('(NOW() - INTERVAL 1 MONTH)'), new Expression('NOW()')], '[[date]] NOT BETWEEN (NOW() - INTERVAL 1 MONTH) AND NOW()', []], + [['not between', 'date', new Expression('(NOW() - INTERVAL 1 MONTH)'), 123], '[[date]] NOT BETWEEN (NOW() - INTERVAL 1 MONTH) AND :qp0', [':qp0' => 123]], // in - [ ['in', 'id', [1, 2, 3]], '[[id]] IN (:qp0, :qp1, :qp2)', [':qp0' => 1, ':qp1' => 2, ':qp2' => 3] ], - [ ['not in', 'id', [1, 2, 3]], '[[id]] NOT IN (:qp0, :qp1, :qp2)', [':qp0' => 1, ':qp1' => 2, ':qp2' => 3] ], - [ ['in', 'id', (new Query())->select('id')->from('users')->where(['active' => 1])], '[[id]] IN (SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1] ], - [ ['not in', 'id', (new Query())->select('id')->from('users')->where(['active' => 1])], '[[id]] NOT IN (SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1] ], + [['in', 'id', [1, 2, 3]], '[[id]] IN (:qp0, :qp1, :qp2)', [':qp0' => 1, ':qp1' => 2, ':qp2' => 3]], + [['not in', 'id', [1, 2, 3]], '[[id]] NOT IN (:qp0, :qp1, :qp2)', [':qp0' => 1, ':qp1' => 2, ':qp2' => 3]], + [['in', 'id', (new Query())->select('id')->from('users')->where(['active' => 1])], '[[id]] IN (SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1]], + [['not in', 'id', (new Query())->select('id')->from('users')->where(['active' => 1])], '[[id]] NOT IN (SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1]], - [ ['in', 'id', 1], '[[id]]=:qp0', [':qp0' => 1] ], - [ ['in', 'id', [1]], '[[id]]=:qp0', [':qp0' => 1] ], - [ ['in', 'id', new TraversableObject([1])], '[[id]]=:qp0', [':qp0' => 1] ], + [['in', 'id', 1], '[[id]]=:qp0', [':qp0' => 1]], + [['in', 'id', [1]], '[[id]]=:qp0', [':qp0' => 1]], + [['in', 'id', new TraversableObject([1])], '[[id]]=:qp0', [':qp0' => 1]], 'composite in' => [ - ['in', ['id', 'name'], [['id' =>1, 'name' => 'oy']]], + ['in', ['id', 'name'], [['id' => 1, 'name' => 'oy']]], '([[id]], [[name]]) IN ((:qp0, :qp1))', - [':qp0' => 1, ':qp1' => 'oy'] + [':qp0' => 1, ':qp1' => 'oy'], ], // in using array objects. - [ ['id' => new TraversableObject([1, 2])], '[[id]] IN (:qp0, :qp1)', [':qp0' => 1, ':qp1' => 2] ], + [['id' => new TraversableObject([1, 2])], '[[id]] IN (:qp0, :qp1)', [':qp0' => 1, ':qp1' => 2]], - [ ['in', 'id', new TraversableObject([1, 2, 3])], '[[id]] IN (:qp0, :qp1, :qp2)', [':qp0' => 1, ':qp1' => 2, ':qp2' => 3] ], + [['in', 'id', new TraversableObject([1, 2, 3])], '[[id]] IN (:qp0, :qp1, :qp2)', [':qp0' => 1, ':qp1' => 2, ':qp2' => 3]], 'composite in using array objects' => [ ['in', new TraversableObject(['id', 'name']), new TraversableObject([ @@ -1096,51 +1100,48 @@ abstract class QueryBuilderTest extends DatabaseTestCase ['id' => 2, 'name' => 'yo'], ])], '([[id]], [[name]]) IN ((:qp0, :qp1), (:qp2, :qp3))', - [':qp0' => 1, ':qp1' => 'oy', ':qp2' => 2, ':qp3' => 'yo'] + [':qp0' => 1, ':qp1' => 'oy', ':qp2' => 2, ':qp3' => 'yo'], ], // exists - [ ['exists', (new Query())->select('id')->from('users')->where(['active' => 1])], 'EXISTS (SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1] ], - [ ['not exists', (new Query())->select('id')->from('users')->where(['active' => 1])], 'NOT EXISTS (SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1] ], + [['exists', (new Query())->select('id')->from('users')->where(['active' => 1])], 'EXISTS (SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1]], + [['not exists', (new Query())->select('id')->from('users')->where(['active' => 1])], 'NOT EXISTS (SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1]], // simple conditions - [ ['=', 'a', 'b'], '[[a]] = :qp0', [':qp0' => 'b'] ], - [ ['>', 'a', 1], '[[a]] > :qp0', [':qp0' => 1] ], - [ ['>=', 'a', 'b'], '[[a]] >= :qp0', [':qp0' => 'b'] ], - [ ['<', 'a', 2], '[[a]] < :qp0', [':qp0' => 2] ], - [ ['<=', 'a', 'b'], '[[a]] <= :qp0', [':qp0' => 'b'] ], - [ ['<>', 'a', 3], '[[a]] <> :qp0', [':qp0' => 3] ], - [ ['!=', 'a', 'b'], '[[a]] != :qp0', [':qp0' => 'b'] ], - [ ['>=', 'date', new Expression('DATE_SUB(NOW(), INTERVAL 1 MONTH)')], '[[date]] >= DATE_SUB(NOW(), INTERVAL 1 MONTH)', [] ], - [ ['>=', 'date', new Expression('DATE_SUB(NOW(), INTERVAL :month MONTH)', [':month' => 2])], '[[date]] >= DATE_SUB(NOW(), INTERVAL :month MONTH)', [':month' => 2] ], - [ ['=', 'date', (new Query())->select('max(date)')->from('test')->where(['id' => 5])], '[[date]] = (SELECT max(date) FROM [[test]] WHERE [[id]]=:qp0)', [':qp0' => 5] ], + [['=', 'a', 'b'], '[[a]] = :qp0', [':qp0' => 'b']], + [['>', 'a', 1], '[[a]] > :qp0', [':qp0' => 1]], + [['>=', 'a', 'b'], '[[a]] >= :qp0', [':qp0' => 'b']], + [['<', 'a', 2], '[[a]] < :qp0', [':qp0' => 2]], + [['<=', 'a', 'b'], '[[a]] <= :qp0', [':qp0' => 'b']], + [['<>', 'a', 3], '[[a]] <> :qp0', [':qp0' => 3]], + [['!=', 'a', 'b'], '[[a]] != :qp0', [':qp0' => 'b']], + [['>=', 'date', new Expression('DATE_SUB(NOW(), INTERVAL 1 MONTH)')], '[[date]] >= DATE_SUB(NOW(), INTERVAL 1 MONTH)', []], + [['>=', 'date', new Expression('DATE_SUB(NOW(), INTERVAL :month MONTH)', [':month' => 2])], '[[date]] >= DATE_SUB(NOW(), INTERVAL :month MONTH)', [':month' => 2]], + [['=', 'date', (new Query())->select('max(date)')->from('test')->where(['id' => 5])], '[[date]] = (SELECT max(date) FROM [[test]] WHERE [[id]]=:qp0)', [':qp0' => 5]], // hash condition - [ ['a' => 1, 'b' => 2], '([[a]]=:qp0) AND ([[b]]=:qp1)', [':qp0' => 1, ':qp1' => 2] ], - [ ['a' => new Expression('CONCAT(col1, col2)'), 'b' => 2], '([[a]]=CONCAT(col1, col2)) AND ([[b]]=:qp0)', [':qp0' => 2] ], + [['a' => 1, 'b' => 2], '([[a]]=:qp0) AND ([[b]]=:qp1)', [':qp0' => 1, ':qp1' => 2]], + [['a' => new Expression('CONCAT(col1, col2)'), 'b' => 2], '([[a]]=CONCAT(col1, col2)) AND ([[b]]=:qp0)', [':qp0' => 2]], // direct conditions - [ 'a = CONCAT(col1, col2)', 'a = CONCAT(col1, col2)', [] ], - [ new Expression('a = CONCAT(col1, :param1)', ['param1' => 'value1']), 'a = CONCAT(col1, :param1)', ['param1' => 'value1'] ], - - - + ['a = CONCAT(col1, col2)', 'a = CONCAT(col1, col2)', []], + [new Expression('a = CONCAT(col1, :param1)', ['param1' => 'value1']), 'a = CONCAT(col1, :param1)', ['param1' => 'value1']], ]; switch ($this->driverName) { case 'sqlsrv': case 'sqlite': $conditions = array_merge($conditions, [ - [ ['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]], '(([[id]] = :qp0 AND [[name]] = :qp1) OR ([[id]] = :qp2 AND [[name]] = :qp3))', [':qp0' => 1, ':qp1' => 'foo', ':qp2' => 2, ':qp3' => 'bar'] ], - [ ['not in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]], '(([[id]] != :qp0 OR [[name]] != :qp1) AND ([[id]] != :qp2 OR [[name]] != :qp3))', [':qp0' => 1, ':qp1' => 'foo', ':qp2' => 2, ':qp3' => 'bar'] ], + [['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]], '(([[id]] = :qp0 AND [[name]] = :qp1) OR ([[id]] = :qp2 AND [[name]] = :qp3))', [':qp0' => 1, ':qp1' => 'foo', ':qp2' => 2, ':qp3' => 'bar']], + [['not in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]], '(([[id]] != :qp0 OR [[name]] != :qp1) AND ([[id]] != :qp2 OR [[name]] != :qp3))', [':qp0' => 1, ':qp1' => 'foo', ':qp2' => 2, ':qp3' => 'bar']], //[ ['in', ['id', 'name'], (new Query())->select(['id', 'name'])->from('users')->where(['active' => 1])], 'EXISTS (SELECT 1 FROM (SELECT [[id]], [[name]] FROM [[users]] WHERE [[active]]=:qp0) AS a WHERE a.[[id]] = [[id AND a.]]name[[ = ]]name`)', [':qp0' => 1] ], //[ ['not in', ['id', 'name'], (new Query())->select(['id', 'name'])->from('users')->where(['active' => 1])], 'NOT EXISTS (SELECT 1 FROM (SELECT [[id]], [[name]] FROM [[users]] WHERE [[active]]=:qp0) AS a WHERE a.[[id]] = [[id]] AND a.[[name = ]]name`)', [':qp0' => 1] ], ]); break; default: $conditions = array_merge($conditions, [ - [ ['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]], '([[id]], [[name]]) IN ((:qp0, :qp1), (:qp2, :qp3))', [':qp0' => 1, ':qp1' => 'foo', ':qp2' => 2, ':qp3' => 'bar'] ], - [ ['not in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]], '([[id]], [[name]]) NOT IN ((:qp0, :qp1), (:qp2, :qp3))', [':qp0' => 1, ':qp1' => 'foo', ':qp2' => 2, ':qp3' => 'bar'] ], - [ ['in', ['id', 'name'], (new Query())->select(['id', 'name'])->from('users')->where(['active' => 1])], '([[id]], [[name]]) IN (SELECT [[id]], [[name]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1] ], - [ ['not in', ['id', 'name'], (new Query())->select(['id', 'name'])->from('users')->where(['active' => 1])], '([[id]], [[name]]) NOT IN (SELECT [[id]], [[name]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1] ], + [['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]], '([[id]], [[name]]) IN ((:qp0, :qp1), (:qp2, :qp3))', [':qp0' => 1, ':qp1' => 'foo', ':qp2' => 2, ':qp3' => 'bar']], + [['not in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]], '([[id]], [[name]]) NOT IN ((:qp0, :qp1), (:qp2, :qp3))', [':qp0' => 1, ':qp1' => 'foo', ':qp2' => 2, ':qp3' => 'bar']], + [['in', ['id', 'name'], (new Query())->select(['id', 'name'])->from('users')->where(['active' => 1])], '([[id]], [[name]]) IN (SELECT [[id]], [[name]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1]], + [['not in', ['id', 'name'], (new Query())->select(['id', 'name'])->from('users')->where(['active' => 1])], '([[id]], [[name]]) NOT IN (SELECT [[id]], [[name]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1]], ]); break; } @@ -1156,41 +1157,41 @@ abstract class QueryBuilderTest extends DatabaseTestCase { $conditions = [ // like - [ ['like', 'name', []], '', [] ], - [ ['not like', 'name', []], '', [] ], - [ ['or like', 'name', []], '', [] ], - [ ['or not like', 'name', []], '', [] ], + [['like', 'name', []], '', []], + [['not like', 'name', []], '', []], + [['or like', 'name', []], '', []], + [['or not like', 'name', []], '', []], // not - [ ['not', ''], '', [] ], + [['not', ''], '', []], // and - [ ['and', '', ''], '', [] ], - [ ['and', '', 'id=2'], '(id=2)', [] ], - [ ['and', 'id=1', ''], '(id=1)', [] ], - [ ['and', 'type=1', ['or', '', 'id=2']], '(type=1) AND ((id=2))', [] ], + [['and', '', ''], '', []], + [['and', '', 'id=2'], '(id=2)', []], + [['and', 'id=1', ''], '(id=1)', []], + [['and', 'type=1', ['or', '', 'id=2']], '(type=1) AND ((id=2))', []], // or - [ ['or', 'id=1', ''], '(id=1)', [] ], - [ ['or', 'type=1', ['or', '', 'id=2']], '(type=1) OR ((id=2))', [] ], + [['or', 'id=1', ''], '(id=1)', []], + [['or', 'type=1', ['or', '', 'id=2']], '(type=1) OR ((id=2))', []], // between - [ ['between', 'id', 1, null], '', [] ], - [ ['not between', 'id', null, 10], '', [] ], + [['between', 'id', 1, null], '', []], + [['not between', 'id', null, 10], '', []], // in - [ ['in', 'id', []], '', [] ], - [ ['not in', 'id', []], '', [] ], + [['in', 'id', []], '', []], + [['not in', 'id', []], '', []], // simple conditions - [ ['=', 'a', ''], '', [] ], - [ ['>', 'a', ''], '', [] ], - [ ['>=', 'a', ''], '', [] ], - [ ['<', 'a', ''], '', [] ], - [ ['<=', 'a', ''], '', [] ], - [ ['<>', 'a', ''], '', [] ], - [ ['!=', 'a', ''], '', [] ], + [['=', 'a', ''], '', []], + [['>', 'a', ''], '', []], + [['>=', 'a', ''], '', []], + [['<', 'a', ''], '', []], + [['<=', 'a', ''], '', []], + [['<>', 'a', ''], '', []], + [['!=', 'a', ''], '', []], ]; // adjust dbms specific escaping @@ -1225,7 +1226,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase public function testAddDropPrimaryKey() { $tableName = 'constraints'; - $pkeyName = $tableName . "_pkey"; + $pkeyName = $tableName . '_pkey'; // ADD $qb = $this->getQueryBuilder(); @@ -1255,8 +1256,8 @@ abstract class QueryBuilderTest extends DatabaseTestCase public function existsParamsProvider() { return [ - ['exists', $this->replaceQuotes("SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE EXISTS (SELECT [[1]] FROM [[Website]] [[w]])")], - ['not exists', $this->replaceQuotes("SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE NOT EXISTS (SELECT [[1]] FROM [[Website]] [[w]])")] + ['exists', $this->replaceQuotes('SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE EXISTS (SELECT [[1]] FROM [[Website]] [[w]])')], + ['not exists', $this->replaceQuotes('SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE NOT EXISTS (SELECT [[1]] FROM [[Website]] [[w]])')], ]; } @@ -1285,9 +1286,9 @@ abstract class QueryBuilderTest extends DatabaseTestCase public function testBuildWhereExistsWithParameters() { $expectedQuerySql = $this->replaceQuotes( - "SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE (EXISTS (SELECT [[1]] FROM [[Website]] [[w]] WHERE (w.id = t.website_id) AND (w.merchant_id = :merchant_id))) AND (t.some_column = :some_value)" + 'SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE (EXISTS (SELECT [[1]] FROM [[Website]] [[w]] WHERE (w.id = t.website_id) AND (w.merchant_id = :merchant_id))) AND (t.some_column = :some_value)' ); - $expectedQueryParams = [':some_value' => "asd", ':merchant_id' => 6]; + $expectedQueryParams = [':some_value' => 'asd', ':merchant_id' => 6]; $subQuery = new Query(); $subQuery->select('1') @@ -1299,7 +1300,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $query->select('id') ->from('TotalExample t') ->where(['exists', $subQuery]) - ->andWhere('t.some_column = :some_value', [':some_value' => "asd"]); + ->andWhere('t.some_column = :some_value', [':some_value' => 'asd']); list($actualQuerySql, $queryParams) = $this->getQueryBuilder()->build($query); $this->assertEquals($expectedQuerySql, $actualQuerySql); @@ -1309,7 +1310,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase public function testBuildWhereExistsWithArrayParameters() { $expectedQuerySql = $this->replaceQuotes( - "SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE (EXISTS (SELECT [[1]] FROM [[Website]] [[w]] WHERE (w.id = t.website_id) AND (([[w]].[[merchant_id]]=:qp0) AND ([[w]].[[user_id]]=:qp1)))) AND ([[t]].[[some_column]]=:qp2)" + 'SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE (EXISTS (SELECT [[1]] FROM [[Website]] [[w]] WHERE (w.id = t.website_id) AND (([[w]].[[merchant_id]]=:qp0) AND ([[w]].[[user_id]]=:qp1)))) AND ([[t]].[[some_column]]=:qp2)' ); $expectedQueryParams = [':qp0' => 6, ':qp1' => 210, ':qp2' => 'asd']; @@ -1323,7 +1324,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $query->select('id') ->from('TotalExample t') ->where(['exists', $subQuery]) - ->andWhere(['t.some_column' => "asd"]); + ->andWhere(['t.some_column' => 'asd']); list($actualQuerySql, $queryParams) = $this->getQueryBuilder()->build($query); $this->assertEquals($expectedQuerySql, $actualQuerySql); @@ -1337,7 +1338,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase public function testBuildUnion() { $expectedQuerySql = $this->replaceQuotes( - "(SELECT [[id]] FROM [[TotalExample]] [[t1]] WHERE (w > 0) AND (x < 2)) UNION ( SELECT [[id]] FROM [[TotalTotalExample]] [[t2]] WHERE w > 5 ) UNION ALL ( SELECT [[id]] FROM [[TotalTotalExample]] [[t3]] WHERE w = 3 )" + '(SELECT [[id]] FROM [[TotalExample]] [[t1]] WHERE (w > 0) AND (x < 2)) UNION ( SELECT [[id]] FROM [[TotalTotalExample]] [[t2]] WHERE w > 5 ) UNION ALL ( SELECT [[id]] FROM [[TotalTotalExample]] [[t3]] WHERE w = 3 )' ); $query = new Query(); $secondQuery = new Query(); @@ -1352,7 +1353,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->from('TotalExample t1') ->where(['and', 'w > 0', 'x < 2']) ->union($secondQuery) - ->union($thirdQuery, TRUE); + ->union($thirdQuery, true); list($actualQuerySql, $queryParams) = $this->getQueryBuilder()->build($query); $this->assertEquals($expectedQuerySql, $actualQuerySql); $this->assertEquals([], $queryParams); @@ -1368,7 +1369,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->select('*') ->from('accounts') ->addSelect(['operations_count' => $subquery]); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT *, (SELECT COUNT(*) FROM [[operations]] WHERE account_id = accounts.id) AS [[operations_count]] FROM [[accounts]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1386,7 +1387,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase new Expression($this->replaceQuotes("case t.Status_Id when 1 then 'Acknowledge' when 2 then 'No Action' else 'Unknown Action' END as [[Next Action]]")), ]) ->from('tablename'); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes( 'SELECT [[t]].[[id]] AS [[ID]], [[gsm]].[[username]] AS [[GSM]], [[part]].[[Part]], [[t]].[[Part_Cost]] AS [[Part Cost]], st_x(location::geometry) as lon,' . ' case t.Status_Id when 1 then \'Acknowledge\' when 2 then \'No Action\' else \'Unknown Action\' END as [[Next Action]] FROM [[tablename]]'); @@ -1397,31 +1398,30 @@ abstract class QueryBuilderTest extends DatabaseTestCase public function testSelectExpression() { $query = (new Query()) - ->select(new Expression("1 AS ab")) + ->select(new Expression('1 AS ab')) ->from('tablename'); - list ($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes("SELECT 1 AS ab FROM [[tablename]]"); + list($sql, $params) = $this->getQueryBuilder()->build($query); + $expected = $this->replaceQuotes('SELECT 1 AS ab FROM [[tablename]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); $query = (new Query()) - ->select(new Expression("1 AS ab")) - ->addSelect(new Expression("2 AS cd")) - ->addSelect(['ef' => new Expression("3")]) + ->select(new Expression('1 AS ab')) + ->addSelect(new Expression('2 AS cd')) + ->addSelect(['ef' => new Expression('3')]) ->from('tablename'); - list ($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes("SELECT 1 AS ab, 2 AS cd, 3 AS [[ef]] FROM [[tablename]]"); + list($sql, $params) = $this->getQueryBuilder()->build($query); + $expected = $this->replaceQuotes('SELECT 1 AS ab, 2 AS cd, 3 AS [[ef]] FROM [[tablename]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); $query = (new Query()) - ->select(new Expression("SUBSTR(name, 0, :len)", [':len' => 4])) + ->select(new Expression('SUBSTR(name, 0, :len)', [':len' => 4])) ->from('tablename'); - list ($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes("SELECT SUBSTR(name, 0, :len) FROM [[tablename]]"); + list($sql, $params) = $this->getQueryBuilder()->build($query); + $expected = $this->replaceQuotes('SELECT SUBSTR(name, 0, :len) FROM [[tablename]]'); $this->assertEquals($expected, $sql); $this->assertEquals([':len' => 4], $params); - } /** @@ -1429,16 +1429,16 @@ abstract class QueryBuilderTest extends DatabaseTestCase */ public function testFromIndexHint() { - $query = (new Query)->from([new Expression('{{%user}} USE INDEX (primary)')]); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + $query = (new Query())->from([new Expression('{{%user}} USE INDEX (primary)')]); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM {{%user}} USE INDEX (primary)'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); - $query = (new Query) + $query = (new Query()) ->from([new Expression('{{user}} {{t}} FORCE INDEX (primary) IGNORE INDEX FOR ORDER BY (i1)')]) ->leftJoin(['p' => 'profile'], 'user.id = profile.user_id USE INDEX (i2)'); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM {{user}} {{t}} FORCE INDEX (primary) IGNORE INDEX FOR ORDER BY (i1) LEFT JOIN [[profile]] [[p]] ON user.id = profile.user_id USE INDEX (i2)'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1447,19 +1447,19 @@ abstract class QueryBuilderTest extends DatabaseTestCase public function testFromSubquery() { // query subquery - $subquery = (new Query)->from('user')->where('account_id = accounts.id'); - $query = (new Query)->from(['activeusers' => $subquery]); + $subquery = (new Query())->from('user')->where('account_id = accounts.id'); + $query = (new Query())->from(['activeusers' => $subquery]); // SELECT * FROM (SELECT * FROM [[user]] WHERE [[active]] = 1) [[activeusers]]; - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM (SELECT * FROM [[user]] WHERE account_id = accounts.id) [[activeusers]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); // query subquery with params - $subquery = (new Query)->from('user')->where('account_id = :id', ['id' => 1]); - $query = (new Query)->from(['activeusers' => $subquery])->where('abc = :abc', ['abc' => 'abc']); + $subquery = (new Query())->from('user')->where('account_id = :id', ['id' => 1]); + $query = (new Query())->from(['activeusers' => $subquery])->where('abc = :abc', ['abc' => 'abc']); // SELECT * FROM (SELECT * FROM [[user]] WHERE [[active]] = 1) [[activeusers]]; - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM (SELECT * FROM [[user]] WHERE account_id = :id) [[activeusers]] WHERE abc = :abc'); $this->assertEquals($expected, $sql); $this->assertEquals([ @@ -1468,10 +1468,10 @@ abstract class QueryBuilderTest extends DatabaseTestCase ], $params); // simple subquery - $subquery = "(SELECT * FROM user WHERE account_id = accounts.id)"; - $query = (new Query)->from(['activeusers' => $subquery]); + $subquery = '(SELECT * FROM user WHERE account_id = accounts.id)'; + $query = (new Query())->from(['activeusers' => $subquery]); // SELECT * FROM (SELECT * FROM [[user]] WHERE [[active]] = 1) [[activeusers]]; - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM (SELECT * FROM user WHERE account_id = accounts.id) [[activeusers]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1484,7 +1484,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->select('*') ->from('operations') ->orderBy('name ASC, date DESC'); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM [[operations]] ORDER BY [[name]], [[date]] DESC'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1494,7 +1494,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->select('*') ->from('operations') ->orderBy(['name' => SORT_ASC, 'date' => SORT_DESC]); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM [[operations]] ORDER BY [[name]], [[date]] DESC'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1505,7 +1505,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->from('operations') ->where('account_id = accounts.id') ->orderBy(new Expression('SUBSTR(name, 3, 4) DESC, x ASC')); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM [[operations]] WHERE account_id = accounts.id ORDER BY SUBSTR(name, 3, 4) DESC, x ASC'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1515,7 +1515,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->select('*') ->from('operations') ->orderBy(new Expression('SUBSTR(name, 3, :to) DESC, x ASC', [':to' => 4])); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM [[operations]] ORDER BY SUBSTR(name, 3, :to) DESC, x ASC'); $this->assertEquals($expected, $sql); $this->assertEquals([':to' => 4], $params); @@ -1528,7 +1528,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->select('*') ->from('operations') ->groupBy('name, date'); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM [[operations]] GROUP BY [[name]], [[date]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1538,7 +1538,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->select('*') ->from('operations') ->groupBy(['name', 'date']); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM [[operations]] GROUP BY [[name]], [[date]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1549,7 +1549,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->from('operations') ->where('account_id = accounts.id') ->groupBy(new Expression('SUBSTR(name, 0, 1), x')); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM [[operations]] WHERE account_id = accounts.id GROUP BY SUBSTR(name, 0, 1), x'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1559,7 +1559,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->select('*') ->from('operations') ->groupBy(new Expression('SUBSTR(name, 0, :to), x', [':to' => 4])); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM [[operations]] GROUP BY SUBSTR(name, 0, :to), x'); $this->assertEquals($expected, $sql); $this->assertEquals([':to' => 4], $params); @@ -1578,43 +1578,43 @@ abstract class QueryBuilderTest extends DatabaseTestCase 'customer', ['email', 'name', 'address'], [['test@example.com', 'silverfire', 'Kyiv {{city}}, Ukraine']], - $this->replaceQuotes("INSERT INTO [[customer]] ([[email]], [[name]], [[address]]) VALUES ('test@example.com', 'silverfire', 'Kyiv {{city}}, Ukraine')") + $this->replaceQuotes("INSERT INTO [[customer]] ([[email]], [[name]], [[address]]) VALUES ('test@example.com', 'silverfire', 'Kyiv {{city}}, Ukraine')"), ], 'escape-danger-chars' => [ 'customer', ['address'], [["SQL-danger chars are escaped: '); --"]], - 'expected' => $this->replaceQuotes("INSERT INTO [[customer]] ([[address]]) VALUES ('SQL-danger chars are escaped: \'); --')") + 'expected' => $this->replaceQuotes("INSERT INTO [[customer]] ([[address]]) VALUES ('SQL-danger chars are escaped: \'); --')"), ], [ 'customer', ['address'], [], - '' + '', ], [ 'customer', [], - [["no columns passed"]], - $this->replaceQuotes("INSERT INTO [[customer]] () VALUES ('no columns passed')") + [['no columns passed']], + $this->replaceQuotes("INSERT INTO [[customer]] () VALUES ('no columns passed')"), ], 'bool-false, bool2-null' => [ 'type', ['bool_col', 'bool_col2'], [[false, null]], - 'expected' => $this->replaceQuotes("INSERT INTO [[type]] ([[bool_col]], [[bool_col2]]) VALUES (0, NULL)") + 'expected' => $this->replaceQuotes('INSERT INTO [[type]] ([[bool_col]], [[bool_col2]]) VALUES (0, NULL)'), ], [ '{{%type}}', ['{{%type}}.[[float_col]]', '[[time]]'], [[null, new Expression('now()')]], - "INSERT INTO {{%type}} ({{%type}}.[[float_col]], [[time]]) VALUES (NULL, now())" + 'INSERT INTO {{%type}} ({{%type}}.[[float_col]], [[time]]) VALUES (NULL, now())', ], 'bool-false, time-now()' => [ '{{%type}}', ['{{%type}}.[[bool_col]]', '[[time]]'], [[false, new Expression('now()')]], - 'expected' => "INSERT INTO {{%type}} ({{%type}}.[[bool_col]], [[time]]) VALUES (0, now())" + 'expected' => 'INSERT INTO {{%type}} ({{%type}}.[[bool_col]], [[time]]) VALUES (0, now())', ], ]; } @@ -1675,26 +1675,26 @@ abstract class QueryBuilderTest extends DatabaseTestCase { $conditions = [ // simple like - [ ['like', 'name', 'foo%'], '[[name]] LIKE :qp0', [':qp0' => '%foo\%%'] ], - [ ['not like', 'name', 'foo%'], '[[name]] NOT LIKE :qp0', [':qp0' => '%foo\%%'] ], - [ ['or like', 'name', 'foo%'], '[[name]] LIKE :qp0', [':qp0' => '%foo\%%'] ], - [ ['or not like', 'name', 'foo%'], '[[name]] NOT LIKE :qp0', [':qp0' => '%foo\%%'] ], + [['like', 'name', 'foo%'], '[[name]] LIKE :qp0', [':qp0' => '%foo\%%']], + [['not like', 'name', 'foo%'], '[[name]] NOT LIKE :qp0', [':qp0' => '%foo\%%']], + [['or like', 'name', 'foo%'], '[[name]] LIKE :qp0', [':qp0' => '%foo\%%']], + [['or not like', 'name', 'foo%'], '[[name]] NOT LIKE :qp0', [':qp0' => '%foo\%%']], // like for many values - [ ['like', 'name', ['foo%', '[abc]']], '[[name]] LIKE :qp0 AND [[name]] LIKE :qp1', [':qp0' => '%foo\%%', ':qp1' => '%[abc]%'] ], - [ ['not like', 'name', ['foo%', '[abc]']], '[[name]] NOT LIKE :qp0 AND [[name]] NOT LIKE :qp1', [':qp0' => '%foo\%%', ':qp1' => '%[abc]%'] ], - [ ['or like', 'name', ['foo%', '[abc]']], '[[name]] LIKE :qp0 OR [[name]] LIKE :qp1', [':qp0' => '%foo\%%', ':qp1' => '%[abc]%'] ], - [ ['or not like', 'name', ['foo%', '[abc]']], '[[name]] NOT LIKE :qp0 OR [[name]] NOT LIKE :qp1', [':qp0' => '%foo\%%', ':qp1' => '%[abc]%'] ], + [['like', 'name', ['foo%', '[abc]']], '[[name]] LIKE :qp0 AND [[name]] LIKE :qp1', [':qp0' => '%foo\%%', ':qp1' => '%[abc]%']], + [['not like', 'name', ['foo%', '[abc]']], '[[name]] NOT LIKE :qp0 AND [[name]] NOT LIKE :qp1', [':qp0' => '%foo\%%', ':qp1' => '%[abc]%']], + [['or like', 'name', ['foo%', '[abc]']], '[[name]] LIKE :qp0 OR [[name]] LIKE :qp1', [':qp0' => '%foo\%%', ':qp1' => '%[abc]%']], + [['or not like', 'name', ['foo%', '[abc]']], '[[name]] NOT LIKE :qp0 OR [[name]] NOT LIKE :qp1', [':qp0' => '%foo\%%', ':qp1' => '%[abc]%']], // like with Expression - [ ['like', 'name', new Expression('CONCAT("test", name, "%")')], '[[name]] LIKE CONCAT("test", name, "%")', [] ], - [ ['not like', 'name', new Expression('CONCAT("test", name, "%")')], '[[name]] NOT LIKE CONCAT("test", name, "%")', [] ], - [ ['or like', 'name', new Expression('CONCAT("test", name, "%")')], '[[name]] LIKE CONCAT("test", name, "%")', [] ], - [ ['or not like', 'name', new Expression('CONCAT("test", name, "%")')], '[[name]] NOT LIKE CONCAT("test", name, "%")', [] ], - [ ['like', 'name', [new Expression('CONCAT("test", name, "%")'), '\ab_c']], '[[name]] LIKE CONCAT("test", name, "%") AND [[name]] LIKE :qp0', [':qp0' => '%\\\ab\_c%'] ], - [ ['not like', 'name', [new Expression('CONCAT("test", name, "%")'), '\ab_c']], '[[name]] NOT LIKE CONCAT("test", name, "%") AND [[name]] NOT LIKE :qp0', [':qp0' => '%\\\ab\_c%'] ], - [ ['or like', 'name', [new Expression('CONCAT("test", name, "%")'), '\ab_c']], '[[name]] LIKE CONCAT("test", name, "%") OR [[name]] LIKE :qp0', [':qp0' => '%\\\ab\_c%'] ], - [ ['or not like', 'name', [new Expression('CONCAT("test", name, "%")'), '\ab_c']], '[[name]] NOT LIKE CONCAT("test", name, "%") OR [[name]] NOT LIKE :qp0', [':qp0' => '%\\\ab\_c%'] ], + [['like', 'name', new Expression('CONCAT("test", name, "%")')], '[[name]] LIKE CONCAT("test", name, "%")', []], + [['not like', 'name', new Expression('CONCAT("test", name, "%")')], '[[name]] NOT LIKE CONCAT("test", name, "%")', []], + [['or like', 'name', new Expression('CONCAT("test", name, "%")')], '[[name]] LIKE CONCAT("test", name, "%")', []], + [['or not like', 'name', new Expression('CONCAT("test", name, "%")')], '[[name]] NOT LIKE CONCAT("test", name, "%")', []], + [['like', 'name', [new Expression('CONCAT("test", name, "%")'), '\ab_c']], '[[name]] LIKE CONCAT("test", name, "%") AND [[name]] LIKE :qp0', [':qp0' => '%\\\ab\_c%']], + [['not like', 'name', [new Expression('CONCAT("test", name, "%")'), '\ab_c']], '[[name]] NOT LIKE CONCAT("test", name, "%") AND [[name]] NOT LIKE :qp0', [':qp0' => '%\\\ab\_c%']], + [['or like', 'name', [new Expression('CONCAT("test", name, "%")'), '\ab_c']], '[[name]] LIKE CONCAT("test", name, "%") OR [[name]] LIKE :qp0', [':qp0' => '%\\\ab\_c%']], + [['or not like', 'name', [new Expression('CONCAT("test", name, "%")'), '\ab_c']], '[[name]] NOT LIKE CONCAT("test", name, "%") OR [[name]] NOT LIKE :qp0', [':qp0' => '%\\\ab\_c%']], ]; // adjust dbms specific escaping diff --git a/tests/framework/db/QueryTest.php b/tests/framework/db/QueryTest.php index 50d038a43f..b225487a14 100644 --- a/tests/framework/db/QueryTest.php +++ b/tests/framework/db/QueryTest.php @@ -1,4 +1,9 @@ select('*'); $this->assertEquals(['*'], $query->select); $this->assertNull($query->distinct); $this->assertEquals(null, $query->selectOption); - $query = new Query; + $query = new Query(); $query->select('id, name', 'something')->distinct(true); $this->assertEquals(['id', 'name'], $query->select); $this->assertTrue($query->distinct); @@ -36,14 +41,14 @@ abstract class QueryTest extends DatabaseTestCase public function testFrom() { - $query = new Query; + $query = new Query(); $query->from('user'); $this->assertEquals(['user'], $query->from); } public function testWhere() { - $query = new Query; + $query = new Query(); $query->where('id = :id', [':id' => 1]); $this->assertEquals('id = :id', $query->where); $this->assertEquals([':id' => 1], $query->params); @@ -59,7 +64,7 @@ abstract class QueryTest extends DatabaseTestCase public function testFilterWhereWithHashFormat() { - $query = new Query; + $query = new Query(); $query->filterWhere([ 'id' => 0, 'title' => ' ', @@ -76,7 +81,7 @@ abstract class QueryTest extends DatabaseTestCase public function testFilterWhereWithOperatorFormat() { - $query = new Query; + $query = new Query(); $condition = ['like', 'name', 'Alex']; $query->filterWhere($condition); $this->assertEquals($condition, $query->where); @@ -111,7 +116,7 @@ abstract class QueryTest extends DatabaseTestCase public function testFilterHavingWithHashFormat() { - $query = new Query; + $query = new Query(); $query->filterHaving([ 'id' => 0, 'title' => ' ', @@ -128,7 +133,7 @@ abstract class QueryTest extends DatabaseTestCase public function testFilterHavingWithOperatorFormat() { - $query = new Query; + $query = new Query(); $condition = ['like', 'name', 'Alex']; $query->filterHaving($condition); $this->assertEquals($condition, $query->having); @@ -174,7 +179,7 @@ abstract class QueryTest extends DatabaseTestCase public function testGroup() { - $query = new Query; + $query = new Query(); $query->groupBy('team'); $this->assertEquals(['team'], $query->groupBy); @@ -187,7 +192,7 @@ abstract class QueryTest extends DatabaseTestCase public function testHaving() { - $query = new Query; + $query = new Query(); $query->having('id = :id', [':id' => 1]); $this->assertEquals('id = :id', $query->having); $this->assertEquals([':id' => 1], $query->params); @@ -203,7 +208,7 @@ abstract class QueryTest extends DatabaseTestCase public function testOrder() { - $query = new Query; + $query = new Query(); $query->orderBy('team'); $this->assertEquals(['team' => SORT_ASC], $query->orderBy); @@ -230,7 +235,7 @@ abstract class QueryTest extends DatabaseTestCase public function testLimitOffset() { - $query = new Query; + $query = new Query(); $query->limit(10)->offset(5); $this->assertEquals(10, $query->limit); $this->assertEquals(5, $query->offset); @@ -255,7 +260,7 @@ abstract class QueryTest extends DatabaseTestCase public function testUnion() { $connection = $this->getConnection(); - $query = new Query; + $query = new Query(); $query->select(['id', 'name']) ->from('item') ->limit(2) @@ -274,10 +279,10 @@ abstract class QueryTest extends DatabaseTestCase { $db = $this->getConnection(); - $result = (new Query)->from('customer')->where(['status' => 2])->one($db); + $result = (new Query())->from('customer')->where(['status' => 2])->one($db); $this->assertEquals('user3', $result['name']); - $result = (new Query)->from('customer')->where(['status' => 3])->one($db); + $result = (new Query())->from('customer')->where(['status' => 3])->one($db); $this->assertFalse($result); } @@ -285,21 +290,21 @@ abstract class QueryTest extends DatabaseTestCase { $db = $this->getConnection(); - $result = (new Query)->from('customer')->where(['status' => 2])->exists($db); + $result = (new Query())->from('customer')->where(['status' => 2])->exists($db); $this->assertTrue($result); - $result = (new Query)->from('customer')->where(['status' => 3])->exists($db); + $result = (new Query())->from('customer')->where(['status' => 3])->exists($db); $this->assertFalse($result); } public function testColumn() { $db = $this->getConnection(); - $result = (new Query)->select('name')->from('customer')->orderBy(['id' => SORT_DESC])->column($db); + $result = (new Query())->select('name')->from('customer')->orderBy(['id' => SORT_DESC])->column($db); $this->assertEquals(['user3', 'user2', 'user1'], $result); // https://github.com/yiisoft/yii2/issues/7515 - $result = (new Query)->from('customer') + $result = (new Query())->from('customer') ->select('name') ->orderBy(['id' => SORT_DESC]) ->indexBy('id') @@ -307,7 +312,7 @@ abstract class QueryTest extends DatabaseTestCase $this->assertEquals([3 => 'user3', 2 => 'user2', 1 => 'user1'], $result); // https://github.com/yiisoft/yii2/issues/12649 - $result = (new Query)->from('customer') + $result = (new Query())->from('customer') ->select(['name', 'id']) ->orderBy(['id' => SORT_DESC]) ->indexBy(function ($row) { @@ -316,7 +321,7 @@ abstract class QueryTest extends DatabaseTestCase ->column($db); $this->assertEquals([6 => 'user3', 4 => 'user2', 2 => 'user1'], $result); - $result = (new Query)->from('customer') + $result = (new Query())->from('customer') ->select(['name']) ->indexBy('name') ->orderBy(['id' => SORT_DESC]) @@ -328,20 +333,20 @@ abstract class QueryTest extends DatabaseTestCase { $db = $this->getConnection(); - $count = (new Query)->from('customer')->count('*', $db); + $count = (new Query())->from('customer')->count('*', $db); $this->assertEquals(3, $count); - $count = (new Query)->from('customer')->where(['status' => 2])->count('*', $db); + $count = (new Query())->from('customer')->where(['status' => 2])->count('*', $db); $this->assertEquals(1, $count); - $count = (new Query)->select('[[status]], COUNT([[id]])')->from('customer')->groupBy('status')->count('*', $db); + $count = (new Query())->select('[[status]], COUNT([[id]])')->from('customer')->groupBy('status')->count('*', $db); $this->assertEquals(2, $count); // testing that orderBy() should be ignored here as it does not affect the count anyway. - $count = (new Query)->from('customer')->orderBy('status')->count('*', $db); + $count = (new Query())->from('customer')->orderBy('status')->count('*', $db); $this->assertEquals(3, $count); - - $count = (new Query)->from('customer')->orderBy('id')->limit(1)->count('*', $db); + + $count = (new Query())->from('customer')->orderBy('id')->limit(1)->count('*', $db); $this->assertEquals(3, $count); } @@ -351,7 +356,7 @@ abstract class QueryTest extends DatabaseTestCase */ public function testAndFilterCompare() { - $query = new Query; + $query = new Query(); $result = $query->andFilterCompare('name', null); $this->assertInstanceOf('yii\db\Query', $result); @@ -390,7 +395,7 @@ abstract class QueryTest extends DatabaseTestCase $db = $this->getConnection(); - $count = (new Query)->from('customer')->having(['status' => 2])->count('*', $db); + $count = (new Query())->from('customer')->having(['status' => 2])->count('*', $db); $this->assertEquals(1, $count); } @@ -496,11 +501,11 @@ abstract class QueryTest extends DatabaseTestCase $tableName = 'like_test'; $columnName = 'col'; - if($db->getSchema()->getTableSchema($tableName) !== null){ + if ($db->getSchema()->getTableSchema($tableName) !== null) { $db->createCommand()->dropTable($tableName)->execute(); } $db->createCommand()->createTable($tableName, [ - $columnName => $db->getSchema()->createColumnSchemaBuilder(Schema::TYPE_STRING, 64) + $columnName => $db->getSchema()->createColumnSchemaBuilder(Schema::TYPE_STRING, 64), ])->execute(); $db->createCommand()->batchInsert($tableName, ['col'], [ ['test0'], diff --git a/tests/framework/db/SchemaTest.php b/tests/framework/db/SchemaTest.php index f80d7aefdf..871529ceb7 100644 --- a/tests/framework/db/SchemaTest.php +++ b/tests/framework/db/SchemaTest.php @@ -1,4 +1,9 @@ 'string', 'allowNull' => true, 'autoIncrement' => false, - 'enumValues' => ['a', 'B','c,D'], + 'enumValues' => ['a', 'B', 'c,D'], 'size' => null, 'precision' => null, 'scale' => null, @@ -376,7 +381,7 @@ abstract class SchemaTest extends DatabaseTestCase $this->assertSame($expected['precision'], $column->precision, "precision of column $name does not match."); $this->assertSame($expected['scale'], $column->scale, "scale of column $name does not match."); if (is_object($expected['defaultValue'])) { - $this->assertTrue(is_object($column->defaultValue), "defaultValue of column $name is expected to be an object but it is not."); + $this->assertInternalType('object', $column->defaultValue, "defaultValue of column $name is expected to be an object but it is not."); $this->assertEquals((string) $expected['defaultValue'], (string) $column->defaultValue, "defaultValue of column $name does not match."); } else { $this->assertSame($expected['defaultValue'], $column->defaultValue, "defaultValue of column $name does not match."); diff --git a/tests/framework/db/UnqueryableQueryMock.php b/tests/framework/db/UnqueryableQueryMock.php index 87172be484..e95d275d69 100644 --- a/tests/framework/db/UnqueryableQueryMock.php +++ b/tests/framework/db/UnqueryableQueryMock.php @@ -1,4 +1,9 @@ createCommand($sql); - $this->assertEquals("SELECT [id], [t].[name] FROM [customer] t", $command->sql); + $this->assertEquals('SELECT [id], [t].[name] FROM [customer] t', $command->sql); } public function testPrepareCancel() diff --git a/tests/framework/db/mssql/ConnectionTest.php b/tests/framework/db/mssql/ConnectionTest.php index 3658b4ca05..7e7024d7de 100644 --- a/tests/framework/db/mssql/ConnectionTest.php +++ b/tests/framework/db/mssql/ConnectionTest.php @@ -1,4 +1,9 @@ primaryKey()->after('col_before'), - 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY AFTER `col_before`' + 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY AFTER `col_before`', ], [ Schema::TYPE_PK . ' FIRST', $this->primaryKey()->first(), - 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST' + 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST', ], [ Schema::TYPE_PK . ' FIRST', $this->primaryKey()->first()->after('col_before'), - 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST' + 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST', ], [ Schema::TYPE_PK . '(8) AFTER `col_before`', $this->primaryKey(8)->after('col_before'), - 'int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY AFTER `col_before`' + 'int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY AFTER `col_before`', ], [ Schema::TYPE_PK . '(8) FIRST', $this->primaryKey(8)->first(), - 'int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST' + 'int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST', ], [ Schema::TYPE_PK . '(8) FIRST', $this->primaryKey(8)->first()->after('col_before'), - 'int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST' + 'int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST', ], [ Schema::TYPE_PK . " COMMENT 'test' AFTER `col_before`", $this->primaryKey()->comment('test')->after('col_before'), - "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'test' AFTER `col_before`" + "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'test' AFTER `col_before`", ], ]); } diff --git a/tests/framework/db/mysql/QueryTest.php b/tests/framework/db/mysql/QueryTest.php index 1e9018ce7b..f22539860f 100644 --- a/tests/framework/db/mysql/QueryTest.php +++ b/tests/framework/db/mysql/QueryTest.php @@ -1,6 +1,12 @@ getConnection(); - $query = (new Query)->from([new Expression('{{%customer}} USE INDEX (primary)')]); + $query = (new Query())->from([new Expression('{{%customer}} USE INDEX (primary)')]); $row = $query->one($db); $this->assertArrayHasKey('id', $row); $this->assertArrayHasKey('name', $row); diff --git a/tests/framework/db/mysql/SchemaTest.php b/tests/framework/db/mysql/SchemaTest.php index b103632e5d..5671904bbf 100644 --- a/tests/framework/db/mysql/SchemaTest.php +++ b/tests/framework/db/mysql/SchemaTest.php @@ -1,4 +1,9 @@ getLogContentAndDelete(); if ($errors) { $this->fail( - join('; ', $errors) + implode('; ', $errors) . ($logContent ? ". Shared children log:\n$logContent" : '') ); } @@ -137,16 +142,16 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest private function childrenSelectAndAccidentUpdate($pidSecond) { try { - $this->log("child 1: connect"); + $this->log('child 1: connect'); /** @var Connection $first */ $first = $this->getConnection(false, false); - $this->log("child 1: delete"); + $this->log('child 1: delete'); $first->createCommand() ->delete('{{customer}}', ['id' => 97]) ->execute(); - $this->log("child 1: insert"); + $this->log('child 1: insert'); // insert test row $first->createCommand() ->insert('{{customer}}', [ @@ -157,15 +162,15 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest ]) ->execute(); - $this->log("child 1: transaction"); + $this->log('child 1: transaction'); $first->transaction(function (Connection $first) use ($pidSecond) { $first->transaction(function (Connection $first) use ($pidSecond) { - $this->log("child 1: select"); + $this->log('child 1: select'); // SELECT with shared lock - $first->createCommand("SELECT id FROM {{customer}} WHERE id = 97 LOCK IN SHARE MODE") + $first->createCommand('SELECT id FROM {{customer}} WHERE id = 97 LOCK IN SHARE MODE') ->execute(); - $this->log("child 1: send signal to child 2"); + $this->log('child 1: send signal to child 2'); // let child to continue if (!posix_kill($pidSecond, SIGUSR1)) { throw new \RuntimeException('Cannot send signal'); @@ -176,16 +181,16 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest // delay to let child hit the lock sleep(2); - $this->log("child 1: update"); + $this->log('child 1: update'); // now do the 3rd update for deadlock $first->createCommand() ->update('{{customer}}', ['name' => 'first'], ['id' => 97]) ->execute(); - $this->log("child 1: commit"); + $this->log('child 1: commit'); }); }, Transaction::REPEATABLE_READ); } catch (Exception $e) { - list ($sqlError, $driverError, $driverMessage) = $e->errorInfo; + list($sqlError, $driverError, $driverMessage) = $e->errorInfo; // Deadlock found when trying to get lock; try restarting transaction if ('40001' === $sqlError && 1213 === $driverError) { return self::CHILD_EXIT_CODE_DEADLOCK; @@ -193,13 +198,13 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest $this->log("child 1: ! sql error $sqlError: $driverError: $driverMessage"); return 1; } catch (\Exception $e) { - $this->log("child 1: ! exit <<" . get_class($e) . " #" . $e->getCode() . ": " . $e->getMessage() . "\n" . $e->getTraceAsString() . ">>"); + $this->log('child 1: ! exit <<' . get_class($e) . ' #' . $e->getCode() . ': ' . $e->getMessage() . "\n" . $e->getTraceAsString() . '>>'); return 1; } catch (\Throwable $e) { - $this->log("child 1: ! exit <<" . get_class($e) . " #" . $e->getCode() . ": " . $e->getMessage() . "\n" . $e->getTraceAsString() . ">>"); + $this->log('child 1: ! exit <<' . get_class($e) . ' #' . $e->getCode() . ': ' . $e->getMessage() . "\n" . $e->getTraceAsString() . '>>'); return 1; } - $this->log("child 1: exit"); + $this->log('child 1: exit'); return 0; } @@ -215,37 +220,37 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest { // install no-op signal handler to prevent termination if (!pcntl_signal(SIGUSR1, function () {}, false)) { - $this->log("child 2: cannot install signal handler"); + $this->log('child 2: cannot install signal handler'); return 1; } try { // at first, parent should do 1st select - $this->log("child 2: wait signal from child 1"); + $this->log('child 2: wait signal from child 1'); if (pcntl_sigtimedwait([SIGUSR1], $info, 10) <= 0) { - $this->log("child 2: wait timeout exceeded"); + $this->log('child 2: wait timeout exceeded'); return 1; } - $this->log("child 2: connect"); + $this->log('child 2: connect'); /** @var Connection $second */ $second = $this->getConnection(true, false); $second->open(); //sleep(1); - $this->log("child 2: transaction"); + $this->log('child 2: transaction'); $second->transaction(function (Connection $second) { $second->transaction(function (Connection $second) { - $this->log("child 2: update"); + $this->log('child 2: update'); // do the 2nd update $second->createCommand() ->update('{{customer}}', ['name' => 'second'], ['id' => 97]) ->execute(); - $this->log("child 2: commit"); + $this->log('child 2: commit'); }); }, Transaction::REPEATABLE_READ); } catch (Exception $e) { - list ($sqlError, $driverError, $driverMessage) = $e->errorInfo; + list($sqlError, $driverError, $driverMessage) = $e->errorInfo; // Deadlock found when trying to get lock; try restarting transaction if ('40001' === $sqlError && 1213 === $driverError) { return self::CHILD_EXIT_CODE_DEADLOCK; @@ -253,13 +258,13 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest $this->log("child 2: ! sql error $sqlError: $driverError: $driverMessage"); return 1; } catch (\Exception $e) { - $this->log("child 2: ! exit <<" . get_class($e) . " #" . $e->getCode() . ": " . $e->getMessage() . "\n" . $e->getTraceAsString() . ">>"); + $this->log('child 2: ! exit <<' . get_class($e) . ' #' . $e->getCode() . ': ' . $e->getMessage() . "\n" . $e->getTraceAsString() . '>>'); return 1; } catch (\Throwable $e) { - $this->log("child 2: ! exit <<" . get_class($e) . " #" . $e->getCode() . ": " . $e->getMessage() . "\n" . $e->getTraceAsString() . ">>"); + $this->log('child 2: ! exit <<' . get_class($e) . ' #' . $e->getCode() . ': ' . $e->getMessage() . "\n" . $e->getTraceAsString() . '>>'); return 1; } - $this->log("child 2: exit"); + $this->log('child 2: exit'); return 0; } diff --git a/tests/framework/db/oci/ActiveDataProviderTest.php b/tests/framework/db/oci/ActiveDataProviderTest.php index b08cfbbf5c..7831afceea 100644 --- a/tests/framework/db/oci/ActiveDataProviderTest.php +++ b/tests/framework/db/oci/ActiveDataProviderTest.php @@ -1,4 +1,9 @@ assertInstanceOf('yii\db\Connection', $unserialized); - $this->assertEquals(123, $unserialized->createCommand("SELECT 123 FROM DUAL")->queryScalar()); + $this->assertEquals(123, $unserialized->createCommand('SELECT 123 FROM DUAL')->queryScalar()); } public function testQuoteTableName() diff --git a/tests/framework/db/oci/ExistValidatorTest.php b/tests/framework/db/oci/ExistValidatorTest.php index ca18cfa2fb..5c5c5831e2 100644 --- a/tests/framework/db/oci/ExistValidatorTest.php +++ b/tests/framework/db/oci/ExistValidatorTest.php @@ -1,4 +1,9 @@ boolean()->notNull()->defaultValue(1), - 'NUMBER(1) DEFAULT 1 NOT NULL' + 'NUMBER(1) DEFAULT 1 NOT NULL', ], ]); } @@ -67,12 +72,12 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $qb = $this->getQueryBuilder(); $expected = 'DROP SEQUENCE "item_SEQ";' - .'CREATE SEQUENCE "item_SEQ" START WITH 6 INCREMENT BY 1 NOMAXVALUE NOCACHE'; + . 'CREATE SEQUENCE "item_SEQ" START WITH 6 INCREMENT BY 1 NOMAXVALUE NOCACHE'; $sql = $qb->resetSequence('item'); $this->assertEquals($expected, $sql); $expected = 'DROP SEQUENCE "item_SEQ";' - .'CREATE SEQUENCE "item_SEQ" START WITH 4 INCREMENT BY 1 NOMAXVALUE NOCACHE'; + . 'CREATE SEQUENCE "item_SEQ" START WITH 4 INCREMENT BY 1 NOMAXVALUE NOCACHE'; $sql = $qb->resetSequence('item', 4); $this->assertEquals($expected, $sql); } @@ -97,10 +102,10 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest ' (' . '([[id]] IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 0, 999)) . '))' . ' OR ([[id]] IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 1000, 1999)) . '))' - . ' OR ([[id]] IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 2000, 2500)) .'))' + . ' OR ([[id]] IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 2000, 2500)) . '))' . ')', - array_flip($this->generateSprintfSeries(':qp%d', 0, 2500)) + array_flip($this->generateSprintfSeries(':qp%d', 0, 2500)), ], [ ['not in', 'id', range(0, 2500)], @@ -108,10 +113,10 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest '(' . '([[id]] NOT IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 0, 999)) . '))' . ' AND ([[id]] NOT IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 1000, 1999)) . '))' - . ' AND ([[id]] NOT IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 2000, 2500)) .'))' + . ' AND ([[id]] NOT IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 2000, 2500)) . '))' . ')', - array_flip($this->generateSprintfSeries(':qp%d', 0, 2500)) + array_flip($this->generateSprintfSeries(':qp%d', 0, 2500)), ], [ ['not in', 'id', new TraversableObject(range(0, 2500))], @@ -119,15 +124,16 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest '(' . '([[id]] NOT IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 0, 999)) . '))' . ' AND ([[id]] NOT IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 1000, 1999)) . '))' - . ' AND ([[id]] NOT IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 2000, 2500)) .'))' + . ' AND ([[id]] NOT IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 2000, 2500)) . '))' . ')', - array_flip($this->generateSprintfSeries(':qp%d', 0, 2500)) + array_flip($this->generateSprintfSeries(':qp%d', 0, 2500)), ], ]); } - protected function generateSprintfSeries ($pattern, $from, $to) { + protected function generateSprintfSeries($pattern, $from, $to) + { $items = []; for ($i = $from; $i <= $to; $i++) { $items[] = sprintf($pattern, $i); diff --git a/tests/framework/db/oci/QueryTest.php b/tests/framework/db/oci/QueryTest.php index 306e7396d4..e2a2c82c97 100644 --- a/tests/framework/db/oci/QueryTest.php +++ b/tests/framework/db/oci/QueryTest.php @@ -1,4 +1,9 @@ getConnection(); - $result = (new Query)->from('customer')->where(['[[status]]' => 2])->one($db); + $result = (new Query())->from('customer')->where(['[[status]]' => 2])->one($db); $this->assertEquals('user3', $result['name']); - $result = (new Query)->from('customer')->where(['[[status]]' => 3])->one($db); + $result = (new Query())->from('customer')->where(['[[status]]' => 3])->one($db); $this->assertFalse($result); } } diff --git a/tests/framework/db/oci/SchemaTest.php b/tests/framework/db/oci/SchemaTest.php index 8198230e6a..a65b0c350b 100644 --- a/tests/framework/db/oci/SchemaTest.php +++ b/tests/framework/db/oci/SchemaTest.php @@ -1,10 +1,12 @@ getConnection(); $db->charset = 'utf8'; - $db->createCommand("DROP TABLE IF EXISTS bool_user;")->execute(); + $db->createCommand('DROP TABLE IF EXISTS bool_user;')->execute(); $db->createCommand()->createTable('bool_user', [ 'id' => Schema::TYPE_PK, 'username' => Schema::TYPE_STRING . ' NOT NULL', diff --git a/tests/framework/db/pgsql/BatchQueryResultTest.php b/tests/framework/db/pgsql/BatchQueryResultTest.php index 9261baa557..e9356116d9 100644 --- a/tests/framework/db/pgsql/BatchQueryResultTest.php +++ b/tests/framework/db/pgsql/BatchQueryResultTest.php @@ -1,4 +1,9 @@ assertTrue(is_object($this->getConnection(true))); + $this->assertInternalType('object', $this->getConnection(true)); } public function testQuoteValue() diff --git a/tests/framework/db/pgsql/ExistValidatorTest.php b/tests/framework/db/pgsql/ExistValidatorTest.php index 978b42af71..0f13237741 100644 --- a/tests/framework/db/pgsql/ExistValidatorTest.php +++ b/tests/framework/db/pgsql/ExistValidatorTest.php @@ -1,4 +1,9 @@ boolean()->notNull()->defaultValue(true), - 'boolean NOT NULL DEFAULT TRUE' + 'boolean NOT NULL DEFAULT TRUE', ], [ Schema::TYPE_CHAR . ' CHECK (value LIKE \'test%\')', $this->char()->check('value LIKE \'test%\''), - 'char(1) CHECK (value LIKE \'test%\')' + 'char(1) CHECK (value LIKE \'test%\')', ], [ Schema::TYPE_CHAR . '(6) CHECK (value LIKE \'test%\')', $this->char(6)->check('value LIKE \'test%\''), - 'char(6) CHECK (value LIKE \'test%\')' + 'char(6) CHECK (value LIKE \'test%\')', ], [ Schema::TYPE_CHAR . '(6)', $this->char(6)->unsigned(), - 'char(6)' + 'char(6)', ], [ Schema::TYPE_INTEGER . '(8)', $this->integer(8)->unsigned(), - 'integer' + 'integer', ], [ Schema::TYPE_TIMESTAMP . '(4)', $this->timestamp(4), - 'timestamp(4)' + 'timestamp(4)', ], ]); } @@ -55,22 +60,22 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest // http://www.postgresql.org/docs/8.3/static/functions-matching.html#FUNCTIONS-LIKE // empty values - [ ['ilike', 'name', []], '0=1', [] ], - [ ['not ilike', 'name', []], '', [] ], - [ ['or ilike', 'name', []], '0=1', [] ], - [ ['or not ilike', 'name', []], '', [] ], + [['ilike', 'name', []], '0=1', []], + [['not ilike', 'name', []], '', []], + [['or ilike', 'name', []], '0=1', []], + [['or not ilike', 'name', []], '', []], // simple ilike - [ ['ilike', 'name', 'heyho'], '"name" ILIKE :qp0', [':qp0' => '%heyho%'] ], - [ ['not ilike', 'name', 'heyho'], '"name" NOT ILIKE :qp0', [':qp0' => '%heyho%'] ], - [ ['or ilike', 'name', 'heyho'], '"name" ILIKE :qp0', [':qp0' => '%heyho%'] ], - [ ['or not ilike', 'name', 'heyho'], '"name" NOT ILIKE :qp0', [':qp0' => '%heyho%'] ], + [['ilike', 'name', 'heyho'], '"name" ILIKE :qp0', [':qp0' => '%heyho%']], + [['not ilike', 'name', 'heyho'], '"name" NOT ILIKE :qp0', [':qp0' => '%heyho%']], + [['or ilike', 'name', 'heyho'], '"name" ILIKE :qp0', [':qp0' => '%heyho%']], + [['or not ilike', 'name', 'heyho'], '"name" NOT ILIKE :qp0', [':qp0' => '%heyho%']], // ilike for many values - [ ['ilike', 'name', ['heyho', 'abc']], '"name" ILIKE :qp0 AND "name" ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%'] ], - [ ['not ilike', 'name', ['heyho', 'abc']], '"name" NOT ILIKE :qp0 AND "name" NOT ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%'] ], - [ ['or ilike', 'name', ['heyho', 'abc']], '"name" ILIKE :qp0 OR "name" ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%'] ], - [ ['or not ilike', 'name', ['heyho', 'abc']], '"name" NOT ILIKE :qp0 OR "name" NOT ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%'] ], + [['ilike', 'name', ['heyho', 'abc']], '"name" ILIKE :qp0 AND "name" ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%']], + [['not ilike', 'name', ['heyho', 'abc']], '"name" NOT ILIKE :qp0 AND "name" NOT ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%']], + [['or ilike', 'name', ['heyho', 'abc']], '"name" ILIKE :qp0 OR "name" ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%']], + [['or not ilike', 'name', ['heyho', 'abc']], '"name" NOT ILIKE :qp0 OR "name" NOT ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%']], ]); } @@ -103,7 +108,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $sql = $qb->addCommentOnColumn('comment', 'text', 'This is my column.'); $this->assertEquals($this->replaceQuotes($expected), $sql); - $expected = "COMMENT ON COLUMN [[comment]].[[text]] IS NULL"; + $expected = 'COMMENT ON COLUMN [[comment]].[[text]] IS NULL'; $sql = $qb->dropCommentFromColumn('comment', 'text'); $this->assertEquals($this->replaceQuotes($expected), $sql); } @@ -116,7 +121,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $sql = $qb->addCommentOnTable('comment', 'This is my table.'); $this->assertEquals($this->replaceQuotes($expected), $sql); - $expected = "COMMENT ON TABLE [[comment]] IS NULL"; + $expected = 'COMMENT ON TABLE [[comment]] IS NULL'; $sql = $qb->dropCommentFromTable('comment'); $this->assertEquals($this->replaceQuotes($expected), $sql); } @@ -127,7 +132,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $data['escape-danger-chars']['expected'] = "INSERT INTO \"customer\" (\"address\") VALUES ('SQL-danger chars are escaped: ''); --')"; $data['bool-false, bool2-null']['expected'] = 'INSERT INTO "type" ("bool_col", "bool_col2") VALUES (FALSE, NULL)'; - $data['bool-false, time-now()']['expected'] = "INSERT INTO {{%type}} ({{%type}}.[[bool_col]], [[time]]) VALUES (FALSE, now())"; + $data['bool-false, time-now()']['expected'] = 'INSERT INTO {{%type}} ({{%type}}.[[bool_col]], [[time]]) VALUES (FALSE, now())'; return $data; } diff --git a/tests/framework/db/pgsql/QueryTest.php b/tests/framework/db/pgsql/QueryTest.php index bf3de4199a..61dc518922 100644 --- a/tests/framework/db/pgsql/QueryTest.php +++ b/tests/framework/db/pgsql/QueryTest.php @@ -1,8 +1,12 @@ createCommand($sql); - $this->assertEquals("SELECT `id`, `t`.`name` FROM `customer` t", $command->sql); + $this->assertEquals('SELECT `id`, `t`.`name` FROM `customer` t', $command->sql); } } diff --git a/tests/framework/db/sqlite/ConnectionTest.php b/tests/framework/db/sqlite/ConnectionTest.php index 2f869bdad0..8a8e00f45d 100644 --- a/tests/framework/db/sqlite/ConnectionTest.php +++ b/tests/framework/db/sqlite/ConnectionTest.php @@ -1,4 +1,9 @@ assertNull($db->getMaster()); } - $this->assertNotEquals('test', $db->createCommand("SELECT description FROM profile WHERE id=1")->queryScalar()); + $this->assertNotEquals('test', $db->createCommand('SELECT description FROM profile WHERE id=1')->queryScalar()); $result = $db->useMaster(function (Connection $db) { - return $db->createCommand("SELECT description FROM profile WHERE id=1")->queryScalar(); + return $db->createCommand('SELECT description FROM profile WHERE id=1')->queryScalar(); }); $this->assertEquals('test', $result); @@ -106,7 +111,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $hit_slaves = $hit_masters = []; - for ($i = $nodesCount * $retryPerNode; $i-- > 0; ) { + for ($i = $nodesCount * $retryPerNode; $i-- > 0;) { $db = $this->prepareMasterSlave($mastersCount, $slavesCount); $db->shuffleMasters = true; @@ -128,7 +133,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $hit_slaves = $hit_masters = []; - for ($i = $nodesCount * $retryPerNode; $i-- > 0; ) { + for ($i = $nodesCount * $retryPerNode; $i-- > 0;) { $db = $this->prepareMasterSlave($mastersCount, $slavesCount); $db->shuffleMasters = false; @@ -193,7 +198,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest public function testAliasDbPath() { $config = [ - 'dsn' => "sqlite:@yiiunit/runtime/yii2aliastest.sq3", + 'dsn' => 'sqlite:@yiiunit/runtime/yii2aliastest.sq3', ]; $connection = new Connection($config); $connection->open(); @@ -207,5 +212,4 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest { // This test does not work on sqlite because preparing the failing query fails } - } diff --git a/tests/framework/db/sqlite/ExistValidatorTest.php b/tests/framework/db/sqlite/ExistValidatorTest.php index 840798f642..8c8652a60e 100644 --- a/tests/framework/db/sqlite/ExistValidatorTest.php +++ b/tests/framework/db/sqlite/ExistValidatorTest.php @@ -1,4 +1,9 @@ primaryKey()->first()->after('col_before'), - 'integer PRIMARY KEY AUTOINCREMENT NOT NULL' + 'integer PRIMARY KEY AUTOINCREMENT NOT NULL', ], ]); } @@ -36,12 +41,12 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest ['id' => 2, 'name' => 'yo'], ])], '(([[id]] = :qp0 AND [[name]] = :qp1) OR ([[id]] = :qp2 AND [[name]] = :qp3))', - [':qp0' => 1, ':qp1' => 'oy', ':qp2' => 2, ':qp3' => 'yo'] + [':qp0' => 1, ':qp1' => 'oy', ':qp2' => 2, ':qp3' => 'yo'], ], 'composite in' => [ - ['in', ['id', 'name'], [['id' =>1, 'name' => 'oy']]], + ['in', ['id', 'name'], [['id' => 1, 'name' => 'oy']]], '(([[id]] = :qp0 AND [[name]] = :qp1))', - [':qp0' => 1, ':qp1' => 'oy'] + [':qp0' => 1, ':qp1' => 'oy'], ], ]); } @@ -81,7 +86,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest public function testRenameTable() { $sql = $this->getQueryBuilder()->renameTable('table_from', 'table_to'); - $this->assertEquals("ALTER TABLE `table_from` RENAME TO `table_to`", $sql); + $this->assertEquals('ALTER TABLE `table_from` RENAME TO `table_to`', $sql); } /** @@ -90,7 +95,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest public function testBuildUnion() { $expectedQuerySql = $this->replaceQuotes( - "SELECT `id` FROM `TotalExample` `t1` WHERE (w > 0) AND (x < 2) UNION SELECT `id` FROM `TotalTotalExample` `t2` WHERE w > 5 UNION ALL SELECT `id` FROM `TotalTotalExample` `t3` WHERE w = 3" + 'SELECT `id` FROM `TotalExample` `t1` WHERE (w > 0) AND (x < 2) UNION SELECT `id` FROM `TotalTotalExample` `t2` WHERE w > 5 UNION ALL SELECT `id` FROM `TotalTotalExample` `t3` WHERE w = 3' ); $query = new Query(); $secondQuery = new Query(); @@ -105,7 +110,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest ->from('TotalExample t1') ->where(['and', 'w > 0', 'x < 2']) ->union($secondQuery) - ->union($thirdQuery, TRUE); + ->union($thirdQuery, true); list($actualQuerySql, $queryParams) = $this->getQueryBuilder()->build($query); $this->assertEquals($expectedQuerySql, $actualQuerySql); $this->assertEquals([], $queryParams); diff --git a/tests/framework/db/sqlite/QueryTest.php b/tests/framework/db/sqlite/QueryTest.php index 37cb55388c..e5ee615119 100644 --- a/tests/framework/db/sqlite/QueryTest.php +++ b/tests/framework/db/sqlite/QueryTest.php @@ -1,4 +1,10 @@ getConnection(); - $query = new Query; + $query = new Query(); $query->select(['id', 'name']) ->from('item') ->union( diff --git a/tests/framework/db/sqlite/SchemaTest.php b/tests/framework/db/sqlite/SchemaTest.php index 425fd661ce..f48518a433 100644 --- a/tests/framework/db/sqlite/SchemaTest.php +++ b/tests/framework/db/sqlite/SchemaTest.php @@ -1,4 +1,9 @@ @@ -43,7 +42,7 @@ class ContainerTest extends TestCase $Qux = Qux::className(); // automatic wiring - $container = new Container; + $container = new Container(); $container->set($QuxInterface, $Qux); $foo = $container->get($Foo); $this->assertInstanceOf($Foo, $foo); @@ -53,7 +52,7 @@ class ContainerTest extends TestCase $this->assertNotSame($foo, $foo2); // full wiring - $container = new Container; + $container = new Container(); $container->set($QuxInterface, $Qux); $container->set($Bar); $container->set($Qux); @@ -64,9 +63,9 @@ class ContainerTest extends TestCase $this->assertInstanceOf($Qux, $foo->bar->qux); // wiring by closure - $container = new Container; + $container = new Container(); $container->set('foo', function () { - $qux = new Qux; + $qux = new Qux(); $bar = new Bar($qux); return new Foo($bar); }); @@ -76,7 +75,7 @@ class ContainerTest extends TestCase $this->assertInstanceOf($Qux, $foo->bar->qux); // wiring by closure which uses container - $container = new Container; + $container = new Container(); $container->set($QuxInterface, $Qux); $container->set('foo', function (Container $c, $params, $config) { return $c->get(Foo::className()); @@ -87,7 +86,7 @@ class ContainerTest extends TestCase $this->assertInstanceOf($Qux, $foo->bar->qux); // predefined constructor parameters - $container = new Container; + $container = new Container(); $container->set('foo', $Foo, [Instance::of('bar')]); $container->set('bar', $Bar, [Instance::of('qux')]); $container->set('qux', $Qux); @@ -97,14 +96,14 @@ class ContainerTest extends TestCase $this->assertInstanceOf($Qux, $foo->bar->qux); // wiring by closure - $container = new Container; - $container->set('qux', new Qux); + $container = new Container(); + $container->set('qux', new Qux()); $qux1 = $container->get('qux'); $qux2 = $container->get('qux'); $this->assertSame($qux1, $qux2); // config - $container = new Container; + $container = new Container(); $container->set('qux', $Qux); $qux = $container->get('qux', [], ['a' => 2]); $this->assertEquals(2, $qux->a); @@ -126,7 +125,7 @@ class ContainerTest extends TestCase 'class' => 'yiiunit\framework\di\stubs\Qux', 'a' => 'belongAppQux2', ], - ] + ], ]); Yii::$container->set('yiiunit\framework\di\stubs\QuxInterface', [ 'class' => 'yiiunit\framework\di\stubs\Qux', @@ -134,21 +133,21 @@ class ContainerTest extends TestCase ]); // use component of application - $callback = function($param, stubs\QuxInterface $qux, Bar $bar) { + $callback = function ($param, stubs\QuxInterface $qux, Bar $bar) { return [$param, $qux instanceof Qux, $qux->a, $bar->qux->a]; }; $result = Yii::$container->invoke($callback, ['D426']); $this->assertEquals(['D426', true, 'belongApp', 'independent'], $result); // another component of application - $callback = function($param, stubs\QuxInterface $qux2, $other = 'default') { + $callback = function ($param, stubs\QuxInterface $qux2, $other = 'default') { return [$param, $qux2 instanceof Qux, $qux2->a, $other]; }; $result = Yii::$container->invoke($callback, ['M2792684']); $this->assertEquals(['M2792684', true, 'belongAppQux2', 'default'], $result); // component not belong application - $callback = function($param, stubs\QuxInterface $notBelongApp, $other) { + $callback = function ($param, stubs\QuxInterface $notBelongApp, $other) { return [$param, $notBelongApp instanceof Qux, $notBelongApp->a, $other]; }; $result = Yii::$container->invoke($callback, ['MDM', 'not_default']); @@ -192,9 +191,9 @@ class ContainerTest extends TestCase 'class' => 'yiiunit\framework\di\stubs\Qux', 'a' => 'belongAppQux2', ], - ] + ], ]); - $closure = function($a, $x = 5, $b) { + $closure = function ($a, $x = 5, $b) { return $a > $b; }; $this->assertFalse(Yii::$container->invoke($closure, ['b' => 5, 'a' => 1])); @@ -213,9 +212,9 @@ class ContainerTest extends TestCase 'class' => 'yiiunit\framework\di\stubs\Qux', 'a' => 'belongAppQux2', ], - ] + ], ]); - $closure = function($a, $b) { + $closure = function ($a, $b) { return $a > $b; }; $this->assertEquals([1, 5], Yii::$container->resolveCallableDependencies($closure, ['b' => 5, 'a' => 1])); @@ -227,7 +226,7 @@ class ContainerTest extends TestCase { $container = new Container(); // Test optional unresolvable dependency. - $closure = function(QuxInterface $test = null) { + $closure = function (QuxInterface $test = null) { return $test; }; $this->assertNull($container->invoke($closure)); @@ -241,11 +240,11 @@ class ContainerTest extends TestCase Cat::className() => Type::className(), 'test\TraversableInterface' => [ ['class' => 'yiiunit\data\base\TraversableObject'], - [['item1', 'item2']] + [['item1', 'item2']], ], 'qux.using.closure' => function () { return new Qux(); - } + }, ]); $container->setDefinitions([]); @@ -266,11 +265,11 @@ class ContainerTest extends TestCase 'model.order' => Order::className(), 'test\TraversableInterface' => [ ['class' => 'yiiunit\data\base\TraversableObject'], - [['item1', 'item2']] + [['item1', 'item2']], ], 'qux.using.closure' => function () { return new Qux(); - } + }, ]); $container->setSingletons([]); diff --git a/tests/framework/di/InstanceTest.php b/tests/framework/di/InstanceTest.php index a6689195eb..cbda936c54 100644 --- a/tests/framework/di/InstanceTest.php +++ b/tests/framework/di/InstanceTest.php @@ -48,7 +48,7 @@ class InstanceTest extends TestCase ]); $this->assertInstanceOf(Connection::className(), Instance::ensure('db', 'yii\db\Connection', $container)); - $this->assertInstanceOf(Connection::className(), Instance::ensure(new Connection, 'yii\db\Connection', $container)); + $this->assertInstanceOf(Connection::className(), Instance::ensure(new Connection(), 'yii\db\Connection', $container)); $this->assertInstanceOf('\\yii\\db\\Connection', Instance::ensure(['class' => 'yii\db\Connection', 'dsn' => 'test'], 'yii\db\Connection', $container)); } @@ -83,7 +83,7 @@ class InstanceTest extends TestCase ]); $this->assertInstanceOf(Connection::className(), Instance::ensure('db', null, $container)); - $this->assertInstanceOf(Connection::className(), Instance::ensure(new Connection, null, $container)); + $this->assertInstanceOf(Connection::className(), Instance::ensure(new Connection(), null, $container)); $this->assertInstanceOf('\\yii\\db\\Connection', Instance::ensure(['class' => 'yii\db\Connection', 'dsn' => 'test'], null, $container)); } @@ -95,14 +95,14 @@ class InstanceTest extends TestCase ]); $this->assertInstanceOf(Connection::className(), Instance::ensure('db')); - $this->assertInstanceOf(Connection::className(), Instance::ensure(new Connection)); + $this->assertInstanceOf(Connection::className(), Instance::ensure(new Connection())); $this->assertInstanceOf(Connection::className(), Instance::ensure(['class' => 'yii\db\Connection', 'dsn' => 'test'])); - Yii::$container = new Container; + Yii::$container = new Container(); } public function testExceptionRefersTo() { - $container = new Container; + $container = new Container(); $container->set('db', [ 'class' => 'yii\db\Connection', 'dsn' => 'test', @@ -118,7 +118,7 @@ class InstanceTest extends TestCase { $this->expectException('yii\base\InvalidConfigException'); $this->expectExceptionMessage('Invalid data type: yii\db\Connection. yii\base\Widget is expected.'); - Instance::ensure(new Connection, 'yii\base\Widget'); + Instance::ensure(new Connection(), 'yii\base\Widget'); } public function testExceptionComponentIsNotSpecified() @@ -135,8 +135,8 @@ class InstanceTest extends TestCase 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'test', - ] - ] + ], + ], ]); $container = Instance::of('db'); @@ -151,10 +151,10 @@ class InstanceTest extends TestCase */ public function testLazyInitializationExample() { - Yii::$container = new Container; + Yii::$container = new Container(); Yii::$container->set('cache', [ 'class' => 'yii\caching\DbCache', - 'db' => Instance::of('db') + 'db' => Instance::of('db'), ]); Yii::$container->set('db', [ 'class' => 'yii\db\Connection', diff --git a/tests/framework/di/ServiceLocatorTest.php b/tests/framework/di/ServiceLocatorTest.php index 36766b70ef..e220d2369d 100644 --- a/tests/framework/di/ServiceLocatorTest.php +++ b/tests/framework/di/ServiceLocatorTest.php @@ -15,7 +15,7 @@ class Creator { public static function create() { - return new TestClass; + return new TestClass(); } } @@ -51,7 +51,7 @@ class ServiceLocatorTest extends TestCase // static method $container = new ServiceLocator(); $className = TestClass::className(); - $container->set($className, [__NAMESPACE__ . "\\Creator", 'create']); + $container->set($className, [__NAMESPACE__ . '\\Creator', 'create']); $object = $container->get($className); $this->assertInstanceOf($className, $object); $this->assertEquals(1, $object->prop1); @@ -62,7 +62,7 @@ class ServiceLocatorTest extends TestCase { $object = new TestClass(); $className = TestClass::className(); - $container = new ServiceLocator; + $container = new ServiceLocator(); $container->set($className, $object); $this->assertSame($container->get($className), $object); } diff --git a/tests/framework/di/stubs/QuxInterface.php b/tests/framework/di/stubs/QuxInterface.php index 8a9847130b..8815021c6c 100644 --- a/tests/framework/di/stubs/QuxInterface.php +++ b/tests/framework/di/stubs/QuxInterface.php @@ -13,5 +13,5 @@ namespace yiiunit\framework\di\stubs; */ interface QuxInterface { - function quxMethod(); + public function quxMethod(); } diff --git a/tests/framework/filters/AccessRuleTest.php b/tests/framework/filters/AccessRuleTest.php index 9de4d80d5a..98ba205fac 100644 --- a/tests/framework/filters/AccessRuleTest.php +++ b/tests/framework/filters/AccessRuleTest.php @@ -1,4 +1,9 @@ 'user2'], null], // user2 is author, can only edit own posts - ['update', true, 'user2', function() { return ['authorID' => 'user2']; }, true], - ['update', true, 'user2', function() { return ['authorID' => 'user1']; }, null], + ['update', true, 'user2', function () { return ['authorID' => 'user2']; }, true], + ['update', true, 'user2', function () { return ['authorID' => 'user1']; }, null], // user1 is admin, can update all posts - ['update', true, 'user1', function() { return ['authorID' => 'user1']; }, true], - ['update', true, 'user1', function() { return ['authorID' => 'user2']; }, true], + ['update', true, 'user1', function () { return ['authorID' => 'user1']; }, true], + ['update', true, 'user1', function () { return ['authorID' => 'user2']; }, true], // unknown user can not edit anything - ['update', true, 'unknown', function() { return ['authorID' => 'user1']; }, null], - ['update', true, 'unknown', function() { return ['authorID' => 'user2']; }, null], + ['update', true, 'unknown', function () { return ['authorID' => 'user1']; }, null], + ['update', true, 'unknown', function () { return ['authorID' => 'user2']; }, null], ]; } @@ -248,12 +254,13 @@ class AccessRuleTest extends \yiiunit\TestCase * * @dataProvider matchRoleProvider * @param string $actionid the action id - * @param boolean $allow whether the rule should allow access + * @param bool $allow whether the rule should allow access * @param string $userid the userid to check * @param array|Closure $roleParams params for $roleParams - * @param boolean $expected the expected result or null + * @param bool $expected the expected result or null */ - public function testMatchRole($actionid, $allow, $userid, $roleParams, $expected) { + public function testMatchRole($actionid, $allow, $userid, $roleParams, $expected) + { $action = $this->mockAction(); $auth = $this->mockAuthManager(); $request = $this->mockRequest(); @@ -277,7 +284,8 @@ class AccessRuleTest extends \yiiunit\TestCase * * @see https://github.com/yiisoft/yii2/issues/4793 */ - public function testMatchRoleWithoutUser() { + public function testMatchRoleWithoutUser() + { $action = $this->mockAction(); $request = $this->mockRequest(); diff --git a/tests/framework/filters/HostControlTest.php b/tests/framework/filters/HostControlTest.php index 9ec462a014..0cb1bc8d25 100644 --- a/tests/framework/filters/HostControlTest.php +++ b/tests/framework/filters/HostControlTest.php @@ -1,4 +1,9 @@ mockWebApplication(); } @@ -33,46 +38,46 @@ class HostControlTest extends TestCase [ null, 'example.com', - true + true, ], [ 'example.com', 'example.com', - true + true, ], [ ['example.com'], 'example.com', - true + true, ], [ ['example.com'], 'domain.com', - false + false, ], [ ['*.example.com'], 'en.example.com', - true + true, ], [ ['*.example.com'], 'fake.com', - false + false, ], [ function () { return ['example.com']; }, 'example.com', - true + true, ], [ function () { return ['example.com']; }, 'fake.com', - false + false, ], ]; } @@ -122,7 +127,7 @@ class HostControlTest extends TestCase $filter = new HostControl(); $filter->allowedHosts = ['example.com']; $this->denyCallBackCalled = false; - $filter->denyCallback = function() { + $filter->denyCallback = function () { $this->denyCallBackCalled = true; }; @@ -137,7 +142,7 @@ class HostControlTest extends TestCase $filter = new HostControl(); $filter->allowedHosts = ['example.com']; $filter->fallbackHostInfo = 'http://yiiframework.com'; - $filter->denyCallback = function() {}; + $filter->denyCallback = function () {}; $controller = new Controller('test', Yii::$app); $action = new Action('test', $controller); diff --git a/tests/framework/filters/HttpCacheTest.php b/tests/framework/filters/HttpCacheTest.php index 46a05df7d3..399eb8f0dc 100644 --- a/tests/framework/filters/HttpCacheTest.php +++ b/tests/framework/filters/HttpCacheTest.php @@ -1,4 +1,9 @@ mockWebApplication(); } @@ -24,14 +29,14 @@ class HttpCacheTest extends \yiiunit\TestCase { $httpCache = new HttpCache(); $this->assertTrue($httpCache->beforeAction(null)); - $httpCache->enabled=false; + $httpCache->enabled = false; $this->assertTrue($httpCache->beforeAction(null)); } public function testEmptyPragma() { $httpCache = new HttpCache(); - $httpCache->etagSeed = function($action, $params) { + $httpCache->etagSeed = function ($action, $params) { return ''; }; $httpCache->beforeAction(null); @@ -41,7 +46,7 @@ class HttpCacheTest extends \yiiunit\TestCase } /** - * @covers yii\filters\HttpCache::validateCache + * @covers \yii\filters\HttpCache::validateCache */ public function testValidateCache() { @@ -71,21 +76,21 @@ class HttpCacheTest extends \yiiunit\TestCase } /** - * @covers yii\filters\HttpCache::generateEtag + * @covers \yii\filters\HttpCache::generateEtag */ public function testGenerateEtag() { $httpCache = new HttpCache(); $httpCache->weakEtag = false; - $httpCache->etagSeed = function($action, $params) { + $httpCache->etagSeed = function ($action, $params) { return null; }; $httpCache->beforeAction(null); $response = Yii::$app->getResponse(); $this->assertFalse($response->getHeaders()->offsetExists('ETag')); - $httpCache->etagSeed = function($action, $params) { + $httpCache->etagSeed = function ($action, $params) { return ''; }; $httpCache->beforeAction(null); diff --git a/tests/framework/filters/PageCacheTest.php b/tests/framework/filters/PageCacheTest.php index c23a797c7b..237049aa74 100644 --- a/tests/framework/filters/PageCacheTest.php +++ b/tests/framework/filters/PageCacheTest.php @@ -1,4 +1,9 @@ 'disabled', 'properties' => [ - 'enabled' => false + 'enabled' => false, ], 'cacheable' => false, ]], @@ -52,64 +57,64 @@ class PageCacheTest extends TestCase [[ 'name' => 'allCookies', 'properties' => [ - 'cacheCookies' => true + 'cacheCookies' => true, ], 'cookies' => [ 'test-cookie-1' => true, 'test-cookie-2' => true, - ] + ], ]], [[ 'name' => 'someCookies', 'properties' => [ - 'cacheCookies' => ['test-cookie-2'] + 'cacheCookies' => ['test-cookie-2'], ], 'cookies' => [ 'test-cookie-1' => false, 'test-cookie-2' => true, - ] + ], ]], [[ 'name' => 'noCookies', 'properties' => [ - 'cacheCookies' => false + 'cacheCookies' => false, ], 'cookies' => [ 'test-cookie-1' => false, 'test-cookie-2' => false, - ] + ], ]], // Headers [[ 'name' => 'allHeaders', 'properties' => [ - 'cacheHeaders' => true + 'cacheHeaders' => true, ], 'headers' => [ 'test-header-1' => true, 'test-header-2' => true, - ] + ], ]], [[ 'name' => 'someHeaders', 'properties' => [ - 'cacheHeaders' => ['test-header-2'] + 'cacheHeaders' => ['test-header-2'], ], 'headers' => [ 'test-header-1' => false, 'test-header-2' => true, - ] + ], ]], [[ 'name' => 'noHeaders', 'properties' => [ - 'cacheHeaders' => false + 'cacheHeaders' => false, ], 'headers' => [ 'test-header-1' => false, 'test-header-2' => false, - ] + ], ]], // All together @@ -117,7 +122,7 @@ class PageCacheTest extends TestCase 'name' => 'someCookiesSomeHeaders', 'properties' => [ 'cacheCookies' => ['test-cookie-2'], - 'cacheHeaders' => ['test-header-2'] + 'cacheHeaders' => ['test-header-2'], ], 'cookies' => [ 'test-cookie-1' => false, @@ -126,7 +131,7 @@ class PageCacheTest extends TestCase 'headers' => [ 'test-header-1' => false, 'test-header-2' => true, - ] + ], ]], ]; } @@ -149,7 +154,7 @@ class PageCacheTest extends TestCase $action = new Action('test', $controller); $filter = new PageCache(array_merge([ 'cache' => $cache = new ArrayCache(), - 'view' => new View() + 'view' => new View(), ], $testCase['properties'])); $this->assertTrue($filter->beforeAction($action), $testCase['name']); // Cookies @@ -160,7 +165,7 @@ class PageCacheTest extends TestCase Yii::$app->response->cookies->add(new Cookie([ 'name' => $name, 'value' => $value, - 'expire' => PHP_INT_MAX + 'expire' => PHP_INT_MAX, ])); $cookies[$name] = $value; } @@ -203,7 +208,7 @@ class PageCacheTest extends TestCase $action = new Action('test', $controller); $filter = new PageCache(array_merge([ 'cache' => $cache, - 'view' => new View() + 'view' => new View(), ]), $testCase['properties']); Yii::$app->params['dynamic'] = $dynamic = Yii::$app->security->generateRandomString(); $this->assertFalse($filter->beforeAction($action), $testCase['name']); @@ -248,7 +253,7 @@ class PageCacheTest extends TestCase $filter = new PageCache([ 'cache' => $cache = new ArrayCache(), 'view' => new View(), - 'duration' => 1 + 'duration' => 1, ]); $this->assertTrue($filter->beforeAction($action)); $static = Yii::$app->security->generateRandomString(); @@ -272,7 +277,7 @@ class PageCacheTest extends TestCase $action = new Action('test', $controller); $filter = new PageCache([ 'cache' => $cache, - 'view' => new View() + 'view' => new View(), ]); Yii::$app->params['dynamic'] = $dynamic = Yii::$app->security->generateRandomString(); $this->assertTrue($filter->beforeAction($action)); @@ -300,7 +305,7 @@ class PageCacheTest extends TestCase $filter = new PageCache([ 'cache' => $cache = new ArrayCache(), 'view' => new View(), - 'varyByRoute' => $enabled + 'varyByRoute' => $enabled, ]); $this->assertTrue($filter->beforeAction($action)); $static = Yii::$app->security->generateRandomString(); @@ -322,7 +327,7 @@ class PageCacheTest extends TestCase $filter = new PageCache([ 'cache' => $cache, 'view' => new View(), - 'varyByRoute' => $enabled + 'varyByRoute' => $enabled, ]); Yii::$app->params['dynamic'] = $dynamic = Yii::$app->security->generateRandomString(); $this->assertSame($enabled, $filter->beforeAction($action), $enabled); @@ -353,7 +358,7 @@ class PageCacheTest extends TestCase $filter = new PageCache([ 'cache' => $cache = new ArrayCache(), 'view' => new View(), - 'variations' => $originalVariations + 'variations' => $originalVariations, ]); $this->assertTrue($filter->beforeAction($action)); $static = Yii::$app->security->generateRandomString(); @@ -374,7 +379,7 @@ class PageCacheTest extends TestCase $filter = new PageCache([ 'cache' => $cache, 'view' => new View(), - 'variations' => $testCase + 'variations' => $testCase, ]); Yii::$app->params['dynamic'] = $dynamic = Yii::$app->security->generateRandomString(); $this->assertNotSame($expected, $filter->beforeAction($action), $expected); @@ -405,7 +410,7 @@ class PageCacheTest extends TestCase 'dependency' => [ 'class' => ExpressionDependency::className(), 'expression' => 'Yii::$app->params[\'dependency\']', - ] + ], ]); $this->assertTrue($filter->beforeAction($action)); $static = Yii::$app->security->generateRandomString(); diff --git a/tests/framework/filters/RateLimiterTest.php b/tests/framework/filters/RateLimiterTest.php index e4ca51574d..e6f0333f2f 100644 --- a/tests/framework/filters/RateLimiterTest.php +++ b/tests/framework/filters/RateLimiterTest.php @@ -1,16 +1,21 @@ 'Request']); @@ -106,7 +111,7 @@ class RateLimiterTest extends TestCase public function testCheckRateLimitTooManyRequests() { /* @var $rateLimit UserIdentity|\Prophecy\ObjectProphecy */ - $rateLimit = new RateLimit; + $rateLimit = new RateLimit(); $rateLimit ->setRateLimit([1, 1]) ->setAllowance([1, time() + 2]); @@ -119,7 +124,7 @@ class RateLimiterTest extends TestCase public function testCheckRateaddRateLimitHeaders() { /* @var $user UserIdentity|\Prophecy\ObjectProphecy */ - $rateLimit = new RateLimit; + $rateLimit = new RateLimit(); $rateLimit ->setRateLimit([1, 1]) ->setAllowance([1, time()]); diff --git a/tests/framework/filters/auth/AuthMethodTest.php b/tests/framework/filters/auth/AuthMethodTest.php index f79e274446..c55293b0e3 100644 --- a/tests/framework/filters/auth/AuthMethodTest.php +++ b/tests/framework/filters/auth/AuthMethodTest.php @@ -1,4 +1,9 @@ mockWebApplication([ 'components' => [ 'user' => [ - 'identityClass' => UserIdentity::className() + 'identityClass' => UserIdentity::className(), ], - ] + ], ]); } @@ -80,4 +85,4 @@ class AuthMethodTest extends TestCase $this->assertFalse($method->invokeArgs($filter, [$this->createAction(['id' => 'index'])])); $this->assertTrue($method->invokeArgs($filter, [$this->createAction(['id' => 'test/index'])])); } -} \ No newline at end of file +} diff --git a/tests/framework/filters/auth/AuthTest.php b/tests/framework/filters/auth/AuthTest.php index e06305e1a9..bba6836a68 100644 --- a/tests/framework/filters/auth/AuthTest.php +++ b/tests/framework/filters/auth/AuthTest.php @@ -1,4 +1,9 @@ [ 'user' => [ - 'identityClass' => UserIdentity::className() + 'identityClass' => UserIdentity::className(), ], ], 'controllerMap' => [ - 'test-auth' => TestAuthController::className() - ] + 'test-auth' => TestAuthController::className(), + ], ]; $this->mockWebApplication($appConfig); @@ -60,7 +65,6 @@ class AuthTest extends \yiiunit\TestCase try { $this->assertEquals($login, $controller->run($action)); } catch (UnauthorizedHttpException $e) { - } } @@ -72,7 +76,6 @@ class AuthTest extends \yiiunit\TestCase try { $this->assertEquals($login, $controller->run($action)); } catch (UnauthorizedHttpException $e) { - } } @@ -84,14 +87,14 @@ class AuthTest extends \yiiunit\TestCase try { $this->assertEquals($login, $controller->run($action)); } catch (UnauthorizedHttpException $e) { - } } /** * @dataProvider tokenProvider */ - public function testQueryParamAuth($token, $login) { + public function testQueryParamAuth($token, $login) + { $_GET['access-token'] = $token; $filter = ['class' => QueryParamAuth::className()]; $this->authOnly($token, $login, $filter, 'query-param-auth'); @@ -102,7 +105,8 @@ class AuthTest extends \yiiunit\TestCase /** * @dataProvider tokenProvider */ - public function testHttpBasicAuth($token, $login) { + public function testHttpBasicAuth($token, $login) + { $_SERVER['PHP_AUTH_USER'] = $token; $_SERVER['PHP_AUTH_PW'] = 'whatever, we are testers'; $filter = ['class' => HttpBasicAuth::className()]; @@ -114,7 +118,8 @@ class AuthTest extends \yiiunit\TestCase /** * @dataProvider tokenProvider */ - public function testHttpBasicAuthCustom($token, $login) { + public function testHttpBasicAuthCustom($token, $login) + { $_SERVER['PHP_AUTH_USER'] = $login; $_SERVER['PHP_AUTH_PW'] = 'whatever, we are testers'; $filter = [ @@ -125,7 +130,7 @@ class AuthTest extends \yiiunit\TestCase } return null; - } + }, ]; $this->authOnly($token, $login, $filter, 'basic-auth'); $this->authOptional($token, $login, $filter, 'basic-auth'); @@ -135,7 +140,8 @@ class AuthTest extends \yiiunit\TestCase /** * @dataProvider tokenProvider */ - public function testHttpBearerAuth($token, $login) { + public function testHttpBearerAuth($token, $login) + { Yii::$app->request->headers->set('Authorization', "Bearer $token"); $filter = ['class' => HttpBearerAuth::className()]; $this->authOnly($token, $login, $filter, 'bearer-auth'); @@ -159,7 +165,7 @@ class AuthTest extends \yiiunit\TestCase public function testActive($authClass) { /** @var $filter AuthMethod */ - $filter = new $authClass; + $filter = new $authClass(); $reflection = new \ReflectionClass($filter); $method = $reflection->getMethod('isActive'); $method->setAccessible(true); @@ -200,7 +206,6 @@ class AuthTest extends \yiiunit\TestCase $this->assertEquals(true, $method->invokeArgs($filter, [new Action('index', $controller)])); $this->assertEquals(false, $method->invokeArgs($filter, [new Action('view', $controller)])); } - } /** diff --git a/tests/framework/filters/auth/CompositeAuthTest.php b/tests/framework/filters/auth/CompositeAuthTest.php index 71a35ecd51..99faf3d592 100644 --- a/tests/framework/filters/auth/CompositeAuthTest.php +++ b/tests/framework/filters/auth/CompositeAuthTest.php @@ -1,4 +1,9 @@ runAction('a'); @@ -36,7 +41,7 @@ class TestController extends Controller public function actionC() { - /** + /* * this call will execute the actionA in a same instance of TestController */ return $this->run('a'); @@ -44,7 +49,7 @@ class TestController extends Controller public function actionD() { - /** + /* * this call will execute the actionA in a new instance of TestController */ return $this->run('test/a'); @@ -52,7 +57,7 @@ class TestController extends Controller public function behaviors() { - /** + /* * the CompositeAuth::authenticate() assumes that it is only executed once per the controller's instance * i believe this is okay as long as we specify in the documentation that if we want to use the authenticate * method again(this might even be also true to other behaviors that attaches to the beforeAction event), @@ -62,7 +67,7 @@ class TestController extends Controller 'authenticator' => [ 'class' => CompositeAuth::className(), 'authMethods' => [ - TestAuth::className() + TestAuth::className(), ], ], ]; @@ -78,18 +83,18 @@ class CompositeAuthTest extends \yiiunit\TestCase { parent::setUp(); - $_SERVER['SCRIPT_FILENAME'] = "/index.php"; - $_SERVER['SCRIPT_NAME'] = "/index.php"; + $_SERVER['SCRIPT_FILENAME'] = '/index.php'; + $_SERVER['SCRIPT_NAME'] = '/index.php'; $appConfig = [ 'components' => [ 'user' => [ - 'identityClass' => UserIdentity::className() + 'identityClass' => UserIdentity::className(), ], ], 'controllerMap' => [ - 'test' => TestController::className() - ] + 'test' => TestController::className(), + ], ]; $this->mockWebApplication($appConfig); diff --git a/tests/framework/filters/stubs/MockAuthManager.php b/tests/framework/filters/stubs/MockAuthManager.php index 956787fb8f..1ed140e043 100644 --- a/tests/framework/filters/stubs/MockAuthManager.php +++ b/tests/framework/filters/stubs/MockAuthManager.php @@ -1,16 +1,21 @@ _rateLimit = $rateLimit; - + return $this; } @@ -40,5 +45,4 @@ class RateLimit extends Object implements RateLimitInterface { return [$action, $allowance, $timestamp]; } - } diff --git a/tests/framework/filters/stubs/UserIdentity.php b/tests/framework/filters/stubs/UserIdentity.php index 18cd026c96..086ab8b11c 100644 --- a/tests/framework/filters/stubs/UserIdentity.php +++ b/tests/framework/filters/stubs/UserIdentity.php @@ -1,4 +1,9 @@ urlCreator = function($model, $key, $index) { + $column->urlCreator = function ($model, $key, $index) { return 'http://test.com'; }; $columnContents = $column->renderDataCell(['id' => 1], 1, 0); @@ -45,14 +48,14 @@ class ActionColumnTest extends \yiiunit\TestCase $this->assertEquals($expectedHtml, $columnContents); $column = new ActionColumn(); - $column->urlCreator = function($model, $key, $index) { + $column->urlCreator = function ($model, $key, $index) { return 'http://test.com'; }; $column->template = '{update}'; $column->buttons = [ - 'update' => function($url, $model, $key) { + 'update' => function ($url, $model, $key) { return 'update_button'; - } + }, ]; //test default visible button @@ -61,31 +64,30 @@ class ActionColumnTest extends \yiiunit\TestCase //test visible button $column->visibleButtons = [ - 'update' => true + 'update' => true, ]; $columnContents = $column->renderDataCell(['id' => 1], 1, 0); $this->assertContains('update_button', $columnContents); //test visible button (condition is callback) $column->visibleButtons = [ - 'update' => function($model, $key, $index) {return $model['id'] == 1;} + 'update' => function ($model, $key, $index) {return $model['id'] == 1;}, ]; $columnContents = $column->renderDataCell(['id' => 1], 1, 0); $this->assertContains('update_button', $columnContents); //test invisible button $column->visibleButtons = [ - 'update' => false + 'update' => false, ]; $columnContents = $column->renderDataCell(['id' => 1], 1, 0); $this->assertNotContains('update_button', $columnContents); //test invisible button (condition is callback) $column->visibleButtons = [ - 'update' => function($model, $key, $index) {return $model['id'] != 1;} + 'update' => function ($model, $key, $index) {return $model['id'] != 1;}, ]; $columnContents = $column->renderDataCell(['id' => 1], 1, 0); $this->assertNotContains('update_button', $columnContents); - } } diff --git a/tests/framework/grid/CheckboxColumnTest.php b/tests/framework/grid/CheckboxColumnTest.php index b69b795087..5612c837b5 100644 --- a/tests/framework/grid/CheckboxColumnTest.php +++ b/tests/framework/grid/CheckboxColumnTest.php @@ -7,13 +7,11 @@ namespace yiiunit\framework\grid; +use Yii; use yii\data\ArrayDataProvider; use yii\grid\CheckboxColumn; use yii\grid\GridView; use yii\helpers\FileHelper; -use yii\i18n\Formatter; -use yii\web\View; -use Yii; use yiiunit\framework\i18n\IntlTestHelper; use yiiunit\TestCase; @@ -69,7 +67,7 @@ class CheckboxColumnTest extends TestCase 'checkboxOptions' => function ($model, $key, $index, $column) { return []; }, - 'grid' => $this->getGrid() + 'grid' => $this->getGrid(), ]); $this->assertContains('value="1"', $column->renderDataCell([], 1, 0)); $this->assertContains('value="42"', $column->renderDataCell([], 42, 0)); @@ -79,7 +77,7 @@ class CheckboxColumnTest extends TestCase 'checkboxOptions' => function ($model, $key, $index, $column) { return ['value' => 42]; }, - 'grid' => $this->getGrid() + 'grid' => $this->getGrid(), ]); $this->assertNotContains('value="1"', $column->renderDataCell([], 1, 0)); $this->assertContains('value="42"', $column->renderDataCell([], 1, 0)); diff --git a/tests/framework/grid/DataColumnTest.php b/tests/framework/grid/DataColumnTest.php index 454fe08fec..eed8c7a379 100644 --- a/tests/framework/grid/DataColumnTest.php +++ b/tests/framework/grid/DataColumnTest.php @@ -1,5 +1,9 @@ new ArrayDataProvider([ 'allModels' => [], 'totalCount' => 0, - 'modelClass' => Order::className() + 'modelClass' => Order::className(), ]), 'columns' => ['customer_id', 'total'], ]); @@ -52,7 +56,7 @@ class DataColumnTest extends \yiiunit\TestCase 'totalCount' => 0, ]), 'columns' => ['customer_id', 'total'], - 'filterModel' => new Order, + 'filterModel' => new Order(), ]); $labels = []; foreach ($grid->columns as $column) { @@ -82,7 +86,6 @@ class DataColumnTest extends \yiiunit\TestCase 'filter' => $filterInput, ], ], - ]); //print_r($grid->columns);exit(); $dataColumn = $grid->columns[0]; @@ -104,8 +107,8 @@ class DataColumnTest extends \yiiunit\TestCase 'db' => [ 'class' => '\yii\db\Connection', 'dsn' => 'sqlite::memory:', - ] - ] + ], + ], ]); $columns = [ 'id' => 'pk', @@ -124,9 +127,9 @@ class DataColumnTest extends \yiiunit\TestCase 0 => [ 'attribute' => 'customer_id', 'filter' => $filterInput, - ] + ], ], - 'filterModel' => new Order, + 'filterModel' => new Order(), ]); $dataColumn = $grid->columns[0]; @@ -155,8 +158,8 @@ HTML 'db' => [ 'class' => '\yii\db\Connection', 'dsn' => 'sqlite::memory:', - ] - ] + ], + ], ]); $columns = [ 'id' => 'pk', @@ -176,7 +179,7 @@ HTML 'format' => 'boolean', // does not make sense for this column but should still output proper dropdown list ], ], - 'filterModel' => new Order, + 'filterModel' => new Order(), ]); $dataColumn = $grid->columns[0]; diff --git a/tests/framework/grid/GridViewTest.php b/tests/framework/grid/GridViewTest.php index 983fd8f65e..deb6687d20 100644 --- a/tests/framework/grid/GridViewTest.php +++ b/tests/framework/grid/GridViewTest.php @@ -1,12 +1,16 @@ @@ -74,7 +78,7 @@ class GridViewTest extends \yiiunit\TestCase public function testGuessColumns() { - $row = ['id' => 1, 'name' => 'Name1', 'value' => 'Value1', 'description' => 'Description1',]; + $row = ['id' => 1, 'name' => 'Name1', 'value' => 'Value1', 'description' => 'Description1']; $grid = new GridView([ 'dataProvider' => new ArrayDataProvider( @@ -94,8 +98,8 @@ class GridViewTest extends \yiiunit\TestCase $this->assertArrayHasKey($column->attribute, $row); } - $row = array_merge($row, ['relation' => ['id' => 1, 'name' => 'RelationName',],]); - $row = array_merge($row, ['otherRelation' => (object)$row['relation']]); + $row = array_merge($row, ['relation' => ['id' => 1, 'name' => 'RelationName']]); + $row = array_merge($row, ['otherRelation' => (object) $row['relation']]); $grid = new GridView([ 'dataProvider' => new ArrayDataProvider( diff --git a/tests/framework/grid/RadiobuttonColumnTest.php b/tests/framework/grid/RadiobuttonColumnTest.php index c011e9e9ce..14acae9ea9 100644 --- a/tests/framework/grid/RadiobuttonColumnTest.php +++ b/tests/framework/grid/RadiobuttonColumnTest.php @@ -16,7 +16,6 @@ use yiiunit\TestCase; /** * Class RadiobuttonColumnTest - * @package yiiunit\framework\grid * @group grid * @since 2.0.11 */ @@ -29,7 +28,7 @@ class RadiobuttonColumnTest extends TestCase public function testException() { new RadioButtonColumn([ - 'name' => null + 'name' => null, ]); } @@ -37,8 +36,8 @@ class RadiobuttonColumnTest extends TestCase { $column = new RadioButtonColumn([ 'radioOptions' => [ - 'value' => 42 - ] + 'value' => 42, + ], ]); $this->assertEquals('', $column->renderDataCell([], 1, 0)); } @@ -47,14 +46,14 @@ class RadiobuttonColumnTest extends TestCase { $model = [ 'label' => 'label', - 'value' => 123 + 'value' => 123, ]; $column = new RadioButtonColumn([ 'radioOptions' => function ($model) { return [ - 'value' => $model['value'] + 'value' => $model['value'], ]; - } + }, ]); $actual = $column->renderDataCell($model, 1, 0); $this->assertEquals('', $actual); @@ -70,7 +69,7 @@ class RadiobuttonColumnTest extends TestCase $models = [ ['label' => 'label1', 'value' => 1], - ['label' => 'label2', 'value' => 2, 'checked' => true] + ['label' => 'label2', 'value' => 2, 'checked' => true], ]; $grid = new GridView([ 'dataProvider' => new ArrayDataProvider(['allModels' => $models]), @@ -81,11 +80,11 @@ class RadiobuttonColumnTest extends TestCase 'radioOptions' => function ($model) { return [ 'value' => $model['value'], - 'checked' => $model['value'] == 2 + 'checked' => $model['value'] == 2, ]; - } - ] - ] + }, + ], + ], ]); ob_start(); $grid->run(); diff --git a/tests/framework/helpers/ArrayHelperTest.php b/tests/framework/helpers/ArrayHelperTest.php index 4d4e737f4f..4e09d65382 100644 --- a/tests/framework/helpers/ArrayHelperTest.php +++ b/tests/framework/helpers/ArrayHelperTest.php @@ -1,11 +1,16 @@ method('toArray')->willReturn([]); $this->assertEquals([], ArrayHelper::toArray($dataArrayable)); $this->assertEquals(['foo'], ArrayHelper::toArray('foo')); - $object = new Post1; + $object = new Post1(); $this->assertEquals(get_object_vars($object), ArrayHelper::toArray($object)); - $object = new Post2; + $object = new Post2(); $this->assertEquals(get_object_vars($object), ArrayHelper::toArray($object)); - $object1 = new Post1; - $object2 = new Post2; + $object1 = new Post1(); + $object2 = new Post2(); $this->assertEquals([ get_object_vars($object1), get_object_vars($object2), @@ -70,7 +75,7 @@ class ArrayHelperTest extends TestCase $object2, ])); - $object = new Post2; + $object = new Post2(); $this->assertEquals([ 'id' => 123, 'secret' => 's', @@ -82,8 +87,8 @@ class ArrayHelperTest extends TestCase '_content' => 'content', 'length' => function ($post) { return strlen($post->content); - } - ] + }, + ], ])); $object = new Post3(); @@ -108,14 +113,14 @@ class ArrayHelperTest extends TestCase $object->className() => [ 'id', 'subObject', 'id_plus_1' => function ($post) { - return $post->id+1; - } + return $post->id + 1; + }, ], $object->subObject->className() => [ 'id', 'id_plus_1' => function ($post) { - return $post->id+1; - } + return $post->id + 1; + }, ], ])); @@ -130,8 +135,8 @@ class ArrayHelperTest extends TestCase $object->subObject->className() => [ 'id', 'id_plus_1' => function ($post) { - return $post->id+1; - } + return $post->id + 1; + }, ], ])); } @@ -154,18 +159,18 @@ class ArrayHelperTest extends TestCase 'Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', - 'Janet' => 'Jackson' + 'Janet' => 'Jackson', ]; $removed = ArrayHelper::removeValue($array, 'Jackson'); $this->assertEquals([ 'Bob' => 'Dylan', - 'Mick' => 'Jagger' + 'Mick' => 'Jagger', ], $array); $this->assertEquals([ 'Michael' => 'Jackson', - 'Janet' => 'Jackson' + 'Janet' => 'Jackson', ], $removed); } @@ -175,7 +180,7 @@ class ArrayHelperTest extends TestCase 'Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', - 'Janet' => 'Jackson' + 'Janet' => 'Jackson', ]; $removed = ArrayHelper::removeValue($array, 'Marley'); @@ -184,7 +189,7 @@ class ArrayHelperTest extends TestCase 'Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', - 'Janet' => 'Jackson' + 'Janet' => 'Jackson', ], $array); $this->assertEquals([], $removed); } @@ -242,21 +247,21 @@ class ArrayHelperTest extends TestCase public function testMultisortNestedObjects() { $obj1 = new \stdClass(); - $obj1->type = "def"; + $obj1->type = 'def'; $obj1->owner = $obj1; $obj2 = new \stdClass(); - $obj2->type = "abc"; + $obj2->type = 'abc'; $obj2->owner = $obj2; $obj3 = new \stdClass(); - $obj3->type = "abc"; + $obj3->type = 'abc'; $obj3->owner = $obj3; $models = [ $obj1, $obj2, - $obj3 + $obj3, ]; $this->assertEquals($obj2, $obj3); @@ -321,7 +326,7 @@ class ArrayHelperTest extends TestCase '- Bug: test4', ]; $i = 0; - ArrayHelper::multisort($changelog, function($line) use (&$i) { + ArrayHelper::multisort($changelog, function ($line) use (&$i) { if (preg_match('/^- (Enh|Bug)( #\d+)?: .+$/', $line, $m)) { $o = ['Bug' => 'C', 'Enh' => 'D']; return $o[$m[1]] . ' ' . (!empty($m[2]) ? $m[2] : 'AAAA' . $i++); @@ -336,7 +341,7 @@ class ArrayHelperTest extends TestCase '- Enh: test3', ], $changelog); } - + /** * @expectedException \yii\base\InvalidParamException */ @@ -498,7 +503,7 @@ class ArrayHelperTest extends TestCase $array = [ ['id' => '123', 'data' => 'abc'], ['id' => '345', 'data' => 'def'], - ['id' => '345', 'data' => 'ghi'] + ['id' => '345', 'data' => 'ghi'], ]; $result = ArrayHelper::index($array, 'id'); $this->assertEquals([ @@ -527,24 +532,25 @@ class ArrayHelperTest extends TestCase return $element['id'] == '345' ? null : $element['id']; }); $this->assertEquals([ - '123' => ['id' => '123', 'data' => 'abc'] + '123' => ['id' => '123', 'data' => 'abc'], ], $result); } - public function testIndexGroupBy() { + public function testIndexGroupBy() + { $array = [ ['id' => '123', 'data' => 'abc'], ['id' => '345', 'data' => 'def'], - ['id' => '345', 'data' => 'ghi'] + ['id' => '345', 'data' => 'ghi'], ]; $expected = [ '123' => [ - ['id' => '123', 'data' => 'abc'] + ['id' => '123', 'data' => 'abc'], ], '345' => [ ['id' => '345', 'data' => 'def'], - ['id' => '345', 'data' => 'ghi'] + ['id' => '345', 'data' => 'ghi'], ], ]; $result = ArrayHelper::index($array, null, ['id']); @@ -556,26 +562,26 @@ class ArrayHelperTest extends TestCase $this->assertEquals([ '123' => [ 'abc' => [ - ['id' => '123', 'data' => 'abc'] - ] + ['id' => '123', 'data' => 'abc'], + ], ], '345' => [ 'def' => [ - ['id' => '345', 'data' => 'def'] + ['id' => '345', 'data' => 'def'], ], 'ghi' => [ - ['id' => '345', 'data' => 'ghi'] - ] + ['id' => '345', 'data' => 'ghi'], + ], ], ], $result); $expected = [ '123' => [ - 'abc' => ['id' => '123', 'data' => 'abc'] + 'abc' => ['id' => '123', 'data' => 'abc'], ], '345' => [ 'def' => ['id' => '345', 'data' => 'def'], - 'ghi' => ['id' => '345', 'data' => 'ghi'] + 'ghi' => ['id' => '345', 'data' => 'ghi'], ], ]; $result = ArrayHelper::index($array, 'data', ['id']); @@ -590,16 +596,16 @@ class ArrayHelperTest extends TestCase $expected = [ '123' => [ 'abc' => [ - 'abc' => ['id' => '123', 'data' => 'abc'] - ] + 'abc' => ['id' => '123', 'data' => 'abc'], + ], ], '345' => [ 'def' => [ - 'def' => ['id' => '345', 'data' => 'def'] + 'def' => ['id' => '345', 'data' => 'def'], ], 'ghi' => [ - 'ghi' => ['id' => '345', 'data' => 'ghi'] - ] + 'ghi' => ['id' => '345', 'data' => 'ghi'], + ], ], ]; $result = ArrayHelper::index($array, 'data', ['id', 'data']); @@ -721,7 +727,7 @@ class ArrayHelperTest extends TestCase return $array['date'] . $defaultValue; }, '31-12-2113test', - 'test' + 'test', ], [['version', '1.0', 'status'], 'released'], [['version', '1.0', 'date'], 'defaultValue', 'defaultValue'], @@ -756,8 +762,8 @@ class ArrayHelperTest extends TestCase ], 'version' => [ '1.0' => [ - 'status' => 'released' - ] + 'status' => 'released', + ], ], ]; @@ -861,7 +867,7 @@ class ArrayHelperTest extends TestCase [ '<>' => 'a<>b', '23' => true, - ] + ], ]; $this->assertEquals([ 'abc' => '123', @@ -871,7 +877,7 @@ class ArrayHelperTest extends TestCase [ '<>' => 'a<>b', '23' => true, - ] + ], ], ArrayHelper::htmlDecode($array)); $this->assertEquals([ 'abc' => '123', @@ -881,7 +887,7 @@ class ArrayHelperTest extends TestCase [ '<>' => 'a<>b', '23' => true, - ] + ], ], ArrayHelper::htmlDecode($array, false)); } @@ -899,7 +905,6 @@ class ArrayHelperTest extends TestCase $this->assertTrue(ArrayHelper::isIn(['a'], new \ArrayObject([['a'], 'b']))); $this->assertFalse(ArrayHelper::isIn('a', new \ArrayObject([['a'], 'b']))); $this->assertFalse(ArrayHelper::isIn('a', [['a'], 'b'])); - } public function testIsInStrict() @@ -947,7 +952,7 @@ class ArrayHelperTest extends TestCase $this->assertTrue(ArrayHelper::isTraversable(['a'])); $this->assertTrue(ArrayHelper::isTraversable(new \ArrayObject(['1']))); $this->assertFalse(ArrayHelper::isTraversable(new \stdClass())); - $this->assertFalse(ArrayHelper::isTraversable("A,B,C")); + $this->assertFalse(ArrayHelper::isTraversable('A,B,C')); $this->assertFalse(ArrayHelper::isTraversable(12)); $this->assertFalse(ArrayHelper::isTraversable(false)); $this->assertFalse(ArrayHelper::isTraversable(null)); diff --git a/tests/framework/helpers/ConsoleTest.php b/tests/framework/helpers/ConsoleTest.php index 89521067d4..f4ad39da13 100644 --- a/tests/framework/helpers/ConsoleTest.php +++ b/tests/framework/helpers/ConsoleTest.php @@ -1,4 +1,9 @@ test' + 'test', ], [Console::ansiFormatCode([Console::RESET]) . Console::ansiFormatCode([Console::RESET]), ''], @@ -109,23 +114,23 @@ class ConsoleTest extends TestCase [ Console::ansiFormatCode([Console::BOLD]) . 'abc' . Console::ansiFormatCode([Console::RESET, Console::FG_GREEN]) . 'ghj' . Console::ansiFormatCode([Console::RESET]), - 'abcghj' + 'abcghj', ], [ Console::ansiFormatCode([Console::FG_GREEN]) . ' a ' . Console::ansiFormatCode([Console::BOLD]) . 'abc' . Console::ansiFormatCode([Console::RESET]) . 'ghj', - ' a abcghj' + ' a abcghj', ], [ Console::ansiFormat('test', [Console::FG_GREEN, Console::BG_BLUE, Console::NEGATIVE]), - 'test' + 'test', ], [ Console::ansiFormat('test', [Console::NEGATIVE]), - 'test' + 'test', ], [ Console::ansiFormat('test', [Console::CONCEALED]), - 'test' + 'test', ], ]; } diff --git a/tests/framework/helpers/FallbackInflector.php b/tests/framework/helpers/FallbackInflector.php index 0eff0e9da3..f9ab341f04 100644 --- a/tests/framework/helpers/FallbackInflector.php +++ b/tests/framework/helpers/FallbackInflector.php @@ -1,9 +1,12 @@ testFilePath . DIRECTORY_SEPARATOR . 'test_chmod'; mkdir($dir); chmod($dir, 0700); - if ($this->getMode($dir) !== "0700") { - /** + if ($this->getMode($dir) !== '0700') { + /* * Chmod returns true but fileperms does not reflect this. * This happens on remote file systems, also has been seen in vagrant mounts. */ @@ -142,7 +148,6 @@ class FileHelperTest extends TestCase $dirName = $basePath . DIRECTORY_SEPARATOR . 'test_dir_perms'; $this->assertTrue(FileHelper::createDirectory($dirName, 0700, false)); $this->assertFileMode(0700, $dirName); - } /** @@ -156,7 +161,7 @@ class FileHelperTest extends TestCase 'file2.txt' => 'file 2 content', ]; $this->createFileStructure([ - $srcDirName => $files + $srcDirName => $files, ]); $basePath = $this->testFilePath; @@ -188,7 +193,7 @@ class FileHelperTest extends TestCase 'file5.txt' => 'file 5 content', ]; $this->createFileStructure([ - $srcDirName => $structure + $srcDirName => $structure, ]); $basePath = $this->testFilePath; @@ -229,7 +234,7 @@ class FileHelperTest extends TestCase 'file5.txt' => 'file 5 content', ]; $this->createFileStructure([ - $srcDirName => $structure + $srcDirName => $structure, ]); $basePath = $this->testFilePath; @@ -312,7 +317,7 @@ class FileHelperTest extends TestCase { $this->createFileStructure([ 'data' => [], - 'backup' => ['data' => []] + 'backup' => ['data' => []], ]); $this->expectException('yii\base\InvalidParamException'); @@ -330,14 +335,14 @@ class FileHelperTest extends TestCase { $this->createFileStructure([ 'data' => [], - 'backup' => ['data' => []] + 'backup' => ['data' => []], ]); FileHelper::copyDirectory( $this->testFilePath . DIRECTORY_SEPARATOR . 'data', $this->testFilePath . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'data' ); - $this->assertTrue(file_exists($this->testFilePath . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'data')); + $this->assertFileExists($this->testFilePath . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'data'); } /** @@ -347,7 +352,7 @@ class FileHelperTest extends TestCase { $this->createFileStructure([ 'data' => [], - 'data-backup' => [] + 'data-backup' => [], ]); FileHelper::copyDirectory( @@ -392,7 +397,7 @@ class FileHelperTest extends TestCase $dirName => [ 'file' => 'Symlinked file.', 'directory' => [ - 'standard-file-1' => 'Standard file 1.' + 'standard-file-1' => 'Standard file 1.', ], 'symlinks' => [ 'standard-file-2' => 'Standard file 2.', @@ -435,7 +440,7 @@ class FileHelperTest extends TestCase $dirName => [ 'file' => 'Symlinked file.', 'directory' => [ - 'standard-file-1' => 'Standard file 1.' + 'standard-file-1' => 'Standard file 1.', ], 'symlinks' => [ 'standard-file-2' => 'Standard file 2.', @@ -514,7 +519,7 @@ class FileHelperTest extends TestCase $options = [ 'filter' => function ($path) use ($passedFileName) { return $passedFileName == basename($path); - } + }, ]; $foundFiles = FileHelper::findFiles($dirName, $options); $this->assertEquals([$dirName . DIRECTORY_SEPARATOR . $passedFileName], $foundFiles); @@ -561,7 +566,7 @@ class FileHelperTest extends TestCase 'file2' => 'def', ], 'symDir' => ['symlink', 'theDir'], - 'file3' => 'root' + 'file3' => 'root', ], ]); $dirName = $this->testFilePath . DIRECTORY_SEPARATOR . $dirName; @@ -609,7 +614,7 @@ class FileHelperTest extends TestCase $foundFiles = FileHelper::findFiles($basePath, ['except' => ['a.[2-8]']]); sort($foundFiles); $expect = array_values(array_filter($flat, function ($p) { - return substr($p, -3)==='a.1'; + return substr($p, -3) === 'a.1'; })); $this->assertEquals($expect, $foundFiles); @@ -617,7 +622,7 @@ class FileHelperTest extends TestCase $foundFiles = FileHelper::findFiles($basePath, ['except' => ['*.1']]); sort($foundFiles); $expect = array_values(array_filter($flat, function ($p) { - return substr($p, -3)!=='a.1'; + return substr($p, -3) !== 'a.1'; })); $this->assertEquals($expect, $foundFiles); @@ -625,7 +630,7 @@ class FileHelperTest extends TestCase $foundFiles = FileHelper::findFiles($basePath, ['except' => ['/one']]); sort($foundFiles); $expect = array_values(array_filter($flat, function ($p) { - return strpos($p, DIRECTORY_SEPARATOR.'one')===false; + return strpos($p, DIRECTORY_SEPARATOR . 'one') === false; })); $this->assertEquals($expect, $foundFiles); @@ -633,9 +638,9 @@ class FileHelperTest extends TestCase $foundFiles = FileHelper::findFiles($basePath, ['except' => ['?*/a.1']]); sort($foundFiles); $expect = array_values(array_filter($flat, function ($p) { - return substr($p, -11, 10)==='one'.DIRECTORY_SEPARATOR.'two'.DIRECTORY_SEPARATOR.'a.' || ( - substr($p, -8)!==DIRECTORY_SEPARATOR.'one'.DIRECTORY_SEPARATOR.'a.1' && - substr($p, -10)!==DIRECTORY_SEPARATOR.'three'.DIRECTORY_SEPARATOR.'a.1' + return substr($p, -11, 10) === 'one' . DIRECTORY_SEPARATOR . 'two' . DIRECTORY_SEPARATOR . 'a.' || ( + substr($p, -8) !== DIRECTORY_SEPARATOR . 'one' . DIRECTORY_SEPARATOR . 'a.1' && + substr($p, -10) !== DIRECTORY_SEPARATOR . 'three' . DIRECTORY_SEPARATOR . 'a.1' ); })); $this->assertEquals($expect, $foundFiles); @@ -658,14 +663,14 @@ class FileHelperTest extends TestCase $options = [ 'except' => ['*.txt'], - 'caseSensitive' => false + 'caseSensitive' => false, ]; $foundFiles = FileHelper::findFiles($dirName, $options); $this->assertCount(0, $foundFiles); $options = [ 'only' => ['*.txt'], - 'caseSensitive' => false + 'caseSensitive' => false, ]; $foundFiles = FileHelper::findFiles($dirName, $options); $this->assertCount(2, $foundFiles); @@ -710,15 +715,15 @@ class FileHelperTest extends TestCase $this->assertEquals("{$ds}b{$ds}c", FileHelper::normalizePath('/a/../b/c')); $this->assertEquals("{$ds}c", FileHelper::normalizePath('/a\\b/../..///c')); $this->assertEquals("{$ds}c", FileHelper::normalizePath('/a/.\\b//../../c')); - $this->assertEquals("c", FileHelper::normalizePath('/a/.\\b/../..//../c')); + $this->assertEquals('c', FileHelper::normalizePath('/a/.\\b/../..//../c')); $this->assertEquals("..{$ds}c", FileHelper::normalizePath('//a/.\\b//..//..//../../c')); // relative paths - $this->assertEquals(".", FileHelper::normalizePath('.')); - $this->assertEquals(".", FileHelper::normalizePath('./')); - $this->assertEquals("a", FileHelper::normalizePath('.\\a')); + $this->assertEquals('.', FileHelper::normalizePath('.')); + $this->assertEquals('.', FileHelper::normalizePath('./')); + $this->assertEquals('a', FileHelper::normalizePath('.\\a')); $this->assertEquals("a{$ds}b", FileHelper::normalizePath('./a\\b')); - $this->assertEquals(".", FileHelper::normalizePath('./a\\../')); + $this->assertEquals('.', FileHelper::normalizePath('./a\\../')); $this->assertEquals("..{$ds}..{$ds}a", FileHelper::normalizePath('../..\\a')); $this->assertEquals("..{$ds}..{$ds}a", FileHelper::normalizePath('../..\\a/../a')); $this->assertEquals("..{$ds}..{$ds}b", FileHelper::normalizePath('../..\\a/../b')); @@ -771,7 +776,7 @@ class FileHelperTest extends TestCase 'file2.dat' => 'data file 2 content', ]; $this->createFileStructure([ - $srcDirName => array_merge($textFiles, $dataFiles) + $srcDirName => array_merge($textFiles, $dataFiles), ]); $basePath = $this->testFilePath; diff --git a/tests/framework/helpers/FormatConverterTest.php b/tests/framework/helpers/FormatConverterTest.php index 0b3dcbf08b..fe193ecc2f 100644 --- a/tests/framework/helpers/FormatConverterTest.php +++ b/tests/framework/helpers/FormatConverterTest.php @@ -1,4 +1,9 @@ assertEquals("a<>&"'�", Html::encode("a<>&\"'\x80")); + $this->assertEquals('a<>&"'�', Html::encode("a<>&\"'\x80")); $this->assertEquals('Sam & Dark', Html::encode('Sam & Dark')); } public function testDecode() { - $this->assertEquals("a<>&\"'", Html::decode("a<>&"'")); + $this->assertEquals("a<>&\"'", Html::decode('a<>&"'')); } public function testTag() @@ -113,7 +118,7 @@ class HtmlTest extends TestCase ]); $this->assertEquals('', Html::csrfMetaTags()); } - + public function testCsrfMetaTagsEnableCsrfValidation() { $this->mockApplication([ @@ -132,7 +137,7 @@ class HtmlTest extends TestCase $actual = Html::csrfMetaTags(); $this->assertStringMatchesFormat($pattern, $actual); } - + public function testCsrfMetaTagsEnableCsrfValidationWithoutCookieValidationKey() { $request = $this->getMock('yii\\web\\Request'); @@ -145,7 +150,7 @@ class HtmlTest extends TestCase /** * @dataProvider dataProviderBeginFormSimulateViaPost - * + * * @param string $expected * @param string $method */ @@ -162,12 +167,12 @@ class HtmlTest extends TestCase public function dataProviderBeginFormSimulateViaPost() { return [ - ['', 'GET'], - ['', 'POST'], - ['%A', 'DELETE'], - ['%A', 'GETFOO'], - ['%A', 'POSTFOO'], - ['%A', 'POSTFOOPOST'], + ['', 'GET'], + ['', 'POST'], + ['%A', 'DELETE'], + ['%A', 'GETFOO'], + ['%A', 'POSTFOO'], + ['%A', 'POSTFOOPOST'], ]; } @@ -197,7 +202,7 @@ class HtmlTest extends TestCase $this->assertEquals('something', Html::a('something', '/example')); $this->assertEquals('something', Html::a('something', '')); $this->assertEquals('http://www.быстроном.рф', Html::a('http://www.быстроном.рф', 'http://www.быстроном.рф')); - $this->assertEquals('Test page', Html::a('Test page', Url::to(['/site/test'], 'https'))); + $this->assertEquals('Test page', Html::a('Test page', Url::to(['/site/test'], 'https'))); } public function testMailto() @@ -311,7 +316,7 @@ class HtmlTest extends TestCase { $this->assertEquals('', Html::button()); $this->assertEquals('', Html::button('content<>', ['name' => 'test', 'value' => 'value'])); - $this->assertEquals('', Html::button('content<>', ['type' => 'submit', 'name' => 'test', 'value' => 'value', 'class' => "t"])); + $this->assertEquals('', Html::button('content<>', ['type' => 'submit', 'name' => 'test', 'value' => 'value', 'class' => 't'])); } public function testSubmitButton() @@ -384,25 +389,25 @@ class HtmlTest extends TestCase '', 'test', null, - [] + [], ], [ '', 'test', 'value<>', - ['class' => 't'] + ['class' => 't'], ], [ '', 'test', 'value<>', - [] + [], ], [ '', 'test', 'value<>', - ['doubleEncode' => false] + ['doubleEncode' => false], ], ]; } @@ -425,7 +430,7 @@ class HtmlTest extends TestCase 'class' => 'a', 'value' => null, 'label' => 'ccc', - 'labelOptions' => ['class' =>'bbb'], + 'labelOptions' => ['class' => 'bbb'], ])); $this->assertEquals('', Html::radio('test', true, [ 'class' => 'a', @@ -445,7 +450,7 @@ class HtmlTest extends TestCase 'class' => 'a', 'value' => null, 'label' => 'ccc', - 'labelOptions' => ['class' =>'bbb'], + 'labelOptions' => ['class' => 'bbb'], ])); $this->assertEquals('', Html::checkbox('test', true, [ 'class' => 'a', @@ -493,7 +498,7 @@ EOD; EOD; $this->assertEqualsWithoutLE($expected, Html::dropDownList('test', null, $this->getDataItems(), [ 'options' => [ - 'value2' => ['selected' => true] + 'value2' => ['selected' => true], ], ])); @@ -620,7 +625,7 @@ EOD; $this->assertEqualsWithoutLE($expected, Html::checkboxList('test', ['value2'], $this->getDataItems(), [ 'item' => function ($index, $label, $name, $checked, $value) { return $index . Html::label($label . ' ' . Html::checkbox($name, $checked, ['value' => $value])); - } + }, ])); $expected = << function ($index, $label, $name, $checked, $value) { return $index . Html::label($label . ' ' . Html::checkbox($name, $checked, ['value' => $value])); }, - 'tag' => false + 'tag' => false, ])); @@ -639,9 +644,8 @@ EOD; 'item' => function ($index, $label, $name, $checked, $value) { return $index . Html::label($label . ' ' . Html::checkbox($name, $checked, ['value' => $value])); }, - 'tag' => false + 'tag' => false, ])); - } public function testRadioList() @@ -676,7 +680,7 @@ EOD; $this->assertEqualsWithoutLE($expected, Html::radioList('test', ['value2'], $this->getDataItems(), [ 'item' => function ($index, $label, $name, $checked, $value) { return $index . Html::label($label . ' ' . Html::radio($name, $checked, ['value' => $value])); - } + }, ])); $expected = << function ($index, $label, $name, $checked, $value) { return $index . Html::label($label . ' ' . Html::radio($name, $checked, ['value' => $value])); }, - 'tag' => false + 'tag' => false, ])); $this->assertEqualsWithoutLE($expected, Html::radioList('test', new \ArrayObject(['value2']), $this->getDataItems(), [ 'item' => function ($index, $label, $name, $checked, $value) { return $index . Html::label($label . ' ' . Html::radio($name, $checked, ['value' => $value])); }, - 'tag' => false + 'tag' => false, ])); } @@ -722,7 +726,7 @@ EOD; 'class' => 'test', 'item' => function ($item, $index) { return "
  • $item
  • "; - } + }, ])); $this->assertEquals('
      ', Html::ul([], ['class' => 'test'])); @@ -756,7 +760,7 @@ EOD; 'class' => 'test', 'item' => function ($item, $index) { return "
    • $item
    • "; - } + }, ])); $this->assertEquals('
        ', Html::ol([], ['class' => 'test'])); @@ -872,7 +876,7 @@ EOD; $this->assertEquals(['class' => 'test test2 test3'], $options); $options = [ - 'class' => ['test'] + 'class' => ['test'], ]; Html::addCssClass($options, 'test2'); $this->assertEquals(['class' => ['test', 'test2']], $options); @@ -882,7 +886,7 @@ EOD; $this->assertEquals(['class' => ['test', 'test2', 'test3']], $options); $options = [ - 'class' => 'test' + 'class' => 'test', ]; Html::addCssClass($options, ['test1', 'test2']); $this->assertEquals(['class' => 'test test1 test2'], $options); @@ -895,8 +899,8 @@ EOD; { $options = [ 'class' => [ - 'persistent' => 'test1' - ] + 'persistent' => 'test1', + ], ]; Html::addCssClass($options, ['persistent' => 'test2']); $this->assertEquals(['persistent' => 'test1'], $options['class']); @@ -924,7 +928,7 @@ EOD; $this->assertEquals([], $options); $options = [ - 'class' => 'test test1 test2' + 'class' => 'test test1 test2', ]; Html::removeCssClass($options, ['test1', 'test2']); $this->assertEquals(['class' => 'test'], $options); @@ -972,7 +976,7 @@ EOD; $options = [ 'style' => [ - 'width' => '100px' + 'width' => '100px', ], ]; Html::addCssStyle($options, ['color' => 'red'], false); @@ -1048,14 +1052,14 @@ EOD; [ '', [ - 'maxlength' => true + 'maxlength' => true, ], '', ], [ '', [ - 'maxlength' => 99 + 'maxlength' => 99, ], '', ], @@ -1091,14 +1095,14 @@ EOD; [ '', [ - 'maxlength' => true + 'maxlength' => true, ], '', ], [ '', [ - 'maxlength' => 99 + 'maxlength' => 99, ], '', ], @@ -1125,7 +1129,7 @@ EOD; [ 'ok', [], - '

        Please fix the following errors:

          ' + '

          Please fix the following errors:

            ', ], [ 'ok', @@ -1135,43 +1139,46 @@ EOD; [ str_repeat('long_string', 60), [], - '

            Please fix the following errors:

            • Name should contain at most 100 characters.
            ' + '

            Please fix the following errors:

            • Name should contain at most 100 characters.
            ', ], [ 'not_an_integer', [], '

            Please fix the following errors:

            • Error message. Here are some chars: < >
            ', - function ($model) { /** @var $model DynamicModel */ + function ($model) { + /* @var $model DynamicModel */ $model->addError('name', 'Error message. Here are some chars: < >'); - } + }, ], [ 'not_an_integer', ['encode' => false], '

            Please fix the following errors:

            • Error message. Here are some chars: < >
            ', - function ($model) { /** @var $model DynamicModel */ + function ($model) { + /* @var $model DynamicModel */ $model->addError('name', 'Error message. Here are some chars: < >'); - } + }, ], [ str_repeat('long_string', 60), [], '

            Please fix the following errors:

            • Error message. Here are some chars: < >
            ', - function ($model) { /** @var $model DynamicModel */ + function ($model) { + /* @var $model DynamicModel */ $model->addError('name', 'Error message. Here are some chars: < >'); - } + }, ], [ 'not_an_integer', ['showAllErrors' => true], '

            Please fix the following errors:

            • Error message. Here are some chars: < >
            • Error message. Here are even more chars: ""
            ', - function ($model) { /** @var $model DynamicModel */ + function ($model) { + /* @var $model DynamicModel */ $model->addError('name', 'Error message. Here are some chars: < >'); $model->addError('name', 'Error message. Here are even more chars: ""'); - } + }, ], - ]; } @@ -1210,21 +1217,21 @@ EOD; [ 'some text', [ - 'maxlength' => true + 'maxlength' => true, ], '', ], [ 'some text', [ - 'maxlength' => 99 + 'maxlength' => 99, ], '', ], [ 'some text', [ - 'value' => 'override text' + 'value' => 'override text', ], '', ], @@ -1263,7 +1270,7 @@ EOD; $noCsrfForm = Html::beginForm('/index.php', 'post', ['csrf' => false, 'id' => 'myform']); $this->assertEquals('', $noCsrfForm); } - + /** * Data provider for [[testActiveRadio()]] * @return array test data @@ -1274,26 +1281,26 @@ EOD; [ true, [], - '' + '', ], [ true, ['uncheck' => false], - '' + '', ], [ true, ['label' => false], - '' + '', ], [ true, ['uncheck' => false, 'label' => false], - '' + '', ], ]; } - + /** * @dataProvider dataProviderActiveRadio * @@ -1307,7 +1314,7 @@ EOD; $model->radio = $value; $this->assertEquals($expectedHtml, Html::activeRadio($model, 'radio', $options)); } - + /** * Data provider for [[testActiveCheckbox()]] * @return array test data @@ -1318,26 +1325,26 @@ EOD; [ true, [], - '' + '', ], [ true, ['uncheck' => false], - '' + '', ], [ true, ['label' => false], - '' + '', ], [ true, ['uncheck' => false, 'label' => false], - '' + '', ], ]; } - + /** * @dataProvider dataProviderActiveCheckbox * @@ -1359,22 +1366,22 @@ EOD; public function validAttributeNamesProvider() { return [ - ["asd]asdf.asdfa[asdfa", "asdf.asdfa"], - ["a", "a"], - ["[0]a", "a"], - ["a[0]", "a"], - ["[0]a[0]", "a"], - ["[0]a.[0]", "a."], + ['asd]asdf.asdfa[asdfa', 'asdf.asdfa'], + ['a', 'a'], + ['[0]a', 'a'], + ['a[0]', 'a'], + ['[0]a[0]', 'a'], + ['[0]a.[0]', 'a.'], // Unicode checks. - ["ä", "ä"], - ["ä", "ä"], - ["asdf]öáöio..[asdfasdf", "öáöio.."], - ["öáöio", "öáöio"], - ["[0]test.ööößß.d", "test.ööößß.d"], - ["ИІК", "ИІК"], - ["]ИІК[", "ИІК"], - ["[0]ИІК[0]", "ИІК"] + ['ä', 'ä'], + ['ä', 'ä'], + ['asdf]öáöio..[asdfasdf', 'öáöio..'], + ['öáöio', 'öáöio'], + ['[0]test.ööößß.d', 'test.ööößß.d'], + ['ИІК', 'ИІК'], + [']ИІК[', 'ИІК'], + ['[0]ИІК[0]', 'ИІК'], ]; } @@ -1387,7 +1394,7 @@ EOD; return [ ['. ..'], ['a +b'], - ['a,b'] + ['a,b'], ]; } @@ -1406,7 +1413,7 @@ EOD; $this->assertEquals($expected, Html::getAttributeName($name)); } } - + /** * @dataProvider invalidAttributeNamesProvider * @@ -1439,19 +1446,19 @@ EOD; public function testGetAttributeValue() { $model = new HtmlTestModel(); - + $expected = null; $actual = Html::getAttributeValue($model, 'types'); $this->assertSame($expected, $actual); - + $activeRecord = $this->getMock('yii\\db\\ActiveRecordInterface'); $activeRecord->method('getPrimaryKey')->willReturn(1); $model->types = $activeRecord; - + $expected = 1; $actual = Html::getAttributeValue($model, 'types'); $this->assertSame($expected, $actual); - + $model->types = [ $activeRecord, ]; diff --git a/tests/framework/helpers/InflectorTest.php b/tests/framework/helpers/InflectorTest.php index 2408ba131e..75a5087bb9 100644 --- a/tests/framework/helpers/InflectorTest.php +++ b/tests/framework/helpers/InflectorTest.php @@ -1,4 +1,9 @@ assertEquals("Me my self and i", Inflector::titleize('MeMySelfAndI')); - $this->assertEquals("Me My Self And I", Inflector::titleize('MeMySelfAndI', true)); + $this->assertEquals('Me my self and i', Inflector::titleize('MeMySelfAndI')); + $this->assertEquals('Me My Self And I', Inflector::titleize('MeMySelfAndI', true)); } public function testCamelize() { - $this->assertEquals("MeMySelfAndI", Inflector::camelize('me my_self-andI')); - $this->assertEquals("QweQweEwq", Inflector::camelize('qwe qwe^ewq')); + $this->assertEquals('MeMySelfAndI', Inflector::camelize('me my_self-andI')); + $this->assertEquals('QweQweEwq', Inflector::camelize('qwe qwe^ewq')); } public function testUnderscore() { - $this->assertEquals("me_my_self_and_i", Inflector::underscore('MeMySelfAndI')); + $this->assertEquals('me_my_self_and_i', Inflector::underscore('MeMySelfAndI')); } public function testCamel2words() @@ -128,18 +133,18 @@ class InflectorTest extends TestCase public function testHumanize() { - $this->assertEquals("Me my self and i", Inflector::humanize('me_my_self_and_i')); - $this->assertEquals("Me My Self And I", Inflector::humanize('me_my_self_and_i', true)); + $this->assertEquals('Me my self and i', Inflector::humanize('me_my_self_and_i')); + $this->assertEquals('Me My Self And I', Inflector::humanize('me_my_self_and_i', true)); } public function testVariablize() { - $this->assertEquals("customerTable", Inflector::variablize('customer_table')); + $this->assertEquals('customerTable', Inflector::variablize('customer_table')); } public function testTableize() { - $this->assertEquals("customer_tables", Inflector::tableize('customerTable')); + $this->assertEquals('customer_tables', Inflector::tableize('customerTable')); } public function testSlugCommons() @@ -340,7 +345,7 @@ class InflectorTest extends TestCase public function testClassify() { - $this->assertEquals("CustomerTable", Inflector::classify('customer_tables')); + $this->assertEquals('CustomerTable', Inflector::classify('customer_tables')); } public function testOrdinalize() diff --git a/tests/framework/helpers/JsonTest.php b/tests/framework/helpers/JsonTest.php index 4222a3ae16..a50ae037ce 100644 --- a/tests/framework/helpers/JsonTest.php +++ b/tests/framework/helpers/JsonTest.php @@ -1,13 +1,18 @@ method('toArray')->willReturn([]); $actual = Json::encode($dataArrayable); $this->assertSame('{}', $actual); - + // basic data encoding $data = '1'; $this->assertSame('"1"', Json::encode($data)); @@ -62,7 +67,7 @@ class JsonTest extends TestCase $expression2 = 'function (b) {}'; $data = [ 'a' => [ - 1, new JsExpression($expression1) + 1, new JsExpression($expression1), ], 'b' => new JsExpression($expression2), ]; @@ -116,14 +121,14 @@ class JsonTest extends TestCase $expression2 = 'function (b) {}'; $data = [ 'a' => [ - 1, new JsExpression($expression1) + 1, new JsExpression($expression1), ], 'b' => new JsExpression($expression2), ]; $this->assertSame("{\"a\":[1,$expression1],\"b\":$expression2}", Json::htmlEncode($data)); // https://github.com/yiisoft/yii2/issues/957 - $data = (object)null; + $data = (object) null; $this->assertSame('{}', Json::htmlEncode($data)); // JsonSerializable @@ -169,8 +174,7 @@ class JsonTest extends TestCase $this->expectException('yii\base\InvalidParamException'); Json::decode($json); } - - + /** * @expectedException \yii\base\InvalidParamException * @expectedExceptionMessage Invalid JSON data. @@ -210,7 +214,7 @@ class JsonModel extends Model implements \JsonSerializable { public $data = ['json' => 'serializable']; - function jsonSerialize() + public function jsonSerialize() { return $this->data; } diff --git a/tests/framework/helpers/MarkdownTest.php b/tests/framework/helpers/MarkdownTest.php index 847884ff22..cc2a6791c5 100644 --- a/tests/framework/helpers/MarkdownTest.php +++ b/tests/framework/helpers/MarkdownTest.php @@ -1,9 +1,15 @@ assertEquals('abcdef', StringHelper::byteSubstr('abcdef', 0)); $this->assertEquals('abcdef', StringHelper::byteSubstr('abcdef', 0, null)); - $this->assertEquals('de', StringHelper::byteSubstr('abcdef', 3, 2)); - $this->assertEquals('def', StringHelper::byteSubstr('abcdef', 3)); - $this->assertEquals('def', StringHelper::byteSubstr('abcdef', 3, null)); + $this->assertEquals('de', StringHelper::byteSubstr('abcdef', 3, 2)); + $this->assertEquals('def', StringHelper::byteSubstr('abcdef', 3)); + $this->assertEquals('def', StringHelper::byteSubstr('abcdef', 3, null)); - $this->assertEquals('cd', StringHelper::byteSubstr('abcdef', -4, 2)); - $this->assertEquals('cdef', StringHelper::byteSubstr('abcdef', -4)); - $this->assertEquals('cdef', StringHelper::byteSubstr('abcdef', -4, null)); + $this->assertEquals('cd', StringHelper::byteSubstr('abcdef', -4, 2)); + $this->assertEquals('cdef', StringHelper::byteSubstr('abcdef', -4)); + $this->assertEquals('cdef', StringHelper::byteSubstr('abcdef', -4, null)); - $this->assertEquals('', StringHelper::byteSubstr('abcdef', 4, 0)); - $this->assertEquals('', StringHelper::byteSubstr('abcdef', -4, 0)); + $this->assertEquals('', StringHelper::byteSubstr('abcdef', 4, 0)); + $this->assertEquals('', StringHelper::byteSubstr('abcdef', -4, 0)); $this->assertEquals('это', StringHelper::byteSubstr('это', 0)); $this->assertEquals('это', StringHelper::byteSubstr('это', 0, null)); - $this->assertEquals('т', StringHelper::byteSubstr('это', 2, 2)); - $this->assertEquals('то', StringHelper::byteSubstr('это', 2)); - $this->assertEquals('то', StringHelper::byteSubstr('это', 2, null)); + $this->assertEquals('т', StringHelper::byteSubstr('это', 2, 2)); + $this->assertEquals('то', StringHelper::byteSubstr('это', 2)); + $this->assertEquals('то', StringHelper::byteSubstr('это', 2, null)); - $this->assertEquals('т', StringHelper::byteSubstr('это', -4, 2)); - $this->assertEquals('то', StringHelper::byteSubstr('это', -4)); - $this->assertEquals('то', StringHelper::byteSubstr('это', -4, null)); + $this->assertEquals('т', StringHelper::byteSubstr('это', -4, 2)); + $this->assertEquals('то', StringHelper::byteSubstr('это', -4)); + $this->assertEquals('то', StringHelper::byteSubstr('это', -4, null)); - $this->assertEquals('', StringHelper::byteSubstr('это', 4, 0)); - $this->assertEquals('', StringHelper::byteSubstr('это', -4, 0)); + $this->assertEquals('', StringHelper::byteSubstr('это', 4, 0)); + $this->assertEquals('', StringHelper::byteSubstr('это', -4, 0)); } public function testBasename() @@ -248,14 +254,14 @@ class StringHelperTest extends TestCase public function testExplode() { - $this->assertEquals(['It', 'is', 'a first', 'test'], StringHelper::explode("It, is, a first, test")); - $this->assertEquals(['It', 'is', 'a test with trimmed digits', '0', '1', '2'], StringHelper::explode("It, is, a test with trimmed digits, 0, 1, 2", ',', true, true)); - $this->assertEquals(['It', 'is', 'a second', 'test'], StringHelper::explode("It+ is+ a second+ test", '+')); - $this->assertEquals(['Save', '', '', 'empty trimmed string'], StringHelper::explode("Save, ,, empty trimmed string", ',')); - $this->assertEquals(['Здесь', 'multibyte', 'строка'], StringHelper::explode("Здесь我 multibyte我 строка", '我')); - $this->assertEquals(['Disable', ' trim ', 'here but ignore empty'], StringHelper::explode("Disable, trim ,,,here but ignore empty", ',', false, true)); - $this->assertEquals(['It/', ' is?', ' a', ' test with rtrim'], StringHelper::explode("It/, is?, a , test with rtrim", ',', 'rtrim')); - $this->assertEquals(['It', ' is', ' a ', ' test with closure'], StringHelper::explode("It/, is?, a , test with closure", ',', function ($value) { return trim($value, '/?'); })); + $this->assertEquals(['It', 'is', 'a first', 'test'], StringHelper::explode('It, is, a first, test')); + $this->assertEquals(['It', 'is', 'a test with trimmed digits', '0', '1', '2'], StringHelper::explode('It, is, a test with trimmed digits, 0, 1, 2', ',', true, true)); + $this->assertEquals(['It', 'is', 'a second', 'test'], StringHelper::explode('It+ is+ a second+ test', '+')); + $this->assertEquals(['Save', '', '', 'empty trimmed string'], StringHelper::explode('Save, ,, empty trimmed string', ',')); + $this->assertEquals(['Здесь', 'multibyte', 'строка'], StringHelper::explode('Здесь我 multibyte我 строка', '我')); + $this->assertEquals(['Disable', ' trim ', 'here but ignore empty'], StringHelper::explode('Disable, trim ,,,here but ignore empty', ',', false, true)); + $this->assertEquals(['It/', ' is?', ' a', ' test with rtrim'], StringHelper::explode('It/, is?, a , test with rtrim', ',', 'rtrim')); + $this->assertEquals(['It', ' is', ' a ', ' test with closure'], StringHelper::explode('It/, is?, a , test with closure', ',', function ($value) { return trim($value, '/?'); })); } public function testWordCount() diff --git a/tests/framework/helpers/UrlTest.php b/tests/framework/helpers/UrlTest.php index 505e70c375..9db7c3c798 100644 --- a/tests/framework/helpers/UrlTest.php +++ b/tests/framework/helpers/UrlTest.php @@ -1,4 +1,10 @@ 'yii\web\Request', 'scriptUrl' => '/base/index.php', 'hostInfo' => 'http://example.com/', - 'url' => '/base/index.php&r=site%2Fcurrent&id=42' + 'url' => '/base/index.php&r=site%2Fcurrent&id=42', ], 'urlManager' => [ 'class' => 'yii\web\UrlManager', diff --git a/tests/framework/helpers/VarDumperTest.php b/tests/framework/helpers/VarDumperTest.php index d2a295663e..c052b580aa 100644 --- a/tests/framework/helpers/VarDumperTest.php +++ b/tests/framework/helpers/VarDumperTest.php @@ -1,4 +1,10 @@ assertContains("__PHP_Incomplete_Class#1\n(", $dumpResult); - $this->assertContains("nonExistingClass", $dumpResult); + $this->assertContains('nonExistingClass', $dumpResult); } public function testExportIncompleteObject() @@ -32,7 +38,7 @@ class VarDumperTest extends TestCase $serializedObj = 'O:16:"nonExistingClass":0:{}'; $incompleteObj = unserialize($serializedObj); $exportResult = VarDumper::export($incompleteObj); - $this->assertContains("nonExistingClass", $exportResult); + $this->assertContains('nonExistingClass', $exportResult); } public function testDumpObject() @@ -46,7 +52,7 @@ class VarDumperTest extends TestCase $dumpResult = VarDumper::dumpAsString($obj); $this->assertContains("stdClass#1\n(", $dumpResult); $this->assertContains("[name] => 'test-name'", $dumpResult); - $this->assertContains("[price] => 19", $dumpResult); + $this->assertContains('[price] => 19', $dumpResult); } /** @@ -60,31 +66,31 @@ class VarDumperTest extends TestCase $data = [ [ 'test string', - var_export('test string', true) + var_export('test string', true), ], [ 75, - var_export(75, true) + var_export(75, true), ], [ 7.5, - var_export(7.5, true) + var_export(7.5, true), ], [ null, - 'null' + 'null', ], [ true, - 'true' + 'true', ], [ false, - 'false' + 'false', ], [ [], - '[]' + '[]', ], ]; @@ -175,7 +181,7 @@ RESULT; $slave = new \StdClass(); $master->slave = $slave; $slave->master = $master; - $master->function = function() {return true;}; + $master->function = function () {return true;}; $exportResult = VarDumper::export($master); $this->assertNotEmpty($exportResult); diff --git a/tests/framework/i18n/DbMessageSourceTest.php b/tests/framework/i18n/DbMessageSourceTest.php index 7c254b208b..8bc21e73e7 100644 --- a/tests/framework/i18n/DbMessageSourceTest.php +++ b/tests/framework/i18n/DbMessageSourceTest.php @@ -1,4 +1,9 @@ [ 'class' => $this->getMessageSourceClass(), 'db' => static::$db, - ] - ] + ], + ], ]); } @@ -60,7 +65,7 @@ class DbMessageSourceTest extends I18NTest ob_start(); $result = Yii::$app->runAction($route, $params); - echo "Result is " . $result; + echo 'Result is ' . $result; if ($result !== \yii\console\Controller::EXIT_CODE_NORMAL) { ob_end_flush(); } else { @@ -119,7 +124,7 @@ class DbMessageSourceTest extends I18NTest public static function getConnection() { if (static::$db == null) { - $db = new Connection; + $db = new Connection(); $db->dsn = static::$database['dsn']; if (isset(static::$database['username'])) { $db->username = static::$database['username']; diff --git a/tests/framework/i18n/FallbackMessageFormatterTest.php b/tests/framework/i18n/FallbackMessageFormatterTest.php index 4b2de7c86a..4281f52b2d 100644 --- a/tests/framework/i18n/FallbackMessageFormatterTest.php +++ b/tests/framework/i18n/FallbackMessageFormatterTest.php @@ -21,11 +21,11 @@ class FallbackMessageFormatterTest extends TestCase const N_VALUE = 42; const F = 'f'; const F_VALUE = 2e+8; - const F_VALUE_FORMATTED = "200,000,000"; + const F_VALUE_FORMATTED = '200,000,000'; const D = 'd'; const D_VALUE = 200000000.101; - const D_VALUE_FORMATTED = "200,000,000.101"; - const D_VALUE_FORMATTED_INTEGER = "200,000,000"; + const D_VALUE_FORMATTED = '200,000,000.101'; + const D_VALUE_FORMATTED_INTEGER = '200,000,000'; const SUBJECT = 'сабж'; const SUBJECT_VALUE = 'Answer to the Ultimate Question of Life, the Universe, and Everything'; @@ -33,62 +33,62 @@ class FallbackMessageFormatterTest extends TestCase { return [ [ - '{'.self::SUBJECT.'} is {'.self::N.'}', // pattern - self::SUBJECT_VALUE.' is '.self::N_VALUE, // expected + '{' . self::SUBJECT . '} is {' . self::N . '}', // pattern + self::SUBJECT_VALUE . ' is ' . self::N_VALUE, // expected [ // params self::N => self::N_VALUE, self::SUBJECT => self::SUBJECT_VALUE, - ] + ], ], [ - '{'.self::SUBJECT.'} is {'.self::N.', number}', // pattern - self::SUBJECT_VALUE.' is '.self::N_VALUE, // expected + '{' . self::SUBJECT . '} is {' . self::N . ', number}', // pattern + self::SUBJECT_VALUE . ' is ' . self::N_VALUE, // expected [ // params self::N => self::N_VALUE, self::SUBJECT => self::SUBJECT_VALUE, - ] + ], ], [ - '{'.self::SUBJECT.'} is {'.self::N.', number, integer}', // pattern - self::SUBJECT_VALUE.' is '.self::N_VALUE, // expected + '{' . self::SUBJECT . '} is {' . self::N . ', number, integer}', // pattern + self::SUBJECT_VALUE . ' is ' . self::N_VALUE, // expected [ // params self::N => self::N_VALUE, self::SUBJECT => self::SUBJECT_VALUE, - ] + ], ], [ - 'Here is a big number: {'.self::F.', number}', // pattern - 'Here is a big number: '.self::F_VALUE_FORMATTED, // expected + 'Here is a big number: {' . self::F . ', number}', // pattern + 'Here is a big number: ' . self::F_VALUE_FORMATTED, // expected [ // params - self::F => self::F_VALUE - ] + self::F => self::F_VALUE, + ], ], [ - 'Here is a big number: {'.self::F.', number, integer}', // pattern - 'Here is a big number: '.self::F_VALUE_FORMATTED, // expected + 'Here is a big number: {' . self::F . ', number, integer}', // pattern + 'Here is a big number: ' . self::F_VALUE_FORMATTED, // expected [ // params - self::F => self::F_VALUE - ] + self::F => self::F_VALUE, + ], ], [ - 'Here is a big number: {'.self::D.', number}', // pattern - 'Here is a big number: '.self::D_VALUE_FORMATTED, // expected + 'Here is a big number: {' . self::D . ', number}', // pattern + 'Here is a big number: ' . self::D_VALUE_FORMATTED, // expected [ // params - self::D => self::D_VALUE - ] + self::D => self::D_VALUE, + ], ], [ - 'Here is a big number: {'.self::D.', number, integer}', // pattern - 'Here is a big number: '.self::D_VALUE_FORMATTED_INTEGER, // expected + 'Here is a big number: {' . self::D . ', number, integer}', // pattern + 'Here is a big number: ' . self::D_VALUE_FORMATTED_INTEGER, // expected [ // params - self::D => self::D_VALUE - ] + self::D => self::D_VALUE, + ], ], // This one was provided by Aura.Intl. Thanks! @@ -116,8 +116,8 @@ _MSG_ 'gender_of_host' => 'male', 'num_guests' => 4, 'host' => 'ralph', - 'guest' => 'beep' - ] + 'guest' => 'beep', + ], ], [ @@ -140,7 +140,7 @@ _MSG_ 'he' => 'wtf', 'she' => 'wtf', 'it' => 'wtf', - ] + ], ], // verify pattern in select message gets replaced @@ -188,10 +188,10 @@ _MSG_ public function testInsufficientArguments() { - $expected = '{'.self::SUBJECT.'} is '.self::N_VALUE; + $expected = '{' . self::SUBJECT . '} is ' . self::N_VALUE; $formatter = new FallbackMessageFormatter(); - $result = $formatter->fallbackFormat('{'.self::SUBJECT.'} is {'.self::N.'}', [ + $result = $formatter->fallbackFormat('{' . self::SUBJECT . '} is {' . self::N . '}', [ self::N => self::N_VALUE, ], 'en-US'); @@ -200,7 +200,7 @@ _MSG_ public function testNoParams() { - $pattern = '{'.self::SUBJECT.'} is '.self::N; + $pattern = '{' . self::SUBJECT . '} is ' . self::N; $formatter = new FallbackMessageFormatter(); $result = $formatter->fallbackFormat($pattern, [], 'en-US'); @@ -217,7 +217,7 @@ _MSG_ public function testUnsupportedPercentException() { - $pattern = 'Number {'.self::N.', number, percent}'; + $pattern = 'Number {' . self::N . ', number, percent}'; $formatter = new FallbackMessageFormatter(); $this->expectException('yii\base\NotSupportedException'); $formatter->fallbackFormat($pattern, [self::N => self::N_VALUE], 'en-US'); @@ -225,7 +225,7 @@ _MSG_ public function testUnsupportedCurrencyException() { - $pattern = 'Number {'.self::N.', number, currency}'; + $pattern = 'Number {' . self::N . ', number, currency}'; $formatter = new FallbackMessageFormatter(); $this->expectException('yii\base\NotSupportedException'); $formatter->fallbackFormat($pattern, [self::N => self::N_VALUE], 'en-US'); diff --git a/tests/framework/i18n/FormatterDateTest.php b/tests/framework/i18n/FormatterDateTest.php index 359f8de09e..509f27d44c 100644 --- a/tests/framework/i18n/FormatterDateTest.php +++ b/tests/framework/i18n/FormatterDateTest.php @@ -1,11 +1,16 @@ assertSame("$value", $this->formatter->asTimestamp(date('Y-m-d H:i:s', $value))); // empty input - $this->assertSame("0", $this->formatter->asTimestamp(0)); - $this->assertSame("0", $this->formatter->asTimestamp(false)); - $this->assertSame("0", $this->formatter->asTimestamp("")); + $this->assertSame('0', $this->formatter->asTimestamp(0)); + $this->assertSame('0', $this->formatter->asTimestamp(false)); + $this->assertSame('0', $this->formatter->asTimestamp('')); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asTimestamp(null)); @@ -277,18 +282,18 @@ class FormatterDateTest extends TestCase public function testAsRelativeTime() { - $interval_1_second = new DateInterval("PT1S"); - $interval_244_seconds = new DateInterval("PT244S"); - $interval_1_minute = new DateInterval("PT1M"); - $interval_33_minutes = new DateInterval("PT33M"); - $interval_1_hour = new DateInterval("PT1H"); - $interval_6_hours = new DateInterval("PT6H"); - $interval_1_day = new DateInterval("P1D"); - $interval_89_days = new DateInterval("P89D"); - $interval_1_month = new DateInterval("P1M"); - $interval_5_months = new DateInterval("P5M"); - $interval_1_year = new DateInterval("P1Y"); - $interval_12_years = new DateInterval("P12Y"); + $interval_1_second = new DateInterval('PT1S'); + $interval_244_seconds = new DateInterval('PT244S'); + $interval_1_minute = new DateInterval('PT1M'); + $interval_33_minutes = new DateInterval('PT33M'); + $interval_1_hour = new DateInterval('PT1H'); + $interval_6_hours = new DateInterval('PT6H'); + $interval_1_day = new DateInterval('P1D'); + $interval_89_days = new DateInterval('P89D'); + $interval_1_month = new DateInterval('P1M'); + $interval_5_months = new DateInterval('P5M'); + $interval_1_year = new DateInterval('P1Y'); + $interval_12_years = new DateInterval('P12Y'); // Pass a DateInterval $this->assertSame('a second ago', $this->formatter->asRelativeTime($interval_1_second)); @@ -389,12 +394,12 @@ class FormatterDateTest extends TestCase $this->assertSame('in 28 days', $this->formatter->asRelativeTime($dateThen, $dateNow)); // just now - $this->assertSame("just now", $this->formatter->asRelativeTime($t = time(), $t)); - $this->assertSame("just now", $this->formatter->asRelativeTime(0, 0)); + $this->assertSame('just now', $this->formatter->asRelativeTime($t = time(), $t)); + $this->assertSame('just now', $this->formatter->asRelativeTime(0, 0)); // empty input - $this->assertSame("just now", $this->formatter->asRelativeTime(false, 0)); - $this->assertSame("just now", $this->formatter->asRelativeTime("", 0)); + $this->assertSame('just now', $this->formatter->asRelativeTime(false, 0)); + $this->assertSame('just now', $this->formatter->asRelativeTime('', 0)); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asRelativeTime(null)); @@ -408,19 +413,19 @@ class FormatterDateTest extends TestCase public function testAsDuration() { - $interval_0_seconds = new DateInterval("PT0S"); - $interval_1_second = new DateInterval("PT1S"); - $interval_244_seconds = new DateInterval("PT244S"); - $interval_1_minute = new DateInterval("PT1M"); - $interval_33_minutes = new DateInterval("PT33M"); - $interval_1_hour = new DateInterval("PT1H"); - $interval_6_hours = new DateInterval("PT6H"); - $interval_1_day = new DateInterval("P1D"); - $interval_89_days = new DateInterval("P89D"); - $interval_1_month = new DateInterval("P1M"); - $interval_5_months = new DateInterval("P5M"); - $interval_1_year = new DateInterval("P1Y"); - $interval_12_years = new DateInterval("P12Y"); + $interval_0_seconds = new DateInterval('PT0S'); + $interval_1_second = new DateInterval('PT1S'); + $interval_244_seconds = new DateInterval('PT244S'); + $interval_1_minute = new DateInterval('PT1M'); + $interval_33_minutes = new DateInterval('PT33M'); + $interval_1_hour = new DateInterval('PT1H'); + $interval_6_hours = new DateInterval('PT6H'); + $interval_1_day = new DateInterval('P1D'); + $interval_89_days = new DateInterval('P89D'); + $interval_1_month = new DateInterval('P1M'); + $interval_5_months = new DateInterval('P5M'); + $interval_1_year = new DateInterval('P1Y'); + $interval_12_years = new DateInterval('P12Y'); // Pass a DateInterval $this->assertSame('0 seconds', $this->formatter->asDuration($interval_0_seconds)); @@ -803,7 +808,5 @@ class FormatterDateTest extends TestCase $this->assertEquals('1924-08-17 00:00:00+0000', $this->formatter->asDateTime($timeStamp, 'yyyy-MM-dd HH:mm:ssZ')); $this->formatter->timeZone = 'Europe/Berlin'; $this->assertEquals('1924-08-17 01:00:00+0100', $this->formatter->asDateTime($timeStamp, 'yyyy-MM-dd HH:mm:ssZ')); - } - } diff --git a/tests/framework/i18n/FormatterNumberTest.php b/tests/framework/i18n/FormatterNumberTest.php index 9be3016a29..000ae85138 100644 --- a/tests/framework/i18n/FormatterNumberTest.php +++ b/tests/framework/i18n/FormatterNumberTest.php @@ -1,10 +1,15 @@ assertSame("123", $this->formatter->asInteger(123)); - $this->assertSame("123", $this->formatter->asInteger(123.23)); - $this->assertSame("123", $this->formatter->asInteger(123.53)); - $this->assertSame("0", $this->formatter->asInteger(0)); - $this->assertSame("-123", $this->formatter->asInteger(-123.23)); - $this->assertSame("-123", $this->formatter->asInteger(-123.53)); + $this->assertSame('123', $this->formatter->asInteger(123)); + $this->assertSame('123', $this->formatter->asInteger(123.23)); + $this->assertSame('123', $this->formatter->asInteger(123.53)); + $this->assertSame('0', $this->formatter->asInteger(0)); + $this->assertSame('-123', $this->formatter->asInteger(-123.23)); + $this->assertSame('-123', $this->formatter->asInteger(-123.53)); - $this->assertSame("123,456", $this->formatter->asInteger(123456)); - $this->assertSame("123,456", $this->formatter->asInteger(123456.789)); + $this->assertSame('123,456', $this->formatter->asInteger(123456)); + $this->assertSame('123,456', $this->formatter->asInteger(123456.789)); // empty input - $this->assertSame("0", $this->formatter->asInteger(false)); - $this->assertSame("0", $this->formatter->asInteger("")); + $this->assertSame('0', $this->formatter->asInteger(false)); + $this->assertSame('0', $this->formatter->asInteger('')); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asInteger(null)); @@ -122,41 +127,41 @@ class FormatterNumberTest extends TestCase public function testIntlAsDecimal() { $value = 123.12; - $this->assertSame("123.12", $this->formatter->asDecimal($value, 2)); - $this->assertSame("123.1", $this->formatter->asDecimal($value, 1)); - $this->assertSame("123", $this->formatter->asDecimal($value, 0)); + $this->assertSame('123.12', $this->formatter->asDecimal($value, 2)); + $this->assertSame('123.1', $this->formatter->asDecimal($value, 1)); + $this->assertSame('123', $this->formatter->asDecimal($value, 0)); $value = 123; - $this->assertSame("123", $this->formatter->asDecimal($value)); - $this->assertSame("123.00", $this->formatter->asDecimal($value, 2)); + $this->assertSame('123', $this->formatter->asDecimal($value)); + $this->assertSame('123.00', $this->formatter->asDecimal($value, 2)); $this->formatter->decimalSeparator = ','; $this->formatter->thousandSeparator = '.'; $value = 123.12; - $this->assertSame("123,12", $this->formatter->asDecimal($value)); - $this->assertSame("123,1", $this->formatter->asDecimal($value, 1)); - $this->assertSame("123", $this->formatter->asDecimal($value, 0)); + $this->assertSame('123,12', $this->formatter->asDecimal($value)); + $this->assertSame('123,1', $this->formatter->asDecimal($value, 1)); + $this->assertSame('123', $this->formatter->asDecimal($value, 0)); $value = 123123.123; - $this->assertSame("123.123", $this->formatter->asDecimal($value, 0)); - $this->assertSame("123.123,12", $this->formatter->asDecimal($value, 2)); + $this->assertSame('123.123', $this->formatter->asDecimal($value, 0)); + $this->assertSame('123.123,12', $this->formatter->asDecimal($value, 2)); $this->formatter->thousandSeparator = ''; - $this->assertSame("123123,1", $this->formatter->asDecimal($value, 1)); + $this->assertSame('123123,1', $this->formatter->asDecimal($value, 1)); $this->formatter->thousandSeparator = ' '; - $this->assertSame("12 31 23,1", $this->formatter->asDecimal($value, 1, [\NumberFormatter::GROUPING_SIZE => 2])); + $this->assertSame('12 31 23,1', $this->formatter->asDecimal($value, 1, [\NumberFormatter::GROUPING_SIZE => 2])); $value = 123123.123; $this->formatter->decimalSeparator = ','; $this->formatter->thousandSeparator = ' '; - $this->assertSame("123 123", $this->formatter->asDecimal($value, 0)); - $this->assertSame("123 123,12", $this->formatter->asDecimal($value, 2)); + $this->assertSame('123 123', $this->formatter->asDecimal($value, 0)); + $this->assertSame('123 123,12', $this->formatter->asDecimal($value, 2)); $this->formatter->decimalSeparator = null; $this->formatter->thousandSeparator = null; $value = '-123456.123'; - $this->assertSame("-123,456.123", $this->formatter->asDecimal($value)); + $this->assertSame('-123,456.123', $this->formatter->asDecimal($value)); // empty input - $this->assertSame("0", $this->formatter->asDecimal(false)); - $this->assertSame("0", $this->formatter->asDecimal("")); + $this->assertSame('0', $this->formatter->asDecimal(false)); + $this->assertSame('0', $this->formatter->asDecimal('')); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asDecimal(null)); @@ -165,39 +170,39 @@ class FormatterNumberTest extends TestCase public function testAsDecimal() { $value = 123.12; - $this->assertSame("123.12", $this->formatter->asDecimal($value)); - $this->assertSame("123.1", $this->formatter->asDecimal($value, 1)); - $this->assertSame("123", $this->formatter->asDecimal($value, 0)); + $this->assertSame('123.12', $this->formatter->asDecimal($value)); + $this->assertSame('123.1', $this->formatter->asDecimal($value, 1)); + $this->assertSame('123', $this->formatter->asDecimal($value, 0)); $value = 123; - $this->assertSame("123.00", $this->formatter->asDecimal($value)); + $this->assertSame('123.00', $this->formatter->asDecimal($value)); $this->formatter->decimalSeparator = ','; $this->formatter->thousandSeparator = '.'; $value = 123.12; - $this->assertSame("123,12", $this->formatter->asDecimal($value)); - $this->assertSame("123,1", $this->formatter->asDecimal($value, 1)); - $this->assertSame("123", $this->formatter->asDecimal($value, 0)); + $this->assertSame('123,12', $this->formatter->asDecimal($value)); + $this->assertSame('123,1', $this->formatter->asDecimal($value, 1)); + $this->assertSame('123', $this->formatter->asDecimal($value, 0)); $value = 123123.123; - $this->assertSame("123.123,12", $this->formatter->asDecimal($value)); + $this->assertSame('123.123,12', $this->formatter->asDecimal($value)); $value = 123123.123; - $this->assertSame("123.123,12", $this->formatter->asDecimal($value)); - $this->assertSame("123.123,12", $this->formatter->asDecimal($value, 2)); + $this->assertSame('123.123,12', $this->formatter->asDecimal($value)); + $this->assertSame('123.123,12', $this->formatter->asDecimal($value, 2)); $this->formatter->decimalSeparator = ','; $this->formatter->thousandSeparator = ' '; - $this->assertSame("123 123,12", $this->formatter->asDecimal($value)); - $this->assertSame("123 123,12", $this->formatter->asDecimal($value, 2)); + $this->assertSame('123 123,12', $this->formatter->asDecimal($value)); + $this->assertSame('123 123,12', $this->formatter->asDecimal($value, 2)); $this->formatter->thousandSeparator = ''; - $this->assertSame("123123,12", $this->formatter->asDecimal($value)); - $this->assertSame("123123,12", $this->formatter->asDecimal($value, 2)); + $this->assertSame('123123,12', $this->formatter->asDecimal($value)); + $this->assertSame('123123,12', $this->formatter->asDecimal($value, 2)); $this->formatter->decimalSeparator = null; $this->formatter->thousandSeparator = null; $value = '-123456.123'; - $this->assertSame("-123,456.123", $this->formatter->asDecimal($value, 3)); + $this->assertSame('-123,456.123', $this->formatter->asDecimal($value, 3)); // empty input - $this->assertSame("0.00", $this->formatter->asDecimal(false)); - $this->assertSame("0.00", $this->formatter->asDecimal("")); + $this->assertSame('0.00', $this->formatter->asDecimal(false)); + $this->assertSame('0.00', $this->formatter->asDecimal('')); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asDecimal(null)); @@ -212,14 +217,14 @@ class FormatterNumberTest extends TestCase { $this->assertSame('12,300%', $this->formatter->asPercent(123)); $this->assertSame('12,300%', $this->formatter->asPercent('123')); - $this->assertSame("12%", $this->formatter->asPercent(0.1234)); - $this->assertSame("12%", $this->formatter->asPercent('0.1234')); - $this->assertSame("-1%", $this->formatter->asPercent(-0.009343)); - $this->assertSame("-1%", $this->formatter->asPercent('-0.009343')); + $this->assertSame('12%', $this->formatter->asPercent(0.1234)); + $this->assertSame('12%', $this->formatter->asPercent('0.1234')); + $this->assertSame('-1%', $this->formatter->asPercent(-0.009343)); + $this->assertSame('-1%', $this->formatter->asPercent('-0.009343')); // empty input - $this->assertSame("0%", $this->formatter->asPercent(false)); - $this->assertSame("0%", $this->formatter->asPercent("")); + $this->assertSame('0%', $this->formatter->asPercent(false)); + $this->assertSame('0%', $this->formatter->asPercent('')); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asPercent(null)); @@ -301,16 +306,16 @@ class FormatterNumberTest extends TestCase $this->formatter->currencyCode = null; $this->formatter->numberFormatterSymbols = []; $this->formatter->thousandSeparator = null; - $this->assertSame("0,00 €", $this->formatter->asCurrency(false)); - $this->assertSame("0,00 €", $this->formatter->asCurrency("")); + $this->assertSame('0,00 €', $this->formatter->asCurrency(false)); + $this->assertSame('0,00 €', $this->formatter->asCurrency('')); // decimal formatting $this->formatter->locale = 'de-DE'; - $this->assertSame("100 $", \Yii::$app->formatter->asCurrency(100, 'USD', [ + $this->assertSame('100 $', \Yii::$app->formatter->asCurrency(100, 'USD', [ NumberFormatter::MAX_FRACTION_DIGITS => 0, ])); - $this->assertSame("100,00 $", $this->formatter->asCurrency(100, 'USD', [ - NumberFormatter::MAX_FRACTION_DIGITS => 2 + $this->assertSame('100,00 $', $this->formatter->asCurrency(100, 'USD', [ + NumberFormatter::MAX_FRACTION_DIGITS => 2, ])); // null display @@ -360,10 +365,10 @@ class FormatterNumberTest extends TestCase { $this->formatter->locale = 'en-US'; $this->formatter->numberFormatterOptions = [ - \NumberFormatter::FRACTION_DIGITS => 0 + \NumberFormatter::FRACTION_DIGITS => 0, ]; $this->formatter->numberFormatterTextOptions = [ - \NumberFormatter::CURRENCY_CODE => 'EUR' + \NumberFormatter::CURRENCY_CODE => 'EUR', ]; $this->assertSame('€100', $this->formatter->asCurrency(100, 'EUR')); } @@ -385,8 +390,8 @@ class FormatterNumberTest extends TestCase // empty input $this->formatter->currencyCode = 'USD'; $this->formatter->numberFormatterSymbols = []; - $this->assertSame("USD 0.00", $this->formatter->asCurrency(false)); - $this->assertSame("USD 0.00", $this->formatter->asCurrency("")); + $this->assertSame('USD 0.00', $this->formatter->asCurrency(false)); + $this->assertSame('USD 0.00', $this->formatter->asCurrency('')); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asCurrency(null)); @@ -397,13 +402,13 @@ class FormatterNumberTest extends TestCase $value = '123'; $this->assertSame('1.23E2', $this->formatter->asScientific($value)); $value = '123456'; - $this->assertSame("1.23456E5", $this->formatter->asScientific($value)); + $this->assertSame('1.23456E5', $this->formatter->asScientific($value)); $value = '-123456.123'; - $this->assertSame("-1.23456123E5", $this->formatter->asScientific($value)); + $this->assertSame('-1.23456123E5', $this->formatter->asScientific($value)); // empty input - $this->assertSame("0E0", $this->formatter->asScientific(false)); - $this->assertSame("0E0", $this->formatter->asScientific("")); + $this->assertSame('0E0', $this->formatter->asScientific(false)); + $this->assertSame('0E0', $this->formatter->asScientific('')); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asScientific(null)); @@ -414,13 +419,13 @@ class FormatterNumberTest extends TestCase $value = '123'; $this->assertSame('1.23E+2', $this->formatter->asScientific($value, 2)); $value = '123456'; - $this->assertSame("1.234560E+5", $this->formatter->asScientific($value)); + $this->assertSame('1.234560E+5', $this->formatter->asScientific($value)); $value = '-123456.123'; - $this->assertSame("-1.234561E+5", $this->formatter->asScientific($value)); + $this->assertSame('-1.234561E+5', $this->formatter->asScientific($value)); // empty input - $this->assertSame("0.000000E+0", $this->formatter->asScientific(false)); - $this->assertSame("0.000000E+0", $this->formatter->asScientific("")); + $this->assertSame('0.000000E+0', $this->formatter->asScientific(false)); + $this->assertSame('0.000000E+0', $this->formatter->asScientific('')); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asScientific(null)); @@ -479,31 +484,31 @@ class FormatterNumberTest extends TestCase // tests for base 1000 $this->formatter->sizeFormatBase = 1000; - $this->assertSame("999 B", $this->formatter->asShortSize(999)); - $this->assertSame("999 B", $this->formatter->asShortSize('999')); - $this->assertSame("1.05 MB", $this->formatter->asShortSize(1024 * 1024)); - $this->assertSame("1 KB", $this->formatter->asShortSize(1000)); - $this->assertSame("1.02 KB", $this->formatter->asShortSize(1023)); - $this->assertNotEquals("3 PB", $this->formatter->asShortSize(3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB + $this->assertSame('999 B', $this->formatter->asShortSize(999)); + $this->assertSame('999 B', $this->formatter->asShortSize('999')); + $this->assertSame('1.05 MB', $this->formatter->asShortSize(1024 * 1024)); + $this->assertSame('1 KB', $this->formatter->asShortSize(1000)); + $this->assertSame('1.02 KB', $this->formatter->asShortSize(1023)); + $this->assertNotEquals('3 PB', $this->formatter->asShortSize(3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB // string values - $this->assertSame("28.41 GB", $this->formatter->asShortSize(28406984038)); - $this->assertSame("28.41 GB", $this->formatter->asShortSize((string)28406984038)); - $this->assertSame("56.81 GB", $this->formatter->asShortSize(28406984038 + 28406984038)); - $this->assertSame("56.81 GB", $this->formatter->asShortSize((string)(28406984038 + 28406984038))); + $this->assertSame('28.41 GB', $this->formatter->asShortSize(28406984038)); + $this->assertSame('28.41 GB', $this->formatter->asShortSize((string) 28406984038)); + $this->assertSame('56.81 GB', $this->formatter->asShortSize(28406984038 + 28406984038)); + $this->assertSame('56.81 GB', $this->formatter->asShortSize((string) (28406984038 + 28406984038))); // tests for base 1024 $this->formatter->sizeFormatBase = 1024; - $this->assertSame("1 KiB", $this->formatter->asShortSize(1024)); - $this->assertSame("1 MiB", $this->formatter->asShortSize(1024 * 1024)); + $this->assertSame('1 KiB', $this->formatter->asShortSize(1024)); + $this->assertSame('1 MiB', $this->formatter->asShortSize(1024 * 1024)); // https://github.com/yiisoft/yii2/issues/4960 - $this->assertSame("1023 B", $this->formatter->asShortSize(1023)); - $this->assertSame("5 GiB", $this->formatter->asShortSize(5 * 1024 * 1024 * 1024)); - $this->assertNotEquals("5 PiB", $this->formatter->asShortSize(5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB + $this->assertSame('1023 B', $this->formatter->asShortSize(1023)); + $this->assertSame('5 GiB', $this->formatter->asShortSize(5 * 1024 * 1024 * 1024)); + $this->assertNotEquals('5 PiB', $this->formatter->asShortSize(5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB //$this->assertSame("1 YiB", $this->formatter->asShortSize(pow(2, 80))); - $this->assertSame("2 GiB", $this->formatter->asShortSize(2147483647)); // round 1.999 up to 2 + $this->assertSame('2 GiB', $this->formatter->asShortSize(2147483647)); // round 1.999 up to 2 $this->formatter->decimalSeparator = ','; $this->formatter->numberFormatterOptions = []; - $this->assertSame("1,001 KiB", $this->formatter->asShortSize(1025, 3)); + $this->assertSame('1,001 KiB', $this->formatter->asShortSize(1025, 3)); // empty values $this->assertSame('0 B', $this->formatter->asShortSize(0)); @@ -516,31 +521,31 @@ class FormatterNumberTest extends TestCase { // tests for base 1000 $this->formatter->sizeFormatBase = 1000; - $this->assertSame("999 B", $this->formatter->asShortSize(999)); - $this->assertSame("999 B", $this->formatter->asShortSize('999')); - $this->assertSame("1.05 MB", $this->formatter->asShortSize(1024 * 1024)); - $this->assertSame("1.0486 MB", $this->formatter->asShortSize(1024 * 1024, 4)); - $this->assertSame("1.00 KB", $this->formatter->asShortSize(1000)); - $this->assertSame("1.02 KB", $this->formatter->asShortSize(1023)); - $this->assertNotEquals("3 PB", $this->formatter->asShortSize(3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB + $this->assertSame('999 B', $this->formatter->asShortSize(999)); + $this->assertSame('999 B', $this->formatter->asShortSize('999')); + $this->assertSame('1.05 MB', $this->formatter->asShortSize(1024 * 1024)); + $this->assertSame('1.0486 MB', $this->formatter->asShortSize(1024 * 1024, 4)); + $this->assertSame('1.00 KB', $this->formatter->asShortSize(1000)); + $this->assertSame('1.02 KB', $this->formatter->asShortSize(1023)); + $this->assertNotEquals('3 PB', $this->formatter->asShortSize(3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB // string values - $this->assertSame("28.41 GB", $this->formatter->asShortSize(28406984038)); - $this->assertSame("28.41 GB", $this->formatter->asShortSize((string)28406984038)); - $this->assertSame("56.81 GB", $this->formatter->asShortSize(28406984038 + 28406984038)); - $this->assertSame("56.81 GB", $this->formatter->asShortSize((string)(28406984038 + 28406984038))); + $this->assertSame('28.41 GB', $this->formatter->asShortSize(28406984038)); + $this->assertSame('28.41 GB', $this->formatter->asShortSize((string) 28406984038)); + $this->assertSame('56.81 GB', $this->formatter->asShortSize(28406984038 + 28406984038)); + $this->assertSame('56.81 GB', $this->formatter->asShortSize((string) (28406984038 + 28406984038))); // tests for base 1024 $this->formatter->sizeFormatBase = 1024; - $this->assertSame("1.00 KiB", $this->formatter->asShortSize(1024)); - $this->assertSame("1.00 MiB", $this->formatter->asShortSize(1024 * 1024)); + $this->assertSame('1.00 KiB', $this->formatter->asShortSize(1024)); + $this->assertSame('1.00 MiB', $this->formatter->asShortSize(1024 * 1024)); // https://github.com/yiisoft/yii2/issues/4960 - $this->assertSame("1023 B", $this->formatter->asShortSize(1023)); - $this->assertSame("5.00 GiB", $this->formatter->asShortSize(5 * 1024 * 1024 * 1024)); - $this->assertNotEquals("5.00 PiB", $this->formatter->asShortSize(5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB + $this->assertSame('1023 B', $this->formatter->asShortSize(1023)); + $this->assertSame('5.00 GiB', $this->formatter->asShortSize(5 * 1024 * 1024 * 1024)); + $this->assertNotEquals('5.00 PiB', $this->formatter->asShortSize(5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB //$this->assertSame("1 YiB", $this->formatter->asShortSize(pow(2, 80))); - $this->assertSame("2.00 GiB", $this->formatter->asShortSize(2147483647)); // round 1.999 up to 2 + $this->assertSame('2.00 GiB', $this->formatter->asShortSize(2147483647)); // round 1.999 up to 2 $this->formatter->decimalSeparator = ','; - $this->assertSame("1,001 KiB", $this->formatter->asShortSize(1025, 3)); + $this->assertSame('1,001 KiB', $this->formatter->asShortSize(1025, 3)); // empty values $this->assertSame('0 B', $this->formatter->asShortSize(0)); @@ -558,24 +563,24 @@ class FormatterNumberTest extends TestCase // tests for base 1000 $this->formatter->sizeFormatBase = 1000; - $this->assertSame("999 bytes", $this->formatter->asSize(999)); - $this->assertSame("999 bytes", $this->formatter->asSize('999')); - $this->assertSame("1.05 megabytes", $this->formatter->asSize(1024 * 1024)); - $this->assertSame("1 kilobyte", $this->formatter->asSize(1000)); - $this->assertSame("1.02 kilobytes", $this->formatter->asSize(1023)); - $this->assertSame("3 gigabytes", $this->formatter->asSize(3 * 1000 * 1000 * 1000)); - $this->assertNotEquals("3 PB", $this->formatter->asSize(3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB + $this->assertSame('999 bytes', $this->formatter->asSize(999)); + $this->assertSame('999 bytes', $this->formatter->asSize('999')); + $this->assertSame('1.05 megabytes', $this->formatter->asSize(1024 * 1024)); + $this->assertSame('1 kilobyte', $this->formatter->asSize(1000)); + $this->assertSame('1.02 kilobytes', $this->formatter->asSize(1023)); + $this->assertSame('3 gigabytes', $this->formatter->asSize(3 * 1000 * 1000 * 1000)); + $this->assertNotEquals('3 PB', $this->formatter->asSize(3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB // tests for base 1024 $this->formatter->sizeFormatBase = 1024; - $this->assertSame("1 kibibyte", $this->formatter->asSize(1024)); - $this->assertSame("1 mebibyte", $this->formatter->asSize(1024 * 1024)); - $this->assertSame("1023 bytes", $this->formatter->asSize(1023)); - $this->assertSame("5 gibibytes", $this->formatter->asSize(5 * 1024 * 1024 * 1024)); - $this->assertNotEquals("5 pibibytes", $this->formatter->asSize(5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB - $this->assertSame("2 gibibytes", $this->formatter->asSize(2147483647)); // round 1.999 up to 2 + $this->assertSame('1 kibibyte', $this->formatter->asSize(1024)); + $this->assertSame('1 mebibyte', $this->formatter->asSize(1024 * 1024)); + $this->assertSame('1023 bytes', $this->formatter->asSize(1023)); + $this->assertSame('5 gibibytes', $this->formatter->asSize(5 * 1024 * 1024 * 1024)); + $this->assertNotEquals('5 pibibytes', $this->formatter->asSize(5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB + $this->assertSame('2 gibibytes', $this->formatter->asSize(2147483647)); // round 1.999 up to 2 $this->formatter->decimalSeparator = ','; $this->formatter->numberFormatterOptions = []; - $this->assertSame("1,001 kibibytes", $this->formatter->asSize(1025, 3)); + $this->assertSame('1,001 kibibytes', $this->formatter->asSize(1025, 3)); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asSize(null)); @@ -590,49 +595,49 @@ class FormatterNumberTest extends TestCase // tests for base 1000 $this->formatter->sizeFormatBase = 1000; - $this->assertSame("-999 bytes", $this->formatter->asSize(-999)); - $this->assertSame("-999 bytes", $this->formatter->asSize('-999')); - $this->assertSame("-1.05 megabytes", $this->formatter->asSize(-1024 * 1024)); - $this->assertSame("-1 kilobyte", $this->formatter->asSize(-1000)); - $this->assertSame("-1.02 kilobytes", $this->formatter->asSize(-1023)); - $this->assertSame("-3 gigabytes", $this->formatter->asSize(-3 * 1000 * 1000 * 1000)); - $this->assertNotEquals("3 PB", $this->formatter->asSize(-3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB + $this->assertSame('-999 bytes', $this->formatter->asSize(-999)); + $this->assertSame('-999 bytes', $this->formatter->asSize('-999')); + $this->assertSame('-1.05 megabytes', $this->formatter->asSize(-1024 * 1024)); + $this->assertSame('-1 kilobyte', $this->formatter->asSize(-1000)); + $this->assertSame('-1.02 kilobytes', $this->formatter->asSize(-1023)); + $this->assertSame('-3 gigabytes', $this->formatter->asSize(-3 * 1000 * 1000 * 1000)); + $this->assertNotEquals('3 PB', $this->formatter->asSize(-3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB // tests for base 1024 $this->formatter->sizeFormatBase = 1024; - $this->assertSame("-1 kibibyte", $this->formatter->asSize(-1024)); - $this->assertSame("-1 mebibyte", $this->formatter->asSize(-1024 * 1024)); - $this->assertSame("-1023 bytes", $this->formatter->asSize(-1023)); - $this->assertSame("-5 gibibytes", $this->formatter->asSize(-5 * 1024 * 1024 * 1024)); - $this->assertNotEquals("-5 pibibytes", $this->formatter->asSize(-5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB - $this->assertSame("-2 gibibytes", $this->formatter->asSize(-2147483647)); // round 1.999 up to 2 + $this->assertSame('-1 kibibyte', $this->formatter->asSize(-1024)); + $this->assertSame('-1 mebibyte', $this->formatter->asSize(-1024 * 1024)); + $this->assertSame('-1023 bytes', $this->formatter->asSize(-1023)); + $this->assertSame('-5 gibibytes', $this->formatter->asSize(-5 * 1024 * 1024 * 1024)); + $this->assertNotEquals('-5 pibibytes', $this->formatter->asSize(-5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB + $this->assertSame('-2 gibibytes', $this->formatter->asSize(-2147483647)); // round 1.999 up to 2 $this->formatter->decimalSeparator = ','; $this->formatter->numberFormatterOptions = []; - $this->assertSame("-1,001 kibibytes", $this->formatter->asSize(-1025, 3)); + $this->assertSame('-1,001 kibibytes', $this->formatter->asSize(-1025, 3)); } public function testAsSize() { // tests for base 1000 $this->formatter->sizeFormatBase = 1000; - $this->assertSame("999 bytes", $this->formatter->asSize(999)); - $this->assertSame("999 bytes", $this->formatter->asSize('999')); - $this->assertSame("1.05 megabytes", $this->formatter->asSize(1024 * 1024)); - $this->assertSame("1.0486 megabytes", $this->formatter->asSize(1024 * 1024, 4)); - $this->assertSame("1.00 kilobyte", $this->formatter->asSize(1000)); - $this->assertSame("1.02 kilobytes", $this->formatter->asSize(1023)); - $this->assertSame("3.00 gigabytes", $this->formatter->asSize(3 * 1000 * 1000 * 1000)); - $this->assertNotEquals("3 PB", $this->formatter->asSize(3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB + $this->assertSame('999 bytes', $this->formatter->asSize(999)); + $this->assertSame('999 bytes', $this->formatter->asSize('999')); + $this->assertSame('1.05 megabytes', $this->formatter->asSize(1024 * 1024)); + $this->assertSame('1.0486 megabytes', $this->formatter->asSize(1024 * 1024, 4)); + $this->assertSame('1.00 kilobyte', $this->formatter->asSize(1000)); + $this->assertSame('1.02 kilobytes', $this->formatter->asSize(1023)); + $this->assertSame('3.00 gigabytes', $this->formatter->asSize(3 * 1000 * 1000 * 1000)); + $this->assertNotEquals('3 PB', $this->formatter->asSize(3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB // tests for base 1024 $this->formatter->sizeFormatBase = 1024; - $this->assertSame("1.00 kibibyte", $this->formatter->asSize(1024)); - $this->assertSame("1.00 mebibyte", $this->formatter->asSize(1024 * 1024)); - $this->assertSame("1023 bytes", $this->formatter->asSize(1023)); - $this->assertSame("5.00 gibibytes", $this->formatter->asSize(5 * 1024 * 1024 * 1024)); - $this->assertNotEquals("5.00 pibibytes", $this->formatter->asSize(5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB - $this->assertSame("2.00 gibibytes", $this->formatter->asSize(2147483647)); // round 1.999 up to 2 + $this->assertSame('1.00 kibibyte', $this->formatter->asSize(1024)); + $this->assertSame('1.00 mebibyte', $this->formatter->asSize(1024 * 1024)); + $this->assertSame('1023 bytes', $this->formatter->asSize(1023)); + $this->assertSame('5.00 gibibytes', $this->formatter->asSize(5 * 1024 * 1024 * 1024)); + $this->assertNotEquals('5.00 pibibytes', $this->formatter->asSize(5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB + $this->assertSame('2.00 gibibytes', $this->formatter->asSize(2147483647)); // round 1.999 up to 2 $this->formatter->decimalSeparator = ','; $this->formatter->numberFormatterOptions = []; - $this->assertSame("1,001 kibibytes", $this->formatter->asSize(1025, 3)); + $this->assertSame('1,001 kibibytes', $this->formatter->asSize(1025, 3)); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asSize(null)); @@ -642,34 +647,34 @@ class FormatterNumberTest extends TestCase { // tests for base 1000 $this->formatter->sizeFormatBase = 1000; - $this->assertSame("-999 bytes", $this->formatter->asSize(-999)); - $this->assertSame("-999 bytes", $this->formatter->asSize('-999')); - $this->assertSame("-1.05 megabytes", $this->formatter->asSize(-1024 * 1024)); - $this->assertSame("-1.0486 megabytes", $this->formatter->asSize(-1024 * 1024, 4)); - $this->assertSame("-1.00 kilobyte", $this->formatter->asSize(-1000)); - $this->assertSame("-1.02 kilobytes", $this->formatter->asSize(-1023)); - $this->assertSame("-3.00 gigabytes", $this->formatter->asSize(-3 * 1000 * 1000 * 1000)); - $this->assertNotEquals("3 PB", $this->formatter->asSize(-3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB + $this->assertSame('-999 bytes', $this->formatter->asSize(-999)); + $this->assertSame('-999 bytes', $this->formatter->asSize('-999')); + $this->assertSame('-1.05 megabytes', $this->formatter->asSize(-1024 * 1024)); + $this->assertSame('-1.0486 megabytes', $this->formatter->asSize(-1024 * 1024, 4)); + $this->assertSame('-1.00 kilobyte', $this->formatter->asSize(-1000)); + $this->assertSame('-1.02 kilobytes', $this->formatter->asSize(-1023)); + $this->assertSame('-3.00 gigabytes', $this->formatter->asSize(-3 * 1000 * 1000 * 1000)); + $this->assertNotEquals('3 PB', $this->formatter->asSize(-3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB // tests for base 1024 $this->formatter->sizeFormatBase = 1024; - $this->assertSame("-1.00 kibibyte", $this->formatter->asSize(-1024)); - $this->assertSame("-1.00 mebibyte", $this->formatter->asSize(-1024 * 1024)); - $this->assertSame("-1023 bytes", $this->formatter->asSize(-1023)); - $this->assertSame("-5.00 gibibytes", $this->formatter->asSize(-5 * 1024 * 1024 * 1024)); - $this->assertNotEquals("-5.00 pibibytes", $this->formatter->asSize(-5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB - $this->assertSame("-2.00 gibibytes", $this->formatter->asSize(-2147483647)); // round 1.999 up to 2 + $this->assertSame('-1.00 kibibyte', $this->formatter->asSize(-1024)); + $this->assertSame('-1.00 mebibyte', $this->formatter->asSize(-1024 * 1024)); + $this->assertSame('-1023 bytes', $this->formatter->asSize(-1023)); + $this->assertSame('-5.00 gibibytes', $this->formatter->asSize(-5 * 1024 * 1024 * 1024)); + $this->assertNotEquals('-5.00 pibibytes', $this->formatter->asSize(-5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB + $this->assertSame('-2.00 gibibytes', $this->formatter->asSize(-2147483647)); // round 1.999 up to 2 $this->formatter->decimalSeparator = ','; $this->formatter->numberFormatterOptions = []; - $this->assertSame("-1,001 kibibytes", $this->formatter->asSize(-1025, 3)); + $this->assertSame('-1,001 kibibytes', $this->formatter->asSize(-1025, 3)); } public function testIntlAsSizeConfiguration() { - $this->assertSame("1023 bytes", $this->formatter->asSize(1023)); - $this->assertSame("1023 B", $this->formatter->asShortSize(1023)); + $this->assertSame('1023 bytes', $this->formatter->asSize(1023)); + $this->assertSame('1023 B', $this->formatter->asShortSize(1023)); $this->formatter->thousandSeparator = '.'; - $this->assertSame("1023 bytes", $this->formatter->asSize(1023)); - $this->assertSame("1023 B", $this->formatter->asShortSize(1023)); + $this->assertSame('1023 bytes', $this->formatter->asSize(1023)); + $this->assertSame('1023 B', $this->formatter->asShortSize(1023)); } /** @@ -677,10 +682,10 @@ class FormatterNumberTest extends TestCase */ public function testAsSizeConfiguration() { - $this->assertSame("1023 bytes", $this->formatter->asSize(1023)); - $this->assertSame("1023 B", $this->formatter->asShortSize(1023)); + $this->assertSame('1023 bytes', $this->formatter->asSize(1023)); + $this->assertSame('1023 B', $this->formatter->asShortSize(1023)); $this->formatter->thousandSeparator = '.'; - $this->assertSame("1023 bytes", $this->formatter->asSize(1023)); - $this->assertSame("1023 B", $this->formatter->asShortSize(1023)); + $this->assertSame('1023 bytes', $this->formatter->asSize(1023)); + $this->assertSame('1023 B', $this->formatter->asShortSize(1023)); } } diff --git a/tests/framework/i18n/FormatterTest.php b/tests/framework/i18n/FormatterTest.php index 8d53f55591..05868aa2d6 100644 --- a/tests/framework/i18n/FormatterTest.php +++ b/tests/framework/i18n/FormatterTest.php @@ -1,9 +1,14 @@ assertSame("$value", $this->formatter->asUrl($value)); $value = 'https://www.yiiframework.com/?name=test&value=5"'; - $this->assertSame("https://www.yiiframework.com/?name=test&value=5"", $this->formatter->asUrl($value)); + $this->assertSame('https://www.yiiframework.com/?name=test&value=5"', $this->formatter->asUrl($value)); $value = 'http://www.yiiframework.com/'; $this->assertSame("$value", $this->formatter->asUrl($value, ['target' => '_blank'])); @@ -173,7 +178,7 @@ class FormatterTest extends TestCase $value = 'http://sample.com/img.jpg'; $this->assertSame("\"\"", $this->formatter->asImage($value)); $value = 'http://sample.com/img.jpg'; - $alt = "Hello!"; + $alt = 'Hello!'; $this->assertSame("\"$alt\"", $this->formatter->asImage($value, ['alt' => $alt])); // null display @@ -184,8 +189,8 @@ class FormatterTest extends TestCase { $this->assertSame('Yes', $this->formatter->asBoolean(true)); $this->assertSame('No', $this->formatter->asBoolean(false)); - $this->assertSame('Yes', $this->formatter->asBoolean("111")); - $this->assertSame('No', $this->formatter->asBoolean("")); + $this->assertSame('Yes', $this->formatter->asBoolean('111')); + $this->assertSame('No', $this->formatter->asBoolean('')); $this->assertSame('No', $this->formatter->asBoolean(0)); // null display diff --git a/tests/framework/i18n/GettextMessageSourceTest.php b/tests/framework/i18n/GettextMessageSourceTest.php index cb586de8e3..036682e71e 100644 --- a/tests/framework/i18n/GettextMessageSourceTest.php +++ b/tests/framework/i18n/GettextMessageSourceTest.php @@ -1,4 +1,9 @@ assertArrayNotHasKey("Missing\n\r\t\"translation.", $context1); $this->assertArrayHasKey("Aliquam tempus elit vel purus molestie placerat. In sollicitudin tincidunt\naliquet. Integer tincidunt gravida tempor. In convallis blandit dui vel malesuada.\nNunc vel sapien nunc, a pretium nulla.", $context1); - $this->assertArrayHasKey("String number two.", $context1); + $this->assertArrayHasKey('String number two.', $context1); $this->assertArrayHasKey("Nunc vel sapien nunc, a pretium nulla.\nPellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.", $context1); $this->assertArrayHasKey("The other\n\ncontext.\n", $context2); $this->assertArrayHasKey("test1\\ntest2\n\\\ntest3", $context2); // translated messages - $this->assertFalse(in_array("", $context1)); + $this->assertFalse(in_array('', $context1)); $this->assertTrue(in_array("Олицетворение однократно. Представленный лексико-семантический анализ является\nпсихолингвистическим в своей основе, но механизм сочленений полидисперсен. Впечатление\nоднократно. Различное расположение выбирает сюжетный механизм сочленений.", $context1)); $this->assertTrue(in_array('Строка номер два.', $context1)); $this->assertTrue(in_array('Короткий перевод.', $context1)); @@ -83,7 +88,7 @@ class GettextMoFileTest extends TestCase // context2 $this->assertCount(4, $context2); - $this->assertArrayHasKey("\"Quotes\"", $context2); + $this->assertArrayHasKey('"Quotes"', $context2); $this->assertTrue(in_array('"Кавычки"', $context2)); $this->assertArrayHasKey("\nNew lines\n", $context2); diff --git a/tests/framework/i18n/GettextPoFileTest.php b/tests/framework/i18n/GettextPoFileTest.php index b7cf3f81a0..d32f312f01 100644 --- a/tests/framework/i18n/GettextPoFileTest.php +++ b/tests/framework/i18n/GettextPoFileTest.php @@ -1,4 +1,9 @@ assertArrayHasKey("Missing\n\r\t\"translation.", $context1); $this->assertArrayHasKey("Aliquam tempus elit vel purus molestie placerat. In sollicitudin tincidunt\naliquet. Integer tincidunt gravida tempor. In convallis blandit dui vel malesuada.\nNunc vel sapien nunc, a pretium nulla.", $context1); - $this->assertArrayHasKey("String number two.", $context1); + $this->assertArrayHasKey('String number two.', $context1); $this->assertArrayHasKey("Nunc vel sapien nunc, a pretium nulla.\nPellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.", $context1); $this->assertArrayHasKey("The other\n\ncontext.\n", $context2); $this->assertArrayHasKey("test1\\\ntest2\n\\\\\ntest3", $context2); // translated messages - $this->assertTrue(in_array("", $context1)); + $this->assertTrue(in_array('', $context1)); $this->assertTrue(in_array("Олицетворение однократно. Представленный лексико-семантический анализ является\nпсихолингвистическим в своей основе, но механизм сочленений полидисперсен. Впечатление\nоднократно. Различное расположение выбирает сюжетный механизм сочленений.", $context1)); $this->assertTrue(in_array('Строка номер два.', $context1)); $this->assertTrue(in_array('Короткий перевод.', $context1)); @@ -90,7 +94,7 @@ class GettextPoFileTest extends TestCase // context2 $this->assertCount(4, $context2); - $this->assertArrayHasKey("\"Quotes\"", $context2); + $this->assertArrayHasKey('"Quotes"', $context2); $this->assertTrue(in_array('"Кавычки"', $context2)); $this->assertArrayHasKey("\nNew lines\n", $context2); diff --git a/tests/framework/i18n/I18NTest.php b/tests/framework/i18n/I18NTest.php index 5b558e5de9..6c893f3170 100644 --- a/tests/framework/i18n/I18NTest.php +++ b/tests/framework/i18n/I18NTest.php @@ -39,8 +39,8 @@ class I18NTest extends TestCase 'test' => [ 'class' => $this->getMessageSourceClass(), 'basePath' => '@yiiunit/data/i18n/messages', - ] - ] + ], + ], ]); } @@ -77,8 +77,8 @@ class I18NTest extends TestCase 'test' => 'test.php', 'foo' => 'test.php', ], - ] - ] + ], + ], ]); $msg = 'The dog runs fast.'; @@ -113,8 +113,8 @@ class I18NTest extends TestCase 'foo' => 'test.php', ], ] - ) - ] + ), + ], ]); $msg = 'The dog runs fast.'; @@ -141,8 +141,8 @@ class I18NTest extends TestCase public function testTranslateParams2() { - if (!extension_loaded("intl")) { - $this->markTestSkipped("intl not installed. Skipping."); + if (!extension_loaded('intl')) { + $this->markTestSkipped('intl not installed. Skipping.'); } $msg = 'His name is {name} and his speed is about {n, number} km/h.'; $params = [ @@ -225,7 +225,7 @@ class I18NTest extends TestCase { return [ ['en-GB'], - ['en'] + ['en'], ]; } diff --git a/tests/framework/i18n/IntlTestHelper.php b/tests/framework/i18n/IntlTestHelper.php index d9a4eb7f75..18862f0c3d 100644 --- a/tests/framework/i18n/IntlTestHelper.php +++ b/tests/framework/i18n/IntlTestHelper.php @@ -1,11 +1,17 @@ self::N_VALUE, self::SUBJECT => self::SUBJECT_VALUE, - ] + ], ], [ - '{'.self::SUBJECT.'} is {'.self::N.', number, integer}', // pattern - self::SUBJECT_VALUE.' is '.self::N_VALUE, // expected + '{' . self::SUBJECT . '} is {' . self::N . ', number, integer}', // pattern + self::SUBJECT_VALUE . ' is ' . self::N_VALUE, // expected [ // params self::N => self::N_VALUE, self::SUBJECT => self::SUBJECT_VALUE, - ] + ], ], [ - 'Here is a big number: {'.self::F.', number}', // pattern - 'Here is a big number: '.self::F_VALUE_FORMATTED, // expected + 'Here is a big number: {' . self::F . ', number}', // pattern + 'Here is a big number: ' . self::F_VALUE_FORMATTED, // expected [ // params - self::F => self::F_VALUE - ] + self::F => self::F_VALUE, + ], ], [ - 'Here is a big number: {'.self::F.', number, integer}', // pattern - 'Here is a big number: '.self::F_VALUE_FORMATTED, // expected + 'Here is a big number: {' . self::F . ', number, integer}', // pattern + 'Here is a big number: ' . self::F_VALUE_FORMATTED, // expected [ // params - self::F => self::F_VALUE - ] + self::F => self::F_VALUE, + ], ], [ - 'Here is a big number: {'.self::D.', number}', // pattern - 'Here is a big number: '.self::D_VALUE_FORMATTED, // expected + 'Here is a big number: {' . self::D . ', number}', // pattern + 'Here is a big number: ' . self::D_VALUE_FORMATTED, // expected [ // params - self::D => self::D_VALUE - ] + self::D => self::D_VALUE, + ], ], [ - 'Here is a big number: {'.self::D.', number, integer}', // pattern - 'Here is a big number: '.self::D_VALUE_FORMATTED_INTEGER, // expected + 'Here is a big number: {' . self::D . ', number, integer}', // pattern + 'Here is a big number: ' . self::D_VALUE_FORMATTED_INTEGER, // expected [ // params - self::D => self::D_VALUE - ] + self::D => self::D_VALUE, + ], ], // This one was provided by Aura.Intl. Thanks! @@ -108,10 +108,10 @@ _MSG_ 'gender_of_host' => 'male', 'num_guests' => 4, 'host' => 'ralph', - 'guest' => 'beep' + 'guest' => 'beep', ], defined('INTL_ICU_VERSION') && version_compare(INTL_ICU_VERSION, '4.8', '<'), - 'select format is available in ICU > 4.4 and plural format with =X selector is avilable since 4.8' + 'select format is available in ICU > 4.4 and plural format with =X selector is avilable since 4.8', ], [ @@ -122,7 +122,7 @@ _MSG_ 'gender' => 'male', ], defined('INTL_ICU_VERSION') && version_compare(INTL_ICU_VERSION, '4.4.2', '<'), - 'select format is available in ICU > 4.4' + 'select format is available in ICU > 4.4', ], // verify pattern in select does not get replaced @@ -138,7 +138,7 @@ _MSG_ 'it' => 'wtf', ], defined('INTL_ICU_VERSION') && version_compare(INTL_ICU_VERSION, '4.4.2', '<'), - 'select format is available in ICU > 4.4' + 'select format is available in ICU > 4.4', ], // verify pattern in select message gets replaced @@ -152,7 +152,7 @@ _MSG_ 'she' => 'wtf', ], defined('INTL_ICU_VERSION') && version_compare(INTL_ICU_VERSION, '4.8', '<'), - 'parameters in select format do not seem to work in ICU < 4.8' + 'parameters in select format do not seem to work in ICU < 4.8', ], // some parser specific verifications @@ -166,7 +166,7 @@ _MSG_ 'she' => 'wtf', ], defined('INTL_ICU_VERSION') && version_compare(INTL_ICU_VERSION, '4.4.2', '<'), - 'select format is available in ICU > 4.4' + 'select format is available in ICU > 4.4', ], // formatting a message that contains params but they are not provided. @@ -192,7 +192,7 @@ _MSG_ 'totalCount' => 12, 'page' => 1, 'pageCount' => 2, - ] + ], ], [ 'Showing {begin, number}-{end, number} of {totalCount, number} {totalCount, plural, one{item} other{items}}.', @@ -204,7 +204,7 @@ _MSG_ 'totalCount' => 1, 'page' => 1, 'pageCount' => 1, - ] + ], ], [ 'Showing {begin, number}-{end, number} of {totalCount, number} {totalCount, plural, one{item} other{items}}.', @@ -216,19 +216,19 @@ _MSG_ 'totalCount' => 0, 'page' => 1, 'pageCount' => 1, - ] + ], ], [ 'Total {count, number} {count, plural, one{item} other{items}}.', 'Total {count, number} {count, plural, one{item} other{items}}.', - [] + [], ], [ 'Total {count, number} {count, plural, one{item} other{items}}.', 'Total 1 item.', [ 'count' => 1, - ] + ], ], [ 'Total {count, number} {count, plural, one{item} other{items}}.', @@ -237,7 +237,7 @@ _MSG_ 'begin' => 5, 'count' => 1, 'end' => 10, - ] + ], ], [ '{0, plural, one {offer} other {offers}}', @@ -266,69 +266,69 @@ _MSG_ { return [ [ - self::SUBJECT_VALUE.' is {0, number}', // pattern - self::SUBJECT_VALUE.' is '.self::N_VALUE, // expected + self::SUBJECT_VALUE . ' is {0, number}', // pattern + self::SUBJECT_VALUE . ' is ' . self::N_VALUE, // expected [ // params 0 => self::N_VALUE, - ] - ], - - [ - self::SUBJECT_VALUE.' is {'.self::N.', number}', // pattern - self::SUBJECT_VALUE.' is '.self::N_VALUE, // expected - [ // params - self::N => self::N_VALUE, - ] - ], - - [ - self::SUBJECT_VALUE.' is {'.self::N.', number, integer}', // pattern - self::SUBJECT_VALUE.' is '.self::N_VALUE, // expected - [ // params - self::N => self::N_VALUE, - ] - ], - - [ - "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree", - "4,560 monkeys on 123 trees make 37.073 monkeys per tree", - [ - 0 => 4560, - 1 => 123, - 2 => 37.073 ], - 'en-US' ], [ - "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum", - "4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum", + self::SUBJECT_VALUE . ' is {' . self::N . ', number}', // pattern + self::SUBJECT_VALUE . ' is ' . self::N_VALUE, // expected + [ // params + self::N => self::N_VALUE, + ], + ], + + [ + self::SUBJECT_VALUE . ' is {' . self::N . ', number, integer}', // pattern + self::SUBJECT_VALUE . ' is ' . self::N_VALUE, // expected + [ // params + self::N => self::N_VALUE, + ], + ], + + [ + '{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree', + '4,560 monkeys on 123 trees make 37.073 monkeys per tree', [ 0 => 4560, 1 => 123, - 2 => 37.073 + 2 => 37.073, + ], + 'en-US', + ], + + [ + '{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum', + '4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum', + [ + 0 => 4560, + 1 => 123, + 2 => 37.073, ], 'de', ], [ - "{monkeyCount,number,integer} monkeys on {trees,number,integer} trees make {monkeysPerTree,number} monkeys per tree", - "4,560 monkeys on 123 trees make 37.073 monkeys per tree", + '{monkeyCount,number,integer} monkeys on {trees,number,integer} trees make {monkeysPerTree,number} monkeys per tree', + '4,560 monkeys on 123 trees make 37.073 monkeys per tree', [ 'monkeyCount' => 4560, 'trees' => 123, - 'monkeysPerTree' => 37.073 + 'monkeysPerTree' => 37.073, ], - 'en-US' + 'en-US', ], [ - "{monkeyCount,number,integer} Affen auf {trees,number,integer} Bäumen sind {monkeysPerTree,number} Affen pro Baum", - "4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum", + '{monkeyCount,number,integer} Affen auf {trees,number,integer} Bäumen sind {monkeysPerTree,number} Affen pro Baum', + '4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum', [ 'monkeyCount' => 4560, 'trees' => 123, - 'monkeysPerTree' => 37.073 + 'monkeysPerTree' => 37.073, ], 'de', ], @@ -353,8 +353,8 @@ _MSG_ */ public function testParseNamedArguments($pattern, $expected, $args, $locale = 'en-US') { - if (!extension_loaded("intl")) { - $this->markTestSkipped("intl not installed. Skipping."); + if (!extension_loaded('intl')) { + $this->markTestSkipped('intl not installed. Skipping.'); } $formatter = new MessageFormatter(); @@ -364,10 +364,10 @@ _MSG_ public function testInsufficientArguments() { - $expected = '{'.self::SUBJECT.'} is '.self::N_VALUE; + $expected = '{' . self::SUBJECT . '} is ' . self::N_VALUE; $formatter = new MessageFormatter(); - $result = $formatter->format('{'.self::SUBJECT.'} is {'.self::N.', number}', [ + $result = $formatter->format('{' . self::SUBJECT . '} is {' . self::N . ', number}', [ self::N => self::N_VALUE, ], 'en-US'); @@ -376,7 +376,7 @@ _MSG_ public function testNoParams() { - $pattern = '{'.self::SUBJECT.'} is '.self::N; + $pattern = '{' . self::SUBJECT . '} is ' . self::N; $formatter = new MessageFormatter(); $result = $formatter->format($pattern, [], 'en-US'); $this->assertEquals($pattern, $result, $formatter->getErrorMessage()); diff --git a/tests/framework/log/DbTargetTest.php b/tests/framework/log/DbTargetTest.php index 26b1e8ae38..c1e92c16df 100644 --- a/tests/framework/log/DbTargetTest.php +++ b/tests/framework/log/DbTargetTest.php @@ -1,4 +1,10 @@ runAction($route, $params); - echo "Result is " . $result; + echo 'Result is ' . $result; if ($result !== \yii\console\Controller::EXIT_CODE_NORMAL) { ob_end_flush(); } else { @@ -91,7 +97,7 @@ abstract class DbTargetTest extends TestCase public static function getConnection() { if (static::$db == null) { - $db = new Connection; + $db = new Connection(); $db->dsn = static::$database['dsn']; if (isset(static::$database['username'])) { $db->username = static::$database['username']; @@ -124,7 +130,7 @@ abstract class DbTargetTest extends TestCase Logger::LEVEL_WARNING, 'test', $time, - [] + [], ]; $logger->messages[] = $messsageData; @@ -147,7 +153,7 @@ abstract class DbTargetTest extends TestCase Logger::LEVEL_WARNING, 'test', time(), - [] + [], ]; $logger->messages[] = $messsageData; diff --git a/tests/framework/log/DispatcherTest.php b/tests/framework/log/DispatcherTest.php index ac915a85a9..a9182f627f 100644 --- a/tests/framework/log/DispatcherTest.php +++ b/tests/framework/log/DispatcherTest.php @@ -1,10 +1,13 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yii\log { - function microtime($get_as_float) { + function microtime($get_as_float) + { if (\yiiunit\framework\log\DispatcherTest::$microtimeIsMocked) { return \yiiunit\framework\log\DispatcherTest::microtime(func_get_args()); } else { @@ -15,10 +18,10 @@ namespace yii\log { namespace yiiunit\framework\log { + use Yii; use yii\base\UserException; use yii\log\Dispatcher; use yii\log\Logger; - use Yii; use yiiunit\TestCase; /** @@ -39,14 +42,14 @@ namespace yiiunit\framework\log { /** * @var bool */ - static $microtimeIsMocked = false; + public static $microtimeIsMocked = false; /** * Array of static functions * * @var array */ - static $functions = []; + public static $functions = []; protected function setUp() { @@ -86,7 +89,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\Dispatcher::setLogger() + * @covers \yii\log\Dispatcher::setLogger() */ public function testSetLogger() { @@ -106,7 +109,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\Dispatcher::getTraceLevel() + * @covers \yii\log\Dispatcher::getTraceLevel() */ public function testGetTraceLevel() { @@ -116,7 +119,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\Dispatcher::setTraceLevel() + * @covers \yii\log\Dispatcher::setTraceLevel() */ public function testSetTraceLevel() { @@ -126,7 +129,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\Dispatcher::getFlushInterval() + * @covers \yii\log\Dispatcher::getFlushInterval() */ public function testGetFlushInterval() { @@ -136,7 +139,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\Dispatcher::setFlushInterval() + * @covers \yii\log\Dispatcher::setFlushInterval() */ public function testSetFlushInterval() { @@ -146,7 +149,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\Dispatcher::dispatch() + * @covers \yii\log\Dispatcher::dispatch() */ public function testDispatchWithDisabledTarget() { @@ -162,7 +165,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\Dispatcher::dispatch() + * @covers \yii\log\Dispatcher::dispatch() */ public function testDispatchWithSuccessTargetCollect() { @@ -182,7 +185,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\Dispatcher::dispatch() + * @covers \yii\log\Dispatcher::dispatch() */ public function testDispatchWithFakeTarget2ThrowExceptionWhenCollect() { @@ -201,13 +204,13 @@ namespace yiiunit\framework\log { [$this->equalTo('messages'), $this->equalTo(true)], [ [[ - 'Unable to send log via '.get_class($target1).': Exception: some error', + 'Unable to send log via ' . get_class($target1) . ': Exception: some error', Logger::LEVEL_WARNING, 'yii\log\Dispatcher::dispatch', 'time data', [], ]], - true + true, ] ); @@ -229,7 +232,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\Dispatcher::init() + * @covers \yii\log\Dispatcher::init() */ public function testInitWithCreateTargetObject() { @@ -237,9 +240,9 @@ namespace yiiunit\framework\log { [ 'targets' => [ 'syslog' => [ - 'class' => 'yii\log\SyslogTarget' - ] - ] + 'class' => 'yii\log\SyslogTarget', + ], + ], ] ); @@ -251,7 +254,8 @@ namespace yiiunit\framework\log { * @param $arguments * @return mixed */ - public static function __callStatic($name, $arguments) { + public static function __callStatic($name, $arguments) + { if (isset(static::$functions[$name]) && is_callable(static::$functions[$name])) { $arguments = isset($arguments[0]) ? $arguments[0] : $arguments; return forward_static_call(static::$functions[$name], $arguments); diff --git a/tests/framework/log/EmailTargetTest.php b/tests/framework/log/EmailTargetTest.php index c1062a75b2..acb73f3c68 100644 --- a/tests/framework/log/EmailTargetTest.php +++ b/tests/framework/log/EmailTargetTest.php @@ -1,6 +1,8 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\framework\log; @@ -10,7 +12,6 @@ use yiiunit\TestCase; /** * Class EmailTargetTest - * @package yiiunit\framework\log * @group log */ class EmailTargetTest extends TestCase @@ -32,16 +33,16 @@ class EmailTargetTest extends TestCase } /** - * @covers yii\log\EmailTarget::init() + * @covers \yii\log\EmailTarget::init() */ public function testInitWithOptionTo() { - $target = new EmailTarget(['mailer' => $this->mailer, 'message'=> ['to' => 'developer1@example.com']]); - $this->assertTrue(is_object($target)); // should be no exception during `init()` + $target = new EmailTarget(['mailer' => $this->mailer, 'message' => ['to' => 'developer1@example.com']]); + $this->assertInternalType('object', $target); // should be no exception during `init()` } /** - * @covers yii\log\EmailTarget::init() + * @covers \yii\log\EmailTarget::init() * @expectedException \yii\base\InvalidConfigException * @expectedExceptionMessage The "to" option must be set for EmailTarget::message. */ @@ -51,8 +52,8 @@ class EmailTargetTest extends TestCase } /** - * @covers yii\log\EmailTarget::export() - * @covers yii\log\EmailTarget::composeMessage() + * @covers \yii\log\EmailTarget::export() + * @covers \yii\log\EmailTarget::composeMessage() */ public function testExportWithSubject() { @@ -76,11 +77,11 @@ class EmailTargetTest extends TestCase ->setConstructorArgs([ [ 'mailer' => $this->mailer, - 'message'=> [ + 'message' => [ 'to' => 'developer@example.com', - 'subject' => 'Hello world' - ] - ] + 'subject' => 'Hello world', + ], + ], ]) ->getMock(); @@ -95,8 +96,8 @@ class EmailTargetTest extends TestCase } /** - * @covers yii\log\EmailTarget::export() - * @covers yii\log\EmailTarget::composeMessage() + * @covers \yii\log\EmailTarget::export() + * @covers \yii\log\EmailTarget::composeMessage() */ public function testExportWithoutSubject() { @@ -120,10 +121,10 @@ class EmailTargetTest extends TestCase ->setConstructorArgs([ [ 'mailer' => $this->mailer, - 'message'=> [ + 'message' => [ 'to' => 'developer@example.com', - ] - ] + ], + ], ]) ->getMock(); diff --git a/tests/framework/log/FileTargetTest.php b/tests/framework/log/FileTargetTest.php index 9e0e90e403..b62e3514b0 100644 --- a/tests/framework/log/FileTargetTest.php +++ b/tests/framework/log/FileTargetTest.php @@ -1,14 +1,16 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\framework\log; +use Yii; use yii\helpers\FileHelper; use yii\log\Dispatcher; use yii\log\Logger; -use Yii; use yiiunit\TestCase; /** @@ -26,7 +28,7 @@ class FileTargetTest extends TestCase { return [ [true], - [false] + [false], ]; } @@ -50,9 +52,9 @@ class FileTargetTest extends TestCase 'maxFileSize' => 1024, // 1 MB 'maxLogFiles' => 1, // one file for rotation and one normal log file 'logVars' => [], - 'rotateByCopy' => $rotateByCopy - ] - ] + 'rotateByCopy' => $rotateByCopy, + ], + ], ]); // one file @@ -102,4 +104,4 @@ class FileTargetTest extends TestCase $this->assertFileNotExists($logFile . '.3'); $this->assertFileNotExists($logFile . '.4'); } -} \ No newline at end of file +} diff --git a/tests/framework/log/LoggerTest.php b/tests/framework/log/LoggerTest.php index 6725158088..ce4932b15f 100644 --- a/tests/framework/log/LoggerTest.php +++ b/tests/framework/log/LoggerTest.php @@ -1,10 +1,13 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\framework\log; +use yii\log\Dispatcher; use yii\log\Logger; use yiiunit\TestCase; @@ -19,20 +22,20 @@ class LoggerTest extends TestCase protected $logger; /** - * @var Dispatcher + * @var Dispatcher|\PHPUnit_Framework_MockObject_MockObject */ protected $dispatcher; protected function setUp() { $this->logger = new Logger(); - $this->dispatcher = $this->getMockBuilder('yii\\log\\Dispatcher') + $this->dispatcher = $this->getMockBuilder('yii\log\Dispatcher') ->setMethods(['dispatch']) ->getMock(); } /** - * @covers yii\log\Logger::Log() + * @covers \yii\log\Logger::Log() */ public function testLog() { @@ -55,7 +58,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::Log() + * @covers \yii\log\Logger::Log() */ public function testLogWithTraceLevel() { @@ -68,21 +71,22 @@ class LoggerTest extends TestCase $this->assertEquals('application', $this->logger->messages[0][2]); $this->assertEquals([ 'file' => __FILE__, - 'line' => 64, + 'line' => 67, 'function' => 'log', 'class' => get_class($this->logger), - 'type' => '->' + 'type' => '->', ], $this->logger->messages[0][4][0]); $this->assertCount(3, $this->logger->messages[0][4]); $this->assertGreaterThanOrEqual($memory, $this->logger->messages[0][5]); } /** - * @covers yii\log\Logger::Log() + * @covers \yii\log\Logger::Log() */ public function testLogWithFlush() { - $logger = $this->getMockBuilder('yii\\log\\Logger') + /* @var $logger Logger|\PHPUnit_Framework_MockObject_MockObject */ + $logger = $this->getMockBuilder('yii\log\Logger') ->setMethods(['flush']) ->getMock(); $logger->flushInterval = 1; @@ -91,7 +95,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::Flush() + * @covers \yii\log\Logger::Flush() */ public function testFlushWithoutDispatcher() { @@ -105,7 +109,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::Flush() + * @covers \yii\log\Logger::Flush() */ public function testFlushWithDispatcherAndDefaultParam() { @@ -120,7 +124,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::Flush() + * @covers \yii\log\Logger::Flush() */ public function testFlushWithDispatcherAndDefinedParam() { @@ -135,7 +139,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::getDbProfiling() + * @covers \yii\log\Logger::getDbProfiling() */ public function testGetDbProfiling() { @@ -145,7 +149,8 @@ class LoggerTest extends TestCase ['duration' => 30], ]; - $logger = $this->getMockBuilder('yii\\log\\Logger') + /* @var $logger Logger|\PHPUnit_Framework_MockObject_MockObject */ + $logger = $this->getMockBuilder('yii\log\Logger') ->setMethods(['getProfiling']) ->getMock(); $logger->method('getProfiling')->willReturn($timings); @@ -156,7 +161,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::calculateTimings() + * @covers \yii\log\Logger::calculateTimings() */ public function testCalculateTimingsWithEmptyMessages() { @@ -164,7 +169,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::calculateTimings() + * @covers \yii\log\Logger::calculateTimings() */ public function testCalculateTimingsWithProfileNotBeginOrEnd() { @@ -180,7 +185,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::calculateTimings() + * @covers \yii\log\Logger::calculateTimings() * * See https://github.com/yiisoft/yii2/issues/14264 */ @@ -199,8 +204,8 @@ class LoggerTest extends TestCase 'level' => 0, 'duration' => 5, 'memory' => 2097152, - 'memoryDiff' => 1048576 - ] + 'memoryDiff' => 1048576, + ], ], $this->logger->calculateTimings($messages) ); @@ -218,15 +223,15 @@ class LoggerTest extends TestCase 'level' => 0, 'duration' => 5, 'memory' => 2097152, - 'memoryDiff' => 1048576 - ] + 'memoryDiff' => 1048576, + ], ], $this->logger->calculateTimings($messages) ); } /** - * @covers yii\log\Logger::calculateTimings() + * @covers \yii\log\Logger::calculateTimings() */ public function testCalculateTimingsWithProfileBeginEndAndNestedLevels() { @@ -245,7 +250,7 @@ class LoggerTest extends TestCase 'level' => 0, 'duration' => 70, 'memory' => 4194304, - 'memoryDiff' => 3145728 + 'memoryDiff' => 3145728, ], [ 'info' => 'secondLevel', @@ -255,8 +260,8 @@ class LoggerTest extends TestCase 'level' => 1, 'duration' => 40, 'memory' => 3145728, - 'memoryDiff' => 1048576 - ] + 'memoryDiff' => 1048576, + ], ], $this->logger->calculateTimings($messages) ); @@ -265,7 +270,7 @@ class LoggerTest extends TestCase /** * See https://github.com/yiisoft/yii2/issues/14133 * - * @covers yii\log\Logger::calculateTimings() + * @covers \yii\log\Logger::calculateTimings() */ public function testCalculateTimingsWithProfileBeginEndAndNestedMixedLevels() { @@ -284,7 +289,7 @@ class LoggerTest extends TestCase 'level' => 1, 'duration' => 70, 'memory' => 4194304, - 'memoryDiff' => 3145728 + 'memoryDiff' => 3145728, ], [ 'info' => 'secondLevel', @@ -294,15 +299,15 @@ class LoggerTest extends TestCase 'level' => 0, 'duration' => 40, 'memory' => 3145728, - 'memoryDiff' => 1048576 - ] + 'memoryDiff' => 1048576, + ], ], $this->logger->calculateTimings($messages) ); } /** - * @covers yii\log\Logger::getElapsedTime() + * @covers \yii\log\Logger::getElapsedTime() */ public function testGetElapsedTime() { @@ -317,7 +322,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::getLevelName() + * @covers \yii\log\Logger::getLevelName() */ public function testGetLevelName() { @@ -332,13 +337,14 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::getProfiling() + * @covers \yii\log\Logger::getProfiling() */ public function testGetProfilingWithEmptyCategoriesAndExcludeCategories() { $messages = ['anyData']; $returnValue = 'return value'; - $logger = $this->getMockBuilder('yii\\log\\Logger') + /* @var $logger Logger|\PHPUnit_Framework_MockObject_MockObject */ + $logger = $this->getMockBuilder('yii\log\Logger') ->setMethods(['calculateTimings']) ->getMock(); @@ -349,7 +355,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::getProfiling() + * @covers \yii\log\Logger::getProfiling() */ public function testGetProfilingWithNotEmptyCategoriesAndNotMatched() { @@ -362,9 +368,10 @@ class LoggerTest extends TestCase 'trace' => 'trace', 'level' => 0, 'duration' => 5, - ] + ], ]; - $logger = $this->getMockBuilder('yii\\log\\Logger') + /* @var $logger Logger|\PHPUnit_Framework_MockObject_MockObject */ + $logger = $this->getMockBuilder('yii\log\Logger') ->setMethods(['calculateTimings']) ->getMock(); @@ -375,7 +382,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::getProfiling() + * @covers \yii\log\Logger::getProfiling() */ public function testGetProfilingWithNotEmptyCategoriesAndMatched() { @@ -398,12 +405,13 @@ class LoggerTest extends TestCase ]; $returnValue = [ 'anyKey' => $matchedByCategoryName, - $secondCategory + $secondCategory, ]; - /** + /* * Matched by category name */ - $logger = $this->getMockBuilder('yii\\log\\Logger') + /* @var $logger Logger|\PHPUnit_Framework_MockObject_MockObject */ + $logger = $this->getMockBuilder('yii\log\Logger') ->setMethods(['calculateTimings']) ->getMock(); @@ -412,10 +420,11 @@ class LoggerTest extends TestCase $logger->expects($this->once())->method('calculateTimings')->with($this->equalTo($messages)); $this->assertEquals([$matchedByCategoryName], $logger->getProfiling(['category'])); - /** + /* * Matched by prefix */ - $logger = $this->getMockBuilder('yii\\log\\Logger') + /* @var $logger Logger|\PHPUnit_Framework_MockObject_MockObject */ + $logger = $this->getMockBuilder('yii\log\Logger') ->setMethods(['calculateTimings']) ->getMock(); @@ -426,7 +435,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::getProfiling() + * @covers \yii\log\Logger::getProfiling() */ public function testGetProfilingWithNotEmptyCategoriesMatchedAndExcludeCategories() { @@ -457,13 +466,14 @@ class LoggerTest extends TestCase 'trace' => 'trace', 'level' => 0, 'duration' => 5, - ] + ], ]; - /** + /* * Exclude by category name */ - $logger = $this->getMockBuilder('yii\\log\\Logger') + /* @var $logger Logger|\PHPUnit_Framework_MockObject_MockObject */ + $logger = $this->getMockBuilder('yii\log\Logger') ->setMethods(['calculateTimings']) ->getMock(); @@ -472,10 +482,11 @@ class LoggerTest extends TestCase $logger->expects($this->once())->method('calculateTimings')->with($this->equalTo($messages)); $this->assertEquals([$fistCategory, $secondCategory], $logger->getProfiling(['cat*'], ['category3'])); - /** + /* * Exclude by category prefix */ - $logger = $this->getMockBuilder('yii\\log\\Logger') + /* @var $logger Logger|\PHPUnit_Framework_MockObject_MockObject */ + $logger = $this->getMockBuilder('yii\log\Logger') ->setMethods(['calculateTimings']) ->getMock(); diff --git a/tests/framework/log/MySQLTargetTest.php b/tests/framework/log/MySQLTargetTest.php index 50fa79b992..fc7fd01d6a 100644 --- a/tests/framework/log/MySQLTargetTest.php +++ b/tests/framework/log/MySQLTargetTest.php @@ -1,5 +1,9 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yii\log { - function openlog() { + function openlog() + { \yiiunit\framework\log\SyslogTargetTest::openlog(func_get_args()); } - function syslog() { + function syslog() + { \yiiunit\framework\log\SyslogTargetTest::syslog(func_get_args()); } - function closelog() { + function closelog() + { \yiiunit\framework\log\SyslogTargetTest::closelog(func_get_args()); } } @@ -22,13 +27,12 @@ namespace yiiunit\framework\log { use PHPUnit_Framework_MockObject_MockObject; use yii\helpers\VarDumper; - use yiiunit\TestCase; use yii\log\Logger; + use yiiunit\TestCase; /** * Class SyslogTargetTest * - * @package yiiunit\framework\log * @group log */ class SyslogTargetTest extends TestCase @@ -38,7 +42,7 @@ namespace yiiunit\framework\log { * * @var array */ - static $functions = []; + public static $functions = []; /** * @var PHPUnit_Framework_MockObject_MockObject @@ -56,7 +60,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\SyslogTarget::export() + * @covers \yii\log\SyslogTarget::export() */ public function testExport() { @@ -148,7 +152,8 @@ namespace yiiunit\framework\log { * @param $arguments * @return mixed */ - public static function __callStatic($name, $arguments) { + public static function __callStatic($name, $arguments) + { if (isset(static::$functions[$name]) && is_callable(static::$functions[$name])) { $arguments = isset($arguments[0]) ? $arguments[0] : $arguments; return forward_static_call(static::$functions[$name], $arguments); @@ -157,7 +162,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\SyslogTarget::formatMessage() + * @covers \yii\log\SyslogTarget::formatMessage() */ public function testFormatMessageWhereTextIsString() { @@ -174,7 +179,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\SyslogTarget::formatMessage() + * @covers \yii\log\SyslogTarget::formatMessage() */ public function testFormatMessageWhereTextIsException() { @@ -192,7 +197,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\SyslogTarget::formatMessage() + * @covers \yii\log\SyslogTarget::formatMessage() */ public function testFormatMessageWhereTextIsNotStringAndNotThrowable() { diff --git a/tests/framework/log/TargetTest.php b/tests/framework/log/TargetTest.php index 67316da32e..a30d203954 100644 --- a/tests/framework/log/TargetTest.php +++ b/tests/framework/log/TargetTest.php @@ -1,6 +1,8 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\framework\log; @@ -25,7 +27,7 @@ class TargetTest extends TestCase [['levels' => 0], ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']], [ ['levels' => Logger::LEVEL_INFO | Logger::LEVEL_WARNING | Logger::LEVEL_ERROR | Logger::LEVEL_TRACE], - ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] + ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], ], [['levels' => ['error']], ['B', 'G', 'H']], [['levels' => Logger::LEVEL_ERROR], ['B', 'G', 'H']], @@ -54,7 +56,7 @@ class TargetTest extends TestCase { static::$messages = []; - $logger = new Logger; + $logger = new Logger(); $dispatcher = new Dispatcher([ 'logger' => $logger, 'targets' => [new TestTarget(array_merge($filter, ['logVars' => []]))], diff --git a/tests/framework/mail/BaseMailerTest.php b/tests/framework/mail/BaseMailerTest.php index 11d6bea1da..4f840b4560 100644 --- a/tests/framework/mail/BaseMailerTest.php +++ b/tests/framework/mail/BaseMailerTest.php @@ -1,12 +1,17 @@ mockApplication([ 'components' => [ 'mailer' => $this->createTestMailComponent(), - ] + ], ]); $filePath = $this->getTestFilePath(); if (!file_exists($filePath)) { @@ -76,11 +81,11 @@ class BaseMailerTest extends TestCase 'params' => [ 'param1' => 'value1', 'param2' => 'value2', - ] + ], ]; $mailer->setView($viewConfig); $view = $mailer->getView(); - $this->assertTrue(is_object($view), 'Unable to setup view via config!'); + $this->assertInternalType('object', $view, 'Unable to setup view via config!'); $this->assertEquals($viewConfig['params'], $view->params, 'Unable to configure view via config array!'); } @@ -91,14 +96,14 @@ class BaseMailerTest extends TestCase { $mailer = new Mailer(); $view = $mailer->getView(); - $this->assertTrue(is_object($view), 'Unable to get default view!'); + $this->assertInternalType('object', $view, 'Unable to get default view!'); } public function testCreateMessage() { $mailer = new Mailer(); $message = $mailer->compose(); - $this->assertTrue(is_object($message), 'Unable to create message instance!'); + $this->assertInternalType('object', $message, 'Unable to create message instance!'); $this->assertEquals($mailer->messageClass, get_class($message), 'Invalid message class!'); } @@ -149,7 +154,7 @@ class BaseMailerTest extends TestCase file_put_contents($viewFileName, $viewFileContent); $params = [ - 'testParam' => 'test output' + 'testParam' => 'test output', ]; $renderResult = $mailer->render($viewName, $params); $this->assertEquals($params['testParam'], $renderResult); @@ -432,13 +437,21 @@ class Message extends BaseMessage return $this; } - public function attachContent($content, array $options = []) {} + public function attachContent($content, array $options = []) + { + } - public function attach($fileName, array $options = []) {} + public function attach($fileName, array $options = []) + { + } - public function embed($fileName, array $options = []) {} + public function embed($fileName, array $options = []) + { + } - public function embedContent($content, array $options = []) {} + public function embedContent($content, array $options = []) + { + } public function toString() { diff --git a/tests/framework/mail/BaseMessageTest.php b/tests/framework/mail/BaseMessageTest.php index 539b730828..92819e4b47 100644 --- a/tests/framework/mail/BaseMessageTest.php +++ b/tests/framework/mail/BaseMessageTest.php @@ -1,4 +1,9 @@ mockApplication([ 'components' => [ - 'mailer' => $this->createTestEmailComponent() - ] + 'mailer' => $this->createTestEmailComponent(), + ], ]); } @@ -84,49 +89,63 @@ class TestMessage extends BaseMessage return ''; } - public function setCharset($charset) {} + public function setCharset($charset) + { + } public function getFrom() { return ''; } - public function setFrom($from) {} + public function setFrom($from) + { + } public function getReplyTo() { return ''; } - public function setReplyTo($replyTo) {} + public function setReplyTo($replyTo) + { + } public function getTo() { return ''; } - public function setTo($to) {} + public function setTo($to) + { + } public function getCc() { return ''; } - public function setCc($cc) {} + public function setCc($cc) + { + } public function getBcc() { return ''; } - public function setBcc($bcc) {} + public function setBcc($bcc) + { + } public function getSubject() { return ''; } - public function setSubject($subject) {} + public function setSubject($subject) + { + } public function setTextBody($text) { @@ -138,13 +157,21 @@ class TestMessage extends BaseMessage $this->html = $html; } - public function attachContent($content, array $options = []) {} + public function attachContent($content, array $options = []) + { + } - public function attach($fileName, array $options = []) {} + public function attach($fileName, array $options = []) + { + } - public function embed($fileName, array $options = []) {} + public function embed($fileName, array $options = []) + { + } - public function embedContent($content, array $options = []) {} + public function embedContent($content, array $options = []) + { + } public function toString() { diff --git a/tests/framework/mutex/FileMutexTest.php b/tests/framework/mutex/FileMutexTest.php index 17d36d2585..778f0f8ff3 100644 --- a/tests/framework/mutex/FileMutexTest.php +++ b/tests/framework/mutex/FileMutexTest.php @@ -1,4 +1,9 @@ $this->getConnection(), ]); } - } diff --git a/tests/framework/mutex/PgsqlMutexTest.php b/tests/framework/mutex/PgsqlMutexTest.php index b61ca1314c..fd26360118 100644 --- a/tests/framework/mutex/PgsqlMutexTest.php +++ b/tests/framework/mutex/PgsqlMutexTest.php @@ -1,4 +1,9 @@ $this->getConnection(), ]); } - } diff --git a/tests/framework/rbac/ActionRule.php b/tests/framework/rbac/ActionRule.php index 30aefdf20d..a5fa76b2d0 100644 --- a/tests/framework/rbac/ActionRule.php +++ b/tests/framework/rbac/ActionRule.php @@ -1,4 +1,9 @@ runAction($route, $params); - echo "Result is " . $result; + echo 'Result is ' . $result; if ($result !== Controller::EXIT_CODE_NORMAL) { ob_end_flush(); } else { @@ -106,7 +112,7 @@ abstract class DbManagerTestCase extends ManagerTestCase public static function createConnection() { - $db = new Connection; + $db = new Connection(); $db->dsn = static::$database['dsn']; if (isset(static::$database['username'])) { $db->username = static::$database['username']; diff --git a/tests/framework/rbac/ExposedPhpManager.php b/tests/framework/rbac/ExposedPhpManager.php index bf7c111ff2..a3a97ddc50 100644 --- a/tests/framework/rbac/ExposedPhpManager.php +++ b/tests/framework/rbac/ExposedPhpManager.php @@ -1,4 +1,10 @@ prepareData(); $rule = $this->auth->getRule('isAuthor'); - $rule->name = "newName"; + $rule->name = 'newName'; $rule->reallyReally = false; $this->auth->update('isAuthor', $rule); @@ -104,7 +109,7 @@ abstract class ManagerTestCase extends TestCase $this->assertEquals(null, $rule); $rule = $this->auth->getRule('newName'); - $this->assertEquals("newName", $rule->name); + $this->assertEquals('newName', $rule->name); $this->assertEquals(false, $rule->reallyReally); $rule->reallyReally = true; @@ -205,7 +210,7 @@ abstract class ManagerTestCase extends TestCase protected function prepareData() { - $rule = new AuthorRule; + $rule = new AuthorRule(); $this->auth->add($rule); $uniqueTrait = $this->auth->createPermission('Fast Metabolism'); diff --git a/tests/framework/rbac/MySQLManagerCacheTest.php b/tests/framework/rbac/MySQLManagerCacheTest.php index 5c2af42c69..bb3ce87331 100644 --- a/tests/framework/rbac/MySQLManagerCacheTest.php +++ b/tests/framework/rbac/MySQLManagerCacheTest.php @@ -1,4 +1,10 @@ $this->getConnection(), 'cache' => new FileCache(['cachePath' => '@yiiunit/runtime/cache']), - 'defaultRoles' => ['myDefaultRole'] + 'defaultRoles' => ['myDefaultRole'], ]); } } diff --git a/tests/framework/rbac/MySQLManagerTest.php b/tests/framework/rbac/MySQLManagerTest.php index 8747242e6b..b37c1675fd 100644 --- a/tests/framework/rbac/MySQLManagerTest.php +++ b/tests/framework/rbac/MySQLManagerTest.php @@ -1,4 +1,10 @@ $this->getConnection(), 'cache' => new FileCache(['cachePath' => '@yiiunit/runtime/cache']), - 'defaultRoles' => ['myDefaultRole'] + 'defaultRoles' => ['myDefaultRole'], ]); } - } diff --git a/tests/framework/rbac/PgSQLManagerTest.php b/tests/framework/rbac/PgSQLManagerTest.php index 1ba965d113..bf211ada4c 100644 --- a/tests/framework/rbac/PgSQLManagerTest.php +++ b/tests/framework/rbac/PgSQLManagerTest.php @@ -1,4 +1,10 @@ $this->getItemFile(), 'assignmentFile' => $this->getAssignmentFile(), 'ruleFile' => $this->getRuleFile(), - 'defaultRoles' => ['myDefaultRole'] + 'defaultRoles' => ['myDefaultRole'], ]); } @@ -121,7 +126,8 @@ class PhpManagerTest extends ManagerTestCase $this->assertTrue($this->auth->update($name, $permission), 'You should be able to update name.'); } - public function testUpdateDescription() { + public function testUpdateDescription() + { $this->prepareData(); $name = 'readPost'; $permission = $this->auth->getPermission($name); @@ -153,6 +159,5 @@ class PhpManagerTest extends ManagerTestCase $this->assertContains('NewAdmin', file_get_contents($this->getAssignmentFile())); $this->auth->remove($role); $this->assertNotContains('NewAdmin', file_get_contents($this->getAssignmentFile())); - } } diff --git a/tests/framework/rbac/SqliteManagerTest.php b/tests/framework/rbac/SqliteManagerTest.php index 7e18a9499e..c94dcf4425 100644 --- a/tests/framework/rbac/SqliteManagerTest.php +++ b/tests/framework/rbac/SqliteManagerTest.php @@ -1,4 +1,10 @@ '/index.php', ], ], - ], 'yii\web\Application'); TestModel::$fields = ['field1', 'field2']; @@ -45,7 +49,7 @@ class SerializerTest extends TestCase [ 'field' => 'field2', 'message' => 'Multiple error 1', - ] + ], ], $serializer->serialize($model)); } @@ -142,7 +146,7 @@ class SerializerTest extends TestCase new ArrayDataProvider([ 'allModels' => [ ['id' => 1, 'username' => 'Bob'], - ['id' => 2, 'username' => 'Tom'] + ['id' => 2, 'username' => 'Tom'], ], 'pagination' => [ 'route' => '/', @@ -150,71 +154,71 @@ class SerializerTest extends TestCase ]), [ ['id' => 1, 'username' => 'Bob'], - ['id' => 2, 'username' => 'Tom'] - ] + ['id' => 2, 'username' => 'Tom'], + ], ], [ new ArrayDataProvider([ 'allModels' => [ ['id' => 1, 'username' => 'Bob'], - ['id' => 2, 'username' => 'Tom'] + ['id' => 2, 'username' => 'Tom'], ], 'pagination' => [ 'route' => '/', 'pageSize' => 1, - 'page' => 0 + 'page' => 0, ], ]), [ ['id' => 1, 'username' => 'Bob'], - ] + ], ], [ new ArrayDataProvider([ 'allModels' => [ ['id' => 1, 'username' => 'Bob'], - ['id' => 2, 'username' => 'Tom'] + ['id' => 2, 'username' => 'Tom'], ], 'pagination' => [ 'route' => '/', 'pageSize' => 1, - 'page' => 1 + 'page' => 1, ], ]), [ - ['id' => 2, 'username' => 'Tom'] - ] + ['id' => 2, 'username' => 'Tom'], + ], ], [ new ArrayDataProvider([ 'allModels' => [ 'Bob' => ['id' => 1, 'username' => 'Bob'], - 'Tom' => ['id' => 2, 'username' => 'Tom'] + 'Tom' => ['id' => 2, 'username' => 'Tom'], ], 'pagination' => [ 'route' => '/', 'pageSize' => 1, - 'page' => 1 + 'page' => 1, ], ]), [ - ['id' => 2, 'username' => 'Tom'] - ] + ['id' => 2, 'username' => 'Tom'], + ], ], [ new ArrayDataProvider([ 'allModels' => [ ['id' => 1, 'username' => 'Bob'], - ['id' => 2, 'username' => 'Tom'] + ['id' => 2, 'username' => 'Tom'], ], 'pagination' => [ 'route' => '/', 'pageSize' => 1, - 'page' => 1 + 'page' => 1, ], ]), [ - 1 => ['id' => 2, 'username' => 'Tom'] + 1 => ['id' => 2, 'username' => 'Tom'], ], true, ], @@ -227,11 +231,11 @@ class SerializerTest extends TestCase 'pagination' => [ 'route' => '/', 'pageSize' => 1, - 'page' => 1 + 'page' => 1, ], ]), [ - 'Tom' => ['id' => 2, 'username' => 'Tom'] + 'Tom' => ['id' => 2, 'username' => 'Tom'], ], true, ], @@ -290,4 +294,4 @@ class TestModel extends Model { return static::$extraFields; } -} \ No newline at end of file +} diff --git a/tests/framework/rest/UrlRuleTest.php b/tests/framework/rest/UrlRuleTest.php index c78d5b584a..1d186a7382 100644 --- a/tests/framework/rest/UrlRuleTest.php +++ b/tests/framework/rest/UrlRuleTest.php @@ -1,4 +1,9 @@ getTestsForControllerNamePluralization(); foreach ($suites as $i => $suite) { - list ($name, $tests) = $suite; + list($name, $tests) = $suite; foreach ($tests as $j => $test) { - list ($config, $expected) = $test; + list($config, $expected) = $test; $rule = new UrlRule($config); $this->assertEquals($expected, $rule->controller, "Test#$i-$j: $name"); } @@ -37,10 +42,10 @@ class UrlRuleTest extends TestCase public function testParseRequest() { $manager = new UrlManager(['cache' => null]); - $request = new Request(['hostInfo' => 'http://en.example.com', 'methodParam' => '_METHOD',]); + $request = new Request(['hostInfo' => 'http://en.example.com', 'methodParam' => '_METHOD']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new UrlRule($config); foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; @@ -78,14 +83,14 @@ class UrlRuleTest extends TestCase ], [ 'prefixed route', - ['controller' => 'post', 'prefix' => 'admin',], + ['controller' => 'post', 'prefix' => 'admin'], [ ['admin/posts', 'post/index'], ], ], [ 'suffixed route', - ['controller' => 'post', 'suffix' => '.json',], + ['controller' => 'post', 'suffix' => '.json'], [ ['posts.json', 'post/index'], ['posts.json', 'post/create', [], 'POST'], @@ -111,12 +116,11 @@ class UrlRuleTest extends TestCase ['posts/123', 'post/delete', ['id' => 123], 'DELETE'], ['posts/new', false], - ], ], [ 'only selected routes', - ['controller' => 'post', 'only' => ['index'],], + ['controller' => 'post', 'only' => ['index']], [ ['posts', 'post/index'], ['posts/123', false], @@ -125,7 +129,7 @@ class UrlRuleTest extends TestCase ], [ 'except routes', - ['controller' => 'post', 'except' => ['delete', 'create'],], + ['controller' => 'post', 'except' => ['delete', 'create']], [ ['posts', 'post/index'], ['posts/123', 'post/view', ['id' => 123]], @@ -135,7 +139,7 @@ class UrlRuleTest extends TestCase ], [ 'extra patterns', - ['controller' => 'post', 'extraPatterns' => ['POST new' => 'create',],], + ['controller' => 'post', 'extraPatterns' => ['POST new' => 'create']], [ ['posts/new', 'post/create', [], 'POST'], ['posts', 'post/create', [], 'POST'], @@ -143,14 +147,14 @@ class UrlRuleTest extends TestCase ], [ 'extra patterns overwrite patterns', - ['controller' => 'post', 'extraPatterns' => ['POST' => 'new',],], + ['controller' => 'post', 'extraPatterns' => ['POST' => 'new']], [ ['posts', 'post/new', [], 'POST'], ], ], [ 'extra patterns rule is higher priority than patterns', - ['controller' => 'post', 'extraPatterns' => ['GET 1337' => 'leet',],], + ['controller' => 'post', 'extraPatterns' => ['GET 1337' => 'leet']], [ ['posts/1337', 'post/leet'], ['posts/1338', 'post/view', ['id' => 1338]], @@ -163,38 +167,43 @@ class UrlRuleTest extends TestCase { return [ [ - 'pluralized automatically', [ - [ - ['controller' => 'user'], - ['users' => 'user'] - ], - [ - ['controller' => 'admin/user'], - ['admin/users' => 'admin/user'] - ], - [ - ['controller' => ['admin/user', 'post']], - ['admin/users' => 'admin/user', 'posts' => 'post'] - ], - ]], - [ - 'explicitly specified', [ - [ - ['controller' => ['customer' => 'user']], - ['customer' => 'user'] - ] - ]], - [ - 'do not pluralize', [ + 'pluralized automatically', [ [ - 'pluralize' => false, - 'controller' => ['admin/user', 'post'], + ['controller' => 'user'], + ['users' => 'user'], ], - ['admin/user' => 'admin/user', 'post' => 'post',] - ] - ]], - + [ + ['controller' => 'admin/user'], + ['admin/users' => 'admin/user'], + ], + [ + ['controller' => ['admin/user', 'post']], + ['admin/users' => 'admin/user', 'posts' => 'post'], + ], + ], + ], + [ + 'explicitly specified', + [ + [ + ['controller' => ['customer' => 'user']], + ['customer' => 'user'], + ], + ], + ], + [ + 'do not pluralize', + [ + [ + [ + 'pluralize' => false, + 'controller' => ['admin/user', 'post'], + ], + ['admin/user' => 'admin/user', 'post' => 'post'], + ], + ], + ], ]; } @@ -216,12 +225,12 @@ class UrlRuleTest extends TestCase 'pluralize' => true, ], [ // test cases: route, expected - [ ['v1/channel/index'], 'v1/channels' ], - [ ['v1/channel/index', 'offset' => 1], 'v1/channels?offset=1' ], - [ ['v1/channel/view', 'id' => 42], 'v1/channels/42' ], - [ ['v1/channel/options'], 'v1/channels' ], - [ ['v1/channel/options', 'id' => 42], 'v1/channels/42' ], - [ ['v1/channel/delete'], false ], + [['v1/channel/index'], 'v1/channels'], + [['v1/channel/index', 'offset' => 1], 'v1/channels?offset=1'], + [['v1/channel/view', 'id' => 42], 'v1/channels/42'], + [['v1/channel/options'], 'v1/channels'], + [['v1/channel/options', 'id' => 42], 'v1/channels/42'], + [['v1/channel/delete'], false], ], ], [ @@ -230,12 +239,12 @@ class UrlRuleTest extends TestCase 'pluralize' => true, ], [ // test cases: route, expected - [ ['v1/channel/index'], 'v1/channels' ], - [ ['v1/channel/index', 'offset' => 1], 'v1/channels?offset=1' ], - [ ['v1/channel/view', 'id' => 42], 'v1/channels/42' ], - [ ['v1/channel/options'], 'v1/channels' ], - [ ['v1/channel/options', 'id' => 42], 'v1/channels/42' ], - [ ['v1/channel/delete'], false ], + [['v1/channel/index'], 'v1/channels'], + [['v1/channel/index', 'offset' => 1], 'v1/channels?offset=1'], + [['v1/channel/view', 'id' => 42], 'v1/channels/42'], + [['v1/channel/options'], 'v1/channels'], + [['v1/channel/options', 'id' => 42], 'v1/channels/42'], + [['v1/channel/delete'], false], ], ], [ @@ -244,16 +253,16 @@ class UrlRuleTest extends TestCase 'pluralize' => true, ], [ // test cases: route, expected - [ ['v1/channel/index'], 'v1/channels' ], - [ ['v1/channel/view', 'id' => 42], 'v1/channels/42' ], - [ ['v1/channel/options'], 'v1/channels' ], - [ ['v1/channel/options', 'id' => 42], 'v1/channels/42' ], - [ ['v1/channel/delete'], false ], - [ ['v1/user/index'], 'v1/u' ], - [ ['v1/user/view', 'id' => 1], 'v1/u/1' ], - [ ['v1/channel/options'], 'v1/channels' ], - [ ['v1/channel/options', 'id' => 42], 'v1/channels/42' ], - [ ['v1/user/delete'], false ], + [['v1/channel/index'], 'v1/channels'], + [['v1/channel/view', 'id' => 42], 'v1/channels/42'], + [['v1/channel/options'], 'v1/channels'], + [['v1/channel/options', 'id' => 42], 'v1/channels/42'], + [['v1/channel/delete'], false], + [['v1/user/index'], 'v1/u'], + [['v1/user/view', 'id' => 1], 'v1/u/1'], + [['v1/channel/options'], 'v1/channels'], + [['v1/channel/options', 'id' => 42], 'v1/channels/42'], + [['v1/user/delete'], false], ], ], @@ -265,12 +274,12 @@ class UrlRuleTest extends TestCase 'pluralize' => false, ], [ // test cases: route, expected - [ ['v1/channel/index'], 'v1/channel' ], - [ ['v1/channel/index', 'offset' => 1], 'v1/channel?offset=1' ], - [ ['v1/channel/view', 'id' => 42], 'v1/channel/42' ], - [ ['v1/channel/options'], 'v1/channel' ], - [ ['v1/channel/options', 'id' => 42], 'v1/channel/42' ], - [ ['v1/channel/delete'], false ], + [['v1/channel/index'], 'v1/channel'], + [['v1/channel/index', 'offset' => 1], 'v1/channel?offset=1'], + [['v1/channel/view', 'id' => 42], 'v1/channel/42'], + [['v1/channel/options'], 'v1/channel'], + [['v1/channel/options', 'id' => 42], 'v1/channel/42'], + [['v1/channel/delete'], false], ], ], [ @@ -279,12 +288,12 @@ class UrlRuleTest extends TestCase 'pluralize' => false, ], [ // test cases: route, expected - [ ['v1/channel/index'], 'v1/channel' ], - [ ['v1/channel/index', 'offset' => 1], 'v1/channel?offset=1' ], - [ ['v1/channel/view', 'id' => 42], 'v1/channel/42' ], - [ ['v1/channel/options'], 'v1/channel' ], - [ ['v1/channel/options', 'id' => 42], 'v1/channel/42' ], - [ ['v1/channel/delete'], false ], + [['v1/channel/index'], 'v1/channel'], + [['v1/channel/index', 'offset' => 1], 'v1/channel?offset=1'], + [['v1/channel/view', 'id' => 42], 'v1/channel/42'], + [['v1/channel/options'], 'v1/channel'], + [['v1/channel/options', 'id' => 42], 'v1/channel/42'], + [['v1/channel/delete'], false], ], ], [ @@ -293,16 +302,16 @@ class UrlRuleTest extends TestCase 'pluralize' => false, ], [ // test cases: route, expected - [ ['v1/channel/index'], 'v1/channel' ], - [ ['v1/channel/view', 'id' => 42], 'v1/channel/42' ], - [ ['v1/channel/options'], 'v1/channel' ], - [ ['v1/channel/options', 'id' => 42], 'v1/channel/42' ], - [ ['v1/channel/delete'], false ], - [ ['v1/user/index'], 'v1/u' ], - [ ['v1/user/view', 'id' => 1], 'v1/u/1' ], - [ ['v1/user/options'], 'v1/u' ], - [ ['v1/user/options', 'id' => 42], 'v1/u/42' ], - [ ['v1/user/delete'], false ], + [['v1/channel/index'], 'v1/channel'], + [['v1/channel/view', 'id' => 42], 'v1/channel/42'], + [['v1/channel/options'], 'v1/channel'], + [['v1/channel/options', 'id' => 42], 'v1/channel/42'], + [['v1/channel/delete'], false], + [['v1/user/index'], 'v1/u'], + [['v1/user/view', 'id' => 1], 'v1/u/1'], + [['v1/user/options'], 'v1/u'], + [['v1/user/options', 'id' => 42], 'v1/u/42'], + [['v1/user/delete'], false], ], ], @@ -320,20 +329,19 @@ class UrlRuleTest extends TestCase ], [ // test cases: route, expected // normal actions should behave as before - [ ['v1/channel/index'], 'v1/channels' ], - [ ['v1/channel/index', 'offset' => 1], 'v1/channels?offset=1' ], - [ ['v1/channel/view', 'id' => 42], 'v1/channels/42' ], - [ ['v1/channel/options'], 'v1/channels' ], - [ ['v1/channel/options', 'id' => 42], 'v1/channels/42' ], - [ ['v1/channel/delete'], false ], + [['v1/channel/index'], 'v1/channels'], + [['v1/channel/index', 'offset' => 1], 'v1/channels?offset=1'], + [['v1/channel/view', 'id' => 42], 'v1/channels/42'], + [['v1/channel/options'], 'v1/channels'], + [['v1/channel/options', 'id' => 42], 'v1/channels/42'], + [['v1/channel/delete'], false], - [ ['v1/channel/my'], 'v1/channels/my' ], - [ ['v1/channel/my', 'id' => 42], 'v1/channels/42/my' ], - [ ['v1/channel/my2'], false ], - [ ['v1/channel/my2', 'id' => 42], false ], + [['v1/channel/my'], 'v1/channels/my'], + [['v1/channel/my', 'id' => 42], 'v1/channels/42/my'], + [['v1/channel/my2'], false], + [['v1/channel/my2', 'id' => 42], false], ], ], - ]; } diff --git a/tests/framework/test/ActiveFixtureTest.php b/tests/framework/test/ActiveFixtureTest.php index 8955ecd4fc..c078a63b7a 100644 --- a/tests/framework/test/ActiveFixtureTest.php +++ b/tests/framework/test/ActiveFixtureTest.php @@ -1,11 +1,15 @@ initFixtures(); + $this->initFixtures(); } public function tearDown() diff --git a/tests/framework/test/ArrayFixtureTest.php b/tests/framework/test/ArrayFixtureTest.php index 9d6061e68a..2ccd51e668 100644 --- a/tests/framework/test/ArrayFixtureTest.php +++ b/tests/framework/test/ArrayFixtureTest.php @@ -8,15 +8,14 @@ namespace yiiunit\framework\test; -use yiiunit\TestCase; use yii\test\ArrayFixture; +use yiiunit\TestCase; /** * @group fixture */ class ArrayFixtureTest extends TestCase { - /** * @var \yii\test\ArrayFixture */ @@ -57,5 +56,4 @@ class ArrayFixtureTest extends TestCase $this->_fixture->dataFile = 'wrong/fixtures/data/path/alias'; $this->_fixture->load(); } - } diff --git a/tests/framework/test/data/array_fixture.php b/tests/framework/test/data/array_fixture.php index c5ccd4b384..39cc75fb2b 100644 --- a/tests/framework/test/data/array_fixture.php +++ b/tests/framework/test/data/array_fixture.php @@ -1,4 +1,9 @@ [ diff --git a/tests/framework/test/data/customer.php b/tests/framework/test/data/customer.php index 2eb7e6cc75..aeb1fcb394 100644 --- a/tests/framework/test/data/customer.php +++ b/tests/framework/test/data/customer.php @@ -1,4 +1,9 @@ [ @@ -6,13 +11,13 @@ return [ 'name' => 'customer1', 'address' => 'address1', 'status' => 1, - 'profile_id' => 1 + 'profile_id' => 1, ], 'customer2' => [ 'email' => 'customer2@example.com', 'name' => 'customer2', 'address' => 'address2', 'status' => 2, - 'profile_id' => 2 + 'profile_id' => 2, ], ]; diff --git a/tests/framework/test/data/profile.php b/tests/framework/test/data/profile.php index 91ebe4c07b..42be091616 100644 --- a/tests/framework/test/data/profile.php +++ b/tests/framework/test/data/profile.php @@ -1,4 +1,9 @@ [ diff --git a/tests/framework/validators/BooleanValidatorTest.php b/tests/framework/validators/BooleanValidatorTest.php index 29b008f646..9835422ebf 100644 --- a/tests/framework/validators/BooleanValidatorTest.php +++ b/tests/framework/validators/BooleanValidatorTest.php @@ -1,9 +1,15 @@ assertTrue($val->validate(true)); $this->assertTrue($val->validate(false)); $this->assertTrue($val->validate('0')); @@ -44,12 +50,12 @@ class BooleanValidatorTest extends TestCase public function testValidateAttributeAndError() { - $obj = new FakedValidationModel; + $obj = new FakedValidationModel(); $obj->attrA = true; $obj->attrB = '1'; $obj->attrC = '0'; $obj->attrD = []; - $val = new BooleanValidator; + $val = new BooleanValidator(); $val->validateAttribute($obj, 'attrA'); $this->assertFalse($obj->hasErrors('attrA')); $val->validateAttribute($obj, 'attrC'); @@ -72,7 +78,7 @@ class BooleanValidatorTest extends TestCase $this->assertEquals('the input value must be either "true" or "false".', $errorMessage); - $obj = new FakedValidationModel; + $obj = new FakedValidationModel(); $obj->attrA = true; $obj->attrB = '1'; $obj->attrC = '0'; @@ -80,15 +86,14 @@ class BooleanValidatorTest extends TestCase $this->assertEquals( 'yii.validation.boolean(value, messages, {"trueValue":true,"falseValue":false,"message":"attrB must be either \"true\" or \"false\".","skipOnEmpty":1,"strict":1});', - $validator->clientValidateAttribute($obj, 'attrB', new ViewStub) + $validator->clientValidateAttribute($obj, 'attrB', new ViewStub()) ); } } -class ViewStub extends \yii\web\View +class ViewStub extends View { public function registerAssetBundle($name, $position = null) { - return; } } diff --git a/tests/framework/validators/CompareValidatorTest.php b/tests/framework/validators/CompareValidatorTest.php index e831cb1e9c..c65cc0a9fc 100644 --- a/tests/framework/validators/CompareValidatorTest.php +++ b/tests/framework/validators/CompareValidatorTest.php @@ -1,4 +1,10 @@ expectException('yii\base\InvalidConfigException'); - $val = new CompareValidator; + $val = new CompareValidator(); $val->validate('val'); } @@ -96,40 +102,40 @@ class CompareValidatorTest extends TestCase public function testValidateAttribute() { // invalid-array - $val = new CompareValidator; - $model = new FakedValidationModel; + $val = new CompareValidator(); + $model = new FakedValidationModel(); $model->attr = ['test_val']; $val->validateAttribute($model, 'attr'); $this->assertTrue($model->hasErrors('attr')); $val = new CompareValidator(['compareValue' => 'test-string']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_test = 'test-string'; $val->validateAttribute($model, 'attr_test'); $this->assertFalse($model->hasErrors('attr_test')); $val = new CompareValidator(['compareAttribute' => 'attr_test_val']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_test = 'test-string'; $model->attr_test_val = 'test-string'; $val->validateAttribute($model, 'attr_test'); $this->assertFalse($model->hasErrors('attr_test')); $this->assertFalse($model->hasErrors('attr_test_val')); $val = new CompareValidator(['compareAttribute' => 'attr_test_val']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_test = 'test-string'; $model->attr_test_val = 'test-string-false'; $val->validateAttribute($model, 'attr_test'); $this->assertTrue($model->hasErrors('attr_test')); $this->assertFalse($model->hasErrors('attr_test_val')); // assume: _repeat - $val = new CompareValidator; - $model = new FakedValidationModel; + $val = new CompareValidator(); + $model = new FakedValidationModel(); $model->attr_test = 'test-string'; $model->attr_test_repeat = 'test-string'; $val->validateAttribute($model, 'attr_test'); $this->assertFalse($model->hasErrors('attr_test')); $this->assertFalse($model->hasErrors('attr_test_repeat')); - $val = new CompareValidator; - $model = new FakedValidationModel; + $val = new CompareValidator(); + $model = new FakedValidationModel(); $model->attr_test = 'test-string'; $model->attr_test_repeat = 'test-string2'; $val->validateAttribute($model, 'attr_test'); @@ -193,12 +199,11 @@ class CompareValidatorTest extends TestCase foreach ($this->getOperationTestData($value) as $operator => $tests) { $val = new CompareValidator(['operator' => $operator, 'compareValue' => $value]); foreach ($tests as $test) { - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_test = $test[0]; $val->validateAttribute($model, 'attr_test'); $this->assertEquals($test[1], !$model->hasErrors('attr_test')); } - } } diff --git a/tests/framework/validators/DateValidatorTest.php b/tests/framework/validators/DateValidatorTest.php index bbf39d32ab..cb2b99cfb1 100644 --- a/tests/framework/validators/DateValidatorTest.php +++ b/tests/framework/validators/DateValidatorTest.php @@ -1,12 +1,17 @@ assertTrue($val->message !== null && strlen($val->message) > 1); } @@ -50,8 +55,8 @@ class DateValidatorTest extends TestCase 'components' => [ 'formatter' => [ 'dateFormat' => 'short', - ] - ] + ], + ], ]); $val = new DateValidator(); $this->assertTrue($val->validate('31/5/2017')); @@ -65,8 +70,8 @@ class DateValidatorTest extends TestCase 'components' => [ 'formatter' => [ 'dateFormat' => 'short', - ] - ] + ], + ], ]); $val = new DateValidator(); $this->assertTrue($val->validate('31.5.2017')); @@ -135,17 +140,17 @@ class DateValidatorTest extends TestCase // error-array-add $val = new DateValidator(['format' => 'php:Y-m-d']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13'; $val->validateAttribute($model, 'attr_date'); $this->assertFalse($model->hasErrors('attr_date')); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '1375293913'; $val->validateAttribute($model, 'attr_date'); $this->assertTrue($model->hasErrors('attr_date')); //// timestamp attribute $val = new DateValidator(['format' => 'php:Y-m-d', 'timestampAttribute' => 'attr_timestamp']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -179,17 +184,17 @@ class DateValidatorTest extends TestCase // error-array-add $val = new DateValidator(['format' => 'yyyy-MM-dd']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13'; $val->validateAttribute($model, 'attr_date'); $this->assertFalse($model->hasErrors('attr_date')); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '1375293913'; $val->validateAttribute($model, 'attr_date'); $this->assertTrue($model->hasErrors('attr_date')); //// timestamp attribute $val = new DateValidator(['format' => 'yyyy-MM-dd', 'timestampAttribute' => 'attr_timestamp']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -243,7 +248,7 @@ class DateValidatorTest extends TestCase $return[] = ['yyyy-MM-dd HH:mm:ss', '2013-09-13', '2013-09-13 00:00:00', $tz[0], $appTz[0]]; $return[] = ['php:Y-m-d', '2013-09-13', '2013-09-13', $tz[0], $appTz[0]]; $return[] = ['php:Y-m-d H:i:s', '2013-09-13', '2013-09-13 00:00:00', $tz[0], $appTz[0]]; - $return[] = ['php:U', '2013-09-13', "1379030400", $tz[0], $appTz[0]]; + $return[] = ['php:U', '2013-09-13', '1379030400', $tz[0], $appTz[0]]; $return[] = [null, '2013-09-13', 1379030400, $tz[0], $appTz[0]]; } } @@ -266,7 +271,7 @@ class DateValidatorTest extends TestCase date_default_timezone_set($timezone); $val = new DateValidator(['format' => 'yyyy-MM-dd', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => $format, 'timeZone' => $appTimezone]); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = $date; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -288,8 +293,8 @@ class DateValidatorTest extends TestCase 'formatter' => [ 'dateFormat' => 'long', 'datetimeFormat' => 'short', // this is the format to be used by the validator by default - ] - ] + ], + ], ]); $val = new DateValidator(['type' => DateValidator::TYPE_DATETIME]); $this->assertTrue($val->validate('31/5/2017 12:30')); @@ -303,8 +308,8 @@ class DateValidatorTest extends TestCase 'formatter' => [ 'dateFormat' => 'long', 'datetimeFormat' => 'short', // this is the format to be used by the validator by default - ] - ] + ], + ], ]); $val = new DateValidator(['type' => DateValidator::TYPE_DATETIME]); $this->assertTrue($val->validate('31.5.2017 12:30')); @@ -322,7 +327,7 @@ class DateValidatorTest extends TestCase date_default_timezone_set($timezone); $val = new DateValidator(['format' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttribute' => 'attr_timestamp', 'timeZone' => 'UTC']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 14:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -331,7 +336,7 @@ class DateValidatorTest extends TestCase $this->assertSame(1379082195, $model->attr_timestamp); $val = new DateValidator(['format' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttribute' => 'attr_timestamp', 'timeZone' => 'Europe/Berlin']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 16:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -340,7 +345,7 @@ class DateValidatorTest extends TestCase $this->assertSame(1379082195, $model->attr_timestamp); $val = new DateValidator(['format' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm:ss', 'timeZone' => 'UTC']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 14:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -349,7 +354,7 @@ class DateValidatorTest extends TestCase $this->assertSame('2013-09-13 14:23:15', $model->attr_timestamp); $val = new DateValidator(['format' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm:ss', 'timeZone' => 'Europe/Berlin']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 16:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -358,7 +363,7 @@ class DateValidatorTest extends TestCase $this->assertSame('2013-09-13 14:23:15', $model->attr_timestamp); $val = new DateValidator(['format' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'php:Y-m-d H:i:s', 'timeZone' => 'UTC']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 14:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -367,7 +372,7 @@ class DateValidatorTest extends TestCase $this->assertSame('2013-09-13 14:23:15', $model->attr_timestamp); $val = new DateValidator(['format' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'php:Y-m-d H:i:s', 'timeZone' => 'Europe/Berlin']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 16:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -392,7 +397,7 @@ class DateValidatorTest extends TestCase date_default_timezone_set($timezone); $val = new DateValidator(['format' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttributeTimeZone' => 'Europe/Berlin', 'timeZone' => 'UTC']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 14:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -400,7 +405,7 @@ class DateValidatorTest extends TestCase $this->assertFalse($model->hasErrors('attr_timestamp')); $this->assertSame('2013-09-13 16:23:15', $model->attr_timestamp); $val = new DateValidator(['format' => 'php:Y-m-d H:i:s', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttributeTimeZone' => 'Europe/Berlin', 'timeZone' => 'UTC']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 14:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -409,7 +414,7 @@ class DateValidatorTest extends TestCase $this->assertSame('2013-09-13 16:23:15', $model->attr_timestamp); $val = new DateValidator(['format' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttributeTimeZone' => 'Europe/Berlin', 'timeZone' => 'Europe/Berlin']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 16:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -417,7 +422,7 @@ class DateValidatorTest extends TestCase $this->assertFalse($model->hasErrors('attr_timestamp')); $this->assertSame('2013-09-13 16:23:15', $model->attr_timestamp); $val = new DateValidator(['format' => 'php:Y-m-d H:i:s', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttributeTimeZone' => 'Europe/Berlin', 'timeZone' => 'Europe/Berlin']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 16:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -426,7 +431,7 @@ class DateValidatorTest extends TestCase $this->assertSame('2013-09-13 16:23:15', $model->attr_timestamp); $val = new DateValidator(['format' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttributeTimeZone' => 'America/New_York', 'timeZone' => 'Europe/Berlin']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 16:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -434,7 +439,7 @@ class DateValidatorTest extends TestCase $this->assertFalse($model->hasErrors('attr_timestamp')); $this->assertSame('2013-09-13 10:23:15', $model->attr_timestamp); $val = new DateValidator(['format' => 'php:Y-m-d H:i:s', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttributeTimeZone' => 'America/New_York', 'timeZone' => 'Europe/Berlin']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 16:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -465,26 +470,26 @@ class DateValidatorTest extends TestCase } $val = new DateValidator(['format' => 'yyyy-MM-dd', 'min' => $min]); - $date = "1958-01-12"; + $date = '1958-01-12'; $this->assertTrue($val->validate($date), "$date is valid"); $val = new DateValidator(['format' => 'yyyy-MM-dd', 'max' => '2000-01-01']); $date = '2014-09-13'; $this->assertFalse($val->validate($date), "$date is too big"); - $date = "1958-01-12"; + $date = '1958-01-12'; $this->assertTrue($val->validate($date), "$date is valid"); $val = new DateValidator(['format' => 'yyyy-MM-dd', 'min' => $min, 'max' => '2000-01-01']); - $this->assertTrue($val->validate('1999-12-31'), "max -1 day is valid"); - $this->assertTrue($val->validate('2000-01-01'), "max is inside range"); - $this->assertTrue($val->validate($min), "min is inside range"); - $this->assertFalse($val->validate($beforeMin), "min -1 day is invalid"); - $this->assertFalse($val->validate('2000-01-02'), "max +1 day is invalid"); + $this->assertTrue($val->validate('1999-12-31'), 'max -1 day is valid'); + $this->assertTrue($val->validate('2000-01-01'), 'max is inside range'); + $this->assertTrue($val->validate($min), 'min is inside range'); + $this->assertFalse($val->validate($beforeMin), 'min -1 day is invalid'); + $this->assertFalse($val->validate('2000-01-02'), 'max +1 day is invalid'); } private function validateModelAttribute($validator, $date, $expected, $message = '') { - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = $date; $validator->validateAttribute($model, 'attr_date'); if (!$expected) { @@ -494,7 +499,8 @@ class DateValidatorTest extends TestCase } } - public function testIntlValidateAttributeRange() { + public function testIntlValidateAttributeRange() + { $this->testValidateAttributeRange(); } @@ -525,17 +531,17 @@ class DateValidatorTest extends TestCase $this->validateModelAttribute($val, $date, true, "$date is valid"); $val = new DateValidator(['format' => 'yyyy-MM-dd', 'min' => $min, 'max' => '2000-01-01']); - $this->validateModelAttribute($val, '1999-12-31', true, "max -1 day is valid"); - $this->validateModelAttribute($val, '2000-01-01', true, "max is inside range"); - $this->validateModelAttribute($val, $min, true, "min is inside range"); - $this->validateModelAttribute($val, $beforeMin, false, "min -1 day is invalid"); - $this->validateModelAttribute($val, '2000-01-02', false, "max +1 day is invalid"); + $this->validateModelAttribute($val, '1999-12-31', true, 'max -1 day is valid'); + $this->validateModelAttribute($val, '2000-01-01', true, 'max is inside range'); + $this->validateModelAttribute($val, $min, true, 'min is inside range'); + $this->validateModelAttribute($val, $beforeMin, false, 'min -1 day is invalid'); + $this->validateModelAttribute($val, '2000-01-02', false, 'max +1 day is invalid'); } public function testIntlValidateValueRangeOld() { if ($this->checkOldIcuBug()) { - $this->markTestSkipped("ICU is too old."); + $this->markTestSkipped('ICU is too old.'); } $date = '14-09-13'; $val = new DateValidator(['format' => 'yyyy-MM-dd', 'min' => '1920-01-01']); @@ -545,7 +551,7 @@ class DateValidatorTest extends TestCase public function testIntlValidateAttributeRangeOld() { if ($this->checkOldIcuBug()) { - $this->markTestSkipped("ICU is too old."); + $this->markTestSkipped('ICU is too old.'); } $date = '14-09-13'; $val = new DateValidator(['format' => 'yyyy-MM-dd', 'min' => '1920-01-01']); diff --git a/tests/framework/validators/DefaultValueValidatorTest.php b/tests/framework/validators/DefaultValueValidatorTest.php index 5699415d2b..cdd68315b8 100644 --- a/tests/framework/validators/DefaultValueValidatorTest.php +++ b/tests/framework/validators/DefaultValueValidatorTest.php @@ -1,4 +1,9 @@ value = 'test_value'; - $obj = new \stdclass; + $obj = new \stdclass(); $obj->attrA = 'attrA'; $obj->attrB = null; $obj->attrC = ''; diff --git a/tests/framework/validators/EachValidatorTest.php b/tests/framework/validators/EachValidatorTest.php index a2757d811f..515f63c94d 100644 --- a/tests/framework/validators/EachValidatorTest.php +++ b/tests/framework/validators/EachValidatorTest.php @@ -1,4 +1,9 @@ [ - ' to be trimmed ' + ' to be trimmed ', ], ]); $validator = new EachValidator(['rule' => ['trim']]); @@ -60,7 +65,7 @@ class EachValidatorTest extends TestCase { $model = FakedValidationModel::createWithAttributes([ 'attr_one' => [ - 'text' + 'text', ], ]); $validator = new EachValidator(['rule' => ['integer']]); @@ -112,7 +117,7 @@ class EachValidatorTest extends TestCase $model = FakedValidationModel::createWithAttributes([ 'attr_one' => [ - '' + '', ], ]); $validator = new EachValidator(['rule' => ['integer', 'skipOnEmpty' => true]]); @@ -165,7 +170,7 @@ class EachValidatorTest extends TestCase { $model = FakedValidationModel::createWithAttributes([ 'attr_one' => [ - 'one', 2, 'three' + 'one', 2, 'three', ], ]); $validator = new EachValidator(['rule' => ['integer']]); @@ -179,4 +184,4 @@ class EachValidatorTest extends TestCase $validator->validateAttribute($model, 'attr_one'); $this->assertCount(2, $model->getErrors('attr_one')); } -} \ No newline at end of file +} diff --git a/tests/framework/validators/EmailValidatorTest.php b/tests/framework/validators/EmailValidatorTest.php index 5fa88ae0ee..37865055e8 100644 --- a/tests/framework/validators/EmailValidatorTest.php +++ b/tests/framework/validators/EmailValidatorTest.php @@ -1,4 +1,10 @@ ', ]; foreach ($emails as $email) { - $this->assertTrue($validator->validate($email),"Email: '$email' failed to validate(checkDNS=true, allowName=true)"); + $this->assertTrue($validator->validate($email), "Email: '$email' failed to validate(checkDNS=true, allowName=true)"); } } diff --git a/tests/framework/validators/ExistValidatorTest.php b/tests/framework/validators/ExistValidatorTest.php index db5eaeb2ac..385c723d3f 100644 --- a/tests/framework/validators/ExistValidatorTest.php +++ b/tests/framework/validators/ExistValidatorTest.php @@ -1,4 +1,9 @@ assertTrue(is_string($val->$attr)); + $this->assertInternalType('string', $val->$attr); } } @@ -126,15 +131,15 @@ class FileValidatorTest extends TestCase 'error' => UPLOAD_ERR_NO_FILE, ], ] - ) + ), ] ); $val->validateAttribute($m, 'attr_files'); $this->assertFalse($m->hasErrors('attr_files')); $m = FakedValidationModel::createWithAttributes([ 'attr_files' => $this->createTestFiles([ - [''], [''], [''] - ]) + [''], [''], [''], + ]), ]); $val->validateAttribute($m, 'attr_files'); $this->assertTrue($m->hasErrors()); @@ -152,19 +157,19 @@ class FileValidatorTest extends TestCase [ 'name' => 'image.png', 'size' => 1024, - 'type' => 'image/png' + 'type' => 'image/png', ], [ 'name' => 'image.png', 'size' => 1024, - 'type' => 'image/png' + 'type' => 'image/png', ], [ 'name' => 'text.txt', - 'size' => 1024 + 'size' => 1024, ], ] - ) + ), ] ); $m->setScenario('validateMultipleFiles'); @@ -179,15 +184,15 @@ class FileValidatorTest extends TestCase [ 'name' => 'image.png', 'size' => 1024, - 'type' => 'image/png' + 'type' => 'image/png', ], [ 'name' => 'image.png', 'size' => 1024, - 'type' => 'image/png' + 'type' => 'image/png', ], ] - ) + ), ] ); $m->setScenario('validateMultipleFiles'); @@ -202,7 +207,7 @@ class FileValidatorTest extends TestCase 'size' => 1024, ], ] - ) + ), ] ); $m->setScenario('validateFile'); @@ -250,7 +255,7 @@ class FileValidatorTest extends TestCase 'tempName' => $tempName, 'type' => $type, 'size' => $size, - 'error' => $error + 'error' => $error, ]); } $files[] = new UploadedFile([ @@ -258,7 +263,7 @@ class FileValidatorTest extends TestCase 'tempName' => $tempName, 'type' => $type, 'size' => $size, - 'error' => $error + 'error' => $error, ]); } @@ -278,7 +283,7 @@ class FileValidatorTest extends TestCase 'tempName' => $filePath, 'type' => FileHelper::getMimeType($filePath), 'size' => filesize($filePath), - 'error' => UPLOAD_ERR_OK + 'error' => UPLOAD_ERR_OK, ]); } @@ -390,7 +395,7 @@ class FileValidatorTest extends TestCase ['test.png', 'IMAGE/*'], ['test.txt', 'text/*'], ['test.xml', '*/xml'], - ['test.odt', 'application/vnd*'] + ['test.odt', 'application/vnd*'], ]; } diff --git a/tests/framework/validators/FilterValidatorTest.php b/tests/framework/validators/FilterValidatorTest.php index 9512c2f622..f0b25ab364 100644 --- a/tests/framework/validators/FilterValidatorTest.php +++ b/tests/framework/validators/FilterValidatorTest.php @@ -1,4 +1,9 @@ '', 'attr_empty2' => null, 'attr_array' => ['Maria', 'Anna', 'Elizabeth'], - 'attr_array_skipped' => ['John', 'Bill'] + 'attr_array_skipped' => ['John', 'Bill'], ]); $val = new FilterValidator(['filter' => 'trim']); $val->validateAttribute($m, 'attr_one'); @@ -48,8 +53,7 @@ class FilterValidatorTest extends TestCase $val->skipOnEmpty = true; $val->validateAttribute($m, 'attr_empty2'); $this->assertNotNull($m->attr_empty2); - $val->filter = function($value) { - + $val->filter = function ($value) { return implode(',', $value); }; $val->skipOnArray = false; diff --git a/tests/framework/validators/IpValidatorTest.php b/tests/framework/validators/IpValidatorTest.php index 54880f0bcb..118dc0b790 100644 --- a/tests/framework/validators/IpValidatorTest.php +++ b/tests/framework/validators/IpValidatorTest.php @@ -1,4 +1,10 @@ false, 'ipv6' => false]); } - public function provideRangesForSubstitution() { + public function provideRangesForSubstitution() + { return [ ['10.0.0.1', ['10.0.0.1']], [['192.168.0.32', 'fa::/32', 'any'], ['192.168.0.32', 'fa::/32', '0.0.0.0/0', '::/0']], [['10.0.0.1', '!private'], ['10.0.0.1', '!10.0.0.0/8', '!172.16.0.0/12', '!192.168.0.0/16', '!fd00::/8']], - [['private', '!system'], ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fd00::/8', '!224.0.0.0/4', '!ff00::/8', '!169.254.0.0/16', '!fe80::/10', '!127.0.0.0/8', '!::1', '!192.0.2.0/24', '!198.51.100.0/24', '!203.0.113.0/24', '!2001:db8::/32']] + [['private', '!system'], ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fd00::/8', '!224.0.0.0/4', '!ff00::/8', '!169.254.0.0/16', '!fe80::/10', '!127.0.0.0/8', '!::1', '!192.0.2.0/24', '!198.51.100.0/24', '!203.0.113.0/24', '!2001:db8::/32']], ]; } @@ -46,7 +53,7 @@ class IpValidatorTest extends TestCase public function testValidateOrder() { $validator = new IpValidator([ - 'ranges' => ['10.0.0.1', '!10.0.0.0/8', '!babe::/8', 'any'] + 'ranges' => ['10.0.0.1', '!10.0.0.0/8', '!babe::/8', 'any'], ]); $this->assertTrue($validator->validate('10.0.0.1')); @@ -56,7 +63,8 @@ class IpValidatorTest extends TestCase $this->assertFalse($validator->validate('babe::cafe')); } - public function provideBadIps() { + public function provideBadIps() + { return [['not.an.ip'], [['what an array', '??']], [123456], [true], [false], ['bad:forSure']]; } @@ -230,7 +238,7 @@ class IpValidatorTest extends TestCase public function testValidateRangeIPv4() { $validator = new IpValidator([ - 'ranges' => ['10.0.1.0/24'] + 'ranges' => ['10.0.1.0/24'], ]); $this->assertTrue($validator->validate('10.0.1.2')); $this->assertFalse($validator->validate('192.5.1.1')); @@ -255,7 +263,7 @@ class IpValidatorTest extends TestCase public function testValidateRangeIPv6() { $validator = new IpValidator([ - 'ranges' => '2001:db0:1:1::/64' + 'ranges' => '2001:db0:1:1::/64', ]); $this->assertTrue($validator->validate('2001:db0:1:1::6')); $this->assertFalse($validator->validate('2001:db0:1:2::7')); @@ -263,7 +271,7 @@ class IpValidatorTest extends TestCase $validator->ranges = ['2001:db0:1:2::/64']; $this->assertTrue($validator->validate('2001:db0:1:2::7')); - $validator->ranges = ['!2001:db0::/32', '2001:db0:1:2::/64', ]; + $validator->ranges = ['!2001:db0::/32', '2001:db0:1:2::/64']; $this->assertFalse($validator->validate('2001:db0:1:2::7')); $validator->subnet = null; diff --git a/tests/framework/validators/NumberValidatorTest.php b/tests/framework/validators/NumberValidatorTest.php index b4456a5fa9..af20efac79 100644 --- a/tests/framework/validators/NumberValidatorTest.php +++ b/tests/framework/validators/NumberValidatorTest.php @@ -1,4 +1,9 @@ assertTrue(is_string($val->message)); - $this->assertTrue(is_null($val->max)); + $val = new NumberValidator(); + $this->assertInternalType('string', $val->message); + $this->assertTrue($val->max === null); $val = new NumberValidator(['min' => -1, 'max' => 20, 'integerOnly' => true]); - $this->assertTrue(is_string($val->message)); - $this->assertTrue(is_string($val->tooSmall)); - $this->assertTrue(is_string($val->tooBig)); + $this->assertInternalType('string', $val->message); + $this->assertInternalType('string', $val->tooSmall); + $this->assertInternalType('string', $val->tooBig); } public function testValidateValueSimple() @@ -210,7 +215,6 @@ class NumberValidatorTest extends TestCase $model->attr_number = new \stdClass(); $val->validateAttribute($model, 'attr_number'); $this->assertTrue($model->hasErrors('attr_number')); - } public function testValidateAttributeWithLocaleWhereDecimalPointIsComma() @@ -234,7 +238,7 @@ class NumberValidatorTest extends TestCase { $val = new NumberValidator([ 'tooSmall' => '{attribute} is to small.', - 'min' => 5 + 'min' => 5, ]); $model = new FakedValidationModel(); $model->attr_number = 0; diff --git a/tests/framework/validators/RangeValidatorTest.php b/tests/framework/validators/RangeValidatorTest.php index f995740327..7990dd49ae 100644 --- a/tests/framework/validators/RangeValidatorTest.php +++ b/tests/framework/validators/RangeValidatorTest.php @@ -1,4 +1,9 @@ []]); - $this->assertTrue(is_string($val->message)); + $this->assertInternalType('string', $val->message); } public function testValidateValue() @@ -40,8 +45,8 @@ class RangeValidatorTest extends TestCase $this->assertFalse($val->validate(11)); $this->assertFalse($val->validate(5.5)); $this->assertTrue($val->validate(10)); - $this->assertTrue($val->validate("10")); - $this->assertTrue($val->validate("5")); + $this->assertTrue($val->validate('10')); + $this->assertTrue($val->validate('5')); } public function testValidateValueEmpty() @@ -63,7 +68,7 @@ class RangeValidatorTest extends TestCase $this->assertTrue($val->validate([6, 7, 8, 9, 10])); $this->assertFalse($val->validate([0, 1, 2])); $this->assertFalse($val->validate([10, 11, 12])); - $this->assertTrue($val->validate(["1", "2", "3", 4, 5, 6])); + $this->assertTrue($val->validate(['1', '2', '3', 4, 5, 6])); } public function testValidateValueStrict() @@ -72,17 +77,17 @@ class RangeValidatorTest extends TestCase $this->assertTrue($val->validate(1)); $this->assertTrue($val->validate(5)); $this->assertTrue($val->validate(10)); - $this->assertFalse($val->validate("1")); - $this->assertFalse($val->validate("10")); - $this->assertFalse($val->validate("5.5")); + $this->assertFalse($val->validate('1')); + $this->assertFalse($val->validate('10')); + $this->assertFalse($val->validate('5.5')); } public function testValidateArrayValueStrict() { $val = new RangeValidator(['range' => range(1, 10, 1), 'strict' => true]); $val->allowArray = true; - $this->assertFalse($val->validate(["1", "2", "3", "4", "5", "6"])); - $this->assertFalse($val->validate(["1", "2", "3", 4, 5, 6])); + $this->assertFalse($val->validate(['1', '2', '3', '4', '5', '6'])); + $this->assertFalse($val->validate(['1', '2', '3', 4, 5, 6])); } public function testValidateValueNot() @@ -93,8 +98,8 @@ class RangeValidatorTest extends TestCase $this->assertTrue($val->validate(11)); $this->assertTrue($val->validate(5.5)); $this->assertFalse($val->validate(10)); - $this->assertFalse($val->validate("10")); - $this->assertFalse($val->validate("5")); + $this->assertFalse($val->validate('10')); + $this->assertFalse($val->validate('5')); } public function testValidateAttribute() @@ -111,25 +116,24 @@ class RangeValidatorTest extends TestCase public function testValidateSubsetArrayable() { - // Test in array, values are arrays. IE: ['a'] in [['a'], ['b']] $val = new RangeValidator([ 'range' => [['a'], ['b']], - 'allowArray' => false + 'allowArray' => false, ]); $this->assertTrue($val->validate(['a'])); // Test in array, values are arrays. IE: ['a', 'b'] subset [['a', 'b', 'c'] $val = new RangeValidator([ 'range' => ['a', 'b', 'c'], - 'allowArray' => true + 'allowArray' => true, ]); $this->assertTrue($val->validate(['a', 'b'])); // Test in array, values are arrays. IE: ['a', 'b'] subset [['a', 'b', 'c'] $val = new RangeValidator([ 'range' => ['a', 'b', 'c'], - 'allowArray' => true + 'allowArray' => true, ]); $this->assertTrue($val->validate(new \ArrayObject(['a', 'b']))); @@ -137,10 +141,8 @@ class RangeValidatorTest extends TestCase // Test range as ArrayObject. $val = new RangeValidator([ 'range' => new \ArrayObject(['a', 'b']), - 'allowArray' => false + 'allowArray' => false, ]); $this->assertTrue($val->validate('a')); - - } } diff --git a/tests/framework/validators/RegularExpressionValidatorTest.php b/tests/framework/validators/RegularExpressionValidatorTest.php index bafb1bc36a..8c1939055a 100644 --- a/tests/framework/validators/RegularExpressionValidatorTest.php +++ b/tests/framework/validators/RegularExpressionValidatorTest.php @@ -1,4 +1,9 @@ '/^[a-zA-Z0-9](\.)?([^\/]*)$/m']); - $this->assertTrue(is_string($val->message)); + $this->assertInternalType('string', $val->message); } public function testInitException() diff --git a/tests/framework/validators/RequiredValidatorTest.php b/tests/framework/validators/RequiredValidatorTest.php index 6f43bff705..1d4fde051d 100644 --- a/tests/framework/validators/RequiredValidatorTest.php +++ b/tests/framework/validators/RequiredValidatorTest.php @@ -1,4 +1,10 @@ 55]); $this->assertTrue($val->validate(55)); - $this->assertTrue($val->validate("55")); - $this->assertFalse($val->validate("should fail")); + $this->assertTrue($val->validate('55')); + $this->assertFalse($val->validate('should fail')); $this->assertTrue($val->validate(true)); $val->strict = true; $this->assertTrue($val->validate(55)); - $this->assertFalse($val->validate("55")); - $this->assertFalse($val->validate("0x37")); - $this->assertFalse($val->validate("should fail")); + $this->assertFalse($val->validate('55')); + $this->assertFalse($val->validate('0x37')); + $this->assertFalse($val->validate('should fail')); $this->assertFalse($val->validate(true)); } diff --git a/tests/framework/validators/StringValidatorTest.php b/tests/framework/validators/StringValidatorTest.php index eadf4fa671..01e4045654 100644 --- a/tests/framework/validators/StringValidatorTest.php +++ b/tests/framework/validators/StringValidatorTest.php @@ -1,4 +1,9 @@ 1, 'max' => 2]); - $this->assertTrue(is_string($val->message)); - $this->assertTrue(is_string($val->tooLong)); - $this->assertTrue(is_string($val->tooShort)); + $this->assertInternalType('string', $val->message); + $this->assertInternalType('string', $val->tooLong); + $this->assertInternalType('string', $val->tooShort); } public function testCustomErrorMessageInValidateAttribute() diff --git a/tests/framework/validators/UniqueValidatorTest.php b/tests/framework/validators/UniqueValidatorTest.php index b6b6d6453a..2ceb40b32a 100644 --- a/tests/framework/validators/UniqueValidatorTest.php +++ b/tests/framework/validators/UniqueValidatorTest.php @@ -1,9 +1,14 @@ assertTrue(is_string($val->message)); + $this->assertInternalType('string', $val->message); } public function testCustomMessage() @@ -81,7 +86,7 @@ abstract class UniqueValidatorTest extends DatabaseTestCase $customerModel->clearErrors(); $customerModel->name = 'test data'; - $customerModel->email = ['email@mail.com', 'email2@mail.com',]; + $customerModel->email = ['email@mail.com', 'email2@mail.com']; $validator->targetAttribute = ['email', 'name']; $validator->validateAttribute($customerModel, 'name'); $this->assertEquals($messageError, $customerModel->getFirstError('name')); @@ -206,7 +211,7 @@ abstract class UniqueValidatorTest extends DatabaseTestCase // Check whether "Description" and "address" aren't equal $val = new UniqueValidator([ 'targetClass' => Customer::className(), - 'targetAttribute' => ['description'=>'address'], + 'targetAttribute' => ['description' => 'address'], ]); /** @var Profile $m */ @@ -235,7 +240,7 @@ abstract class UniqueValidatorTest extends DatabaseTestCase $validator = new UniqueValidator(); /** @var Profile $profileModel */ - $profileModel = new Profile(['description'=>'profile customer 1']); + $profileModel = new Profile(['description' => 'profile customer 1']); $validator->validateAttribute($profileModel, 'description'); $this->assertTrue($profileModel->hasErrors('description')); @@ -381,8 +386,8 @@ abstract class UniqueValidatorTest extends DatabaseTestCase $this->assertEquals($expected, $query->createCommand()->getSql()); $params = ['val_attr_b' => 'test value b']; - $query = $this->invokeMethod(new UniqueValidator(['filter' => function($query) { - $query->orWhere('val_attr_a > 0'); + $query = $this->invokeMethod(new UniqueValidator(['filter' => function ($query) { + $query->orWhere('val_attr_a > 0'); }]), 'prepareQuery', [$model, $params]); $expected = "SELECT * FROM {$schema->quoteTableName('validator_main')} WHERE ({$schema->quoteColumnName('val_attr_b')}=:qp0) OR (val_attr_a > 0)"; $this->assertEquals($expected, $query->createCommand()->getSql()); @@ -395,7 +400,7 @@ abstract class UniqueValidatorTest extends DatabaseTestCase public function testAmbiguousColumnName() { $validator = new UniqueValidator([ - 'filter' => function($query) { + 'filter' => function ($query) { $query->joinWith('items', false); }, ]); diff --git a/tests/framework/validators/UrlValidatorTest.php b/tests/framework/validators/UrlValidatorTest.php index 1448866300..3243e8bf38 100644 --- a/tests/framework/validators/UrlValidatorTest.php +++ b/tests/framework/validators/UrlValidatorTest.php @@ -1,9 +1,14 @@ assertFalse($val->validate('google.de')); $this->assertTrue($val->validate('http://google.de')); $this->assertTrue($val->validate('https://google.de')); $this->assertFalse($val->validate('htp://yiiframework.com')); $this->assertTrue($val->validate('https://www.google.de/search?q=yii+framework&ie=utf-8&oe=utf-8' - .'&rls=org.mozilla:de:official&client=firefox-a&gws_rd=cr')); + . '&rls=org.mozilla:de:official&client=firefox-a&gws_rd=cr')); $this->assertFalse($val->validate('ftp://ftp.ruhr-uni-bochum.de/')); $this->assertFalse($val->validate('http://invalid,domain')); $this->assertFalse($val->validate('http://example.com,')); @@ -96,25 +101,25 @@ class UrlValidatorTest extends TestCase public function testValidateLength() { $url = 'http://' . str_pad('base', 2000, 'url') . '.de'; - $val = new UrlValidator; + $val = new UrlValidator(); $this->assertFalse($val->validate($url)); } public function testValidateAttributeAndError() { - $obj = new FakedValidationModel; + $obj = new FakedValidationModel(); $obj->attr_url = 'http://google.de'; - $val = new UrlValidator; + $val = new UrlValidator(); $val->validateAttribute($obj, 'attr_url'); $this->assertFalse($obj->hasErrors('attr_url')); $this->assertSame('http://google.de', $obj->attr_url); - $obj = new FakedValidationModel; + $obj = new FakedValidationModel(); $val->defaultScheme = 'http'; $obj->attr_url = 'google.de'; $val->validateAttribute($obj, 'attr_url'); $this->assertFalse($obj->hasErrors('attr_url')); $this->assertNotFalse(stripos($obj->attr_url, 'http')); - $obj = new FakedValidationModel; + $obj = new FakedValidationModel(); $obj->attr_url = 'gttp;/invalid string'; $val->validateAttribute($obj, 'attr_url'); $this->assertTrue($obj->hasErrors('attr_url')); diff --git a/tests/framework/validators/ValidatorTest.php b/tests/framework/validators/ValidatorTest.php index 8e9dcbecd7..9ed2e10ccc 100644 --- a/tests/framework/validators/ValidatorTest.php +++ b/tests/framework/validators/ValidatorTest.php @@ -1,4 +1,9 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\framework\web; use Yii; use yii\helpers\FileHelper; -use yii\web\View; use yii\web\AssetBundle; use yii\web\AssetManager; +use yii\web\View; /** * @group web @@ -103,7 +103,7 @@ class AssetBundleTest extends \yiiunit\TestCase 'linkAssets' => true, 'hashCallback' => function ($path) { return sprintf('%x/%x', crc32($path), crc32(Yii::getVersion())); - } + }, ]); $bundle = $this->verifySourcesPublishedBySymlink($view); $this->assertTrue(is_dir(dirname($bundle->basePath))); @@ -114,7 +114,7 @@ class AssetBundleTest extends \yiiunit\TestCase $view = $this->getView([ 'beforeCopy' => function ($from, $to) { return false; - } + }, ]); $am = $view->assetManager; @@ -137,7 +137,7 @@ class AssetBundleTest extends \yiiunit\TestCase $bundle->publishOptions = [ 'beforeCopy' => function ($from, $to) { return false; - } + }, ]; $bundle->publish($am); @@ -156,8 +156,8 @@ class AssetBundleTest extends \yiiunit\TestCase $bundle = new TestSourceAsset([ 'publishOptions' => [ 'only' => [ - 'js/*' - ] + 'js/*', + ], ], ]); $bundle->publish($am); @@ -441,46 +441,46 @@ EOF; [ 'js', '@web/assetSources/js/missing-file1.js', true, '1234', - '/backend' + '/backend', ], [ 'js', 'http://full-url.example.com/backend/assetSources/js/missing-file.js', true, '1234', - '/backend' + '/backend', ], [ 'css', '//backend/backend/assetSources/js/missing-file.js', true, '1234', - '/backend' + '/backend', ], [ 'css', '@web/assetSources/css/stub.css', false, '1234', - '/en/blog/backend' + '/en/blog/backend', ], // UTF-8 chars [ 'css', '@web/assetSources/css/stub.css', false, '1234', - '/рус/сайт' + '/рус/сайт', ], [ 'js', '@web/assetSources/js/jquery.js', false, '1234', - '/汉语/漢語' + '/汉语/漢語', ], // Custom alias repeats in the asset URL [ 'css', '@web/assetSources/repeat/css/stub.css', false, '1234', - '/repeat' + '/repeat', ], [ 'js', '@web/assetSources/repeat/js/jquery.js', false, '1234', - '/repeat' + '/repeat', ], ]; } @@ -541,7 +541,7 @@ class TestAssetBundle extends AssetBundle 'jsFile.js', ]; public $depends = [ - 'yiiunit\\framework\\web\\TestJqueryAsset' + 'yiiunit\\framework\\web\\TestJqueryAsset', ]; } @@ -553,7 +553,7 @@ class TestJqueryAsset extends AssetBundle 'jquery.js', ]; public $depends = [ - 'yiiunit\\framework\\web\\TestAssetLevel3' + 'yiiunit\\framework\\web\\TestAssetLevel3', ]; } @@ -571,7 +571,7 @@ class TestAssetCircleA extends AssetBundle 'jquery.js', ]; public $depends = [ - 'yiiunit\\framework\\web\\TestAssetCircleB' + 'yiiunit\\framework\\web\\TestAssetCircleB', ]; } @@ -583,7 +583,7 @@ class TestAssetCircleB extends AssetBundle 'jquery.js', ]; public $depends = [ - 'yiiunit\\framework\\web\\TestAssetCircleA' + 'yiiunit\\framework\\web\\TestAssetCircleA', ]; } @@ -594,7 +594,7 @@ class TestAssetPerFileOptions extends AssetBundle public $css = [ 'default_options.css', ['tv.css', 'media' => 'tv'], - ['screen_and_print.css', 'media' => 'screen, print'] + ['screen_and_print.css', 'media' => 'screen, print'], ]; public $js = [ 'normal.js', diff --git a/tests/framework/web/AssetConverterTest.php b/tests/framework/web/AssetConverterTest.php index 97fe56e91e..aa47c8890e 100644 --- a/tests/framework/web/AssetConverterTest.php +++ b/tests/framework/web/AssetConverterTest.php @@ -1,6 +1,8 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\framework\web; diff --git a/tests/framework/web/CacheSessionTest.php b/tests/framework/web/CacheSessionTest.php index 3cb9383a26..c73a960e02 100644 --- a/tests/framework/web/CacheSessionTest.php +++ b/tests/framework/web/CacheSessionTest.php @@ -1,4 +1,9 @@ controller, 'actionAksi1'); $params = ['fromGet' => 'from query params', 'q' => 'd426', 'validator' => 'avaliable']; @@ -32,7 +30,6 @@ class ControllerTest extends TestCase list($fromGet, $other) = $this->controller->bindActionParams($aksi1, $params); $this->assertEquals('from query params', $fromGet); $this->assertEquals('avaliable', $other); - } public function testAsJson() @@ -76,7 +73,6 @@ class ControllerTest extends TestCase $this->assertEquals($this->controller->redirect(['//controller/index', 'id' => 3])->headers->get('location'), '/index.php?r=controller%2Findex&id=3'); $this->assertEquals($this->controller->redirect(['//controller/index', 'id_1' => 3, 'id_2' => 4])->headers->get('location'), '/index.php?r=controller%2Findex&id_1=3&id_2=4'); $this->assertEquals($this->controller->redirect(['//controller/index', 'slug' => 'äöüß!"§$%&/()'])->headers->get('location'), '/index.php?r=controller%2Findex&slug=%C3%A4%C3%B6%C3%BC%C3%9F%21%22%C2%A7%24%25%26%2F%28%29'); - } protected function setUp() @@ -92,9 +88,8 @@ class ControllerTest extends TestCase 'scriptFile' => __DIR__ . '/index.php', 'scriptUrl' => '/index.php', ], - ] + ], ])); $this->mockWebApplication(['controller' => $this->controller]); } - } diff --git a/tests/framework/web/DbSessionTest.php b/tests/framework/web/DbSessionTest.php index eefc0ad5b8..0702e04856 100644 --- a/tests/framework/web/DbSessionTest.php +++ b/tests/framework/web/DbSessionTest.php @@ -1,4 +1,9 @@ writeCallback = function ($session) { return [ - 'user_id' => 15 + 'user_id' => 15, ]; }; @@ -113,7 +118,7 @@ class DbSessionTest extends TestCase $migrate->run($action, $params); ob_get_clean(); - return array_map(function($version) { + return array_map(function ($version) { return substr($version, 15); }, (new Query())->select(['version'])->from('migration')->column()); } @@ -125,7 +130,7 @@ class DbSessionTest extends TestCase 'db' => [ 'class' => Connection::className(), 'dsn' => 'sqlite::memory:', - ] + ], ], ]); @@ -133,7 +138,7 @@ class DbSessionTest extends TestCase $this->assertEquals(['base'], $history); $history = $this->runMigrate('up'); - $this->assertEquals(['base','session_init'], $history); + $this->assertEquals(['base', 'session_init'], $history); $history = $this->runMigrate('down'); $this->assertEquals(['base'], $history); diff --git a/tests/framework/web/ErrorActionTest.php b/tests/framework/web/ErrorActionTest.php index f6e57f2151..9cd82ce8a8 100644 --- a/tests/framework/web/ErrorActionTest.php +++ b/tests/framework/web/ErrorActionTest.php @@ -1,4 +1,9 @@ getController()->runAction('error') $controller = $this->getController([ 'defaultName' => 'Oops...', - 'defaultMessage' => 'The system is drunk' + 'defaultMessage' => 'The system is drunk', ]); $this->assertEquals('Name: Oops... @@ -103,8 +108,6 @@ Exception: yii\web\NotFoundHttpException', $this->getController()->runAction('er $this->expectExceptionMessageRegExp('#The view file does not exist: .*?views' . $ds . 'test' . $ds . 'error.php#'); $this->invokeMethod($action, 'renderHtmlResponse'); } - - } class TestController extends Controller diff --git a/tests/framework/web/ErrorHandlerTest.php b/tests/framework/web/ErrorHandlerTest.php index 2cdd1deb2a..4077efbca0 100644 --- a/tests/framework/web/ErrorHandlerTest.php +++ b/tests/framework/web/ErrorHandlerTest.php @@ -1,4 +1,9 @@ getErrorHandler(); - ob_start(); // suppress response output + ob_start(); // suppress response output $this->invokeMethod($handler, 'renderException', [new NotFoundHttpException('This message is displayed to end user')]); - ob_get_clean(); - $out = Yii::$app->response->data; - $this->assertEquals('Code: 404 + ob_get_clean(); + $out = Yii::$app->response->data; + $this->assertEquals('Code: 404 Message: This message is displayed to end user Exception: yii\web\NotFoundHttpException', $out); - } + } } class ErrorHandler extends \yii\web\ErrorHandler @@ -44,4 +49,4 @@ class ErrorHandler extends \yii\web\ErrorHandler { return false; } -} \ No newline at end of file +} diff --git a/tests/framework/web/FakeController.php b/tests/framework/web/FakeController.php index 6bd920281e..572d169e5b 100644 --- a/tests/framework/web/FakeController.php +++ b/tests/framework/web/FakeController.php @@ -20,5 +20,4 @@ class FakeController extends Controller public function actionAksi1($fromGet, $other = 'default') { } - } diff --git a/tests/framework/web/FormatterTest.php b/tests/framework/web/FormatterTest.php index b67052b596..abaa04b1d8 100644 --- a/tests/framework/web/FormatterTest.php +++ b/tests/framework/web/FormatterTest.php @@ -1,5 +1,9 @@ mockApplication(); - $this->response = new Response; + $this->response = new Response(); $this->formatter = $this->getFormatterInstance(); } @@ -36,7 +40,7 @@ abstract class FormatterTest extends \yiiunit\TestCase { $this->response->data = null; $this->formatter->format($this->response); - $this->assertEquals(null, $this->response->content); + $this->assertNull($this->response->content); } /** diff --git a/tests/framework/web/GroupUrlRuleTest.php b/tests/framework/web/GroupUrlRuleTest.php index 414e16a65a..138eeafd18 100644 --- a/tests/framework/web/GroupUrlRuleTest.php +++ b/tests/framework/web/GroupUrlRuleTest.php @@ -1,10 +1,15 @@ null]); $suites = $this->getTestsForCreateUrl(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new GroupUrlRule($config); foreach ($tests as $j => $test) { - list ($route, $params, $expected, $status) = $test; + list($route, $params, $expected, $status) = $test; $url = $rule->createUrl($manager, $route, $params); $this->assertEquals($expected, $url, "Test#$i-$j: $name"); $this->assertSame($status, $rule->getCreateUrlStatus(), "Test#$i-$j: $name"); @@ -41,7 +46,7 @@ class GroupUrlRuleTest extends TestCase $request = new Request(['hostInfo' => 'http://en.example.com']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new GroupUrlRule($config); foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; @@ -120,7 +125,7 @@ class GroupUrlRuleTest extends TestCase 'routePrefix' => 'admin', 'ruleConfig' => [ 'suffix' => '.html', - 'class' => 'yii\\web\\UrlRule' + 'class' => 'yii\\web\\UrlRule', ], 'rules' => [ 'login' => 'user/login', @@ -140,7 +145,7 @@ class GroupUrlRuleTest extends TestCase 'routePrefix' => 'admin', 'ruleConfig' => [ 'suffix' => '.html', - 'class' => 'yii\web\UrlRule' + 'class' => 'yii\web\UrlRule', ], 'rules' => [ 'login' => 'user/login', @@ -158,7 +163,7 @@ class GroupUrlRuleTest extends TestCase [ [ 'admin/user/logout', [], false, - UrlRule::CREATE_STATUS_PARSING_ONLY | UrlRule::CREATE_STATUS_ROUTE_MISMATCH | UrlRule::CREATE_STATUS_PARAMS_MISMATCH + UrlRule::CREATE_STATUS_PARSING_ONLY | UrlRule::CREATE_STATUS_ROUTE_MISMATCH | UrlRule::CREATE_STATUS_PARAMS_MISMATCH, ], ], ], @@ -229,7 +234,7 @@ class GroupUrlRuleTest extends TestCase 'routePrefix' => 'admin', 'ruleConfig' => [ 'suffix' => '.html', - 'class' => 'yii\\web\\UrlRule' + 'class' => 'yii\\web\\UrlRule', ], 'rules' => [ 'login' => 'user/login', diff --git a/tests/framework/web/JsonResponseFormatterTest.php b/tests/framework/web/JsonResponseFormatterTest.php index 89f75f90eb..07a1c1d072 100644 --- a/tests/framework/web/JsonResponseFormatterTest.php +++ b/tests/framework/web/JsonResponseFormatterTest.php @@ -32,7 +32,7 @@ class JsonResponseFormatterTest extends FormatterTest [1, 1], ['abc', '"abc"'], [true, 'true'], - ["<>", '"<>"'], + ['<>', '"<>"'], ]; } @@ -40,25 +40,36 @@ class JsonResponseFormatterTest extends FormatterTest { return [ // input, json, pretty json - [[], "[]", "[]"], + [[], '[]', '[]'], [[1, 'abc'], '[1,"abc"]', "[\n 1,\n \"abc\"\n]"], - [[ - 'a' => 1, - 'b' => 'abc', - ], '{"a":1,"b":"abc"}', "{\n \"a\": 1,\n \"b\": \"abc\"\n}"], - [[ - 1, - 'abc', - [2, 'def'], - true, - ], '[1,"abc",[2,"def"],true]', "[\n 1,\n \"abc\",\n [\n 2,\n \"def\"\n ],\n true\n]"], - [[ - 'a' => 1, - 'b' => 'abc', - 'c' => [2, '<>'], - true, - ], '{"a":1,"b":"abc","c":[2,"<>"],"0":true}', - "{\n \"a\": 1,\n \"b\": \"abc\",\n \"c\": [\n 2,\n \"<>\"\n ],\n \"0\": true\n}"], + [ + [ + 'a' => 1, + 'b' => 'abc', + ], + '{"a":1,"b":"abc"}', + "{\n \"a\": 1,\n \"b\": \"abc\"\n}", + ], + [ + [ + 1, + 'abc', + [2, 'def'], + true, + ], + '[1,"abc",[2,"def"],true]', + "[\n 1,\n \"abc\",\n [\n 2,\n \"def\"\n ],\n true\n]", + ], + [ + [ + 'a' => 1, + 'b' => 'abc', + 'c' => [2, '<>'], + true, + ], + '{"a":1,"b":"abc","c":[2,"<>"],"0":true}', + "{\n \"a\": 1,\n \"b\": \"abc\",\n \"c\": [\n 2,\n \"<>\"\n ],\n \"0\": true\n}", + ], ]; } @@ -84,14 +95,14 @@ class JsonResponseFormatterTest extends FormatterTest $postsStack->push(new Post(456, 'record2')); return [ - [$postsStack, '{"1":{"id":456,"title":"record2"},"0":{"id":915,"title":"record1"}}'] + [$postsStack, '{"1":{"id":456,"title":"record2"},"0":{"id":915,"title":"record1"}}'], ]; } public function formatModelDataProvider() { return [ - [new ModelStub(['id' => 123, 'title' => 'abc', 'hidden' => 'hidden']), '{"id":123,"title":"abc"}'] + [new ModelStub(['id' => 123, 'title' => 'abc', 'hidden' => 'hidden']), '{"id":123,"title":"abc"}'], ]; } @@ -108,5 +119,4 @@ class JsonResponseFormatterTest extends FormatterTest $this->formatter->format($this->response); $this->assertEquals($prettyJson, $this->response->content); } - } diff --git a/tests/framework/web/MultipartFormDataParserTest.php b/tests/framework/web/MultipartFormDataParserTest.php index 3f9e867b4d..68375eb9a4 100644 --- a/tests/framework/web/MultipartFormDataParserTest.php +++ b/tests/framework/web/MultipartFormDataParserTest.php @@ -1,4 +1,9 @@ 'test-title', 'Item' => [ - 'name' => 'test-name' - ] + 'name' => 'test-name', + ], ]; $this->assertEquals($expectedBodyParams, $bodyParams); @@ -55,7 +60,7 @@ class MultipartFormDataParserTest extends TestCase $parser = new MultipartFormDataParser(); $_POST = [ - 'name' => 'value' + 'name' => 'value', ]; $bodyParams = $parser->parse('should not matter', 'multipart/form-data; boundary=---12345'); @@ -74,7 +79,7 @@ class MultipartFormDataParserTest extends TestCase 'file' => [ 'name' => 'file.txt', 'type' => 'text/plain', - ] + ], ]; $boundary = '---------------------------22472926011618'; @@ -123,4 +128,4 @@ class MultipartFormDataParserTest extends TestCase $this->assertCount(3, $_FILES); $this->assertEquals(UPLOAD_ERR_INI_SIZE, $_FILES['thirdFile']['error']); } -} \ No newline at end of file +} diff --git a/tests/framework/web/Post.php b/tests/framework/web/Post.php index d6ebc68525..0f27868e9d 100644 --- a/tests/framework/web/Post.php +++ b/tests/framework/web/Post.php @@ -1,4 +1,10 @@ id = $id; $this->title = $title; } -} \ No newline at end of file +} diff --git a/tests/framework/web/RequestTest.php b/tests/framework/web/RequestTest.php index 667f7d7808..c8e765e9fd 100644 --- a/tests/framework/web/RequestTest.php +++ b/tests/framework/web/RequestTest.php @@ -17,7 +17,7 @@ class RequestTest extends TestCase { public function testParseAcceptHeader() { - $request = new Request; + $request = new Request(); $this->assertEquals([], $request->parseAcceptHeader(' ')); @@ -149,7 +149,6 @@ class RequestTest extends TestCase $request->setBodyParams([$request->csrfParam => $token]); $this->assertTrue($request->validateCsrfToken()); } - } /** @@ -179,7 +178,6 @@ class RequestTest extends TestCase $request->headers->add(Request::CSRF_HEADER, $token); $this->assertTrue($request->validateCsrfToken()); } - } public function testResolve() @@ -194,8 +192,8 @@ class RequestTest extends TestCase 'posts' => 'post/list', 'post/' => 'post/view', ], - ] - ] + ], + ], ]); $request = new Request(); diff --git a/tests/framework/web/ResponseTest.php b/tests/framework/web/ResponseTest.php index edfe1700f1..902fac3ce6 100644 --- a/tests/framework/web/ResponseTest.php +++ b/tests/framework/web/ResponseTest.php @@ -1,10 +1,15 @@ mockWebApplication(); - $this->response = new \yii\web\Response; + $this->response = new \yii\web\Response(); } public function rightRanges() @@ -51,8 +56,8 @@ class ResponseTest extends \yiiunit\TestCase $this->assertEquals($expectedContent, $content); $this->assertEquals(206, $this->response->statusCode); $headers = $this->response->headers; - $this->assertEquals("bytes", $headers->get('Accept-Ranges')); - $this->assertEquals("bytes " . $expectedHeader . '/' . StringHelper::byteLength($fullContent), $headers->get('Content-Range')); + $this->assertEquals('bytes', $headers->get('Accept-Ranges')); + $this->assertEquals('bytes ' . $expectedHeader . '/' . StringHelper::byteLength($fullContent), $headers->get('Content-Range')); $this->assertEquals('text/plain', $headers->get('Content-Type')); $this->assertEquals("$length", $headers->get('Content-Length')); } @@ -62,10 +67,10 @@ class ResponseTest extends \yiiunit\TestCase // TODO test more cases for range requests and check for rfc compatibility // http://www.w3.org/Protocols/rfc2616/rfc2616.txt return [ - ['1-2,3-5,6-10'], // multiple range request not supported - ['5-1'], // last-byte-pos value is less than its first-byte-pos value - ['-100000'], // last-byte-pos bigger then content length - ['10000-'], // first-byte-pos bigger then content length + ['1-2,3-5,6-10'], // multiple range request not supported + ['5-1'], // last-byte-pos value is less than its first-byte-pos value + ['-100000'], // last-byte-pos bigger then content length + ['10000-'], // first-byte-pos bigger then content length ]; } @@ -93,7 +98,7 @@ class ResponseTest extends \yiiunit\TestCase { ob_start(); $this->response->sendContentAsFile('test', 'test.txt')->send([ - 'mimeType' => 'text/plain' + 'mimeType' => 'text/plain', ]); $content = ob_get_clean(); @@ -124,7 +129,6 @@ class ResponseTest extends \yiiunit\TestCase /** * @dataProvider dataProviderSetStatusCodeByException - * */ public function testSetStatusCodeByException($exception, $statusCode) { diff --git a/tests/framework/web/SessionTest.php b/tests/framework/web/SessionTest.php index 370d1aa2d9..c5d353dd06 100644 --- a/tests/framework/web/SessionTest.php +++ b/tests/framework/web/SessionTest.php @@ -1,4 +1,9 @@ md5(mt_rand()), 'type' => 'image/jpeg', 'size' => mt_rand(1000, 10000), - 'error' => 0 + 'error' => 0, ]; } @@ -67,4 +72,4 @@ class UploadedFileTest extends TestCase $this->assertInstanceOf(VendorImage::className(), $vendorImage); } } -} \ No newline at end of file +} diff --git a/tests/framework/web/UrlManagerCreateUrlTest.php b/tests/framework/web/UrlManagerCreateUrlTest.php index 004db57c42..0c0cf04267 100644 --- a/tests/framework/web/UrlManagerCreateUrlTest.php +++ b/tests/framework/web/UrlManagerCreateUrlTest.php @@ -1,4 +1,9 @@ '', 'route' => 'site/index', 'defaults' => [ - 'language' => 'en' + 'language' => 'en', ], ], ]; @@ -434,7 +439,7 @@ class UrlManagerCreateUrlTest extends TestCase */ public function testWithEmptyPattern($method, $showScriptName, $prefix, $config) { - $assertations = function($manager) use ($method, $prefix) { + $assertations = function ($manager) use ($method, $prefix) { // match first rule $url = $manager->$method(['front/site/index']); $this->assertEquals("$prefix/", $url); @@ -551,7 +556,6 @@ class UrlManagerCreateUrlTest extends TestCase $this->assertEquals("$prefix/post/index?page=1#testhash", $manager->createUrl($urlParams)); $expected = "http://www.example.com$prefix/post/index?page=1#testhash"; $this->assertEquals($expected, $manager->createAbsoluteUrl($urlParams)); - } /** @@ -754,5 +758,4 @@ class UrlManagerCreateUrlTest extends TestCase $this->assertEquals(2, $rules[0]->createCounter); $this->assertEquals(1, $rules[1]->createCounter); } - } diff --git a/tests/framework/web/UrlManagerParseUrlTest.php b/tests/framework/web/UrlManagerParseUrlTest.php index 805b5c20d1..439e65974e 100644 --- a/tests/framework/web/UrlManagerParseUrlTest.php +++ b/tests/framework/web/UrlManagerParseUrlTest.php @@ -1,4 +1,9 @@ getUrlManager($config); // matching pathinfo - $result = $manager->parseRequest($this->getRequest("book/123/this+is+sample")); + $result = $manager->parseRequest($this->getRequest('book/123/this+is+sample')); $this->assertFalse($result); $result = $manager->parseRequest($this->getRequest("book/123/this+is+sample$suffix")); $this->assertEquals(['book/view', ['id' => '123', 'title' => 'this+is+sample']], $result); // trailing slash is significant, no match - $result = $manager->parseRequest($this->getRequest("book/123/this+is+sample/")); + $result = $manager->parseRequest($this->getRequest('book/123/this+is+sample/')); if ($suffix === '/') { $this->assertEquals(['book/view', ['id' => '123', 'title' => 'this+is+sample']], $result); } else { @@ -224,12 +229,12 @@ class UrlManagerParseUrlTest extends TestCase $result = $manager->parseRequest($this->getRequest('')); $this->assertEquals(['', []], $result); // normal pathinfo - $result = $manager->parseRequest($this->getRequest("site/index")); + $result = $manager->parseRequest($this->getRequest('site/index')); $this->assertFalse($result); $result = $manager->parseRequest($this->getRequest("site/index$suffix")); $this->assertEquals(['site/index', []], $result); // pathinfo with module - $result = $manager->parseRequest($this->getRequest("module/site/index")); + $result = $manager->parseRequest($this->getRequest('module/site/index')); $this->assertFalse($result); $result = $manager->parseRequest($this->getRequest("module/site/index$suffix")); $this->assertEquals(['module/site/index', []], $result); @@ -252,12 +257,12 @@ class UrlManagerParseUrlTest extends TestCase $manager->enableStrictParsing = true; // matching pathinfo - $result = $manager->parseRequest($this->getRequest("book/123/this+is+sample")); + $result = $manager->parseRequest($this->getRequest('book/123/this+is+sample')); $this->assertFalse($result); $result = $manager->parseRequest($this->getRequest("book/123/this+is+sample$suffix")); $this->assertEquals(['book/view', ['id' => '123', 'title' => 'this+is+sample']], $result); // trailing slash is significant, no match - $result = $manager->parseRequest($this->getRequest("book/123/this+is+sample/")); + $result = $manager->parseRequest($this->getRequest('book/123/this+is+sample/')); if ($suffix === '/') { $this->assertEquals(['book/view', ['id' => '123', 'title' => 'this+is+sample']], $result); } else { @@ -269,12 +274,12 @@ class UrlManagerParseUrlTest extends TestCase $result = $manager->parseRequest($this->getRequest('')); $this->assertFalse($result); // normal pathinfo - $result = $manager->parseRequest($this->getRequest("site/index")); + $result = $manager->parseRequest($this->getRequest('site/index')); $this->assertFalse($result); $result = $manager->parseRequest($this->getRequest("site/index$suffix")); $this->assertFalse($result); // pathinfo with module - $result = $manager->parseRequest($this->getRequest("module/site/index")); + $result = $manager->parseRequest($this->getRequest('module/site/index')); $this->assertFalse($result); $result = $manager->parseRequest($this->getRequest("module/site/index$suffix")); $this->assertFalse($result); @@ -288,7 +293,7 @@ class UrlManagerParseUrlTest extends TestCase public function testParseRESTRequest() { - $request = new Request; + $request = new Request(); // pretty URL rules $manager = new UrlManager([ @@ -328,16 +333,13 @@ class UrlManagerParseUrlTest extends TestCase 'components' => [ 'request' => [ 'hostInfo' => 'http://localhost/', - 'baseUrl' => '/app' - ] - ] + 'baseUrl' => '/app', + ], + ], ], \yii\web\Application::className()); $this->assertEquals('/app/post/delete?id=123', $manager->createUrl(['post/delete', 'id' => 123])); $this->destroyApplication(); unset($_SERVER['REQUEST_METHOD']); } - - - -} \ No newline at end of file +} diff --git a/tests/framework/web/UrlManagerTest.php b/tests/framework/web/UrlManagerTest.php index 9993ea0824..ee5f8b7c6c 100644 --- a/tests/framework/web/UrlManagerTest.php +++ b/tests/framework/web/UrlManagerTest.php @@ -1,4 +1,10 @@ mockApplication(); - Yii::$app->set('request', function() { + Yii::$app->set('request', function () { $this->fail('Request component should not be accessed by UrlManager with current settings.'); }); @@ -214,7 +220,7 @@ class UrlManagerTest extends TestCase public function testParseRequest($routeParam) { $manager = $this->getUrlManager(['routeParam' => $routeParam]); - $request = new Request; + $request = new Request(); // default setting without 'r' param $request->setQueryParams([]); diff --git a/tests/framework/web/UrlRuleTest.php b/tests/framework/web/UrlRuleTest.php index 2e9846adbb..69bcfacb54 100644 --- a/tests/framework/web/UrlRuleTest.php +++ b/tests/framework/web/UrlRuleTest.php @@ -1,15 +1,20 @@ null]); $suites = $this->getTestsForCreateUrl(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new UrlRule($config); foreach ($tests as $j => $test) { - list ($route, $params, $expected) = $test; + list($route, $params, $expected) = $test; $url = $rule->createUrl($manager, $route, $params); $this->assertSame($expected, $url, "Test#$i-$j: $name"); } @@ -47,7 +52,7 @@ class UrlRuleTest extends TestCase $request = new Request(['hostInfo' => 'http://en.example.com']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new UrlRule($config); foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; @@ -71,7 +76,7 @@ class UrlRuleTest extends TestCase $request = new Request(['hostInfo' => 'http://en.example.com']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new UrlRule($config); foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; @@ -102,7 +107,7 @@ class UrlRuleTest extends TestCase $request = new Request(['hostInfo' => 'http://en.example.com']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new UrlRule($config); foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; @@ -131,7 +136,7 @@ class UrlRuleTest extends TestCase $request = new Request(['hostInfo' => 'http://en.example.com']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new UrlRule($config); foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; @@ -160,7 +165,7 @@ class UrlRuleTest extends TestCase $request = new Request(['hostInfo' => 'http://en.example.com']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new UrlRule($config); foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; @@ -188,7 +193,7 @@ class UrlRuleTest extends TestCase $request = new Request(['hostInfo' => 'http://en.example.com']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new UrlRule($config); foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; @@ -217,7 +222,7 @@ class UrlRuleTest extends TestCase $request = new Request(['hostInfo' => 'http://en.example.com']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new UrlRule($config); foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; @@ -278,7 +283,7 @@ class UrlRuleTest extends TestCase { $suites = $this->getTestsForToString(); foreach ($suites as $i => $suite) { - list ($name, $config, $test) = $suite; + list($name, $config, $test) = $suite; $rule = new UrlRule($config); $this->assertEquals($rule->__toString(), $test, "Test#$i: $name"); } @@ -494,7 +499,7 @@ class UrlRuleTest extends TestCase 'pattern' => '', 'route' => 'page/view', 'defaults' => ['page' => 'index'], - 'suffix' => '/' + 'suffix' => '/', ], [ ['page/view', ['page' => 'index'], ''], @@ -1236,7 +1241,7 @@ class UrlRuleTest extends TestCase 'pattern' => '', 'route' => 'post/index', ], - '/' + '/', ], [ 'multiple params with special chars', @@ -1244,7 +1249,7 @@ class UrlRuleTest extends TestCase 'pattern' => 'post///', 'route' => 'post/index', ], - 'post///' + 'post///', ], [ 'with host info', @@ -1254,7 +1259,7 @@ class UrlRuleTest extends TestCase 'defaults' => ['page' => 1], 'host' => 'http://.example.com', ], - 'http://.example.com/post//' + 'http://.example.com/post//', ], [ 'with host info in pattern', @@ -1263,28 +1268,26 @@ class UrlRuleTest extends TestCase 'route' => 'post/index', 'defaults' => ['page' => 1], ], - 'http://.example.com/post//' + 'http://.example.com/post//', ], [ 'with verb', [ 'verb' => ['POST'], 'pattern' => 'post/', - 'route' => 'post/index' + 'route' => 'post/index', ], - 'POST post/' + 'POST post/', ], [ 'with verbs', [ 'verb' => ['PUT', 'POST'], 'pattern' => 'post/', - 'route' => 'post/index' + 'route' => 'post/index', ], - 'PUT,POST post/' + 'PUT,POST post/', ], - - ]; } diff --git a/tests/framework/web/UserTest.php b/tests/framework/web/UserTest.php index 0b2e4db112..9880566fd1 100644 --- a/tests/framework/web/UserTest.php +++ b/tests/framework/web/UserTest.php @@ -1,5 +1,9 @@ '@runtime/user_test_rbac_items.php', 'assignmentFile' => '@runtime/user_test_rbac_assignments.php', 'ruleFile' => '@runtime/user_test_rbac_rules.php', - ] + ], ], ]; $this->mockWebApplication($appConfig); @@ -91,7 +95,6 @@ class UserTest extends TestCase $this->mockWebApplication($appConfig); $this->assertTrue(Yii::$app->user->isGuest); $this->assertFalse(Yii::$app->user->can('doSomething')); - } public function testCookieCleanup() @@ -124,12 +127,12 @@ class UserTest extends TestCase Yii::$app->user->getIdentity(); $this->assertEquals(strlen($cookiesMock->getValue(Yii::$app->user->identityCookie['name'])), 0); - Yii::$app->user->login(UserIdentity::findIdentity('user1'),3600); + Yii::$app->user->login(UserIdentity::findIdentity('user1'), 3600); $this->assertFalse(Yii::$app->user->isGuest); $this->assertSame(Yii::$app->user->id, 'user1'); $this->assertNotEquals(strlen($cookiesMock->getValue(Yii::$app->user->identityCookie['name'])), 0); - Yii::$app->user->login(UserIdentity::findIdentity('user2'),0); + Yii::$app->user->login(UserIdentity::findIdentity('user2'), 0); $this->assertFalse(Yii::$app->user->isGuest); $this->assertSame(Yii::$app->user->id, 'user2'); $this->assertEquals(strlen($cookiesMock->getValue(Yii::$app->user->identityCookie['name'])), 0); @@ -150,9 +153,9 @@ class UserTest extends TestCase Yii::$app->set('response', ['class' => 'yii\web\Response']); Yii::$app->set('request', [ 'class' => 'yii\web\Request', - 'scriptFile' => __DIR__ .'/index.php', + 'scriptFile' => __DIR__ . '/index.php', 'scriptUrl' => '/index.php', - 'url' => '' + 'url' => '', ]); Yii::$app->user->setReturnUrl(null); } @@ -168,7 +171,7 @@ class UserTest extends TestCase 'itemFile' => '@runtime/user_test_rbac_items.php', 'assignmentFile' => '@runtime/user_test_rbac_assignments.php', 'ruleFile' => '@runtime/user_test_rbac_rules.php', - ] + ], ], ]; $this->mockWebApplication($appConfig); @@ -222,7 +225,8 @@ class UserTest extends TestCase $_SERVER['HTTP_ACCEPT'] = 'text/json, */*; q=0.1'; try { $user->loginRequired(); - } catch (ForbiddenHttpException $e) {} + } catch (ForbiddenHttpException $e) { + } $this->assertFalse(Yii::$app->response->getIsRedirection()); $this->reset(); @@ -259,7 +263,8 @@ class UserTest extends TestCase $_SERVER['HTTP_ACCEPT'] = 'text/json;q=0.1'; try { $user->loginRequired(); - } catch (ForbiddenHttpException $e) {} + } catch (ForbiddenHttpException $e) { + } $this->assertNotEquals('json-only', $user->getReturnUrl()); $this->reset(); @@ -280,7 +285,7 @@ class UserTest extends TestCase 'itemFile' => '@runtime/user_test_rbac_items.php', 'assignmentFile' => '@runtime/user_test_rbac_assignments.php', 'ruleFile' => '@runtime/user_test_rbac_rules.php', - ] + ], ], ]; @@ -290,7 +295,6 @@ class UserTest extends TestCase $this->expectException('yii\\web\\ForbiddenHttpException'); Yii::$app->user->loginRequired(); } - } class UserIdentity extends Component implements IdentityInterface @@ -342,7 +346,7 @@ class MockRequest extends \yii\web\Request global $cookiesMock; return $cookiesMock; - } + } } class MockResponse extends \yii\web\Response diff --git a/tests/framework/web/ViewTest.php b/tests/framework/web/ViewTest.php index d780526fd9..9064352e62 100644 --- a/tests/framework/web/ViewTest.php +++ b/tests/framework/web/ViewTest.php @@ -1,4 +1,9 @@ mockWebApplication([ 'components' => [ 'request' => [ - 'scriptFile' => __DIR__ .'/baseUrl/index.php', + 'scriptFile' => __DIR__ . '/baseUrl/index.php', 'scriptUrl' => '/baseUrl/index.php', - ] - ] + ], + ], ]); $view = new View(); @@ -34,7 +39,7 @@ class ViewTest extends TestCase $view = new View(); $view->registerJsFile('@web/js/somefile.js', ['position' => View::POS_BEGIN]); $html = $view->render('@yiiunit/data/views/layout.php', ['content' => 'content']); - $this->assertContains(''."\n".'', $html); + $this->assertContains('' . "\n" . '', $html); $view = new View(); $view->registerJsFile('@web/js/somefile.js', ['position' => View::POS_END]); @@ -47,10 +52,10 @@ class ViewTest extends TestCase $this->mockWebApplication([ 'components' => [ 'request' => [ - 'scriptFile' => __DIR__ .'/baseUrl/index.php', + 'scriptFile' => __DIR__ . '/baseUrl/index.php', 'scriptUrl' => '/baseUrl/index.php', - ] - ] + ], + ], ]); $view = new View(); @@ -58,5 +63,4 @@ class ViewTest extends TestCase $html = $view->render('@yiiunit/data/views/layout.php', ['content' => 'content']); $this->assertContains('', $html); } - -} \ No newline at end of file +} diff --git a/tests/framework/web/XmlResponseFormatterTest.php b/tests/framework/web/XmlResponseFormatterTest.php index 046f2bbf18..6d07b3029d 100644 --- a/tests/framework/web/XmlResponseFormatterTest.php +++ b/tests/framework/web/XmlResponseFormatterTest.php @@ -44,7 +44,7 @@ class XmlResponseFormatterTest extends FormatterTest ['abc', "abc\n"], [true, "true\n"], [false, "false\n"], - ["<>", "<>\n"], + ['<>', "<>\n"], ]); } @@ -77,7 +77,7 @@ class XmlResponseFormatterTest extends FormatterTest '2015-06-18' => '2015-06-18', 'b:c' => 'b:c', 'a b c' => 'a b c', - 'äøñ' => 'äøñ' + 'äøñ' => 'äøñ', ], "12015-06-18b:ca b c<äøñ>äøñ\n"], ]); } @@ -97,7 +97,7 @@ class XmlResponseFormatterTest extends FormatterTest $expectedXmlForStack; $data = [ - [$postsStack, "$expectedXmlForStack\n"] + [$postsStack, "$expectedXmlForStack\n"], ]; return $this->addXmlHead($data); @@ -123,8 +123,8 @@ class XmlResponseFormatterTest extends FormatterTest return $this->addXmlHead([ [ new ModelStub(['id' => 123, 'title' => 'abc', 'hidden' => 'hidden']), - "123abc\n" - ] + "123abc\n", + ], ]); } diff --git a/tests/framework/web/stubs/CachedUrlRule.php b/tests/framework/web/stubs/CachedUrlRule.php index 36116442a7..9444fff963 100644 --- a/tests/framework/web/stubs/CachedUrlRule.php +++ b/tests/framework/web/stubs/CachedUrlRule.php @@ -1,4 +1,9 @@ mockWebApplication(); @@ -78,7 +83,7 @@ EOD; { // field will be the html of the model's attribute wrapped with the return string below. $field = $this->attributeName; - $content = function($field) { + $content = function ($field) { return "
            $field
            "; }; @@ -119,7 +124,7 @@ EOD; public function testBeginHasErrors() { - $this->helperModel->addError($this->attributeName, "Error Message"); + $this->helperModel->addError($this->attributeName, 'Error Message'); $expectedValue = '
            '; $actualValue = $this->activeField->begin(); @@ -139,7 +144,7 @@ EOD; public function testBeginHasErrorAndRequired() { - $this->helperModel->addError($this->attributeName, "Error Message"); + $this->helperModel->addError($this->attributeName, 'Error Message'); $this->helperModel->addRule($this->attributeName, 'required'); $expectedValue = '
            '; @@ -156,13 +161,13 @@ EOD; $this->assertEquals($expectedValue, $actualValue); - $expectedValue = ""; + $expectedValue = ''; $this->activeField->options['tag'] = null; $actualValue = $this->activeField->begin(); $this->assertEquals($expectedValue, $actualValue); - $expectedValue = ""; + $expectedValue = ''; $this->activeField->options['tag'] = false; $actualValue = $this->activeField->begin(); @@ -177,19 +182,19 @@ EOD; $this->assertEquals($expectedValue, $actualValue); // other tag - $expectedValue = ""; + $expectedValue = ''; $this->activeField->options['tag'] = 'article'; $actualValue = $this->activeField->end(); $this->assertEquals($expectedValue, $actualValue); - $expectedValue = ""; + $expectedValue = ''; $this->activeField->options['tag'] = false; $actualValue = $this->activeField->end(); $this->assertEquals($expectedValue, $actualValue); - $expectedValue = ""; + $expectedValue = ''; $this->activeField->options['tag'] = null; $actualValue = $this->activeField->end(); @@ -266,7 +271,7 @@ EOT; $expectedValue = << EOD; - $this->activeField->input("password"); + $this->activeField->input('password'); $this->assertEquals($expectedValue, $this->activeField->parts['{input}']); @@ -274,7 +279,7 @@ EOD; $expectedValue = << EOD; - $this->activeField->input("password", ['weird' => 'value']); + $this->activeField->input('password', ['weird' => 'value']); $this->assertEquals($expectedValue, $this->activeField->parts['{input}']); } @@ -305,7 +310,7 @@ EOD; EOD; - $this->activeField->listBox(["1" => "Item One", "2" => "Item 2"]); + $this->activeField->listBox(['1' => 'Item One', '2' => 'Item 2']); $this->assertEqualsWithoutLE($expectedValue, $this->activeField->parts['{input}']); // https://github.com/yiisoft/yii2/issues/8848 @@ -315,7 +320,7 @@ EOD; EOD; - $this->activeField->listBox(["value1" => "Item One", "value2" => "Item 2"], ['options' => [ + $this->activeField->listBox(['value1' => 'Item One', 'value2' => 'Item 2'], ['options' => [ 'value1' => ['disabled' => true], 'value2' => ['label' => 'value 2'], ]]); @@ -328,7 +333,7 @@ EOD; EOD; $this->activeField->model->{$this->attributeName} = 'value2'; - $this->activeField->listBox(["value1" => "Item One", "value2" => "Item 2"], ['options' => [ + $this->activeField->listBox(['value1' => 'Item One', 'value2' => 'Item 2'], ['options' => [ 'value1' => ['disabled' => true], 'value2' => ['label' => 'value 2'], ]]); @@ -355,7 +360,6 @@ EOD; // expected empty $actualValue = $this->activeField->getClientOptions(); $this->assertEmpty($actualValue); - } public function testGetClientOptionsClientValidation() @@ -365,7 +369,7 @@ EOD; $this->activeField->model->addRule($this->attributeName, 'yiiunit\framework\widgets\TestValidator'); $this->activeField->enableClientValidation = true; $actualValue = $this->activeField->getClientOptions(); - $expectedJsExpression = "function (attribute, value, messages, deferred, \$form) {return true;}"; + $expectedJsExpression = 'function (attribute, value, messages, deferred, $form) {return true;}'; $this->assertEquals($expectedJsExpression, $actualValue['validate']); $this->assertNotTrue(isset($actualValue['validateOnChange'])); @@ -400,7 +404,7 @@ EOD; } $actualValue = $this->activeField->getClientOptions(); - $expectedJsExpression = "function (attribute, value, messages, deferred, \$form) {if ((function (attribute, value) " + $expectedJsExpression = 'function (attribute, value, messages, deferred, $form) {if ((function (attribute, value) ' . "{ return 'yii2' == 'yii2'; })(attribute, value)) { return true; }}"; $this->assertEquals($expectedJsExpression, $actualValue['validate']->expression); @@ -534,7 +538,6 @@ EOD; return $view; } - } class ActiveFieldTestModel extends DynamicModel @@ -576,10 +579,9 @@ class ActiveFieldExtend extends ActiveField class TestValidator extends \yii\validators\Validator { - public function clientValidateAttribute($object, $attribute, $view) { - return "return true;"; + return 'return true;'; } public function setWhenClient($js) @@ -605,4 +607,4 @@ class TestInputWidget extends InputWidget { return 'Render: ' . get_class($this); } -} \ No newline at end of file +} diff --git a/tests/framework/widgets/ActiveFormTest.php b/tests/framework/widgets/ActiveFormTest.php index 9496bca0c0..0123e5e2a4 100644 --- a/tests/framework/widgets/ActiveFormTest.php +++ b/tests/framework/widgets/ActiveFormTest.php @@ -1,6 +1,8 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\framework\widgets; @@ -52,7 +54,6 @@ EOF
            EOF , (string) $form->field($model, 'name', $o)->input('email', ['required' => 'test'])); - } public function testIssue5356() @@ -105,7 +106,6 @@ EOF HTML , $content); - } public function testRegisterClientScript() diff --git a/tests/framework/widgets/BreadcrumbsTest.php b/tests/framework/widgets/BreadcrumbsTest.php index 17a816e984..d2d0f3e14d 100644 --- a/tests/framework/widgets/BreadcrumbsTest.php +++ b/tests/framework/widgets/BreadcrumbsTest.php @@ -1,4 +1,9 @@ mockWebApplication(); $this->breadcrumbs = new Breadcrumbs(); @@ -33,7 +38,7 @@ class BreadcrumbsTest extends \yiiunit\TestCase $expectedHtml = "
            • Home
            • \n" . "
            • My Home Page
            • \n" . "
            • http://my.example.com/yii2/link/page
            • \n" - . "
            "; + . ''; ob_start(); $this->breadcrumbs->run(); @@ -55,7 +60,7 @@ class BreadcrumbsTest extends \yiiunit\TestCase $expectedHtml = "
            • My Home Page
            • \n" . "
            • http://my.example.com/yii2/link/page
            • \n" - . "
            "; + . ''; ob_start(); $this->breadcrumbs->run(); @@ -74,7 +79,7 @@ class BreadcrumbsTest extends \yiiunit\TestCase $expectedHtml = "
            • home-link
            • \n" . "
            • My Home Page
            • \n" . "
            • http://my.example.com/yii2/link/page
            • \n" - . "
            "; + . ''; ob_start(); $this->breadcrumbs->run(); diff --git a/tests/framework/widgets/DetailViewTest.php b/tests/framework/widgets/DetailViewTest.php index 0fb2949377..ea0b505fd5 100644 --- a/tests/framework/widgets/DetailViewTest.php +++ b/tests/framework/widgets/DetailViewTest.php @@ -1,6 +1,8 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\framework\widgets; @@ -164,7 +166,7 @@ class DetailViewTest extends \yiiunit\TestCase 'label' => 'Id', 'value' => 'Displayed id', 'visible' => true, - ] + ], ], $this->detailView->attributes); $this->assertEquals(5, $model->getDisplayedIdCallCount()); } @@ -211,13 +213,13 @@ class DetailViewTest extends \yiiunit\TestCase 'attribute' => 'id', 'format' => 'text', 'label' => 'Id', - 'value' => 1 + 'value' => 1, ], [ 'attribute' => 'text', 'format' => 'text', 'label' => 'Text', - 'value' => 'I`m arrayable' + 'value' => 'I`m arrayable', ], ]; @@ -239,13 +241,13 @@ class DetailViewTest extends \yiiunit\TestCase 'attribute' => 'id', 'format' => 'text', 'label' => 'Id', - 'value' => 1 + 'value' => 1, ], [ 'attribute' => 'text', 'format' => 'text', 'label' => 'Text', - 'value' => 'I`m an object' + 'value' => 'I`m an object', ], ]; @@ -267,19 +269,19 @@ class DetailViewTest extends \yiiunit\TestCase 'attribute' => 'id', 'format' => 'text', 'label' => 'Id', - 'value' => 1 + 'value' => 1, ], [ 'attribute' => 'text', 'format' => 'text', 'label' => 'Text', - 'value' => 'I`m an array' + 'value' => 'I`m an array', ], ]; $model = [ 'id' => 1, - 'text' => 'I`m an array' + 'text' => 'I`m an array', ]; $this->detailView = new DetailView([ @@ -307,7 +309,7 @@ class DetailViewTest extends \yiiunit\TestCase ], ]); - foreach ($this->detailView->attributes as $index=>$attribute) { + foreach ($this->detailView->attributes as $index => $attribute) { $a = $this->detailView->renderAttribute($attribute, $index); $this->assertEquals($expectedValue, $a); } diff --git a/tests/framework/widgets/FragmentCacheTest.php b/tests/framework/widgets/FragmentCacheTest.php index 0800c6b24b..90d6f35ef2 100644 --- a/tests/framework/widgets/FragmentCacheTest.php +++ b/tests/framework/widgets/FragmentCacheTest.php @@ -1,10 +1,15 @@ assertTrue($view->beginCache('test')); - echo "cached fragment"; + echo 'cached fragment'; $view->endCache(); ob_start(); ob_implicit_flush(false); $this->assertFalse($view->beginCache('test')); - $this->assertEquals("cached fragment", ob_get_clean()); + $this->assertEquals('cached fragment', ob_get_clean()); ob_end_clean(); $this->assertEquals($expectedLevel, ob_get_level(), 'Output buffer not closed correctly.'); @@ -49,15 +54,15 @@ class FragmentCacheTest extends \yiiunit\TestCase $view = new View(); $this->assertTrue($view->beginCache('test', ['enabled' => false])); - echo "cached fragment"; + echo 'cached fragment'; $view->endCache(); ob_start(); ob_implicit_flush(false); $this->assertTrue($view->beginCache('test', ['enabled' => false])); - echo "cached fragment"; + echo 'cached fragment'; $view->endCache(); - $this->assertEquals("cached fragment", ob_get_clean()); + $this->assertEquals('cached fragment', ob_get_clean()); ob_end_clean(); $this->assertEquals($expectedLevel, ob_get_level(), 'Output buffer not closed correctly.'); @@ -71,15 +76,15 @@ class FragmentCacheTest extends \yiiunit\TestCase $view = new View(); $this->assertTrue($view->beginCache('test')); - echo "cached fragment"; + echo 'cached fragment'; $view->endCache(); ob_start(); ob_implicit_flush(false); $this->assertTrue($view->beginCache('test', ['enabled' => false])); - echo "cached fragment other"; + echo 'cached fragment other'; $view->endCache(); - $this->assertEquals("cached fragment other", ob_get_clean()); + $this->assertEquals('cached fragment other', ob_get_clean()); ob_end_clean(); $this->assertEquals($expectedLevel, ob_get_level(), 'Output buffer not closed correctly.'); diff --git a/tests/framework/widgets/LinkPagerTest.php b/tests/framework/widgets/LinkPagerTest.php index 90acf13b5b..e3af651b8c 100644 --- a/tests/framework/widgets/LinkPagerTest.php +++ b/tests/framework/widgets/LinkPagerTest.php @@ -1,4 +1,9 @@ mockApplication([ 'components' => [ 'urlManager' => [ - 'scriptUrl' => '/' - ] - ] + 'scriptUrl' => '/', + ], + ], ]); } @@ -32,7 +37,7 @@ class LinkPagerTest extends \yiiunit\TestCase $output = LinkPager::widget([ 'pagination' => $pagination, 'firstPageLabel' => true, - 'lastPageLabel' => true + 'lastPageLabel' => true, ]); static::assertContains('
          • 1
          • ', $output); @@ -41,7 +46,7 @@ class LinkPagerTest extends \yiiunit\TestCase $output = LinkPager::widget([ 'pagination' => $pagination, 'firstPageLabel' => 'First', - 'lastPageLabel' => 'Last' + 'lastPageLabel' => 'Last', ]); static::assertContains('
          • First
          • ', $output); @@ -50,7 +55,7 @@ class LinkPagerTest extends \yiiunit\TestCase $output = LinkPager::widget([ 'pagination' => $pagination, 'firstPageLabel' => false, - 'lastPageLabel' => false + 'lastPageLabel' => false, ]); static::assertNotContains('
          • ', $output); diff --git a/tests/framework/widgets/LinkSorterTest.php b/tests/framework/widgets/LinkSorterTest.php index b7703565f0..f0fd9a6c79 100644 --- a/tests/framework/widgets/LinkSorterTest.php +++ b/tests/framework/widgets/LinkSorterTest.php @@ -1,4 +1,9 @@ $dataProvider, - 'layout' => "{sorter}", + 'layout' => '{sorter}', ]); $actualHtml = ob_get_clean(); @@ -64,7 +69,7 @@ class LinkSorterTest extends DatabaseTestCase ob_start(); echo ListView::widget([ 'dataProvider' => $dataProvider, - 'layout' => "{sorter}", + 'layout' => '{sorter}', ]); $actualHtml = ob_get_clean(); @@ -73,5 +78,4 @@ class LinkSorterTest extends DatabaseTestCase $this->assertNotFalse(strpos($actualHtml, 'Invoice Total')); } - } diff --git a/tests/framework/widgets/ListViewTest.php b/tests/framework/widgets/ListViewTest.php index 701352779e..b1d069c9f1 100644 --- a/tests/framework/widgets/ListViewTest.php +++ b/tests/framework/widgets/ListViewTest.php @@ -1,4 +1,9 @@ getListView([ 'dataProvider' => new ArrayDataProvider(['allModels' => []]), - 'emptyText' => "Nothing at all", + 'emptyText' => 'Nothing at all', ])->run(); $this->expectOutputString('
            Nothing at all
            '); @@ -160,7 +165,6 @@ HTML 'index' => $index, 'id' => $model['id'], ], - ]; }, '
            Showing 1-3 of 3 items.
            @@ -196,7 +200,7 @@ HTML }; $this->getListView([ 'beforeItem' => $before, - 'afterItem' => $after + 'afterItem' => $after, ])->run(); $this->expectOutputString(<< [ [ 'encode' => false, - 'label' => ' Users', - 'url' => '#', + 'label' => ' Users', + 'url' => '#', ], [ 'encode' => true, - 'label' => 'Authors & Publications', - 'url' => '#', + 'label' => 'Authors & Publications', + 'url' => '#', ], - ] + ], ]); $expected = << [ [ 'encode' => false, - 'label' => ' Users', - 'url' => '#', + 'label' => ' Users', + 'url' => '#', ], [ 'encode' => true, - 'label' => 'Authors & Publications', - 'url' => '#', + 'label' => 'Authors & Publications', + 'url' => '#', ], - ] + ], ]); $expected = << [ [ - 'label' => 'item1', - 'url' => '#', + 'label' => 'item1', + 'url' => '#', 'options' => ['tag' => 'div'], ], [ - 'label' => 'item2', - 'url' => '#', + 'label' => 'item2', + 'url' => '#', 'options' => ['tag' => false], ], - ] + ], ]); $expected = << [ [ - 'label' => 'item1', - 'url' => '#', + 'label' => 'item1', + 'url' => '#', ], [ - 'label' => 'item2', - 'url' => '#', + 'label' => 'item2', + 'url' => '#', ], ], - 'itemOptions' => ['tag' => false] + 'itemOptions' => ['tag' => false], ]); $expected = << '', 'items' => [ [ - 'label' => 'item1', - 'url' => '#', - 'template' => 'label: {label}; url: {url}' + 'label' => 'item1', + 'url' => '#', + 'template' => 'label: {label}; url: {url}', ], [ - 'label' => 'item2', - 'template' => 'label: {label}' + 'label' => 'item2', + 'template' => 'label: {label}', ], [ - 'label' => 'item3 (no template)', + 'label' => 'item3 (no template)', ], - ] + ], ]); $expected = << '', 'items' => [ [ - 'label' => 'item1', - 'url' => '#', + 'label' => 'item1', + 'url' => '#', 'template' => 'label: {label}; url: {url}', 'active' => function ($item, $hasActiveChild, $isItemActive, $widget) { return isset($item, $hasActiveChild, $isItemActive, $widget); - } + }, ], [ - 'label' => 'item2', + 'label' => 'item2', 'template' => 'label: {label}', - 'active' => false + 'active' => false, ], [ - 'label' => 'item3 (no template)', - 'active' => 'somestring' + 'label' => 'item3 (no template)', + 'active' => 'somestring', ], - ] + ], ]); $expected = <<mockWebApplication(); } - } diff --git a/tests/framework/widgets/SpacelessTest.php b/tests/framework/widgets/SpacelessTest.php index ae41b4c024..a8ae7fb204 100644 --- a/tests/framework/widgets/SpacelessTest.php +++ b/tests/framework/widgets/SpacelessTest.php @@ -1,4 +1,9 @@ Bye!

            \n"; echo "\n"; - $expected = "\n

            This is a left bar!

            ". + $expected = "\n

            This is a left bar!

            " . "

            This is a right bar!

            \t

            Bye!

            \n\n"; $this->assertEquals($expected, ob_get_clean()); }