diff --git a/apps/advanced/backend/config/AppAsset.php b/apps/advanced/backend/config/AppAsset.php index 267e48c..2fd15ca 100644 --- a/apps/advanced/backend/config/AppAsset.php +++ b/apps/advanced/backend/config/AppAsset.php @@ -17,13 +17,10 @@ class AppAsset extends AssetBundle { public $basePath = '@webroot'; public $baseUrl = '@web'; - public $css = array( - 'css/site.css', - ); - public $js = array( - ); - public $depends = array( + public $css = ['css/site.css']; + public $js = []; + public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', - ); + ]; } diff --git a/apps/advanced/backend/config/main.php b/apps/advanced/backend/config/main.php index 30c1825..f820f4e 100644 --- a/apps/advanced/backend/config/main.php +++ b/apps/advanced/backend/config/main.php @@ -8,35 +8,34 @@ $params = array_merge( require(__DIR__ . '/params-local.php') ); -return array( +return [ 'id' => 'app-backend', 'basePath' => dirname(__DIR__), 'vendorPath' => dirname(dirname(__DIR__)) . '/vendor', - 'preload' => array('log'), + 'preload' => ['log'], 'controllerNamespace' => 'backend\controllers', - 'modules' => array( - ), - 'components' => array( - 'request' => array( + 'modules' => [], + 'components' => [ + 'request' => [ 'enableCsrfValidation' => true, - ), + ], 'db' => $params['components.db'], 'cache' => $params['components.cache'], - 'user' => array( + 'user' => [ 'identityClass' => 'common\models\User', - ), - 'log' => array( + ], + 'log' => [ 'traceLevel' => YII_DEBUG ? 3 : 0, - 'targets' => array( - array( + 'targets' => [ + [ 'class' => 'yii\log\FileTarget', - 'levels' => array('error', 'warning'), - ), - ), - ), - 'errorHandler' => array( + 'levels' => ['error', 'warning'], + ], + ], + ], + 'errorHandler' => [ 'errorAction' => 'site/error', - ), - ), + ], + ], 'params' => $params, -); +]; diff --git a/apps/advanced/backend/config/params.php b/apps/advanced/backend/config/params.php index 1643a70..0e625dc 100644 --- a/apps/advanced/backend/config/params.php +++ b/apps/advanced/backend/config/params.php @@ -1,4 +1,4 @@ 'admin@example.com', -); +]; diff --git a/apps/advanced/console/migrations/m130524_201442_init.php b/apps/advanced/console/migrations/m130524_201442_init.php index e7b9e84..1315d8d 100644 --- a/apps/advanced/console/migrations/m130524_201442_init.php +++ b/apps/advanced/console/migrations/m130524_201442_init.php @@ -9,7 +9,7 @@ class m130524_201442_init extends \yii\db\Migration // MySQL-specific table options. Adjust if you plan working with another DBMS $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB'; - $this->createTable('tbl_user', array( + $this->createTable('tbl_user', [ 'id' => Schema::TYPE_PK, 'username' => Schema::TYPE_STRING.' NOT NULL', 'auth_key' => Schema::TYPE_STRING.'(32) NOT NULL', @@ -21,7 +21,7 @@ class m130524_201442_init extends \yii\db\Migration 'status' => 'tinyint NOT NULL DEFAULT 10', 'create_time' => Schema::TYPE_INTEGER.' NOT NULL', 'update_time' => Schema::TYPE_INTEGER.' NOT NULL', - ), $tableOptions); + ], $tableOptions); } public function down() diff --git a/apps/advanced/environments/dev/backend/config/main-local.php b/apps/advanced/environments/dev/backend/config/main-local.php index 0c1f40e..cc887e5 100644 --- a/apps/advanced/environments/dev/backend/config/main-local.php +++ b/apps/advanced/environments/dev/backend/config/main-local.php @@ -4,8 +4,8 @@ return [ //'debug', ], 'modules' => [ -// 'debug' => array( +// 'debug' => [ // 'class' => 'yii\debug\Module', -// ), +// ], ], ]; diff --git a/apps/advanced/environments/dev/frontend/config/main-local.php b/apps/advanced/environments/dev/frontend/config/main-local.php index 70a97ab..40df724 100644 --- a/apps/advanced/environments/dev/frontend/config/main-local.php +++ b/apps/advanced/environments/dev/frontend/config/main-local.php @@ -4,8 +4,8 @@ return [ //'debug', ], 'modules' => [ -// 'debug' => array( +// 'debug' => [ // 'class' => 'yii\debug\Module', -// ), +// ], ], ]; diff --git a/apps/advanced/environments/index.php b/apps/advanced/environments/index.php index 50f578f..a2097bf 100644 --- a/apps/advanced/environments/index.php +++ b/apps/advanced/environments/index.php @@ -6,14 +6,14 @@ * format: * * ```php - * return array( - * 'environment name' => array( + * return [ + * 'environment name' => [ * 'path' => 'directory storing the local files', - * 'writable' => array( + * 'writable' => [ * // list of directories that should be set writable - * ), - * ), - * ); + * ], + * ], + * ]; * ``` */ return [ diff --git a/apps/benchmark/index.php b/apps/benchmark/index.php index ddf6081..984beb2 100644 --- a/apps/benchmark/index.php +++ b/apps/benchmark/index.php @@ -4,15 +4,15 @@ defined('YII_DEBUG') or define('YII_DEBUG', false); require(__DIR__ . '/protected/vendor/yiisoft/yii2/yii/Yii.php'); -$config = array( +$config = [ 'id' => 'benchmark', 'basePath' => __DIR__ . '/protected', - 'components' => array( - 'urlManager' => array( + 'components' => [ + 'urlManager' => [ 'enablePrettyUrl' => true, - ), - ) -); + ], + ], +]; $application = new yii\web\Application($config); $application->run(); diff --git a/build/build b/build/build index a6c7cc8..b1d6bb2 100755 --- a/build/build +++ b/build/build @@ -13,9 +13,9 @@ defined('STDIN') or define('STDIN', fopen('php://stdin', 'r')); require(__DIR__ . '/../framework/yii/Yii.php'); -$application = new yii\console\Application(array( +$application = new yii\console\Application([ 'id' => 'yii-build', 'basePath' => __DIR__, 'controllerNamespace' => 'yii\build\controllers', -)); +]); $application->run(); diff --git a/build/controllers/ClassmapController.php b/build/controllers/ClassmapController.php index 6a5ac8c..9fd84e8 100644 --- a/build/controllers/ClassmapController.php +++ b/build/controllers/ClassmapController.php @@ -32,7 +32,7 @@ class ClassmapController extends Controller if ($mapFile === null) { $mapFile = YII_PATH . '/classes.php'; } - $options = array( + $options = [ 'filter' => function ($path) { if (is_file($path)) { $file = basename($path); @@ -42,18 +42,18 @@ class ClassmapController extends Controller } return null; }, - 'only' => array('.php'), - 'except' => array( + 'only' => ['.php'], + 'except' => [ 'Yii.php', 'BaseYii.php', '/debug/', '/console/', '/test/', '/gii/', - ), - ); + ], + ]; $files = FileHelper::findFiles($root, $options); - $map = array(); + $map = []; foreach ($files as $file) { if (($pos = strpos($file, $root)) !== 0) { die("Something wrong: $file\n"); @@ -76,9 +76,9 @@ class ClassmapController extends Controller * @license http://www.yiiframework.com/license/ */ -return array( +return [ $map -); +]; EOD; if (is_file($mapFile) && file_get_contents($mapFile) === $output) { diff --git a/build/controllers/PhpDocController.php b/build/controllers/PhpDocController.php index cb574ff..a104dd5 100644 --- a/build/controllers/PhpDocController.php +++ b/build/controllers/PhpDocController.php @@ -44,7 +44,7 @@ class PhpDocController extends Controller $root = YII_PATH; } $root = FileHelper::normalizePath($root); - $options = array( + $options = [ 'filter' => function ($path) { if (is_file($path)) { $file = basename($path); @@ -54,16 +54,16 @@ class PhpDocController extends Controller } return null; }, - 'only' => array('.php'), - 'except' => array( + 'only' => ['.php'], + 'except' => [ 'BaseYii.php', 'Yii.php', '/debug/views/', '/requirements/', '/gii/views/', '/gii/generators/', - ), - ); + ], + ]; $files = FileHelper::findFiles($root, $options); $nFilesTotal = 0; $nFilesUpdated = 0; @@ -89,7 +89,7 @@ class PhpDocController extends Controller public function globalOptions() { - return array_merge(parent::globalOptions(), array('updateFiles')); + return array_merge(parent::globalOptions(), ['updateFiles']); } protected function updateClassPropertyDocs($file, $className, $propertyDoc) @@ -136,7 +136,7 @@ class PhpDocController extends Controller $start = $ref->getStartLine() - 2; $docStart = $start - count(explode("\n", $oldDoc)) + 1; - $newFileContent = array(); + $newFileContent = []; $n = count($fileContent); for($i = 0; $i < $n; $i++) { if ($i > $start || $i < $docStart) { @@ -253,16 +253,15 @@ class PhpDocController extends Controller '[\s\n]{2,}public function [g|s]et(?\w+)\(((?:,? ?\$\w+ ?= ?[^,]+)*|\$\w+(?:, ?\$\w+ ?= ?[^,]+)*)\)#', $class['content']); $acrs = array_merge($properties, $gets, $sets); - //print_r($acrs); continue; - $props = array(); + $props = []; foreach ($acrs as &$acr) { $acr['name'] = lcfirst($acr['name']); $acr['comment'] = trim(preg_replace('#(^|\n)\s+\*\s?#', '$1 * ', $acr['comment'])); - $props[$acr['name']][$acr['kind']] = array( + $props[$acr['name']][$acr['kind']] = [ 'type' => $acr['type'], 'comment' => $this->fixSentence($acr['comment']), - ); + ]; } ksort($props); @@ -299,12 +298,12 @@ class PhpDocController extends Controller $phpdoc .= " *\n"; } } - return array($className, $phpdoc); + return [$className, $phpdoc]; } protected function match($pattern, $subject) { - $sets = array(); + $sets = []; preg_match_all($pattern . 'suU', $subject, $sets, PREG_SET_ORDER); foreach ($sets as &$set) foreach ($set as $i => $match) diff --git a/docs/api/base/Component.md b/docs/api/base/Component.md index 01ef462..f198798 100644 --- a/docs/api/base/Component.md +++ b/docs/api/base/Component.md @@ -25,8 +25,8 @@ In the above, an anonymous function is attached to the "update" event of the pos the following types of event handlers: - anonymous function: `function($event) { ... }` -- object method: `array($object, 'handleAdd')` -- static class method: `array('Page', 'handleAdd')` +- object method: `[$object, 'handleAdd']` +- static class method: `['Page', 'handleAdd']` - global function: `'handleAdd'` The signature of an event handler should be like the following: @@ -41,9 +41,9 @@ You can also attach a handler to an event when configuring a component with a co The syntax is like the following: ~~~ -array( +[ 'on add' => function($event) { ... } -) +] ~~~ where `on add` stands for attaching an event to the `add` event. @@ -69,11 +69,11 @@ One can also attach a behavior to a component when configuring it with a configu following: ~~~ -array( - 'as tree' => array( +[ + 'as tree' => [ 'class' => 'Tree', - ), -) + ], +] ~~~ where `as tree` stands for attaching a behavior named `tree`, and the array will be passed to [[\Yii::createObject()]] diff --git a/docs/api/base/Object.md b/docs/api/base/Object.md index 1b9fca0..a6ab2c1 100644 --- a/docs/api/base/Object.md +++ b/docs/api/base/Object.md @@ -50,12 +50,12 @@ In order to ensure the above life cycles, if a child class of Object needs to ov it should be done like the following: ~~~ -public function __construct($param1, $param2, ..., $config = array()) +public function __construct($param1, $param2, ..., $config = []) { ... parent::__construct($config); } ~~~ -That is, a `$config` parameter (defaults to `array()`) should be declared as the last parameter +That is, a `$config` parameter (defaults to `[]`) should be declared as the last parameter of the constructor, and the parent implementation should be called at the end of the constructor. diff --git a/docs/api/db/ActiveRecord-find.md b/docs/api/db/ActiveRecord-find.md index 42940b6..8653853 100644 --- a/docs/api/db/ActiveRecord-find.md +++ b/docs/api/db/ActiveRecord-find.md @@ -8,7 +8,7 @@ $customers = Customer::find()->all(); // find all active customers and order them by their age: $customers = Customer::find() - ->where(array('status' => 1)) + ->where(['status' => 1]) ->orderBy('age') ->all(); @@ -16,11 +16,11 @@ $customers = Customer::find() $customer = Customer::find(10); // the above is equivalent to: -$customer = Customer::find()->where(array('id' => 10))->one(); +$customer = Customer::find()->where(['id' => 10])->one(); // find a single customer whose age is 30 and whose status is 1 -$customer = Customer::find(array('age' => 30, 'status' => 1)); +$customer = Customer::find(['age' => 30, 'status' => 1]); // the above is equivalent to: -$customer = Customer::find()->where(array('age' => 30, 'status' => 1))->one(); +$customer = Customer::find()->where(['age' => 30, 'status' => 1])->one(); ~~~ \ No newline at end of file diff --git a/docs/api/db/ActiveRecord.md b/docs/api/db/ActiveRecord.md index d8bedb4..0120998 100644 --- a/docs/api/db/ActiveRecord.md +++ b/docs/api/db/ActiveRecord.md @@ -40,18 +40,18 @@ instance which serves as the DB connection. Usually this component is configured via application configuration like the following: ~~~ -return array( - 'components' => array( - 'db' => array( +return [ + 'components' => [ + 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=testdb', 'username' => 'demo', 'password' => 'demo', // turn on schema caching to improve performance // 'schemaCacheDuration' => 3600, - ), - ), -); + ], + ], +]; ~~~ @@ -70,13 +70,13 @@ The followings are some examples, ~~~ // to retrieve all *active* customers and order them by their ID: $customers = Customer::find() - ->where(array('status' => $active)) + ->where(['status' => $active]) ->orderBy('id') ->all(); // to return a single customer whose ID is 1: $customer = Customer::find() - ->where(array('id' => 1)) + ->where(['id' => 1]) ->one(); // or use the following shortcut approach: @@ -88,7 +88,7 @@ $customers = Customer::findBySql($sql)->all(); // to return the number of *active* customers: $count = Customer::find() - ->where(array('status' => $active)) + ->where(['status' => $active]) ->count(); // to return customers in terms of arrays rather than `Customer` objects: @@ -158,7 +158,7 @@ $customer = Customer::find($id); $customer->delete(); // to increment the age of all customers by 1 -Customer::updateAllCounters(array('age' => 1)); +Customer::updateAllCounters(['age' => 1]); ~~~ @@ -175,7 +175,7 @@ class Customer extends \yii\db\ActiveRecord { public function getOrders() { - return $this->hasMany('Order', array('customer_id' => 'id')); + return $this->hasMany('Order', ['customer_id' => 'id']); } } @@ -183,7 +183,7 @@ class Order extends \yii\db\ActiveRecord { public function getCustomer() { - return $this->hasOne('Customer', array('id' => 'customer_id')); + return $this->hasOne('Customer', ['id' => 'customer_id']); } } ~~~ @@ -223,8 +223,8 @@ class Customer extends \yii\db\ActiveRecord { public function getBigOrders($threshold = 100) { - return $this->hasMany('Order', array('customer_id' => 'id')) - ->where('subtotal > :threshold', array(':threshold' => $threshold)) + return $this->hasMany('Order', ['customer_id' => 'id']) + ->where('subtotal > :threshold', [':threshold' => $threshold]) ->orderBy('id'); } } @@ -244,8 +244,8 @@ class Order extends \yii\db\ActiveRecord { public function getItems() { - return $this->hasMany('Item', array('id' => 'item_id')) - ->viaTable('tbl_order_item', array('order_id' => 'id')); + return $this->hasMany('Item', ['id' => 'item_id']) + ->viaTable('tbl_order_item', ['order_id' => 'id']); } } ~~~ @@ -259,12 +259,12 @@ class Order extends \yii\db\ActiveRecord { public function getOrderItems() { - return $this->hasMany('OrderItem', array('order_id' => 'id')); + return $this->hasMany('OrderItem', ['order_id' => 'id']); } public function getItems() { - return $this->hasMany('Item', array('id' => 'item_id')) + return $this->hasMany('Item', ['id' => 'item_id']) ->via('orderItems'); } } @@ -331,11 +331,11 @@ $orders = $customer->getOrders()->where('subtotal>100')->all(); // eager loading: SELECT * FROM tbl_customer LIMIT 10 SELECT * FROM tbl_order WHERE customer_id IN (1,2,...) AND subtotal>100 -$customers = Customer::find()->limit(100)->with(array( +$customers = Customer::find()->limit(100)->with([ 'orders' => function($query) { $query->andWhere('subtotal>100'); }, -))->all(); +])->all(); ~~~ @@ -437,7 +437,7 @@ class Customer extends \yii\db\ActiveRecord */ public static function olderThan($query, $age = 30) { - $query->andWhere('age > :age', array(':age' => $age)); + $query->andWhere('age > :age', [':age' => $age]); } } diff --git a/docs/guide/active-record.md b/docs/guide/active-record.md index 7d0c744..3de4a01 100644 --- a/docs/guide/active-record.md +++ b/docs/guide/active-record.md @@ -54,16 +54,16 @@ By default, ActiveRecord assumes that there is an application component named `d [[Connection]] instance. Usually this component is configured in application configuration file: ```php -return array( - 'components' => array( - 'db' => array( +return [ + 'components' => [ + 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=testdb', 'username' => 'demo', 'password' => 'demo', - ), - ), -); + ], + ], +]; ``` Please read the [Database basics](database-basics.md) section to learn more on how to configure and use database connections. @@ -82,7 +82,7 @@ the same set of flexible and powerful DB query methods. The following examples d ```php // to retrieve all *active* customers and order them by their ID: $customers = Customer::find() - ->where(array('status' => $active)) + ->where(['status' => $active]) ->orderBy('id') ->all(); @@ -91,7 +91,7 @@ $customer = Customer::find(1); // the above code is equivalent to the following: $customer = Customer::find() - ->where(array('id' => 1)) + ->where(['id' => 1]) ->one(); // to retrieve customers using a raw SQL statement: @@ -100,7 +100,7 @@ $customers = Customer::findBySql($sql)->all(); // to return the number of *active* customers: $count = Customer::find() - ->where(array('status' => $active)) + ->where(['status' => $active]) ->count(); // to return customers in terms of arrays rather than `Customer` objects: @@ -172,7 +172,7 @@ $customer = Customer::find($id); $customer->delete(); // to increment the age of ALL customers by 1 -Customer::updateAllCounters(array('age' => 1)); +Customer::updateAllCounters(['age' => 1]); ``` > Info: The `save()` method will either perform an `INSERT` or `UPDATE` SQL statement, depending @@ -202,7 +202,7 @@ class Customer extends \yii\db\ActiveRecord { public function getOrders() { - return $this->hasMany('Order', array('customer_id' => 'id')); + return $this->hasMany('Order', ['customer_id' => 'id']); } } @@ -210,7 +210,7 @@ class Order extends \yii\db\ActiveRecord { public function getCustomer() { - return $this->hasOne('Customer', array('id' => 'customer_id')); + return $this->hasOne('Customer', ['id' => 'customer_id']); } } ``` @@ -257,8 +257,8 @@ class Customer extends \yii\db\ActiveRecord { public function getBigOrders($threshold = 100) { - return $this->hasMany('Order', array('customer_id' => 'id')) - ->where('subtotal > :threshold', array(':threshold' => $threshold)) + return $this->hasMany('Order', ['customer_id' => 'id']) + ->where('subtotal > :threshold', [':threshold' => $threshold]) ->orderBy('id'); } } @@ -291,8 +291,8 @@ class Order extends \yii\db\ActiveRecord { public function getItems() { - return $this->hasMany('Item', array('id' => 'item_id')) - ->viaTable('tbl_order_item', array('order_id' => 'id')); + return $this->hasMany('Item', ['id' => 'item_id']) + ->viaTable('tbl_order_item', ['order_id' => 'id']); } } ``` @@ -306,12 +306,12 @@ class Order extends \yii\db\ActiveRecord { public function getOrderItems() { - return $this->hasMany('OrderItem', array('order_id' => 'id')); + return $this->hasMany('OrderItem', ['order_id' => 'id']); } public function getItems() { - return $this->hasMany('Item', array('id' => 'item_id')) + return $this->hasMany('Item', ['id' => 'item_id']) ->via('orderItems'); } } @@ -379,11 +379,11 @@ $orders = $customer->getOrders()->where('subtotal>100')->all(); // eager loading: SELECT * FROM tbl_customer LIMIT 10 SELECT * FROM tbl_order WHERE customer_id IN (1,2,...) AND subtotal>100 -$customers = Customer::find()->limit(100)->with(array( +$customers = Customer::find()->limit(100)->with([ 'orders' => function($query) { $query->andWhere('subtotal>100'); }, -))->all(); +])->all(); ``` @@ -483,7 +483,7 @@ class Customer extends \yii\db\ActiveRecord */ public static function olderThan($query, $age = 30) { - $query->andWhere('age > :age', array(':age' => $age)); + $query->andWhere('age > :age', [':age' => $age]); } } @@ -517,7 +517,7 @@ class Feature extends \yii\db\ActiveRecord public function getProduct() { - return $this->hasOne('Product', array('product_id' => 'id')); + return $this->hasOne('Product', ['product_id' => 'id']); } } @@ -527,7 +527,7 @@ class Product extends \yii\db\ActiveRecord public function getFeatures() { - return $this->hasMany('Feature', array('id' => 'product_id')); + return $this->hasMany('Feature', ['id' => 'product_id']); } } ``` @@ -566,17 +566,17 @@ class Feature extends \yii\db\ActiveRecord public function getProduct() { - return $this->hasOne('Product', array('product_id' => 'id')); + return $this->hasOne('Product', ['product_id' => 'id']); } public function scenarios() { - return array( - 'userCreates' => array( - 'attributes' => array('name', 'value'), - 'atomic' => array(self::OP_INSERT), - ), - ); + return [ + 'userCreates' => [ + 'attributes' => ['name', 'value'], + 'atomic' => [self::OP_INSERT], + ], + ]; } } @@ -586,17 +586,17 @@ class Product extends \yii\db\ActiveRecord public function getFeatures() { - return $this->hasMany('Feature', array('id' => 'product_id')); + return $this->hasMany('Feature', ['id' => 'product_id']); } public function scenarios() { - return array( - 'userCreates' => array( - 'attributes' => array('title', 'price'), - 'atomic' => array(self::OP_INSERT), - ), - ); + return [ + 'userCreates' => [ + 'attributes' => ['title', 'price'], + 'atomic' => [self::OP_INSERT], + ], + ]; } public function afterValidate() diff --git a/docs/guide/bootstrap-widgets.md b/docs/guide/bootstrap-widgets.md index 432dcd8..45d6c3c 100644 --- a/docs/guide/bootstrap-widgets.md +++ b/docs/guide/bootstrap-widgets.md @@ -17,11 +17,11 @@ convenient way to include bootstrap assets in your pages with a single line adde `config` directory: ```php -public $depends = array( +public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', // this line // 'yii\bootstrap\BootstrapThemeAsset' // uncomment to apply bootstrap 2 style to bootstrap 3 -); +]; ``` Using bootstrap through Yii asset manager allows you to minimize its resources and combine with your own resources when diff --git a/docs/guide/caching.md b/docs/guide/caching.md index 64c7e8d..1c379c5 100644 --- a/docs/guide/caching.md +++ b/docs/guide/caching.md @@ -13,23 +13,23 @@ two cache servers. Note, this configuration should be done in file located at `@ in case you're using basic sample application. ```php -'components' => array( - 'cache' => array( +'components' => [ + 'cache' => [ 'class' => '\yii\caching\MemCache', - 'servers' => array( - array( + 'servers' => [ + [ 'host' => 'server1', 'port' => 11211, 'weight' => 100, - ), - array( + ], + [ 'host' => 'server2', 'port' => 11211, 'weight' => 50, - ), - ), - ), -), + ], + ], + ], +], ``` When the application is running, the cache component can be accessed through `Yii::$app->cache` call. diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index 8325855..8358ba0 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -29,12 +29,12 @@ stored in a PHP file in `/config` directory of the application and looks like th ```php 'applicationId', 'basePath' => dirname(__DIR__), - 'components' => array( + 'components' => [ // ... - ), + ], 'params' => require(__DIR__ . '/params.php'), ); ``` @@ -53,31 +53,25 @@ Majority of Yii functionality are application components. These are attached to ```php 'applicationId', 'basePath' => dirname(__DIR__), - 'components' => array( - 'cache' => array( - 'class' => 'yii\caching\FileCache', - ), - 'user' => array( - 'identityClass' => 'app\models\User', - ), - 'errorHandler' => array( - 'errorAction' => 'site/error', - ), - 'log' => array( + 'components' => [ + 'cache' => ['class' => 'yii\caching\FileCache'], + 'user' => ['identityClass' => 'app\models\User'], + 'errorHandler' => ['errorAction' => 'site/error'], + 'log' => [ 'traceLevel' => YII_DEBUG ? 3 : 0, - 'targets' => array( - array( + 'targets' => [ + [ 'class' => 'yii\log\FileTarget', - 'levels' => array('error', 'warning'), - ), - ), - ), - ), + 'levels' => ['error', 'warning'], + ], + ], + ], + ], // ... -); +]; ``` In the above four components are configured: `cache`, `user`, `errorHandler`, `log`. Each entry key is a component ID diff --git a/docs/guide/controller.md b/docs/guide/controller.md index c665037..bb78120 100644 --- a/docs/guide/controller.md +++ b/docs/guide/controller.md @@ -93,10 +93,10 @@ class BlogController extends Controller $text = $post->getHistory($version); } - return $this->render('view', array( + return $this->render('view', [ 'post' => $post, 'text' => $text, - )); + ]); } } ``` @@ -128,13 +128,11 @@ class BlogController extends Controller if(\Yii::$app->request->isPost)) { $post->load($_POST); if($post->save()) { - $this->redirect(array('view', 'id' => $post->id)); + $this->redirect(['view', 'id' => $post->id]); } } - return $this->render('update', array( - 'post' => $post, - )); + return $this->render('update', ['post' => $post]); } } ``` @@ -167,13 +165,12 @@ public SiteController extends \yii\web\Controller { public function actions() { - return array( - 'about' => array( + return [ + 'about' => [ 'class' => '@app/actions/Page', - 'view' => 'about', - ), - ), - ); + 'view' => 'about', + ], + ]; } } ``` diff --git a/docs/guide/database-basics.md b/docs/guide/database-basics.md index 85bc042..559f1e9 100644 --- a/docs/guide/database-basics.md +++ b/docs/guide/database-basics.md @@ -19,11 +19,11 @@ In order to start using database you need to configure database connection compo to application configuration (for "basic" web application it's `config/web.php`) like the following: ```php -return array( +return [ // ... - 'components' => array( + 'components' => [ // ... - 'db' => array( + 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=mydatabase', // MySQL, MariaDB //'dsn' => 'sqlite:/path/to/database/file', // SQLite @@ -36,10 +36,10 @@ return array( 'username' => 'root', 'password' => '', 'charset' => 'utf8', - ), - ), + ], + ], // ... -); +]; ``` Please refer to the [PHP manual](http://www.php.net/manual/en/function.PDO-construct.php) for more details on the format of the DSN string. @@ -61,11 +61,11 @@ $secondaryConnection = \Yii::$app->secondDb; If you don't want to define the connection as an application component you can instantiate it directly: ```php -$connection = new \yii\db\Connection(array( +$connection = new \yii\db\Connection([ 'dsn' => $dsn, 'username' => $username, 'password' => $password, -)); +]); $connection->open(); ``` @@ -118,22 +118,20 @@ Alternatively the following syntax that takes care of proper table and column na ```php // INSERT -$connection->createCommand()->insert('tbl_user', array( +$connection->createCommand()->insert('tbl_user', [ 'name' => 'Sam', 'age' => 30, -))->execute(); +])->execute(); // INSERT multiple rows at once -$connection->createCommand()->batchInsert('tbl_user', array('name', 'age'), array( - array('Tom', 30), - array('Jane', 20), - array('Linda', 25), -))->execute(); +$connection->createCommand()->batchInsert('tbl_user', ['name', 'age'], [ + ['Tom', 30], + ['Jane', 20], + ['Linda', 25], +])->execute(); // UPDATE -$connection->createCommand()->update('tbl_user', array( - 'status' => 1, -), 'age > 30')->execute(); +$connection->createCommand()->update('tbl_user', ['status' => 1], 'age > 30')->execute(); // DELETE $connection->createCommand()->delete('tbl_user', 'status = 0')->execute(); @@ -236,11 +234,11 @@ These can be used as follows: ```php // CREATE TABLE -$connection->createCommand()->createTable('tbl_post', array( +$connection->createCommand()->createTable('tbl_post', [ 'id' => 'pk', 'title' => 'string', 'text' => 'text', -); +]; ``` For the full reference check [[\yii\db\Command]]. diff --git a/docs/guide/i18n.md b/docs/guide/i18n.md index 57f08f7..e44dc6b 100644 --- a/docs/guide/i18n.md +++ b/docs/guide/i18n.md @@ -24,7 +24,7 @@ Target language is what's currently used. It's defined in application configurat ```php // ... -return array( +return [ 'id' => 'applicationID', 'basePath' => dirname(__DIR__), 'language' => 'ru_RU' // ← here! @@ -50,22 +50,22 @@ echo \Yii::t('app', 'This is a string to translate!'); Yii tries to load approprite translation from one of the message sources defined via `i18n` component configuration: ```php -'components' => array( +'components' => [ // ... - 'i18n' => array( - 'translations' => array( - 'app*' => array( + 'i18n' => [ + 'translations' => [ + 'app*' => [ 'class' => 'yii\i18n\PhpMessageSource', //'basePath' => '@app/messages', //'sourceLanguage' => 'en_US', - 'fileMap' => array( + 'fileMap' => [ 'app' => 'app.php', 'app/error' => 'error.php', - ), - ), - ), - ), -), + ], + ], + ], + ], +], ``` In the above `app*` is a pattern that specifies which categories are handled by the message source. In this case we're @@ -95,9 +95,9 @@ The format for this is to use curly brackets around the parameter name as you ca ```php $username = 'Alexander'; -echo \Yii::t('app', 'Hello, {username}!', array( +echo \Yii::t('app', 'Hello, {username}!', [ 'username' => $username, -)); +]); ``` Note that the parameter assignment is without the brackets. @@ -190,17 +190,13 @@ echo \Yii::t('app', 'It is {0, date, HH:mm}', time()); ### Spellout ```php -echo \Yii::t('app', '{n,number} is spelled as {n, spellout}', array( - 'n' => 42, -)); +echo \Yii::t('app', '{n,number} is spelled as {n, spellout}', ['n' => 42]); ``` ### Ordinal ```php -echo \Yii::t('app', 'You are {n, ordinal} visitor here!', array( - 'n' => 42, -)); +echo \Yii::t('app', 'You are {n, ordinal} visitor here!', ['n' => 42]); ``` Will produce "You are 42nd visitor here!". @@ -209,9 +205,7 @@ Will produce "You are 42nd visitor here!". ```php -echo \Yii::t('app', 'You are here for {n, duration} already!', array( - 'n' => 42, -)); +echo \Yii::t('app', 'You are here for {n, duration} already!', ['n' => 42]); ``` Will produce "You are here for 47 sec. already!". @@ -223,9 +217,7 @@ functionality is provided without the need to specify inflection rule. Instead i word in certain situations. ```php -echo \Yii::t('app', 'There {n, plural, =0{are no cats} =1{is one cat} other{are # cats}}!', array( - 'n' => 0, -)); +echo \Yii::t('app', 'There {n, plural, =0{are no cats} =1{is one cat} other{are # cats}}!', ['n' => 0]); ``` Will give us "There are no cats!". @@ -249,10 +241,10 @@ You can select phrases based on keywords. The pattern in this case specifies how provides a default phrase. ```php -echo \Yii::t('app', '{name} is {gender} and {gender, select, female{she} male{he} other{it}} loves Yii!', array( +echo \Yii::t('app', '{name} is {gender} and {gender, select, female{she} male{he} other{it}} loves Yii!', [ 'name' => 'Snoopy', 'gender' => 'dog', -)); +]); ``` Will produce "Snoopy is dog and it loves Yii!". diff --git a/docs/guide/migration.md b/docs/guide/migration.md index d6c7165..8474bbe 100644 --- a/docs/guide/migration.md +++ b/docs/guide/migration.md @@ -82,11 +82,11 @@ class m101129_185401_create_news_table extends \yii\db\Migration { public function up() { - $this->db->createCommand()->createTable('tbl_news', array( + $this->db->createCommand()->createTable('tbl_news', [ 'id' => 'pk', 'title' => 'string(128) NOT NULL', 'content' => 'text', - ))->execute(); + ])->execute(); } public function down() @@ -128,11 +128,11 @@ class m101129_185401_create_news_table extends \yii\db\Migration $transaction=$this->getDbConnection()->beginTransaction(); try { - $this->db->createCommand()->createTable('tbl_news', array( + $this->db->createCommand()->createTable('tbl_news', [ 'id' => 'pk', 'title' => 'string NOT NULL', 'content' => 'text', - ))->execute(); + ])->execute(); $transaction->commit(); } catch(Exception $e) diff --git a/docs/guide/model.md b/docs/guide/model.md index b93fb7a..154fd38 100644 --- a/docs/guide/model.md +++ b/docs/guide/model.md @@ -77,10 +77,10 @@ class LoginForm extends \yii\base\Model public function attributeLabels() { - return array( + return [ 'username' => 'Your name', 'password' => 'Your password', - ); + ]; } } ``` @@ -105,10 +105,10 @@ class User extends \yii\db\ActiveRecord { public function scenarios() { - return array( - 'login' => array('username', 'password'), - 'register' => array('username', 'email', 'password'), - ); + return [ + 'login' => ['username', 'password'], + 'register' => ['username', 'email', 'password'], + ]; } } ``` @@ -117,7 +117,7 @@ Sometimes, we want to mark an attribute as not safe for massive assignment (but We may do so by prefixing an exclamation character to the attribute name when declaring it in `scenarios()`. For example, ```php -array('username', 'password', '!secret') +['username', 'password', '!secret'] ``` Active model scenario could be set using one of the following ways: @@ -128,14 +128,14 @@ class EmployeeController extends \yii\web\Controller public function actionCreate($id = null) { // first way - $employee = new Employee(array('scenario' => 'managementPanel')); + $employee = new Employee(['scenario' => 'managementPanel']); // second way $employee = new Employee; $employee->scenario = 'managementPanel'; // third way - $employee = Employee::find()->where('id = :id', array(':id' => $id))->one(); + $employee = Employee::find()->where('id = :id', [':id' => $id])->one(); if ($employee !== null) { $employee->setScenario('managementPanel'); } @@ -171,7 +171,7 @@ or several attributes and is effective in one or several scenarios. A rule can b instance of a [[\yii\validators\Validator]] child class, or an array with the following format: ```php -array( +[ 'attribute1, attribute2, ...', 'validator class or alias', // specifies in which scenario(s) this rule is active. @@ -182,7 +182,7 @@ array( 'property1' => 'value1', 'property2' => 'value2', // ... -) +] ``` When `validate()` is called, the actual validation rules executed are determined using both of the following criteria: @@ -216,10 +216,10 @@ var_dump($attributes); Using the same `attributes` property you can massively assign data from associative array to model attributes: ```php -$attributes = array( +$attributes = [ 'title' => 'Model attributes', 'create_time' => time(), -); +]; $post->attributes = $attributes; ``` @@ -238,24 +238,24 @@ assignment is described in `scenarios` method: ```php function rules() { - return array( + return [ // rule applied when corresponding field is "safe" - array('username', 'string', 'length' => array(4, 32)), - array('first_name', 'string', 'max' => 128), - array('password', 'required'), + ['username', 'string', 'length' => [4, 32]], + ['first_name', 'string', 'max' => 128], + ['password', 'required'], // rule applied when scenario is "signup" no matter if field is "safe" or not - array('hashcode', 'check', 'on' => 'signup'), - ); + ['hashcode', 'check', 'on' => 'signup'], + ]; } function scenarios() { - return array( + return [ // on signup allow mass assignment of username - 'signup' => array('username', 'password'), - 'update' => array('username', 'first_name'), - ); + 'signup' => ['username', 'password'], + 'update' => ['username', 'first_name'], + ]; } ``` diff --git a/docs/guide/performance.md b/docs/guide/performance.md index 3d89af9..d16d962 100644 --- a/docs/guide/performance.md +++ b/docs/guide/performance.md @@ -41,11 +41,11 @@ to save the time of parsing database schema. This can be done by setting the `protected/config/main.php`: ```php -return array( +return [ // ... - 'components' => array( + 'components' => [ // ... - 'db' => array( + 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=mydatabase', 'username' => 'root', @@ -57,12 +57,12 @@ return array( // Name of the cache component used. Default is 'cache'. //'schemaCache' => 'cache', - ), - 'cache' => array( + ], + 'cache' => [ 'class' => 'yii\caching\FileCache', - ), - ), -); + ], + ], +]; ``` Note that `cache` application component should be configured. @@ -79,10 +79,10 @@ switch to another storage such as database. You can do so by configuring your application via `protected/config/main.php`: ```php -return array( +return [ // ... - 'components' => array( - 'session' => array( + 'components' => [ + 'session' => [ 'class' => 'yii\web\DbSession', // Set the following if want to use DB component other than @@ -91,9 +91,9 @@ return array( // To override default session table set the following // 'sessionTable' => 'my_session', - ), - ), -); + ], + ], +]; ``` You can use `CacheSession` to store sessions using cache. Note that some @@ -154,9 +154,7 @@ class PostController extends Controller public function actionIndex() { $posts = Post::find()->orderBy('id DESC')->limit(100)->asArray()->all(); - return $this->render('index', array( - 'posts' => $posts, - )); + return $this->render('index', ['posts' => $posts]); } } ``` diff --git a/docs/guide/query-builder.md b/docs/guide/query-builder.md index 2ec2581..ffc9871 100644 --- a/docs/guide/query-builder.md +++ b/docs/guide/query-builder.md @@ -40,7 +40,7 @@ $query->select('user_id')->distinct()->from('tbl_post'); Select options can be specified as array. It's especially useful when these are formed dynamically. ```php -$query->select(array('tbl_user.name AS author', 'tbl_post.title as title')) // <-- specified as array +$query->select(['tbl_user.name AS author', 'tbl_post.title as title']) // <-- specified as array ->from('tbl_user') ->leftJoin('tbl_post', 'tbl_post.user_id = tbl_user.id'); // <-- join with another table ``` @@ -67,9 +67,7 @@ is `where`. There are multiple ways to use it. The simplest is to specify condition in a string: ```php -$query->where('status=:status', array( - ':status' => $status, -)); +$query->where('status=:status', [':status' => $status]); ``` When using this format make sure you're binding parameters and not creating a query by string concatenation. @@ -79,19 +77,17 @@ Instead of binding status value immediately you can do it using `params` or `add ```php $query->where('status=:status'); -$query->addParams(array( - ':status' => $status, -)); +$query->addParams([':status' => $status]); ``` There is another convenient way to use the method called hash format: ```php -$query->where(array( +$query->where([ 'status' => 10, 'type' => 2, - 'id' => array(4, 8, 15, 16, 23, 42), -)); + 'id' => [4, 8, 15, 16, 23, 42], +]); ``` It will generate the following SQL: @@ -103,9 +99,7 @@ WHERE (`status` = 10) AND (`type` = 2) AND (`id` IN (4, 8, 15, 16, 23, 42)) If you'll specify value as `null` such as the following: ```php -$query->where(array( - 'status' => null, -)); +$query->where(['status' => null]); ``` SQL generated will be: @@ -114,31 +108,31 @@ SQL generated will be: WHERE (`status` IS NULL) ``` -Another way to use the method is the operand format which is `array(operator, operand1, operand2, ...)`. +Another way to use the method is the operand format which is `[operator, operand1, operand2, ...]`. Operator can be one of the following: - `and`: the operands should be concatenated together using `AND`. For example, - `array('and', 'id=1', 'id=2')` will generate `id=1 AND id=2`. If an operand is an array, + `['and', 'id=1', 'id=2']` will generate `id=1 AND id=2`. If an operand is an array, it will be converted into a string using the rules described here. For example, - `array('and', 'type=1', array('or', 'id=1', 'id=2'))` will generate `type=1 AND (id=1 OR id=2)`. + `['and', 'type=1', ['or', 'id=1', 'id=2']]` will generate `type=1 AND (id=1 OR id=2)`. The method will NOT do any quoting or escaping. - `or`: similar to the `and` operator except that the operands are concatenated using `OR`. - `between`: operand 1 should be the column name, and operand 2 and 3 should be the starting and ending values of the range that the column is in. - For example, `array('between', 'id', 1, 10)` will generate `id BETWEEN 1 AND 10`. + For example, `['between', 'id', 1, 10]` will generate `id BETWEEN 1 AND 10`. - `not between`: similar to `between` except the `BETWEEN` is replaced with `NOT BETWEEN` in the generated condition. - `in`: operand 1 should be a column or DB expression, and operand 2 be an array representing the range of the values that the column or DB expression should be in. For example, - `array('in', 'id', array(1, 2, 3))` will generate `id IN (1, 2, 3)`. + `['in', 'id', [1, 2, 3]]` will generate `id IN (1, 2, 3)`. The method will properly quote the column name and escape values in the range. - `not in`: similar to the `in` operator except that `IN` is replaced with `NOT IN` in the generated condition. - `like`: operand 1 should be a column or DB expression, and operand 2 be a string or an array representing the values that the column or DB expression should be like. - For example, `array('like', 'name', '%tester%')` will generate `name LIKE '%tester%'`. + For example, `['like', 'name', '%tester%']` will generate `name LIKE '%tester%'`. When the value range is given as an array, multiple `LIKE` predicates will be generated and concatenated - using `AND`. For example, `array('like', 'name', array('%test%', '%sample%'))` will generate + using `AND`. For example, `['like', 'name', ['%test%', '%sample%']]` will generate `name LIKE '%test%' AND name LIKE '%sample%'`. The method will properly quote the column name and escape values in the range. - `or like`: similar to the `like` operator except that `OR` is used to concatenate the `LIKE` @@ -154,7 +148,7 @@ If you are building parts of condition dynamically it's very convenient to use ` $status = 10; $search = 'yii'; -$query->where(array('status' => $status)); +$query->where(['status' => $status]); if (!empty($search)) { $query->addWhere('like', 'title', $search); } @@ -172,10 +166,10 @@ Order For ordering results `orderBy` and `addOrderBy` could be used: ```php -$query->orderBy(array( +$query->orderBy([ 'id' => Query::SORT_ASC, 'name' => Query::SORT_DESC, -)); +]); ``` Here we are ordering by `id` ascending and then by `name` descending. @@ -192,14 +186,14 @@ $query->groupBy('id, status'); If you want to add another field after using `groupBy`: ```php -$query->addGroupBy(array('created_at', 'updated_at')); +$query->addGroupBy(['created_at', 'updated_at']); ``` To add a `HAVING` condition the corresponding `having` method and its `andHaving` and `orHaving` can be used. Parameters for these are similar to the ones for `where` methods group: ```php -$query->having(array('status' => $status)); +$query->having(['status' => $status]); ``` Limit and offset diff --git a/docs/guide/template.md b/docs/guide/template.md index f9405ff..aec1a70 100644 --- a/docs/guide/template.md +++ b/docs/guide/template.md @@ -7,23 +7,23 @@ The `view` component is responsible for rendering views. You can add a custom template engines by reconfiguring this component's behavior: ```php -array( - 'components' => array( - 'view' => array( +[ + 'components' => [ + 'view' => [ 'class' => 'yii\base\View', - 'renderers' => array( - 'tpl' => array( + 'renderers' => [ + 'tpl' => [ 'class' => 'yii\renderers\SmartyViewRenderer', - ), - 'twig' => array( + ], + 'twig' => [ 'class' => 'yii\renderers\TwigViewRenderer', 'twigPath' => '@app/vendors/Twig', - ), + ], // ... - ), - ), - ), -) + ], + ], + ], +] ``` Note that the Smarty and Twig packages themselves are not bundled with Yii. You must download them yourself. Then unpack the packages and place the resulting files in a logical location, such as the application's `protected/vendor` folder. Finally, specify the correct `smartyPath` or `twigPath`, as in the code above (for Twig). @@ -36,7 +36,7 @@ Unlike standard view files, when using Twig, you must include the extension whe or `$this->renderPartial()` from your controller: ```php -echo $this->render('renderer.twig', array('username' => 'Alex')); +echo $this->render('renderer.twig', ['username' => 'Alex']); ``` ### Additional functions @@ -63,7 +63,7 @@ To use Smarty, you need to create templates in files with the `.tpl` extension ( or `$this->renderPartial()` from your controller: ```php -echo $this->render('renderer.tpl', array('username' => 'Alex')); +echo $this->render('renderer.tpl', ['username' => 'Alex']); ``` ### Additional functions diff --git a/docs/guide/upgrade-from-v1.md b/docs/guide/upgrade-from-v1.md index bf6e562..713f967 100644 --- a/docs/guide/upgrade-from-v1.md +++ b/docs/guide/upgrade-from-v1.md @@ -40,7 +40,7 @@ it can be properly configured: ```php class MyClass extends \yii\Object { - public function __construct($param1, $param2, $config = array()) + public function __construct($param1, $param2, $config = []) { // ... initialization before configuration is applied @@ -65,11 +65,11 @@ By following this convention, you will be able to create and configure a new obj using a configuration array like the following: ```php -$object = Yii::createObject(array( +$object = Yii::createObject([ 'class' => 'MyClass', 'property1' => 'abc', 'property2' => 'cde', -), $param1, $param2); +], $param1, $param2); ``` @@ -177,10 +177,10 @@ if (isset($_POST['Post'])) { $model->save(); -$postTags = array(); +$postTags = []; $tagsCount = count($_POST['PostTag']); while($tagsCount-- > 0){ - $postTags[] = new PostTag(array('post_id' => $model->id)); + $postTags[] = new PostTag(['post_id' => $model->id]); } Model::loadMultiple($postTags, $_POST); ``` @@ -193,10 +193,10 @@ a list of scenarios and the corresponding attributes that need to be validated w ```php public function scenarios() { - return array( - 'backend' => array('email', 'role'), - 'frontend' => array('email', '!name'), - ); + return [ + 'backend' => ['email', 'role'], + 'frontend' => ['email', '!name'], + ]; } ``` @@ -229,13 +229,13 @@ methods of the `Widget` class. For example, ```php // Note that you have to "echo" the result to display it -echo \yii\widgets\Menu::widget(array('items' => $items)); +echo \yii\widgets\Menu::widget(['items' => $items]); // Passing an array to initialize the object properties -$form = \yii\widgets\ActiveForm::begin(array( - 'options' => array('class' => 'form-horizontal'), - 'fieldConfig' => array('inputOptions' => array('class' => 'input-xlarge')), -)); +$form = \yii\widgets\ActiveForm::begin([ + 'options' => ['class' => 'form-horizontal'], + 'fieldConfig' => ['inputOptions' => ['class' => 'input-xlarge']], +]); ... form inputs here ... \yii\widgets\ActiveForm::end(); ``` @@ -249,7 +249,7 @@ Themes Themes work completely different in 2.0. They are now based on a path map to "translate" a source view into a themed view. For example, if the path map for a theme is -`array('/web/views' => '/web/themes/basic')`, then the themed version for a view file +`['/web/views' => '/web/themes/basic']`, then the themed version for a view file `/web/views/site/index.php` will be `/web/themes/basic/site/index.php`. For this reason, theme can now be applied to any view file, even if a view rendered outside @@ -295,11 +295,11 @@ code in a controller: ```php public function behaviors() { - return array( - 'access' => array( + return [ + 'access' => [ 'class' => 'yii\web\AccessControl', - 'rules' => array( - array('allow' => true, 'actions' => array('admin'), 'roles' => array('@')), + 'rules' => [ + ['allow' => true, 'actions' => ['admin'], 'roles' => ['@']], ), ), ); @@ -386,7 +386,7 @@ class Customer extends \yii\db\ActiveRecord { public function getOrders() { - return $this->hasMany('Order', array('customer_id' => 'id')); + return $this->hasMany('Order', ['customer_id' => 'id']); } } ``` @@ -409,7 +409,7 @@ use the `find()` method: ```php // to retrieve all *active* customers and order them by their ID: $customers = Customer::find() - ->where(array('status' => $active)) + ->where(['status' => $active]) ->orderBy('id') ->all(); // return the customer whose PK is 1 @@ -467,11 +467,11 @@ both `post/popular` and `post/1/popular`. In 1.1, you would have to use two rule the same goal. ```php -array( +[ 'pattern' => 'post//', 'route' => 'post/index', - 'defaults' => array('page' => 1), -) + 'defaults' => ['page' => 1], +] ``` diff --git a/docs/guide/validation.md b/docs/guide/validation.md index c555913..c8c8674 100644 --- a/docs/guide/validation.md +++ b/docs/guide/validation.md @@ -90,16 +90,16 @@ Converts the attribute value according to a filter. Typically a callback is either the name of PHP function: ```php -array('password', 'filter', 'filter' => 'trim'), +['password', 'filter', 'filter' => 'trim'], ``` Or an anonymous function: ```php -array('text', 'filter', 'filter' => function ($value) { +['text', 'filter', 'filter' => function ($value) { // here we are removing all swear words from text return $newValue; -}), +}], ``` ### `in`: [[RangeValidator]] @@ -139,7 +139,7 @@ Serves as a dummy validator whose main purpose is to mark the attributes to be s Validates that the attribute value is of certain length. -- `length` specifies the length limit of the value to be validated. Can be `exactly X`, `array(min X)`, `array(min X, max Y)`. +- `length` specifies the length limit of the value to be validated. Can be `exactly X`, `[min X]`, `[min X, max Y]`. - `max` maximum length. If not set, it means no maximum length limit. - `min` minimum length. If not set, it means no minimum length limit. - `encoding` the encoding of the string value to be validated. _([[\yii\base\Application::charset]])_ @@ -157,7 +157,7 @@ Validates that the attribute value is unique in the corresponding database table Validates that the attribute value is a valid http or https URL. -- `validSchemes` list of URI schemes which should be considered valid. _array('http', 'https')_ +- `validSchemes` list of URI schemes which should be considered valid. _['http', 'https']_ - `defaultScheme` the default URI scheme. If the input doesn't contain the scheme part, the default scheme will be prepended to it. _(null)_ - `enableIDN` whether validation process should take into account IDN (internationalized domain names). _(false)_ diff --git a/docs/guide/view.md b/docs/guide/view.md index be64d22..27a90ae 100644 --- a/docs/guide/view.md +++ b/docs/guide/view.md @@ -16,9 +16,7 @@ View is typically called from controller action like the following: ```php public function actionIndex() { - return $this->render('index', array( - 'username' => 'samdark', - )); + return $this->render('index', ['username' => 'samdark']); } ``` @@ -47,13 +45,13 @@ In order to use widget you need to do the following: ```php // Note that you have to "echo" the result to display it -echo \yii\widgets\Menu::widget(array('items' => $items)); +echo \yii\widgets\Menu::widget(['items' => $items]); // Passing an array to initialize the object properties -$form = \yii\widgets\ActiveForm::begin(array( - 'options' => array('class' => 'form-horizontal'), - 'fieldConfig' => array('inputOptions' => array('class' => 'input-xlarge')), -)); +$form = \yii\widgets\ActiveForm::begin([ + 'options' => ['class' => 'form-horizontal'], + 'fieldConfig' => ['inputOptions' => ['class' => 'input-xlarge']], +]); ... form inputs here ... \yii\widgets\ActiveForm::end(); ``` @@ -132,7 +130,7 @@ $this->title = 'My page title'; Adding meta tags such as encoding, description, keywords is easy with view object as well: ```php -$this->registerMetaTag(array('encoding' => 'utf-8')); +$this->registerMetaTag(['encoding' => 'utf-8']); ``` The first argument is an map of `` tag option names and values. The code above will produce: @@ -144,8 +142,8 @@ The first argument is an map of `` tag option names and values. The code a Sometimes there's a need to have only a single tag of a type. In this case you need to specify the second argument: ```html -$this->registerMetaTag(array('description' => 'This is my cool website made with Yii!'), 'meta-description'); -$this->registerMetaTag(array('description' => 'This website is about funny raccoons.'), 'meta-description'); +$this->registerMetaTag(['description' => 'This is my cool website made with Yii!'], 'meta-description'); +$this->registerMetaTag(['description' => 'This website is about funny raccoons.'], 'meta-description'); ``` If there are multiple calls with the same value of the second argument (`meta-description` in this case), the latter will @@ -161,12 +159,12 @@ override the former and only a single tag will be rendered: server. Yii view object has a method to work with these: ```php -$this->registerLinkTag(array( +$this->registerLinkTag([ 'title' => 'Lives News for Yii Framework', 'rel' => 'alternate', 'type' => 'application/rss+xml', 'href' => 'http://www.yiiframework.com/rss.xml/', -)); +]); ``` The code above will result in @@ -200,7 +198,7 @@ If you want to specify additional properties of the style tag, pass array of nam need to make sure there's only a single style tag use third argument as was mentioned in meta tags description. ```php -$this->registerCssFile("http://example.com/css/themes/black-and-white.css", array('media' => 'print'), 'css-print-theme'); +$this->registerCssFile("http://example.com/css/themes/black-and-white.css", ['media' => 'print'], 'css-print-theme'); ``` The code above will add a link to CSS file to the head section of the page. The CSS will be used only when printing the @@ -308,10 +306,10 @@ Then we're using it in `index.php` view where we display a list of users:
render('_profile', array( + echo $this->render('_profile', [ 'username' => $user->name, 'tagline' => $user->tagline, - )); + ]); } ?>
@@ -320,10 +318,10 @@ Then we're using it in `index.php` view where we display a list of users: Same way we can reuse it in another view displaying a single user profile: ```php -echo $this->render('_profile', array( +echo $this->render('_profile', [ 'username' => $user->name, 'tagline' => $user->tagline, -)); +]); ``` ### Accessing context @@ -347,13 +345,13 @@ Since view is also an application component named `view` you can replace it with from `yii\base\View`. It can be done via application configuration file such as `config/web.php`: ```php -return array( +return [ // ... - 'components' => array( - 'view' => array( + 'components' => [ + 'view' => [ 'class' => 'app\components\View', - ), + ], // ... - ), -); + ], +]; ``` diff --git a/docs/internals/ar.md b/docs/internals/ar.md index d59ba6a..d186939 100644 --- a/docs/internals/ar.md +++ b/docs/internals/ar.md @@ -9,16 +9,16 @@ Possible scenario formats supported by ActiveRecord: ```php public function scenarios() { - return array( + return [ // attributes array, all operations won't be wrapped with transaction - 'scenario1' => array('attribute1', 'attribute2'), + 'scenario1' => ['attribute1', 'attribute2'], // insert and update operations will be wrapped with transaction, delete won't be wrapped - 'scenario2' => array( - 'attributes' => array('attribute1', 'attribute2'), - 'atomic' => array(self::OP_INSERT, self::OP_UPDATE), - ), - ); + 'scenario2' => [ + 'attributes' => ['attribute1', 'attribute2'], + 'atomic' => [self::OP_INSERT, self::OP_UPDATE], + ], + ]; } ``` diff --git a/extensions/composer/yii/composer/InstallHandler.php b/extensions/composer/yii/composer/InstallHandler.php index be4037b..289262f 100644 --- a/extensions/composer/yii/composer/InstallHandler.php +++ b/extensions/composer/yii/composer/InstallHandler.php @@ -36,10 +36,10 @@ class InstallHandler */ public static function setPermissions($event) { - $options = array_merge(array( - self::PARAM_WRITABLE => array(), - self::PARAM_EXECUTABLE => array(), - ), $event->getComposer()->getPackage()->getExtra()); + $options = array_merge([ + self::PARAM_WRITABLE => [], + self::PARAM_EXECUTABLE => [], + ], $event->getComposer()->getPackage()->getExtra()); foreach ((array)$options[self::PARAM_WRITABLE] as $path) { echo "Setting writable: $path ..."; @@ -70,9 +70,9 @@ class InstallHandler */ public static function run($event) { - $options = array_merge(array( - self::PARAM_COMMANDS => array(), - ), $event->getComposer()->getPackage()->getExtra()); + $options = array_merge([ + self::PARAM_COMMANDS => [], + ], $event->getComposer()->getPackage()->getExtra()); if (!isset($options[self::PARAM_CONFIG])) { throw new Exception('Please specify the "' . self::PARAM_CONFIG . '" parameter in composer.json.'); diff --git a/extensions/composer/yii/composer/Installer.php b/extensions/composer/yii/composer/Installer.php index 8b5b9ea..3082c3b 100644 --- a/extensions/composer/yii/composer/Installer.php +++ b/extensions/composer/yii/composer/Installer.php @@ -63,7 +63,7 @@ class Installer extends LibraryInstaller protected function addPackage(PackageInterface $package) { - $extension = array('name' => $package->getPrettyName()); + $extension = ['name' => $package->getPrettyName()]; $root = $package->getPrettyName(); if ($targetDir = $package->getTargetDir()) { @@ -112,7 +112,7 @@ class Installer extends LibraryInstaller { $file = $this->vendorDir . '/yii-extensions.php'; if (!is_file($file)) { - return array(); + return []; } $extensions = require($file); /** @var string $vendorDir defined in yii-extensions.php */ @@ -147,10 +147,10 @@ class Installer extends LibraryInstaller */ public static function setPermissions($event) { - $options = array_merge(array( - self::EXTRA_WRITABLES => array(), - self::EXTRA_EXECUTABLES => array(), - ), $event->getComposer()->getPackage()->getExtra()); + $options = array_merge([ + self::EXTRA_WRITABLES => [], + self::EXTRA_EXECUTABLES => [], + ], $event->getComposer()->getPackage()->getExtra()); foreach ((array)$options[self::EXTRA_WRITABLES] as $path) { echo "Setting writable: $path ..."; @@ -181,9 +181,9 @@ class Installer extends LibraryInstaller */ public static function run($event) { - $options = array_merge(array( - self::EXTRA_COMMANDS => array(), - ), $event->getComposer()->getPackage()->getExtra()); + $options = array_merge([ + self::EXTRA_COMMANDS => [], + ], $event->getComposer()->getPackage()->getExtra()); if (!isset($options[self::EXTRA_CONFIG])) { throw new Exception('Please specify the "' . self::EXTRA_CONFIG . '" parameter in composer.json.'); diff --git a/extensions/jui/README.md b/extensions/jui/README.md index 0403acb..260f69a 100644 --- a/extensions/jui/README.md +++ b/extensions/jui/README.md @@ -44,11 +44,11 @@ You can use these widgets in your view files after you have registered the corre Example: ```php -echo ProgressBar::widget(array( - 'clientOptions' => array( +echo ProgressBar::widget([ + 'clientOptions' => [ 'value' => 75, - ), -)); + ], +]); ``` For further instructions refer to the yii guide. diff --git a/extensions/jui/yii/jui/Accordion.php b/extensions/jui/yii/jui/Accordion.php index 7f32bc2..42897a9 100644 --- a/extensions/jui/yii/jui/Accordion.php +++ b/extensions/jui/yii/jui/Accordion.php @@ -17,36 +17,24 @@ use yii\helpers\Html; * For example: * * ```php - * echo Accordion::widget(array( - * 'items' => array( - * array( + * echo Accordion::widget([ + * 'items' => [ + * [ * 'header' => 'Section 1', * 'content' => 'Mauris mauris ante, blandit et, ultrices a, suscipit eget...', - * ), - * array( + * ], + * [ * 'header' => 'Section 2', - * 'headerOptions' => array( - * 'tag' => 'h3', - * ), + * 'headerOptions' => ['tag' => 'h3'], * 'content' => 'Sed non urna. Phasellus eu ligula. Vestibulum sit amet purus...', - * 'options' => array( - * 'tag' => 'div', - * ), - * ), - * ), - * 'options' => array( - * 'tag' => 'div', - * ), - * 'itemOptions' => array( - * 'tag' => 'div', - * ), - * 'headerOptions' => array( - * 'tag' => 'h3', - * ), - * 'clientOptions' => array( - * 'collapsible' => false, - * ), - * )); + * 'options' => ['tag' => 'div'], + * ], + * ], + * 'options' => ['tag' => 'div'], + * 'itemOptions' => ['tag' => 'div'], + * 'headerOptions' => ['tag' => 'h3'], + * 'clientOptions' => ['collapsible' => false], + * ]); * ``` * * @see http://api.jqueryui.com/accordion/ @@ -60,36 +48,36 @@ class Accordion extends Widget * * - tag: string, defaults to "div", the tag name of the container tag of this widget */ - public $options = array(); + public $options = []; /** * @var array list of collapsible items. Each item can be an array of the following structure: * * ~~~ - * array( + * [ * 'header' => 'Item header', * 'content' => 'Item content', * // the HTML attributes of the item header container tag. This will overwrite "headerOptions". - * 'headerOptions' => array(), + * 'headerOptions' => [], * // the HTML attributes of the item container tag. This will overwrite "itemOptions". - * 'options' => array(), - * ) + * 'options' => [], + * ] * ~~~ */ - public $items = array(); + public $items = []; /** * @var array list of HTML attributes for the item container tags. This will be overwritten * by the "options" set in individual [[items]]. The following special options are recognized: * * - tag: string, defaults to "div", the tag name of the item container tags. */ - public $itemOptions = array(); + public $itemOptions = []; /** * @var array list of HTML attributes for the item header container tags. This will be overwritten * by the "headerOptions" set in individual [[items]]. The following special options are recognized: * * - tag: string, defaults to "h3", the tag name of the item container tags. */ - public $headerOptions = array(); + public $headerOptions = []; /** @@ -112,7 +100,7 @@ class Accordion extends Widget */ protected function renderItems() { - $items = array(); + $items = []; foreach ($this->items as $item) { if (!isset($item['header'])) { throw new InvalidConfigException("The 'header' option is required."); @@ -120,10 +108,10 @@ class Accordion extends Widget if (!isset($item['content'])) { throw new InvalidConfigException("The 'content' option is required."); } - $headerOptions = array_merge($this->headerOptions, ArrayHelper::getValue($item, 'headerOptions', array())); + $headerOptions = array_merge($this->headerOptions, ArrayHelper::getValue($item, 'headerOptions', [])); $headerTag = ArrayHelper::remove($headerOptions, 'tag', 'h3'); $items[] = Html::tag($headerTag, $item['header'], $headerOptions); - $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', array())); + $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', [])); $tag = ArrayHelper::remove($options, 'tag', 'div'); $items[] = Html::tag($tag, $item['content'], $options); } diff --git a/extensions/jui/yii/jui/AccordionAsset.php b/extensions/jui/yii/jui/AccordionAsset.php index ae6accb..a032429 100644 --- a/extensions/jui/yii/jui/AccordionAsset.php +++ b/extensions/jui/yii/jui/AccordionAsset.php @@ -15,11 +15,11 @@ use yii\web\AssetBundle; class AccordionAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.accordion.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\jui\CoreAsset', 'yii\jui\EffectAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/AutoComplete.php b/extensions/jui/yii/jui/AutoComplete.php index be31c55..ac0c997 100644 --- a/extensions/jui/yii/jui/AutoComplete.php +++ b/extensions/jui/yii/jui/AutoComplete.php @@ -16,24 +16,24 @@ use yii\helpers\Html; * For example: * * ```php - * echo AutoComplete::widget(array( + * echo AutoComplete::widget([ * 'model' => $model, * 'attribute' => 'country', - * 'clientOptions' => array( - * 'source' => array('USA', 'RUS'), - * ), - * )); + * 'clientOptions' => [ + * 'source' => ['USA', 'RUS'], + * ], + * ]); * ``` * * The following example will use the name property instead: * * ```php - * echo AutoComplete::widget(array( - * 'name' => 'country', - * 'clientOptions' => array( - * 'source' => array('USA', 'RUS'), - * ), - * )); + * echo AutoComplete::widget([ + * 'name' => 'country', + * 'clientOptions' => [ + * 'source' => ['USA', 'RUS'], + * ], + * ]); *``` * * @see http://api.jqueryui.com/autocomplete/ diff --git a/extensions/jui/yii/jui/AutoCompleteAsset.php b/extensions/jui/yii/jui/AutoCompleteAsset.php index d0af190..f48e064 100644 --- a/extensions/jui/yii/jui/AutoCompleteAsset.php +++ b/extensions/jui/yii/jui/AutoCompleteAsset.php @@ -15,11 +15,11 @@ use yii\web\AssetBundle; class AutoCompleteAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.autocomplete.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\jui\CoreAsset', 'yii\jui\MenuAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/ButtonAsset.php b/extensions/jui/yii/jui/ButtonAsset.php index 1676e8e..6616b34 100644 --- a/extensions/jui/yii/jui/ButtonAsset.php +++ b/extensions/jui/yii/jui/ButtonAsset.php @@ -15,10 +15,10 @@ use yii\web\AssetBundle; class ButtonAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.button.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\jui\CoreAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/CoreAsset.php b/extensions/jui/yii/jui/CoreAsset.php index 2f0d62a..d77a25f 100644 --- a/extensions/jui/yii/jui/CoreAsset.php +++ b/extensions/jui/yii/jui/CoreAsset.php @@ -15,13 +15,13 @@ use yii\web\AssetBundle; class CoreAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.core.js', 'jquery.ui.widget.js', 'jquery.ui.position.js', 'jquery.ui.mouse.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\web\JqueryAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/DatePicker.php b/extensions/jui/yii/jui/DatePicker.php index 1d3012d..06ca356 100644 --- a/extensions/jui/yii/jui/DatePicker.php +++ b/extensions/jui/yii/jui/DatePicker.php @@ -17,26 +17,26 @@ use yii\helpers\Json; * For example: * * ```php - * echo DatePicker::widget(array( + * echo DatePicker::widget([ * 'language' => 'ru', * 'model' => $model, * 'attribute' => 'country', - * 'clientOptions' => array( + * 'clientOptions' => [ * 'dateFormat' => 'yy-mm-dd', - * ), - * )); + * ], + * ]); * ``` * * The following example will use the name property instead: * * ```php - * echo DatePicker::widget(array( + * echo DatePicker::widget([ * 'language' => 'ru', * 'name' => 'country', - * 'clientOptions' => array( + * 'clientOptions' => [ * 'dateFormat' => 'yy-mm-dd', - * ), - * )); + * ], + * ]); *``` * * @see http://api.jqueryui.com/datepicker/ @@ -84,7 +84,7 @@ class DatePicker extends InputWidget */ protected function renderWidget() { - $contents = array(); + $contents = []; if ($this->inline === false) { if ($this->hasModel()) { diff --git a/extensions/jui/yii/jui/DatePickerAsset.php b/extensions/jui/yii/jui/DatePickerAsset.php index 4102675..fddd8df 100644 --- a/extensions/jui/yii/jui/DatePickerAsset.php +++ b/extensions/jui/yii/jui/DatePickerAsset.php @@ -15,11 +15,11 @@ use yii\web\AssetBundle; class DatePickerAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.datepicker.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\jui\CoreAsset', 'yii\jui\EffectAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/DatePickerRegionalAsset.php b/extensions/jui/yii/jui/DatePickerRegionalAsset.php index 44fc60a..249373a 100644 --- a/extensions/jui/yii/jui/DatePickerRegionalAsset.php +++ b/extensions/jui/yii/jui/DatePickerRegionalAsset.php @@ -15,10 +15,10 @@ use yii\web\AssetBundle; class DatePickerRegionalAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.datepicker-i18n.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\jui\DatePickerAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/Dialog.php b/extensions/jui/yii/jui/Dialog.php index 1285a90..a5cbaf2 100644 --- a/extensions/jui/yii/jui/Dialog.php +++ b/extensions/jui/yii/jui/Dialog.php @@ -15,11 +15,11 @@ use yii\helpers\Html; * For example: * * ```php - * Dialog::begin(array( - * 'clientOptions' => array( + * Dialog::begin([ + * 'clientOptions' => [ * 'modal' => true, - * ), - * )); + * ], + * ]); * * echo 'Dialog contents here...'; * diff --git a/extensions/jui/yii/jui/DialogAsset.php b/extensions/jui/yii/jui/DialogAsset.php index 04ba950..109243e 100644 --- a/extensions/jui/yii/jui/DialogAsset.php +++ b/extensions/jui/yii/jui/DialogAsset.php @@ -15,13 +15,13 @@ use yii\web\AssetBundle; class DialogAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.dialog.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\jui\CoreAsset', 'yii\jui\ButtonAsset', 'yii\jui\DraggableAsset', 'yii\jui\ResizableAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/Draggable.php b/extensions/jui/yii/jui/Draggable.php index 5fa6491..02e4973 100644 --- a/extensions/jui/yii/jui/Draggable.php +++ b/extensions/jui/yii/jui/Draggable.php @@ -15,11 +15,9 @@ use yii\helpers\Html; * For example: * * ```php - * Draggable::begin(array( - * 'clientOptions' => array( - * 'grid' => array(50, 20), - * ), - * )); + * Draggable::begin([ + * 'clientOptions' => ['grid' => [50, 20]], + * ]); * * echo 'Draggable contents here...'; * diff --git a/extensions/jui/yii/jui/DraggableAsset.php b/extensions/jui/yii/jui/DraggableAsset.php index 44f8e66..f3286a5 100644 --- a/extensions/jui/yii/jui/DraggableAsset.php +++ b/extensions/jui/yii/jui/DraggableAsset.php @@ -15,10 +15,10 @@ use yii\web\AssetBundle; class DraggableAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.draggable.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\jui\CoreAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/Droppable.php b/extensions/jui/yii/jui/Droppable.php index d9f366c..530e736 100644 --- a/extensions/jui/yii/jui/Droppable.php +++ b/extensions/jui/yii/jui/Droppable.php @@ -15,11 +15,9 @@ use yii\helpers\Html; * For example: * * ```php - * Droppable::begin(array( - * 'clientOptions' => array( - * 'accept' => '.special', - * ), - * )); + * Droppable::begin([ + * 'clientOptions' => ['accept' => '.special'], + * ]); * * echo 'Droppable body here...'; * diff --git a/extensions/jui/yii/jui/DroppableAsset.php b/extensions/jui/yii/jui/DroppableAsset.php index 3274c74..84b64b8 100644 --- a/extensions/jui/yii/jui/DroppableAsset.php +++ b/extensions/jui/yii/jui/DroppableAsset.php @@ -15,10 +15,10 @@ use yii\web\AssetBundle; class DroppableAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.droppable.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\jui\DraggableAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/EffectAsset.php b/extensions/jui/yii/jui/EffectAsset.php index b882f45..79c5aaa 100644 --- a/extensions/jui/yii/jui/EffectAsset.php +++ b/extensions/jui/yii/jui/EffectAsset.php @@ -15,10 +15,10 @@ use yii\web\AssetBundle; class EffectAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.effect-all.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\web\JqueryAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/Menu.php b/extensions/jui/yii/jui/Menu.php index a2aadd9..46c7ee0 100644 --- a/extensions/jui/yii/jui/Menu.php +++ b/extensions/jui/yii/jui/Menu.php @@ -25,14 +25,14 @@ class Menu extends \yii\widgets\Menu * For example, [this page](http://api.jqueryui.com/accordion/) shows * how to use the "Accordion" widget and the supported options (e.g. "header"). */ - public $clientOptions = array(); + public $clientOptions = []; /** * @var array the event handlers for the underlying jQuery UI widget. * Please refer to the corresponding jQuery UI widget Web page for possible events. * For example, [this page](http://api.jqueryui.com/accordion/) shows * how to use the "Accordion" widget and the supported events (e.g. "create"). */ - public $clientEvents = array(); + public $clientEvents = []; /** @@ -68,7 +68,7 @@ class Menu extends \yii\widgets\Menu } if (!empty($this->clientEvents)) { - $js = array(); + $js = []; foreach ($this->clientEvents as $event => $handler) { $js[] = "jQuery('#$id').on('menu$event', $handler);"; } diff --git a/extensions/jui/yii/jui/MenuAsset.php b/extensions/jui/yii/jui/MenuAsset.php index 96a11a5..8b840a8 100644 --- a/extensions/jui/yii/jui/MenuAsset.php +++ b/extensions/jui/yii/jui/MenuAsset.php @@ -15,10 +15,10 @@ use yii\web\AssetBundle; class MenuAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.menu.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\jui\CoreAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/ProgressBar.php b/extensions/jui/yii/jui/ProgressBar.php index b06c06a..1c555f1 100644 --- a/extensions/jui/yii/jui/ProgressBar.php +++ b/extensions/jui/yii/jui/ProgressBar.php @@ -15,22 +15,20 @@ use yii\helpers\Html; * For example: * * ```php - * echo ProgressBar::widget(array( - * 'clientOptions' => array( + * echo ProgressBar::widget([ + * 'clientOptions' => [ * 'value' => 75, - * ), - * )); + * ], + * ]); * ``` * * The following example will show the content enclosed between the [[begin()]] * and [[end()]] calls within the widget container: * * ~~~php - * ProgressBar::widget(array( - * 'clientOptions' => array( - * 'value' => 75, - * ), - * )); + * ProgressBar::widget([ + * 'clientOptions' => ['value' => 75], + * ]); * * echo '
Loading...
'; * diff --git a/extensions/jui/yii/jui/ProgressBarAsset.php b/extensions/jui/yii/jui/ProgressBarAsset.php index cc36d03..d485fbd 100644 --- a/extensions/jui/yii/jui/ProgressBarAsset.php +++ b/extensions/jui/yii/jui/ProgressBarAsset.php @@ -15,10 +15,10 @@ use yii\web\AssetBundle; class ProgressBarAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.progressbar.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\jui\CoreAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/Resizable.php b/extensions/jui/yii/jui/Resizable.php index 21ec70c..bcff9a8 100644 --- a/extensions/jui/yii/jui/Resizable.php +++ b/extensions/jui/yii/jui/Resizable.php @@ -15,11 +15,11 @@ use yii\helpers\Html; * For example: * * ```php - * Resizable::begin(array( - * 'clientOptions' => array( - * 'grid' => array(20, 10), - * ), - * )); + * Resizable::begin([ + * 'clientOptions' => [ + * 'grid' => [20, 10], + * ], + * ]); * * echo 'Resizable contents here...'; * diff --git a/extensions/jui/yii/jui/ResizableAsset.php b/extensions/jui/yii/jui/ResizableAsset.php index 35b4849..acf4c73 100644 --- a/extensions/jui/yii/jui/ResizableAsset.php +++ b/extensions/jui/yii/jui/ResizableAsset.php @@ -15,10 +15,10 @@ use yii\web\AssetBundle; class ResizableAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.resizable.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\jui\CoreAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/Selectable.php b/extensions/jui/yii/jui/Selectable.php index b77cfa9..94e4faf 100644 --- a/extensions/jui/yii/jui/Selectable.php +++ b/extensions/jui/yii/jui/Selectable.php @@ -17,29 +17,29 @@ use yii\helpers\Html; * For example: * * ```php - * echo Selectable::widget(array( - * 'items' => array( + * echo Selectable::widget([ + * 'items' => [ * 'Item 1', - * array( + * [ * 'content' => 'Item2', - * ), - * array( + * ], + * [ * 'content' => 'Item3', - * 'options' => array( + * 'options' => [ * 'tag' => 'li', - * ), - * ), + * ], + * ], * ), - * 'options' => array( + * 'options' => [ * 'tag' => 'ul', - * ), - * 'itemOptions' => array( + * ], + * 'itemOptions' => [ * 'tag' => 'li', - * ), - * 'clientOptions' => array( + * ], + * 'clientOptions' => [ * 'tolerance' => 'fit', - * ), - * )); + * ], + * ]); * ``` * * @see http://api.jqueryui.com/selectable/ @@ -53,27 +53,27 @@ class Selectable extends Widget * * - tag: string, defaults to "ul", the tag name of the container tag of this widget */ - public $options = array(); + public $options = []; /** * @var array list of selectable items. Each item can be a string representing the item content * or an array of the following structure: * * ~~~ - * array( + * [ * 'content' => 'item content', * // the HTML attributes of the item container tag. This will overwrite "itemOptions". - * 'options' => array(), - * ) + * 'options' => [], + * ] * ~~~ */ - public $items = array(); + public $items = []; /** * @var array list of HTML attributes for the item container tags. This will be overwritten * by the "options" set in individual [[items]]. The following special options are recognized: * * - tag: string, defaults to "li", the tag name of the item container tags. */ - public $itemOptions = array(); + public $itemOptions = []; /** @@ -96,7 +96,7 @@ class Selectable extends Widget */ public function renderItems() { - $items = array(); + $items = []; foreach ($this->items as $item) { $options = $this->itemOptions; $tag = ArrayHelper::remove($options, 'tag', 'li'); @@ -104,7 +104,7 @@ class Selectable extends Widget if (!isset($item['content'])) { throw new InvalidConfigException("The 'content' option is required."); } - $options = array_merge($options, ArrayHelper::getValue($item, 'options', array())); + $options = array_merge($options, ArrayHelper::getValue($item, 'options', [])); $tag = ArrayHelper::remove($options, 'tag', $tag); $items[] = Html::tag($tag, $item['content'], $options); } else { diff --git a/extensions/jui/yii/jui/SelectableAsset.php b/extensions/jui/yii/jui/SelectableAsset.php index 59cd485..61f405f 100644 --- a/extensions/jui/yii/jui/SelectableAsset.php +++ b/extensions/jui/yii/jui/SelectableAsset.php @@ -15,10 +15,10 @@ use yii\web\AssetBundle; class SelectableAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.selectable.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\jui\CoreAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/Slider.php b/extensions/jui/yii/jui/Slider.php index e1adb2b..c19f2db 100644 --- a/extensions/jui/yii/jui/Slider.php +++ b/extensions/jui/yii/jui/Slider.php @@ -16,26 +16,26 @@ use yii\helpers\Html; * For example: * * ```php - * echo Slider::widget(array( + * echo Slider::widget([ * 'model' => $model, * 'attribute' => 'amount', - * 'clientOptions' => array( + * 'clientOptions' => [ * 'min' => 1, * 'max' => 10, - * ), - * )); + * ], + * ]); * ``` * * The following example will use the name property instead: * * ```php - * echo Slider::widget(array( + * echo Slider::widget([ * 'name' => 'amount', - * 'clientOptions' => array( + * 'clientOptions' => [ * 'min' => 1, * 'max' => 10, - * ), - * )); + * ], + * ]); *``` * * @see http://api.jqueryui.com/slider/ diff --git a/extensions/jui/yii/jui/SliderAsset.php b/extensions/jui/yii/jui/SliderAsset.php index f0c7dc2..56c2451 100644 --- a/extensions/jui/yii/jui/SliderAsset.php +++ b/extensions/jui/yii/jui/SliderAsset.php @@ -15,10 +15,10 @@ use yii\web\AssetBundle; class SliderAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.slider.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\jui\CoreAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/Sortable.php b/extensions/jui/yii/jui/Sortable.php index 6c0d48a..6209cb6 100644 --- a/extensions/jui/yii/jui/Sortable.php +++ b/extensions/jui/yii/jui/Sortable.php @@ -17,28 +17,18 @@ use yii\helpers\Html; * For example: * * ```php - * echo Sortable::widget(array( - * 'items' => array( + * echo Sortable::widget([ + * 'items' => [ * 'Item 1', - * array( - * 'content' => 'Item2', - * ), - * array( + * ['content' => 'Item2'], + * [ * 'content' => 'Item3', - * 'options' => array( - * 'tag' => 'li', - * ), - * ), - * ), - * 'options' => array( - * 'tag' => 'ul', - * ), - * 'itemOptions' => array( - * 'tag' => 'li', - * ), - * 'clientOptions' => array( - * 'cursor' => 'move', - * ), + * 'options' => ['tag' => 'li'], + * ], + * ], + * 'options' => ['tag' => 'ul'], + * 'itemOptions' => ['tag' => 'li'], + * 'clientOptions' => ['cursor' => 'move'], * )); * ``` * @@ -53,27 +43,27 @@ class Sortable extends Widget * * - tag: string, defaults to "ul", the tag name of the container tag of this widget */ - public $options = array(); + public $options = []; /** * @var array list of sortable items. Each item can be a string representing the item content * or an array of the following structure: * * ~~~ - * array( + * [ * 'content' => 'item content', * // the HTML attributes of the item container tag. This will overwrite "itemOptions". - * 'options' => array(), - * ) + * 'options' => [], + * ] * ~~~ */ - public $items = array(); + public $items = []; /** * @var array list of HTML attributes for the item container tags. This will be overwritten * by the "options" set in individual [[items]]. The following special options are recognized: * * - tag: string, defaults to "li", the tag name of the item container tags. */ - public $itemOptions = array(); + public $itemOptions = []; /** @@ -96,7 +86,7 @@ class Sortable extends Widget */ public function renderItems() { - $items = array(); + $items = []; foreach ($this->items as $item) { $options = $this->itemOptions; $tag = ArrayHelper::remove($options, 'tag', 'li'); @@ -104,7 +94,7 @@ class Sortable extends Widget if (!isset($item['content'])) { throw new InvalidConfigException("The 'content' option is required."); } - $options = array_merge($options, ArrayHelper::getValue($item, 'options', array())); + $options = array_merge($options, ArrayHelper::getValue($item, 'options', [])); $tag = ArrayHelper::remove($options, 'tag', $tag); $items[] = Html::tag($tag, $item['content'], $options); } else { diff --git a/extensions/jui/yii/jui/SortableAsset.php b/extensions/jui/yii/jui/SortableAsset.php index 9a19e64..69c9ba3 100644 --- a/extensions/jui/yii/jui/SortableAsset.php +++ b/extensions/jui/yii/jui/SortableAsset.php @@ -15,10 +15,10 @@ use yii\web\AssetBundle; class SortableAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.sortable.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\jui\CoreAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/Spinner.php b/extensions/jui/yii/jui/Spinner.php index 29e947e..caf73f3 100644 --- a/extensions/jui/yii/jui/Spinner.php +++ b/extensions/jui/yii/jui/Spinner.php @@ -16,24 +16,20 @@ use yii\helpers\Html; * For example: * * ```php - * echo Spinner::widget(array( + * echo Spinner::widget([ * 'model' => $model, * 'attribute' => 'country', - * 'clientOptions' => array( - * 'step' => 2, - * ), - * )); + * 'clientOptions' => ['step' => 2], + * ]); * ``` * * The following example will use the name property instead: * * ```php - * echo Spinner::widget(array( + * echo Spinner::widget([ * 'name' => 'country', - * 'clientOptions' => array( - * 'step' => 2, - * ), - * )); + * 'clientOptions' => ['step' => 2], + * ]); *``` * * @see http://api.jqueryui.com/spinner/ diff --git a/extensions/jui/yii/jui/SpinnerAsset.php b/extensions/jui/yii/jui/SpinnerAsset.php index 2eb67f8..89a8c59 100644 --- a/extensions/jui/yii/jui/SpinnerAsset.php +++ b/extensions/jui/yii/jui/SpinnerAsset.php @@ -15,11 +15,11 @@ use yii\web\AssetBundle; class SpinnerAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.spinner.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\jui\CoreAsset', 'yii\jui\ButtonAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/Tabs.php b/extensions/jui/yii/jui/Tabs.php index 7ddf7bb..9d2a2be 100644 --- a/extensions/jui/yii/jui/Tabs.php +++ b/extensions/jui/yii/jui/Tabs.php @@ -17,47 +17,33 @@ use yii\helpers\Html; * For example: * * ```php - * echo Tabs::widget(array( - * 'items' => array( - * array( + * echo Tabs::widget([ + * 'items' => [ + * [ * 'label' => 'Tab one', * 'content' => 'Mauris mauris ante, blandit et, ultrices a, suscipit eget...', - * ), - * array( + * ], + * [ * 'label' => 'Tab two', * 'content' => 'Sed non urna. Phasellus eu ligula. Vestibulum sit amet purus...', - * 'options' => array( - * 'tag' => 'div', - * ), - * 'headerOptions' => array( - * 'class' => 'my-class', - * ), - * ), - * array( + * 'options' => ['tag' => 'div'], + * 'headerOptions' => ['class' => 'my-class'], + * ], + * [ * 'label' => 'Tab with custom id', * 'content' => 'Morbi tincidunt, dui sit amet facilisis feugiat...', - * 'options' => array( - * 'id' => 'my-tab', - * ), - * ), - * array( + * 'options' => ['id' => 'my-tab'], + * ], + * [ * 'label' => 'Ajax tab', - * 'url' => array('ajax/content'), - * ), + * 'url' => ['ajax/content'], + * ], * ), - * 'options' => array( - * 'tag' => 'div', - * ), - * 'itemOptions' => array( - * 'tag' => 'div', - * ), - * 'headerOptions' => array( - * 'class' => 'my-class', - * ), - * 'clientOptions' => array( - * 'collapsible' => false, - * ), - * )); + * 'options' => ['tag' => 'div'], + * 'itemOptions' => ['tag' => 'div'], + * 'headerOptions' => ['class' => 'my-class'], + * 'clientOptions' => ['collapsible' => false], + * ]); * ``` * * @see http://api.jqueryui.com/tabs/ @@ -71,7 +57,7 @@ class Tabs extends Widget * * - tag: string, defaults to "div", the tag name of the container tag of this widget */ - public $options = array(); + public $options = []; /** * @var array list of tab items. Each item can be an array of the following structure: * @@ -84,19 +70,19 @@ class Tabs extends Widget * - options: array, optional, the HTML attributes of the header. * - headerOptions: array, optional, the HTML attributes for the header container tag. */ - public $items = array(); + public $items = []; /** * @var array list of HTML attributes for the item container tags. This will be overwritten * by the "options" set in individual [[items]]. The following special options are recognized: * * - tag: string, defaults to "div", the tag name of the item container tags. */ - public $itemOptions = array(); + public $itemOptions = []; /** * @var array list of HTML attributes for the header container tags. This will be overwritten * by the "headerOptions" set in individual [[items]]. */ - public $headerOptions = array(); + public $headerOptions = []; /** * @var string the default header template to render the link. */ @@ -127,8 +113,8 @@ class Tabs extends Widget */ protected function renderItems() { - $headers = array(); - $items = array(); + $headers = []; + $items = []; foreach ($this->items as $n => $item) { if (!isset($item['label'])) { throw new InvalidConfigException("The 'label' option is required."); @@ -139,7 +125,7 @@ class Tabs extends Widget if (!isset($item['content'])) { throw new InvalidConfigException("The 'content' or 'url' option is required."); } - $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', array())); + $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', [])); $tag = ArrayHelper::remove($options, 'tag', 'div'); if (!isset($options['id'])) { $options['id'] = $this->options['id'] . '-tab' . $n; @@ -147,12 +133,12 @@ class Tabs extends Widget $url = '#' . $options['id']; $items[] = Html::tag($tag, $item['content'], $options); } - $headerOptions = array_merge($this->headerOptions, ArrayHelper::getValue($item, 'headerOptions', array())); + $headerOptions = array_merge($this->headerOptions, ArrayHelper::getValue($item, 'headerOptions', [])); $template = ArrayHelper::getValue($item, 'template', $this->linkTemplate); - $headers[] = Html::tag('li', strtr($template, array( + $headers[] = Html::tag('li', strtr($template, [ '{label}' => $this->encodeLabels ? Html::encode($item['label']) : $item['label'], '{url}' => $url, - )), $headerOptions); + ]), $headerOptions); } return Html::tag('ul', implode("\n", $headers)) . "\n" . implode("\n", $items); } diff --git a/extensions/jui/yii/jui/TabsAsset.php b/extensions/jui/yii/jui/TabsAsset.php index 2cdf477..5bef4c0 100644 --- a/extensions/jui/yii/jui/TabsAsset.php +++ b/extensions/jui/yii/jui/TabsAsset.php @@ -15,11 +15,11 @@ use yii\web\AssetBundle; class TabsAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.tabs.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\jui\CoreAsset', 'yii\jui\EffectAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/ThemeAsset.php b/extensions/jui/yii/jui/ThemeAsset.php index 2ca0631..dedcb00 100644 --- a/extensions/jui/yii/jui/ThemeAsset.php +++ b/extensions/jui/yii/jui/ThemeAsset.php @@ -15,7 +15,7 @@ use yii\web\AssetBundle; class ThemeAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $css = array( + public $css = [ 'theme/jquery.ui.css', - ); + ]; } diff --git a/extensions/jui/yii/jui/TooltipAsset.php b/extensions/jui/yii/jui/TooltipAsset.php index 9d6f781..1fa4490 100644 --- a/extensions/jui/yii/jui/TooltipAsset.php +++ b/extensions/jui/yii/jui/TooltipAsset.php @@ -15,11 +15,11 @@ use yii\web\AssetBundle; class TooltipAsset extends AssetBundle { public $sourcePath = '@yii/jui/assets'; - public $js = array( + public $js = [ 'jquery.ui.tooltip.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\jui\CoreAsset', 'yii\jui\EffectAsset', - ); + ]; } diff --git a/extensions/jui/yii/jui/Widget.php b/extensions/jui/yii/jui/Widget.php index 815bbe9..2bbc9e4 100644 --- a/extensions/jui/yii/jui/Widget.php +++ b/extensions/jui/yii/jui/Widget.php @@ -26,21 +26,21 @@ class Widget extends \yii\base\Widget /** * @var array the HTML attributes for the widget container tag. */ - public $options = array(); + public $options = []; /** * @var array the options for the underlying jQuery UI widget. * Please refer to the corresponding jQuery UI widget Web page for possible options. * For example, [this page](http://api.jqueryui.com/accordion/) shows * how to use the "Accordion" widget and the supported options (e.g. "header"). */ - public $clientOptions = array(); + public $clientOptions = []; /** * @var array the event handlers for the underlying jQuery UI widget. * Please refer to the corresponding jQuery UI widget Web page for possible events. * For example, [this page](http://api.jqueryui.com/accordion/) shows * how to use the "Accordion" widget and the supported events (e.g. "create"). */ - public $clientEvents = array(); + public $clientEvents = []; /** @@ -77,7 +77,7 @@ class Widget extends \yii\base\Widget } if (!empty($this->clientEvents)) { - $js = array(); + $js = []; foreach ($this->clientEvents as $event => $handler) { $js[] = "jQuery('#$id').on('$name$event', $handler);"; } diff --git a/extensions/jui/yii/jui/assets.php b/extensions/jui/yii/jui/assets.php index e6c5151..ab4c930 100644 --- a/extensions/jui/yii/jui/assets.php +++ b/extensions/jui/yii/jui/assets.php @@ -1,6 +1,6 @@ db - ->createCommand('SELECT GET_LOCK(:name, :timeout)', array(':name' => $name, ':timeout' => $timeout)) + ->createCommand('SELECT GET_LOCK(:name, :timeout)', [':name' => $name, ':timeout' => $timeout]) ->queryScalar(); } @@ -51,7 +51,7 @@ class MysqlMutex extends Mutex protected function releaseLock($name) { return (boolean)$this->db - ->createCommand('SELECT RELEASE_LOCK(:name)', array(':name' => $name)) + ->createCommand('SELECT RELEASE_LOCK(:name)', [':name' => $name]) ->queryScalar(); } } diff --git a/extensions/smarty/README.md b/extensions/smarty/README.md index adf764f..b73a507 100644 --- a/extensions/smarty/README.md +++ b/extensions/smarty/README.md @@ -45,20 +45,20 @@ Example: ```php array( - 'view' => array( + 'components' => [ + 'view' => [ 'class' => 'yii\base\View', - 'renderers' => array( - 'tpl' => array( + 'renderers' => [ + 'tpl' => [ 'class' => 'yii\smarty\ViewRenderer', //'cachePath' => '@runtime/Smarty/cache', - ), - ), - ), - ), -); + ], + ], + ], + ], +]; ``` For further instructions refer to the related section in the yii guide. diff --git a/extensions/smarty/yii/smarty/ViewRenderer.php b/extensions/smarty/yii/smarty/ViewRenderer.php index 7a9554e..2cfb216 100644 --- a/extensions/smarty/yii/smarty/ViewRenderer.php +++ b/extensions/smarty/yii/smarty/ViewRenderer.php @@ -44,7 +44,7 @@ class ViewRenderer extends BaseViewRenderer $this->smarty->setCompileDir(Yii::getAlias($this->compilePath)); $this->smarty->setCacheDir(Yii::getAlias($this->cachePath)); - $this->smarty->registerPlugin('function', 'path', array($this, 'smarty_function_path')); + $this->smarty->registerPlugin('function', 'path', [$this, 'smarty_function_path']); } /** diff --git a/extensions/twig/README.md b/extensions/twig/README.md index cc6bab0..57342f7 100644 --- a/extensions/twig/README.md +++ b/extensions/twig/README.md @@ -44,21 +44,21 @@ Example: ```php array( - 'view' => array( + 'components' => [ + 'view' => [ 'class' => 'yii\base\View', - 'renderers' => array( - 'twig' => array( + 'renderers' => [ + 'twig' => [ 'class' => 'yii\twig\ViewRenderer', //'cachePath' => '@runtime/Twig/cache', - //'options' => array(), /* Array of twig options */ - ), - ), - ), - ), -); + //'options' => [], /* Array of twig options */ + ], + ], + ], + ], +]; ``` For further instructions refer to the related section in the yii guide. diff --git a/extensions/twig/yii/twig/ViewRenderer.php b/extensions/twig/yii/twig/ViewRenderer.php index 860a2f2..b1598cf 100644 --- a/extensions/twig/yii/twig/ViewRenderer.php +++ b/extensions/twig/yii/twig/ViewRenderer.php @@ -31,7 +31,7 @@ class ViewRenderer extends BaseViewRenderer * @var array Twig options * @see http://twig.sensiolabs.org/doc/api.html#environment-options */ - public $options = array(); + public $options = []; /** * @var \Twig_Environment @@ -42,12 +42,12 @@ class ViewRenderer extends BaseViewRenderer { $loader = new \Twig_Loader_String(); - $this->twig = new \Twig_Environment($loader, array_merge(array( + $this->twig = new \Twig_Environment($loader, array_merge([ 'cache' => Yii::getAlias($this->cachePath), - ), $this->options)); + ], $this->options)); - $this->twig->addFunction('path', new \Twig_Function_Function(function ($path, $args = array()) { - return Html::url(array_merge(array($path), $args)); + $this->twig->addFunction('path', new \Twig_Function_Function(function ($path, $args = []) { + return Html::url(array_merge([$path], $args)); })); $this->twig->addGlobal('app', \Yii::$app); diff --git a/framework/yii/BaseYii.php b/framework/yii/BaseYii.php index cf94166..49499fb 100644 --- a/framework/yii/BaseYii.php +++ b/framework/yii/BaseYii.php @@ -67,7 +67,7 @@ class BaseYii * @see import * @see autoload */ - public static $classMap = array(); + public static $classMap = []; /** * @var \yii\console\Application|\yii\web\Application the application instance */ @@ -77,28 +77,28 @@ class BaseYii * @see getAlias * @see setAlias */ - public static $aliases = array('@yii' => __DIR__); + public static $aliases = ['@yii' => __DIR__]; /** * @var array initial property values that will be applied to objects newly created via [[createObject]]. * The array keys are class names without leading backslashes "\", and the array values are the corresponding * name-value pairs for initializing the created class instances. For example, * * ~~~ - * array( - * 'Bar' => array( + * [ + * 'Bar' => [ * 'prop1' => 'value1', * 'prop2' => 'value2', - * ), - * 'mycompany\foo\Car' => array( + * ], + * 'mycompany\foo\Car' => [ * 'prop1' => 'value1', * 'prop2' => 'value2', - * ), - * ) + * ], + * ] * ~~~ * * @see createObject */ - public static $objectConfig = array(); + public static $objectConfig = []; /** @@ -127,7 +127,7 @@ class BaseYii { foreach ($namespaces as $name => $path) { if ($name !== '') { - $name = trim(strtr($name, array('\\' => '/', '_' => '/')), '/'); + $name = trim(strtr($name, ['\\' => '/', '_' => '/']), '/'); if (is_array($path)) { $path = reset($path); } @@ -262,16 +262,16 @@ class BaseYii if ($pos === false) { self::$aliases[$root] = $path; } else { - self::$aliases[$root] = array($alias => $path); + self::$aliases[$root] = [$alias => $path]; } } elseif (is_string(self::$aliases[$root])) { if ($pos === false) { self::$aliases[$root] = $path; } else { - self::$aliases[$root] = array( + self::$aliases[$root] = [ $alias => $path, $root => self::$aliases[$root], - ); + ]; } } else { self::$aliases[$root][$alias] = $path; @@ -360,17 +360,17 @@ class BaseYii * * ~~~ * $object = \Yii::createObject('@app/components/GoogleMap'); - * $object = \Yii::createObject(array( + * $object = \Yii::createObject([ * 'class' => '\app\components\GoogleMap', * 'apiKey' => 'xyz', - * )); + * ]); * ~~~ * * This method can be used to create any object as long as the object's constructor is * defined like the following: * * ~~~ - * public function __construct(..., $config = array()) { + * public function __construct(..., $config = []) { * } * ~~~ * @@ -384,11 +384,11 @@ class BaseYii */ public static function createObject($config) { - static $reflections = array(); + static $reflections = []; if (is_string($config)) { $class = $config; - $config = array(); + $config = []; } elseif (isset($config['class'])) { $class = $config['class']; unset($config['class']); @@ -538,7 +538,7 @@ class BaseYii * [[\yii\base\Application::language|application language]] will be used. * @return string the translated message. */ - public static function t($category, $message, $params = array(), $language = null) + public static function t($category, $message, $params = [], $language = null) { if (self::$app !== null) { return self::$app->getI18n()->translate($category, $message, $params, $language ?: self::$app->language); diff --git a/framework/yii/Yii.php b/framework/yii/Yii.php index 232117f..272b35f 100644 --- a/framework/yii/Yii.php +++ b/framework/yii/Yii.php @@ -22,5 +22,5 @@ class Yii extends \yii\BaseYii { } -spl_autoload_register(array('Yii', 'autoload'), true, true); +spl_autoload_register(['Yii', 'autoload'], true, true); Yii::$classMap = include(__DIR__ . '/classes.php'); diff --git a/framework/yii/assets.php b/framework/yii/assets.php index c52bca6..df4ee10 100644 --- a/framework/yii/assets.php +++ b/framework/yii/assets.php @@ -1,6 +1,6 @@ 1)`. + * And the parameters provided for the action are: `['id' => 1]`. * Then the `run()` method will be invoked as `run(1)` automatically. * * @property string $uniqueId The unique ID of this action among the whole application. This property is @@ -51,7 +51,7 @@ class Action extends Component * @param Controller $controller the controller that owns this action * @param array $config name-value pairs that will be used to initialize the object properties */ - public function __construct($id, $controller, $config = array()) + public function __construct($id, $controller, $config = []) { $this->id = $id; $this->controller = $controller; @@ -84,6 +84,6 @@ class Action extends Component if (Yii::$app->requestedParams === null) { Yii::$app->requestedParams = $args; } - return call_user_func_array(array($this, 'run'), $args); + return call_user_func_array([$this, 'run'], $args); } } diff --git a/framework/yii/base/ActionEvent.php b/framework/yii/base/ActionEvent.php index 9b6c2f0..6e123a0 100644 --- a/framework/yii/base/ActionEvent.php +++ b/framework/yii/base/ActionEvent.php @@ -37,7 +37,7 @@ class ActionEvent extends Event * @param Action $action the action associated with this action event. * @param array $config name-value pairs that will be used to initialize the object properties */ - public function __construct($action, $config = array()) + public function __construct($action, $config = []) { $this->action = $action; parent::__construct($config); diff --git a/framework/yii/base/ActionFilter.php b/framework/yii/base/ActionFilter.php index bc3b60c..60be177 100644 --- a/framework/yii/base/ActionFilter.php +++ b/framework/yii/base/ActionFilter.php @@ -24,7 +24,7 @@ class ActionFilter extends Behavior * @var array list of action IDs that this filter should not apply to. * @see only */ - public $except = array(); + public $except = []; /** * Declares event handlers for the [[owner]]'s events. @@ -32,10 +32,10 @@ class ActionFilter extends Behavior */ public function events() { - return array( + return [ Controller::EVENT_BEFORE_ACTION => 'beforeFilter', Controller::EVENT_AFTER_ACTION => 'afterFilter', - ); + ]; } /** diff --git a/framework/yii/base/Application.php b/framework/yii/base/Application.php index 683b9ce..d92b05c 100644 --- a/framework/yii/base/Application.php +++ b/framework/yii/base/Application.php @@ -80,7 +80,7 @@ abstract class Application extends Module /** * @var array IDs of the components that need to be loaded when the application starts. */ - public $preload = array(); + public $preload = []; /** * @var Controller the currently active controller instance */ @@ -121,7 +121,7 @@ abstract class Application extends Module * Note that the configuration must contain both [[id]] and [[basePath]]. * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing. */ - public function __construct($config = array()) + public function __construct($config = []) { Yii::$app = $this; if (!isset($config['id'])) { @@ -188,12 +188,12 @@ abstract class Application extends Module { if (YII_ENABLE_ERROR_HANDLER) { ini_set('display_errors', 0); - set_exception_handler(array($this, 'handleException')); - set_error_handler(array($this, 'handleError'), error_reporting()); + set_exception_handler([$this, 'handleException']); + set_error_handler([$this, 'handleError'], error_reporting()); if ($this->memoryReserveSize > 0) { $this->_memoryReserve = str_repeat('x', $this->memoryReserveSize); } - register_shutdown_function(array($this, 'handleFatalError')); + register_shutdown_function([$this, 'handleFatalError']); } } @@ -403,26 +403,14 @@ abstract class Application extends Module */ public function registerCoreComponents() { - $this->setComponents(array( - 'log' => array( - 'class' => 'yii\log\Logger', - ), - 'errorHandler' => array( - 'class' => 'yii\base\ErrorHandler', - ), - 'formatter' => array( - 'class' => 'yii\base\Formatter', - ), - 'i18n' => array( - 'class' => 'yii\i18n\I18N', - ), - 'urlManager' => array( - 'class' => 'yii\web\UrlManager', - ), - 'view' => array( - 'class' => 'yii\base\View', - ), - )); + $this->setComponents([ + 'log' => ['class' => 'yii\log\Logger'], + 'errorHandler' => ['class' => 'yii\base\ErrorHandler'], + 'formatter' => ['class' => 'yii\base\Formatter'], + 'i18n' => ['class' => 'yii\i18n\I18N'], + 'urlManager' => ['class' => 'yii\web\UrlManager'], + 'view' => ['class' => 'yii\base\View'], + ]); } /** diff --git a/framework/yii/base/Behavior.php b/framework/yii/base/Behavior.php index abe08bb..1443e06 100644 --- a/framework/yii/base/Behavior.php +++ b/framework/yii/base/Behavior.php @@ -37,25 +37,25 @@ class Behavior extends \yii\base\Object * * The callbacks can be any of the followings: * - * - method in this behavior: `'handleClick'`, equivalent to `array($this, 'handleClick')` - * - object method: `array($object, 'handleClick')` - * - static method: `array('Page', 'handleClick')` + * - method in this behavior: `'handleClick'`, equivalent to `[$this, 'handleClick']` + * - object method: `[$object, 'handleClick']` + * - static method: `['Page', 'handleClick']` * - anonymous function: `function($event) { ... }` * * The following is an example: * * ~~~ - * array( + * [ * 'beforeValidate' => 'myBeforeValidate', * 'afterValidate' => 'myAfterValidate', - * ) + * ] * ~~~ * * @return array events (array keys) and the corresponding event handler methods (array values). */ public function events() { - return array(); + return []; } /** @@ -69,7 +69,7 @@ class Behavior extends \yii\base\Object { $this->owner = $owner; foreach ($this->events() as $event => $handler) { - $owner->on($event, is_string($handler) ? array($this, $handler) : $handler); + $owner->on($event, is_string($handler) ? [$this, $handler] : $handler); } } @@ -83,7 +83,7 @@ class Behavior extends \yii\base\Object { if ($this->owner) { foreach ($this->events() as $event => $handler) { - $this->owner->off($event, is_string($handler) ? array($this, $handler) : $handler); + $this->owner->off($event, is_string($handler) ? [$this, $handler] : $handler); } $this->owner = null; } diff --git a/framework/yii/base/Component.php b/framework/yii/base/Component.php index 2ad2c94..9d5258a 100644 --- a/framework/yii/base/Component.php +++ b/framework/yii/base/Component.php @@ -195,7 +195,7 @@ class Component extends Object $this->ensureBehaviors(); foreach ($this->_behaviors as $object) { if ($object->hasMethod($name)) { - return call_user_func_array(array($object, $name), $params); + return call_user_func_array([$object, $name], $params); } } @@ -329,11 +329,11 @@ class Component extends Object * the behavior class or an array of the following structure: * * ~~~ - * 'behaviorName' => array( + * 'behaviorName' => [ * 'class' => 'BehaviorClass', * 'property1' => 'value1', * 'property2' => 'value2', - * ) + * ] * ~~~ * * Note that a behavior class must extend from [[Behavior]]. Behavior names can be strings @@ -347,7 +347,7 @@ class Component extends Object */ public function behaviors() { - return array(); + return []; } /** @@ -369,9 +369,9 @@ class Component extends Object * * ~~~ * function ($event) { ... } // anonymous function - * array($object, 'handleClick') // $object->handleClick() - * array('Page', 'handleClick') // Page::handleClick() - * 'handleClick' // global function handleClick() + * [$object, 'handleClick'] // $object->handleClick() + * ['Page', 'handleClick'] // Page::handleClick() + * 'handleClick' // global function handleClick() * ~~~ * * An event handler must be defined with the following signature, @@ -391,7 +391,7 @@ class Component extends Object public function on($name, $handler, $data = null) { $this->ensureBehaviors(); - $this->_events[$name][] = array($handler, $data); + $this->_events[$name][] = [$handler, $data]; } /** @@ -408,7 +408,7 @@ class Component extends Object $this->ensureBehaviors(); if (isset($this->_events[$name])) { if ($handler === null) { - $this->_events[$name] = array(); + $this->_events[$name] = []; } else { $removed = false; foreach ($this->_events[$name] as $i => $event) { @@ -543,7 +543,7 @@ class Component extends Object $this->detachBehavior($name); } } - $this->_behaviors = array(); + $this->_behaviors = []; } /** @@ -552,7 +552,7 @@ class Component extends Object public function ensureBehaviors() { if ($this->_behaviors === null) { - $this->_behaviors = array(); + $this->_behaviors = []; foreach ($this->behaviors() as $name => $behavior) { $this->attachBehaviorInternal($name, $behavior); } diff --git a/framework/yii/base/Controller.php b/framework/yii/base/Controller.php index 3eebaa0..9a168da 100644 --- a/framework/yii/base/Controller.php +++ b/framework/yii/base/Controller.php @@ -72,7 +72,7 @@ class Controller extends Component * @param Module $module the module that this controller belongs to. * @param array $config name-value pairs that will be used to initialize the object properties */ - public function __construct($id, $module, $config = array()) + public function __construct($id, $module, $config = []) { $this->id = $id; $this->module = $module; @@ -86,14 +86,14 @@ class Controller extends Component * action class names or action configuration arrays. For example, * * ~~~ - * return array( + * return [ * 'action1' => '@app/components/Action1', - * 'action2' => array( + * 'action2' => [ * 'class' => '@app/components/Action2', * 'property1' => 'value1', * 'property2' => 'value2', - * ), - * ); + * ], + * ]; * ~~~ * * [[\Yii::createObject()]] will be used later to create the requested action @@ -101,7 +101,7 @@ class Controller extends Component */ public function actions() { - return array(); + return []; } /** @@ -113,7 +113,7 @@ class Controller extends Component * @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully. * @see createAction */ - public function runAction($id, $params = array()) + public function runAction($id, $params = []) { $action = $this->createAction($id); if ($action !== null) { @@ -152,7 +152,7 @@ class Controller extends Component * @see runAction * @see forward */ - public function run($route, $params = array()) + public function run($route, $params = []) { $pos = strpos($route, '/'); if ($pos === false) { @@ -173,7 +173,7 @@ class Controller extends Component */ public function bindActionParams($action, $params) { - return array(); + return []; } /** @@ -244,7 +244,7 @@ class Controller extends Component */ public function getActionParams() { - return array(); + return []; } /** @@ -303,13 +303,13 @@ class Controller extends Component * @return string the rendering result. * @throws InvalidParamException if the view file or the layout file does not exist. */ - public function render($view, $params = array()) + public function render($view, $params = []) { $viewFile = $this->findViewFile($view); $output = $this->getView()->renderFile($viewFile, $params, $this); $layoutFile = $this->findLayoutFile(); if ($layoutFile !== false) { - return $this->getView()->renderFile($layoutFile, array('content' => $output), $this); + return $this->getView()->renderFile($layoutFile, ['content' => $output], $this); } else { return $output; } @@ -323,7 +323,7 @@ class Controller extends Component * @return string the rendering result. * @throws InvalidParamException if the view file does not exist. */ - public function renderPartial($view, $params = array()) + public function renderPartial($view, $params = []) { $viewFile = $this->findViewFile($view); return $this->getView()->renderFile($viewFile, $params, $this); @@ -336,7 +336,7 @@ class Controller extends Component * @return string the rendering result. * @throws InvalidParamException if the view file does not exist. */ - public function renderFile($file, $params = array()) + public function renderFile($file, $params = []) { return $this->getView()->renderFile($file, $params, $this); } diff --git a/framework/yii/base/ErrorException.php b/framework/yii/base/ErrorException.php index 8e1977a..eed6908 100644 --- a/framework/yii/base/ErrorException.php +++ b/framework/yii/base/ErrorException.php @@ -51,7 +51,7 @@ class ErrorException extends Exception } // XDebug has a different key name - $frame['args'] = array(); + $frame['args'] = []; if (isset($frame['params']) && !isset($frame['args'])) { $frame['args'] = $frame['params']; } @@ -81,7 +81,7 @@ class ErrorException extends Exception */ public static function isFatalError($error) { - return isset($error['type']) && in_array($error['type'], array(E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING)); + return isset($error['type']) && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING]); } /** @@ -89,7 +89,7 @@ class ErrorException extends Exception */ public function getName() { - $names = array( + $names = [ E_ERROR => Yii::t('yii', 'Fatal Error'), E_PARSE => Yii::t('yii', 'Parse Error'), E_CORE_ERROR => Yii::t('yii', 'Core Error'), @@ -103,7 +103,7 @@ class ErrorException extends Exception E_NOTICE => Yii::t('yii', 'Notice'), E_RECOVERABLE_ERROR => Yii::t('yii', 'Recoverable Error'), E_DEPRECATED => Yii::t('yii', 'Deprecated'), - ); + ]; return isset($names[$this->getCode()]) ? $names[$this->getCode()] : Yii::t('yii', 'Error'); } } diff --git a/framework/yii/base/ErrorHandler.php b/framework/yii/base/ErrorHandler.php index dec5779..ead9646 100644 --- a/framework/yii/base/ErrorHandler.php +++ b/framework/yii/base/ErrorHandler.php @@ -112,19 +112,19 @@ class ErrorHandler extends Component ini_set('display_errors', 1); } $file = $useErrorView ? $this->errorView : $this->exceptionView; - $response->data = $this->renderFile($file, array( + $response->data = $this->renderFile($file, [ 'exception' => $exception, - )); + ]); } } elseif ($exception instanceof Arrayable) { $response->data = $exception; } else { - $response->data = array( + $response->data = [ 'type' => get_class($exception), 'name' => 'Exception', 'message' => $exception->getMessage(), 'code' => $exception->getCode(), - ); + ]; } if ($exception instanceof HttpException) { @@ -212,9 +212,7 @@ class ErrorHandler extends Component public function renderPreviousExceptions($exception) { if (($previous = $exception->getPrevious()) !== null) { - return $this->renderFile($this->previousExceptionView, array( - 'exception' => $previous, - )); + return $this->renderFile($this->previousExceptionView, ['exception' => $previous]); } else { return ''; } @@ -231,7 +229,7 @@ class ErrorHandler extends Component */ public function renderCallStackItem($file, $line, $class, $method, $index) { - $lines = array(); + $lines = []; $begin = $end = 0; if ($file !== null && $line !== null) { $line--; // adjust line number from one-based to zero-based @@ -245,7 +243,7 @@ class ErrorHandler extends Component $end = $line + $half < $lineCount ? $line + $half : $lineCount - 1; } - return $this->renderFile($this->callStackItemView, array( + return $this->renderFile($this->callStackItemView, [ 'file' => $file, 'line' => $line, 'class' => $class, @@ -254,7 +252,7 @@ class ErrorHandler extends Component 'lines' => $lines, 'begin' => $begin, 'end' => $end, - )); + ]); } /** @@ -264,7 +262,7 @@ class ErrorHandler extends Component public function renderRequest() { $request = ''; - foreach (array('_GET', '_POST', '_SERVER', '_FILES', '_COOKIE', '_SESSION', '_ENV') as $name) { + foreach (['_GET', '_POST', '_SERVER', '_FILES', '_COOKIE', '_SESSION', '_ENV'] as $name) { if (!empty($GLOBALS[$name])) { $request .= '$' . $name . ' = ' . var_export($GLOBALS[$name], true) . ";\n\n"; } @@ -300,14 +298,14 @@ class ErrorHandler extends Component */ public function createServerInformationLink() { - static $serverUrls = array( - 'http://httpd.apache.org/' => array('apache'), - 'http://nginx.org/' => array('nginx'), - 'http://lighttpd.net/' => array('lighttpd'), - 'http://gwan.com/' => array('g-wan', 'gwan'), - 'http://iis.net/' => array('iis', 'services'), - 'http://php.net/manual/en/features.commandline.webserver.php' => array('development'), - ); + static $serverUrls = [ + 'http://httpd.apache.org/' => ['apache'], + 'http://nginx.org/' => ['nginx'], + 'http://lighttpd.net/' => ['lighttpd'], + 'http://gwan.com/' => ['g-wan', 'gwan'], + 'http://iis.net/' => ['iis', 'services'], + 'http://php.net/manual/en/features.commandline.webserver.php' => ['development'], + ]; if (isset($_SERVER['SERVER_SOFTWARE'])) { foreach ($serverUrls as $url => $keywords) { foreach ($keywords as $keyword) { diff --git a/framework/yii/base/Exception.php b/framework/yii/base/Exception.php index 64f1d1b..7e01bd4 100644 --- a/framework/yii/base/Exception.php +++ b/framework/yii/base/Exception.php @@ -39,12 +39,12 @@ class Exception extends \Exception implements Arrayable */ protected function toArrayRecursive($exception) { - $array = array( + $array = [ 'type' => get_class($exception), 'name' => $exception instanceof self ? $exception->getName() : 'Exception', 'message' => $exception->getMessage(), 'code' => $exception->getCode(), - ); + ]; if (($prev = $exception->getPrevious()) !== null) { $array['previous'] = $this->toArrayRecursive($prev); } diff --git a/framework/yii/base/Formatter.php b/framework/yii/base/Formatter.php index 84b4b8d..18faaff 100644 --- a/framework/yii/base/Formatter.php +++ b/framework/yii/base/Formatter.php @@ -42,7 +42,7 @@ class Formatter extends Component public $nullDisplay; /** * @var array the text to be displayed when formatting a boolean value. The first element corresponds - * to the text display for false, the second element for true. Defaults to `array('No', 'Yes')`. + * to the text display for false, the second element for true. Defaults to `['No', 'Yes']`. */ public $booleanFormat; /** @@ -63,7 +63,7 @@ class Formatter extends Component public function init() { if (empty($this->booleanFormat)) { - $this->booleanFormat = array(Yii::t('yii', 'No'), Yii::t('yii', 'Yes')); + $this->booleanFormat = [Yii::t('yii', 'No'), Yii::t('yii', 'Yes')]; } if ($this->nullDisplay === null) { $this->nullDisplay = Yii::t('yii', '(not set)'); @@ -79,7 +79,7 @@ class Formatter extends Component * @param string|array $format the format of the value, e.g., "html", "text". To specify additional * parameters of the formatting method, you may use an array. The first element of the array * specifies the format name, while the rest of the elements will be used as the parameters to the formatting - * method. For example, a format of `array('date', 'Y-m-d')` will cause the invocation of `asDate($value, 'Y-m-d')`. + * method. For example, a format of `['date', 'Y-m-d']` will cause the invocation of `asDate($value, 'Y-m-d')`. * @return string the formatting result * @throws InvalidParamException if the type is not supported by this class. */ @@ -94,11 +94,11 @@ class Formatter extends Component $params = $format; $format = $f; } else { - $params = array($value); + $params = [$value]; } $method = 'as' . $format; if (method_exists($this, $method)) { - return call_user_func_array(array($this, $method), $params); + return call_user_func_array([$this, $method], $params); } else { throw new InvalidParamException("Unknown type: $format"); } diff --git a/framework/yii/base/InlineAction.php b/framework/yii/base/InlineAction.php index a669563..412b357 100644 --- a/framework/yii/base/InlineAction.php +++ b/framework/yii/base/InlineAction.php @@ -31,7 +31,7 @@ class InlineAction extends Action * @param string $actionMethod the controller method that this inline action is associated with * @param array $config name-value pairs that will be used to initialize the object properties */ - public function __construct($id, $controller, $actionMethod, $config = array()) + public function __construct($id, $controller, $actionMethod, $config = []) { $this->actionMethod = $actionMethod; parent::__construct($id, $controller, $config); @@ -50,6 +50,6 @@ class InlineAction extends Action if (Yii::$app->requestedParams === null) { Yii::$app->requestedParams = $args; } - return call_user_func_array(array($this->controller, $this->actionMethod), $args); + return call_user_func_array([$this->controller, $this->actionMethod], $args); } } diff --git a/framework/yii/base/Model.php b/framework/yii/base/Model.php index 7fb8c35..e469f66 100644 --- a/framework/yii/base/Model.php +++ b/framework/yii/base/Model.php @@ -90,12 +90,12 @@ class Model extends Component implements IteratorAggregate, ArrayAccess * Each rule is an array with the following structure: * * ~~~ - * array( + * [ * 'attribute list', * 'validator type', * 'on' => 'scenario name', * ...other parameters... - * ) + * ] * ~~~ * * where @@ -126,18 +126,18 @@ class Model extends Component implements IteratorAggregate, ArrayAccess * Below are some examples: * * ~~~ - * array( + * [ * // built-in "required" validator - * array('username', 'required'), + * ['username', 'required'], * // built-in "string" validator customized with "min" and "max" properties - * array('username', 'string', 'min' => 3, 'max' => 12), + * ['username', 'string', 'min' => 3, 'max' => 12], * // built-in "compare" validator that is used in "register" scenario only - * array('password', 'compare', 'compareAttribute' => 'password2', 'on' => 'register'), + * ['password', 'compare', 'compareAttribute' => 'password2', 'on' => 'register'], * // an inline validator defined via the "authenticate()" method in the model class - * array('password', 'authenticate', 'on' => 'login'), + * ['password', 'authenticate', 'on' => 'login'], * // a validator of class "DateRangeValidator" - * array('dateRange', 'DateRangeValidator'), - * ); + * ['dateRange', 'DateRangeValidator'], + * ]; * ~~~ * * Note, in order to inherit rules defined in the parent class, a child class needs to @@ -148,7 +148,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess */ public function rules() { - return array(); + return []; } /** @@ -157,11 +157,11 @@ class Model extends Component implements IteratorAggregate, ArrayAccess * The returned array should be in the following format: * * ~~~ - * array( - * 'scenario1' => array('attribute11', 'attribute12', ...), - * 'scenario2' => array('attribute21', 'attribute22', ...), + * [ + * 'scenario1' => ['attribute11', 'attribute12', ...], + * 'scenario2' => ['attribute21', 'attribute22', ...], * ... - * ) + * ] * ~~~ * * By default, an active attribute that is considered safe and can be massively assigned. @@ -177,8 +177,8 @@ class Model extends Component implements IteratorAggregate, ArrayAccess */ public function scenarios() { - $scenarios = array(); - $defaults = array(); + $scenarios = []; + $defaults = []; /** @var $validator Validator */ foreach ($this->getValidators() as $validator) { if (empty($validator->on)) { @@ -231,7 +231,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess public function attributes() { $class = new ReflectionClass($this); - $names = array(); + $names = []; foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) { $name = $property->getName(); if (!$property->isStatic()) { @@ -259,7 +259,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess */ public function attributeLabels() { - return array(); + return []; } /** @@ -367,7 +367,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess */ public function getActiveValidators($attribute = null) { - $validators = array(); + $validators = []; $scenario = $this->getScenario(); /** @var $validator Validator */ foreach ($this->getValidators() as $validator) { @@ -472,15 +472,15 @@ class Model extends Component implements IteratorAggregate, ArrayAccess * Note that when returning errors for all attributes, the result is a two-dimensional array, like the following: * * ~~~ - * array( - * 'username' => array( + * [ + * 'username' => [ * 'Username is required.', * 'Username must contain only word characters.', - * ), - * 'email' => array( + * ], + * 'email' => [ * 'Email address is invalid.', - * ) - * ) + * ] + * ] * ~~~ * * @see getFirstErrors @@ -489,9 +489,9 @@ class Model extends Component implements IteratorAggregate, ArrayAccess public function getErrors($attribute = null) { if ($attribute === null) { - return $this->_errors === null ? array() : $this->_errors; + return $this->_errors === null ? [] : $this->_errors; } else { - return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array(); + return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : []; } } @@ -504,9 +504,9 @@ class Model extends Component implements IteratorAggregate, ArrayAccess public function getFirstErrors() { if (empty($this->_errors)) { - return array(); + return []; } else { - $errors = array(); + $errors = []; foreach ($this->_errors as $attributeErrors) { if (isset($attributeErrors[0])) { $errors[] = $attributeErrors[0]; @@ -545,7 +545,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess public function clearErrors($attribute = null) { if ($attribute === null) { - $this->_errors = array(); + $this->_errors = []; } else { unset($this->_errors[$attribute]); } @@ -572,9 +572,9 @@ class Model extends Component implements IteratorAggregate, ArrayAccess * @param array $except list of attributes whose value should NOT be returned. * @return array attribute values (name => value). */ - public function getAttributes($names = null, $except = array()) + public function getAttributes($names = null, $except = []) { - $values = array(); + $values = []; if ($names === null) { $names = $this->attributes(); } @@ -657,9 +657,9 @@ class Model extends Component implements IteratorAggregate, ArrayAccess $scenario = $this->getScenario(); $scenarios = $this->scenarios(); if (!isset($scenarios[$scenario])) { - return array(); + return []; } - $attributes = array(); + $attributes = []; foreach ($scenarios[$scenario] as $attribute) { if ($attribute[0] !== '!') { $attributes[] = $attribute; @@ -677,7 +677,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess $scenario = $this->getScenario(); $scenarios = $this->scenarios(); if (!isset($scenarios[$scenario])) { - return array(); + return []; } $attributes = $scenarios[$scenario]; foreach ($attributes as $i => $attribute) { diff --git a/framework/yii/base/Module.php b/framework/yii/base/Module.php index 7c29a8b..ee3949b 100644 --- a/framework/yii/base/Module.php +++ b/framework/yii/base/Module.php @@ -39,11 +39,11 @@ abstract class Module extends Component /** * @var array custom module parameters (name => value). */ - public $params = array(); + public $params = []; /** * @var array the IDs of the components or modules that should be preloaded when this module is created. */ - public $preload = array(); + public $preload = []; /** * @var string an ID that uniquely identifies this module among other modules which have the same [[module|parent]]. */ @@ -68,16 +68,16 @@ abstract class Module extends Component * in the array are used to initialize the corresponding controller properties. For example, * * ~~~ - * array( + * [ * 'account' => '@app/controllers/UserController', - * 'article' => array( + * 'article' => [ * 'class' => '@app/controllers/PostController', * 'pageTitle' => 'something new', - * ), - * ) + * ], + * ] * ~~~ */ - public $controllerMap = array(); + public $controllerMap = []; /** * @var string the namespace that controller classes are in. If not set, * it will use the "controllers" sub-namespace under the namespace of this module. @@ -113,11 +113,11 @@ abstract class Module extends Component /** * @var array child modules of this module */ - private $_modules = array(); + private $_modules = []; /** * @var array components registered under this module */ - private $_components = array(); + private $_components = []; /** * Constructor. @@ -125,7 +125,7 @@ abstract class Module extends Component * @param Module $parent the parent module (if any) * @param array $config name-value pairs that will be used to initialize the object properties */ - public function __construct($id, $parent = null, $config = array()) + public function __construct($id, $parent = null, $config = []) { $this->id = $id; $this->module = $parent; @@ -312,10 +312,10 @@ abstract class Module extends Component * For example, * * ~~~ - * array( + * [ * '@models' => '@app/models', // an existing alias * '@backend' => __DIR__ . '/../backend', // a directory - * ) + * ] * ~~~ */ public function setAliases($aliases) @@ -401,7 +401,7 @@ abstract class Module extends Component public function getModules($loadedOnly = false) { if ($loadedOnly) { - $modules = array(); + $modules = []; foreach ($this->_modules as $module) { if ($module instanceof Module) { $modules[] = $module; @@ -426,15 +426,13 @@ abstract class Module extends Component * The following is an example for registering two sub-modules: * * ~~~ - * array( - * 'comment' => array( + * [ + * 'comment' => [ * 'class' => 'app\modules\comment\CommentModule', * 'db' => 'db', - * ), - * 'booking' => array( - * 'class' => 'app\modules\booking\BookingModule', - * ), - * ) + * ], + * 'booking' => ['class' => 'app\modules\booking\BookingModule'], + * ] * ~~~ * * @param array $modules modules (id => module configuration or instances) @@ -506,7 +504,7 @@ abstract class Module extends Component public function getComponents($loadedOnly = false) { if ($loadedOnly) { - $components = array(); + $components = []; foreach ($this->_components as $component) { if ($component instanceof Component) { $components[] = $component; @@ -531,16 +529,16 @@ abstract class Module extends Component * The following is an example for setting two components: * * ~~~ - * array( - * 'db' => array( + * [ + * 'db' => [ * 'class' => 'yii\db\Connection', * 'dsn' => 'sqlite:path/to/file.db', - * ), - * 'cache' => array( + * ], + * 'cache' => [ * 'class' => 'yii\caching\DbCache', * 'db' => 'db', - * ), - * ) + * ], + * ] * ~~~ * * @param array $components components (id => component configuration or instance) @@ -582,7 +580,7 @@ abstract class Module extends Component * @return mixed the result of the action. * @throws InvalidRouteException if the requested route cannot be resolved into an action successfully */ - public function runAction($route, $params = array()) + public function runAction($route, $params = []) { $parts = $this->createController($route); if (is_array($parts)) { @@ -646,7 +644,7 @@ abstract class Module extends Component } } - return isset($controller) ? array($controller, $route) : false; + return isset($controller) ? [$controller, $route] : false; } /** diff --git a/framework/yii/base/Object.php b/framework/yii/base/Object.php index 55754de..ddb0f58 100644 --- a/framework/yii/base/Object.php +++ b/framework/yii/base/Object.php @@ -38,7 +38,7 @@ class Object implements Arrayable * * @param array $config name-value pairs that will be used to initialize the object properties */ - public function __construct($config = array()) + public function __construct($config = []) { if (!empty($config)) { Yii::configure($this, $config); diff --git a/framework/yii/base/Theme.php b/framework/yii/base/Theme.php index 658ada1..d21d4bf 100644 --- a/framework/yii/base/Theme.php +++ b/framework/yii/base/Theme.php @@ -21,7 +21,7 @@ use yii\helpers\FileHelper; * with its themed version if part of its path matches one of the keys in [[pathMap]]. * Then the matched part will be replaced with the corresponding array value. * - * For example, if [[pathMap]] is `array('/web/views' => '/web/themes/basic')`, + * For example, if [[pathMap]] is `['/web/views' => '/web/themes/basic']`, * then the themed version for a view file `/web/views/site/index.php` will be * `/web/themes/basic/site/index.php`. * @@ -29,12 +29,12 @@ use yii\helpers\FileHelper; * component like the following: * * ~~~ - * 'view' => array( - * 'theme' => array( + * 'view' => [ + * 'theme' => [ * 'basePath' => '@webroot/themes/basic', * 'baseUrl' => '@web/themes/basic', - * ), - * ), + * ], + * ], * ~~~ * * The above configuration specifies a theme located under the "themes/basic" directory of the Web folder @@ -76,12 +76,12 @@ class Theme extends Component if (empty($this->pathMap)) { if ($this->basePath !== null) { $this->basePath = Yii::getAlias($this->basePath); - $this->pathMap = array(Yii::$app->getBasePath() => $this->basePath); + $this->pathMap = [Yii::$app->getBasePath() => $this->basePath]; } else { throw new InvalidConfigException('The "basePath" property must be set.'); } } - $paths = array(); + $paths = []; foreach ($this->pathMap as $from => $to) { $from = FileHelper::normalizePath(Yii::getAlias($from)); $to = FileHelper::normalizePath(Yii::getAlias($to)); diff --git a/framework/yii/base/View.php b/framework/yii/base/View.php index f9cae98..28e7b71 100644 --- a/framework/yii/base/View.php +++ b/framework/yii/base/View.php @@ -96,21 +96,17 @@ class View extends Component /** * @var mixed custom parameters that are shared among view templates. */ - public $params = array(); + public $params = []; /** * @var array a list of available renderers indexed by their corresponding supported file extensions. * Each renderer may be a view renderer object or the configuration for creating the renderer object. * For example, the following configuration enables both Smarty and Twig view renderers: * * ~~~ - * array( - * 'tpl' => array( - * 'class' => 'yii\smarty\ViewRenderer', - * ), - * 'twig' => array( - * 'class' => 'yii\twig\ViewRenderer', - * ), - * ) + * [ + * 'tpl' => ['class' => 'yii\smarty\ViewRenderer'], + * 'twig' => ['class' => 'yii\twig\ViewRenderer'], + * ] * ~~~ * * If no renderer is available for the given view file, the view file will be treated as a normal PHP @@ -134,19 +130,19 @@ class View extends Component * is used internally to implement the content caching feature. Do not modify it directly. * @internal */ - public $cacheStack = array(); + public $cacheStack = []; /** * @var array a list of placeholders for embedding dynamic contents. This property * is used internally to implement the content caching feature. Do not modify it directly. * @internal */ - public $dynamicPlaceholders = array(); + public $dynamicPlaceholders = []; /** * @var AssetBundle[] list of the registered asset bundles. The keys are the bundle names, and the values * are the registered [[AssetBundle]] objects. * @see registerAssetBundle */ - public $assetBundles = array(); + public $assetBundles = []; /** * @var string the page title */ @@ -214,7 +210,7 @@ class View extends Component * @throws InvalidParamException if the view cannot be resolved or the view file does not exist. * @see renderFile */ - public function render($view, $params = array()) + public function render($view, $params = []) { if ($this->context instanceof Controller) { return $this->context->renderPartial($view, $params); @@ -244,7 +240,7 @@ class View extends Component * @return string the rendering result * @throws InvalidParamException if the view file does not exist */ - public function renderFile($viewFile, $params = array(), $context = null) + public function renderFile($viewFile, $params = [], $context = null) { $viewFile = Yii::getAlias($viewFile); if ($this->theme !== null) { @@ -328,7 +324,7 @@ class View extends Component * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file. * @return string the rendering result */ - public function renderPhpFile($_file_, $_params_ = array()) + public function renderPhpFile($_file_, $_params_ = []) { ob_start(); ob_implicit_flush(false); @@ -393,11 +389,11 @@ class View extends Component */ public function beginBlock($id, $renderInPlace = false) { - return Block::begin(array( + return Block::begin([ 'id' => $id, 'renderInPlace' => $renderInPlace, 'view' => $this, - )); + ]); } /** @@ -425,13 +421,13 @@ class View extends Component * @return ContentDecorator the ContentDecorator widget instance * @see ContentDecorator */ - public function beginContent($viewFile, $params = array()) + public function beginContent($viewFile, $params = []) { - return ContentDecorator::begin(array( + return ContentDecorator::begin([ 'viewFile' => $viewFile, 'params' => $params, 'view' => $this, - )); + ]); } /** @@ -461,7 +457,7 @@ class View extends Component * @return boolean whether you should generate the content for caching. * False if the cached version is available. */ - public function beginCache($id, $properties = array()) + public function beginCache($id, $properties = []) { $properties['id'] = $id; $properties['view'] = $this; @@ -526,11 +522,11 @@ class View extends Component foreach(array_keys($this->assetBundles) as $bundle) { $this->registerAssetFiles($bundle); } - echo strtr($content, array( + echo strtr($content, [ self::PH_HEAD => $this->renderHeadHtml(), self::PH_BODY_BEGIN => $this->renderBodyBeginHtml(), self::PH_BODY_END => $this->renderBodyEndHtml(), - )); + ]); unset( $this->metaTags, @@ -670,7 +666,7 @@ class View extends Component * $css as the key. If two CSS code blocks are registered with the same key, the latter * will overwrite the former. */ - public function registerCss($css, $options = array(), $key = null) + public function registerCss($css, $options = [], $key = null) { $key = $key ?: md5($css); $this->css[$key] = Html::style($css, $options); @@ -684,7 +680,7 @@ class View extends Component * $url as the key. If two CSS files are registered with the same key, the latter * will overwrite the former. */ - public function registerCssFile($url, $options = array(), $key = null) + public function registerCssFile($url, $options = [], $key = null) { $key = $key ?: $url; $this->cssFiles[$key] = Html::cssFile($url, $options); @@ -732,7 +728,7 @@ class View extends Component * $url as the key. If two JS files are registered with the same key, the latter * will overwrite the former. */ - public function registerJsFile($url, $options = array(), $key = null) + public function registerJsFile($url, $options = [], $key = null) { $position = isset($options['position']) ? $options['position'] : self::POS_END; unset($options['position']); @@ -747,15 +743,15 @@ class View extends Component */ protected function renderHeadHtml() { - $lines = array(); + $lines = []; if (!empty($this->metaTags)) { $lines[] = implode("\n", $this->metaTags); } $request = Yii::$app->getRequest(); if ($request instanceof \yii\web\Request && $request->enableCsrfValidation) { - $lines[] = Html::tag('meta', '', array('name' => 'csrf-var', 'content' => $request->csrfVar)); - $lines[] = Html::tag('meta', '', array('name' => 'csrf-token', 'content' => $request->getCsrfToken())); + $lines[] = Html::tag('meta', '', ['name' => 'csrf-var', 'content' => $request->csrfVar]); + $lines[] = Html::tag('meta', '', ['name' => 'csrf-token', 'content' => $request->getCsrfToken()]); } if (!empty($this->linkTags)) { @@ -771,7 +767,7 @@ class View extends Component $lines[] = implode("\n", $this->jsFiles[self::POS_HEAD]); } if (!empty($this->js[self::POS_HEAD])) { - $lines[] = Html::script(implode("\n", $this->js[self::POS_HEAD]), array('type' => 'text/javascript')); + $lines[] = Html::script(implode("\n", $this->js[self::POS_HEAD]), ['type' => 'text/javascript']); } return empty($lines) ? '' : implode("\n", $lines); } @@ -783,12 +779,12 @@ class View extends Component */ protected function renderBodyBeginHtml() { - $lines = array(); + $lines = []; if (!empty($this->jsFiles[self::POS_BEGIN])) { $lines[] = implode("\n", $this->jsFiles[self::POS_BEGIN]); } if (!empty($this->js[self::POS_BEGIN])) { - $lines[] = Html::script(implode("\n", $this->js[self::POS_BEGIN]), array('type' => 'text/javascript')); + $lines[] = Html::script(implode("\n", $this->js[self::POS_BEGIN]), ['type' => 'text/javascript']); } return empty($lines) ? '' : implode("\n", $lines); } @@ -800,16 +796,16 @@ class View extends Component */ protected function renderBodyEndHtml() { - $lines = array(); + $lines = []; if (!empty($this->jsFiles[self::POS_END])) { $lines[] = implode("\n", $this->jsFiles[self::POS_END]); } if (!empty($this->js[self::POS_END])) { - $lines[] = Html::script(implode("\n", $this->js[self::POS_END]), array('type' => 'text/javascript')); + $lines[] = Html::script(implode("\n", $this->js[self::POS_END]), ['type' => 'text/javascript']); } if (!empty($this->js[self::POS_READY])) { $js = "jQuery(document).ready(function(){\n" . implode("\n", $this->js[self::POS_READY]) . "\n});"; - $lines[] = Html::script($js, array('type' => 'text/javascript')); + $lines[] = Html::script($js, ['type' => 'text/javascript']); } return empty($lines) ? '' : implode("\n", $lines); } diff --git a/framework/yii/base/ViewEvent.php b/framework/yii/base/ViewEvent.php index f1ee7b9..b5734f4 100644 --- a/framework/yii/base/ViewEvent.php +++ b/framework/yii/base/ViewEvent.php @@ -36,7 +36,7 @@ class ViewEvent extends Event * @param string $viewFile the view file path that is being rendered by [[View::renderFile()]]. * @param array $config name-value pairs that will be used to initialize the object properties */ - public function __construct($viewFile, $config = array()) + public function __construct($viewFile, $config = []) { $this->viewFile = $viewFile; parent::__construct($config); diff --git a/framework/yii/base/Widget.php b/framework/yii/base/Widget.php index 943d007..14c4cba 100644 --- a/framework/yii/base/Widget.php +++ b/framework/yii/base/Widget.php @@ -32,7 +32,7 @@ class Widget extends Component * is maintained by [[begin()]] and [[end()]] methods. * @internal */ - public static $_stack = array(); + public static $_stack = []; /** @@ -42,7 +42,7 @@ class Widget extends Component * @param array $config name-value pairs that will be used to initialize the object properties * @return Widget the newly created widget instance */ - public static function begin($config = array()) + public static function begin($config = []) { $config['class'] = get_called_class(); /** @var Widget $widget */ @@ -78,7 +78,7 @@ class Widget extends Component * @param array $config name-value pairs that will be used to initialize the object properties * @return string the rendering result of the widget. */ - public static function widget($config = array()) + public static function widget($config = []) { ob_start(); ob_implicit_flush(false); @@ -165,7 +165,7 @@ class Widget extends Component * @return string the rendering result. * @throws InvalidParamException if the view file does not exist. */ - public function render($view, $params = array()) + public function render($view, $params = []) { $viewFile = $this->findViewFile($view); return $this->getView()->renderFile($viewFile, $params, $this); @@ -178,7 +178,7 @@ class Widget extends Component * @return string the rendering result. * @throws InvalidParamException if the view file does not exist. */ - public function renderFile($file, $params = array()) + public function renderFile($file, $params = []) { return $this->getView()->renderFile($file, $params, $this); } diff --git a/framework/yii/behaviors/AutoTimestamp.php b/framework/yii/behaviors/AutoTimestamp.php index 63a3ef0..0e0844a 100644 --- a/framework/yii/behaviors/AutoTimestamp.php +++ b/framework/yii/behaviors/AutoTimestamp.php @@ -21,11 +21,9 @@ use yii\db\ActiveRecord; * ~~~ * public function behaviors() * { - * return array( - * 'timestamp' => array( - * 'class' => 'yii\behaviors\AutoTimestamp', - * ), - * ); + * return [ + * 'timestamp' => ['class' => 'yii\behaviors\AutoTimestamp'], + * ]; * } * ~~~ * @@ -46,10 +44,10 @@ class AutoTimestamp extends Behavior * The default setting is to update the `create_time` attribute upon AR insertion, * and update the `update_time` attribute upon AR updating. */ - public $attributes = array( + public $attributes = [ ActiveRecord::EVENT_BEFORE_INSERT => 'create_time', ActiveRecord::EVENT_BEFORE_UPDATE => 'update_time', - ); + ]; /** * @var \Closure|Expression The expression that will be used for generating the timestamp. * This can be either an anonymous function that returns the timestamp value, @@ -78,7 +76,7 @@ class AutoTimestamp extends Behavior */ public function updateTimestamp($event) { - $attributes = isset($this->attributes[$event->name]) ? (array)$this->attributes[$event->name] : array(); + $attributes = isset($this->attributes[$event->name]) ? (array)$this->attributes[$event->name] : []; if (!empty($attributes)) { $timestamp = $this->evaluateTimestamp(); foreach ($attributes as $attribute) { diff --git a/framework/yii/bootstrap/Alert.php b/framework/yii/bootstrap/Alert.php index d57bcbe..29844bd 100644 --- a/framework/yii/bootstrap/Alert.php +++ b/framework/yii/bootstrap/Alert.php @@ -17,24 +17,22 @@ use yii\helpers\Html; * For example, * * ```php - * echo Alert::widget(array( + * echo Alert::widget([ * 'body' => 'Say hello...', - * 'closeButton' => array( + * 'closeButton' => [ * 'label' => '×', * 'tag' => 'a', - * ), - * )); + * ], + * ]); * ``` * * The following example will show the content enclosed between the [[begin()]] * and [[end()]] calls within the alert box: * * ```php - * Alert::begin(array( - * 'closeButton' => array( - * 'label' => '×', - * ), - * )); + * Alert::begin([ + * 'closeButton' => ['label' => '×'], + * ]); * * echo 'Say hello...'; * @@ -67,7 +65,7 @@ class Alert extends Widget * Please refer to the [Alert plugin help](http://twitter.github.com/bootstrap/javascript.html#alerts) * for the supported HTML attributes. */ - public $closeButton = array(); + public $closeButton = []; /** @@ -136,18 +134,16 @@ class Alert extends Widget */ protected function initOptions() { - $this->options = array_merge(array( - 'class' => 'fade in', - ), $this->options); + $this->options = array_merge(['class' => 'fade in'], $this->options); Html::addCssClass($this->options, 'alert'); if ($this->closeButton !== null) { - $this->closeButton = array_merge(array( + $this->closeButton = array_merge([ 'data-dismiss' => 'alert', 'aria-hidden' => 'true', 'class' => 'close', - ), $this->closeButton); + ], $this->closeButton); } } } diff --git a/framework/yii/bootstrap/BootstrapAsset.php b/framework/yii/bootstrap/BootstrapAsset.php index 26dad31..05601c6 100644 --- a/framework/yii/bootstrap/BootstrapAsset.php +++ b/framework/yii/bootstrap/BootstrapAsset.php @@ -16,7 +16,7 @@ use yii\web\AssetBundle; class BootstrapAsset extends AssetBundle { public $sourcePath = '@yii/bootstrap/assets'; - public $css = array( + public $css = [ 'css/bootstrap.css', - ); + ]; } diff --git a/framework/yii/bootstrap/BootstrapPluginAsset.php b/framework/yii/bootstrap/BootstrapPluginAsset.php index 613e120..e291ac0 100644 --- a/framework/yii/bootstrap/BootstrapPluginAsset.php +++ b/framework/yii/bootstrap/BootstrapPluginAsset.php @@ -17,11 +17,11 @@ use yii\web\AssetBundle; class BootstrapPluginAsset extends AssetBundle { public $sourcePath = '@yii/bootstrap/assets'; - public $js = array( + public $js = [ 'js/bootstrap.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\web\JqueryAsset', 'yii\bootstrap\BootstrapAsset', - ); + ]; } diff --git a/framework/yii/bootstrap/BootstrapThemeAsset.php b/framework/yii/bootstrap/BootstrapThemeAsset.php index d21f308..81cc921 100644 --- a/framework/yii/bootstrap/BootstrapThemeAsset.php +++ b/framework/yii/bootstrap/BootstrapThemeAsset.php @@ -18,10 +18,10 @@ use yii\web\AssetBundle; class BootstrapThemeAsset extends AssetBundle { public $sourcePath = '@yii/bootstrap/assets'; - public $css = array( + public $css = [ 'css/bootstrap-theme.css', - ); - public $depends = array( + ]; + public $depends = [ 'yii\bootstrap\BootstrapAsset', - ); + ]; } diff --git a/framework/yii/bootstrap/Button.php b/framework/yii/bootstrap/Button.php index 5c45747..88acab7 100644 --- a/framework/yii/bootstrap/Button.php +++ b/framework/yii/bootstrap/Button.php @@ -15,10 +15,10 @@ use yii\helpers\Html; * For example, * * ```php - * echo Button::widget(array( + * echo Button::widget([ * 'label' => 'Action', - * 'options' => array('class' => 'btn-lg'), - * )); + * 'options' => ['class' => 'btn-lg'], + * ]); * ``` * @see http://twitter.github.io/bootstrap/javascript.html#buttons * @author Antonio Ramirez diff --git a/framework/yii/bootstrap/ButtonDropdown.php b/framework/yii/bootstrap/ButtonDropdown.php index 2e04cb6..1ffde7d 100644 --- a/framework/yii/bootstrap/ButtonDropdown.php +++ b/framework/yii/bootstrap/ButtonDropdown.php @@ -16,21 +16,15 @@ use yii\helpers\Html; * * ```php * // a button group using Dropdown widget - * echo ButtonDropdown::widget(array( + * echo ButtonDropdown::widget([ * 'label' => 'Action', - * 'dropdown' => array( - * 'items' => array( - * array( - * 'label' => 'DropdownA', - * 'url' => '/', - * ), - * array( - * 'label' => 'DropdownB', - * 'url' => '#', - * ), - * ), - * ), - * )); + * 'dropdown' => [ + * 'items' => [ + * ['label' => 'DropdownA', 'url' => '/'], + * ['label' => 'DropdownB', 'url' => '#'], + * ], + * ], + * ]); * ``` * @see http://twitter.github.io/bootstrap/javascript.html#buttons * @see http://twitter.github.io/bootstrap/components.html#buttonDropdowns @@ -46,11 +40,11 @@ class ButtonDropdown extends Widget /** * @var array the HTML attributes of the button. */ - public $options = array(); + public $options = []; /** * @var array the configuration array for [[Dropdown]]. */ - public $dropdown = array(); + public $dropdown = []; /** * @var boolean whether to display a group of split-styled button group. */ @@ -78,11 +72,11 @@ class ButtonDropdown extends Widget $options = $this->options; $this->options['data-toggle'] = 'dropdown'; Html::addCssClass($this->options, 'dropdown-toggle'); - $splitButton = Button::widget(array( + $splitButton = Button::widget([ 'label' => '', 'encodeLabel' => false, 'options' => $this->options, - )); + ]); } else { $tag = 'a'; $this->label .= ' '; @@ -94,12 +88,12 @@ class ButtonDropdown extends Widget $options['data-toggle'] = 'dropdown'; $splitButton = ''; } - return Button::widget(array( + return Button::widget([ 'tagName' => $tag, 'label' => $this->label, 'options' => $options, 'encodeLabel' => false, - )) . "\n" . $splitButton; + ]) . "\n" . $splitButton; } /** diff --git a/framework/yii/bootstrap/ButtonGroup.php b/framework/yii/bootstrap/ButtonGroup.php index f2656c0..529c7ef 100644 --- a/framework/yii/bootstrap/ButtonGroup.php +++ b/framework/yii/bootstrap/ButtonGroup.php @@ -17,20 +17,20 @@ use yii\helpers\Html; * * ```php * // a button group with items configuration - * echo ButtonGroup::::widget(array( - * 'buttons' => array( - * array('label' => 'A'), - * array('label' => 'B'), - * ) - * )); + * echo ButtonGroup::::widget([ + * 'buttons' => [ + * ['label' => 'A'], + * ['label' => 'B'], + * ] + * ]); * * // button group with an item as a string - * echo ButtonGroup::::widget(array( - * 'buttons' => array( - * Button::widget(array('label' => 'A')), - * array('label' => 'B'), - * ) - * )); + * echo ButtonGroup::::widget([ + * 'buttons' => [ + * Button::widget(['label' => 'A']), + * ['label' => 'B'], + * ] + * ]); * ``` * @see http://twitter.github.io/bootstrap/javascript.html#buttons * @see http://twitter.github.io/bootstrap/components.html#buttonGroups @@ -46,7 +46,7 @@ class ButtonGroup extends Widget * - label: string, required, the button label. * - options: array, optional, the HTML attributes of the button. */ - public $buttons = array(); + public $buttons = []; /** * @var boolean whether to HTML-encode the button labels. */ @@ -78,16 +78,16 @@ class ButtonGroup extends Widget */ protected function renderButtons() { - $buttons = array(); + $buttons = []; foreach ($this->buttons as $button) { if (is_array($button)) { $label = ArrayHelper::getValue($button, 'label'); $options = ArrayHelper::getValue($button, 'options'); - $buttons[] = Button::widget(array( + $buttons[] = Button::widget([ 'label' => $label, 'options' => $options, 'encodeLabel' => $this->encodeLabels - )); + ]); } else { $buttons[] = $button; } diff --git a/framework/yii/bootstrap/Carousel.php b/framework/yii/bootstrap/Carousel.php index ec9a0c9..b7e378a 100644 --- a/framework/yii/bootstrap/Carousel.php +++ b/framework/yii/bootstrap/Carousel.php @@ -17,20 +17,18 @@ use yii\helpers\Html; * For example: * * ```php - * echo Carousel::widget(array( - * 'items' => array( + * echo Carousel::widget([ + * 'items' => [ * // the item contains only the image * '', * // equivalent to the above - * array( - * 'content' => '', - * ), + * ['content' => ''], * // the item contains both the image and the caption - * array( + * [ * 'content' => '', * 'caption' => '

This is title

This is the caption text

', - * 'options' => array(...), - * ), + * 'options' => [...], + * ], * ) * )); * ``` @@ -45,23 +43,23 @@ class Carousel extends Widget * @var array|boolean the labels for the previous and the next control buttons. * If false, it means the previous and the next control buttons should not be displayed. */ - public $controls = array('‹', '›'); + public $controls = ['‹', '›']; /** * @var array list of slides in the carousel. Each array element represents a single * slide with the following structure: * * ```php - * array( + * [ * // required, slide content (HTML), such as an image tag * 'content' => '', * // optional, the caption (HTML) of the slide * 'caption' => '

This is title

This is the caption text

', * // optional the HTML attributes of the slide container - * 'options' => array(), - * ) + * 'options' => [], + * ] * ``` */ - public $items = array(); + public $items = []; /** @@ -92,15 +90,15 @@ class Carousel extends Widget */ public function renderIndicators() { - $indicators = array(); + $indicators = []; for ($i = 0, $count = count($this->items); $i < $count; $i++) { - $options = array('data-target' => '#' . $this->options['id'], 'data-slide-to' => $i); + $options = ['data-target' => '#' . $this->options['id'], 'data-slide-to' => $i]; if ($i === 0) { Html::addCssClass($options, 'active'); } $indicators[] = Html::tag('li', '', $options); } - return Html::tag('ol', implode("\n", $indicators), array('class' => 'carousel-indicators')); + return Html::tag('ol', implode("\n", $indicators), ['class' => 'carousel-indicators']); } /** @@ -109,11 +107,11 @@ class Carousel extends Widget */ public function renderItems() { - $items = array(); + $items = []; for ($i = 0, $count = count($this->items); $i < $count; $i++) { $items[] = $this->renderItem($this->items[$i], $i); } - return Html::tag('div', implode("\n", $items), array('class' => 'carousel-inner')); + return Html::tag('div', implode("\n", $items), ['class' => 'carousel-inner']); } /** @@ -128,14 +126,14 @@ class Carousel extends Widget if (is_string($item)) { $content = $item; $caption = null; - $options = array(); + $options = []; } elseif (isset($item['content'])) { $content = $item['content']; $caption = ArrayHelper::getValue($item, 'caption'); if ($caption !== null) { - $caption = Html::tag('div', $caption, array('class' => 'carousel-caption')); + $caption = Html::tag('div', $caption, ['class' => 'carousel-caption']); } - $options = ArrayHelper::getValue($item, 'options', array()); + $options = ArrayHelper::getValue($item, 'options', []); } else { throw new InvalidConfigException('The "content" option is required.'); } @@ -155,14 +153,14 @@ class Carousel extends Widget public function renderControls() { if (isset($this->controls[0], $this->controls[1])) { - return Html::a($this->controls[0], '#' . $this->options['id'], array( + return Html::a($this->controls[0], '#' . $this->options['id'], [ 'class' => 'left carousel-control', 'data-slide' => 'prev', - )) . "\n" - . Html::a($this->controls[1], '#' . $this->options['id'], array( + ]) . "\n" + . Html::a($this->controls[1], '#' . $this->options['id'], [ 'class' => 'right carousel-control', 'data-slide' => 'next', - )); + ]); } elseif ($this->controls === false) { return ''; } else { diff --git a/framework/yii/bootstrap/Collapse.php b/framework/yii/bootstrap/Collapse.php index 77fdde7..08bde22 100644 --- a/framework/yii/bootstrap/Collapse.php +++ b/framework/yii/bootstrap/Collapse.php @@ -17,22 +17,22 @@ use yii\helpers\Html; * For example: * * ```php - * echo Collapse::widget(array( - * 'items' => array( + * echo Collapse::widget([ + * 'items' => [ * // equivalent to the above - * 'Collapsible Group Item #1' => array( + * 'Collapsible Group Item #1' => [ * 'content' => 'Anim pariatur cliche...', * // open its content by default - * 'contentOptions' => array('class' => 'in') - * ), + * 'contentOptions' => ['class' => 'in'] + * ], * // another group item - * 'Collapsible Group Item #2' => array( + * 'Collapsible Group Item #2' => [ * 'content' => 'Anim pariatur cliche...', - * 'contentOptions' => array(...), - * 'options' => array(...), - * ), - * ) - * )); + * 'contentOptions' => [...], + * 'options' => [...], + * ], + * ] + * ]); * ``` * * @see http://twitter.github.io/bootstrap/javascript.html#collapse @@ -47,17 +47,17 @@ class Collapse extends Widget * * ```php * // item key is the actual group header - * 'Collapsible Group Item #1' => array( + * 'Collapsible Group Item #1' => [ * // required, the content (HTML) of the group * 'content' => 'Anim pariatur cliche...', * // optional the HTML attributes of the content group - * 'contentOptions' => array(), + * 'contentOptions' => [], * // optional the HTML attributes of the group - * 'options' => array(), - * ) + * 'options' => [], + * ] * ``` */ - public $items = array(); + public $items = []; /** @@ -86,10 +86,10 @@ class Collapse extends Widget */ public function renderItems() { - $items = array(); + $items = []; $index = 0; foreach ($this->items as $header => $item) { - $options = ArrayHelper::getValue($item, 'options', array()); + $options = ArrayHelper::getValue($item, 'options', []); Html::addCssClass($options, 'accordion-group'); $items[] = Html::tag('div', $this->renderItem($header, $item, ++$index), $options); } @@ -109,23 +109,23 @@ class Collapse extends Widget { if (isset($item['content'])) { $id = $this->options['id'] . '-collapse' . $index; - $options = ArrayHelper::getValue($item, 'contentOptions', array()); + $options = ArrayHelper::getValue($item, 'contentOptions', []); $options['id'] = $id; Html::addCssClass($options, 'accordion-body collapse'); - $header = Html::a($header, '#' . $id, array( + $header = Html::a($header, '#' . $id, [ 'class' => 'accordion-toggle', 'data-toggle' => 'collapse', 'data-parent' => '#' . $this->options['id'] - )) . "\n"; + ]) . "\n"; - $content = Html::tag('div', $item['content'], array('class' => 'accordion-inner')) . "\n"; + $content = Html::tag('div', $item['content'], ['class' => 'accordion-inner']) . "\n"; } else { throw new InvalidConfigException('The "content" option is required.'); } - $group = array(); + $group = []; - $group[] = Html::tag('div', $header, array('class' => 'accordion-heading')); + $group[] = Html::tag('div', $header, ['class' => 'accordion-heading']); $group[] = Html::tag('div', $content, $options); return implode("\n", $group); diff --git a/framework/yii/bootstrap/Dropdown.php b/framework/yii/bootstrap/Dropdown.php index 1cc389e..e9ef0ef 100644 --- a/framework/yii/bootstrap/Dropdown.php +++ b/framework/yii/bootstrap/Dropdown.php @@ -30,7 +30,7 @@ class Dropdown extends Widget * - linkOptions: array, optional, the HTML attributes of the item link. * - options: array, optional, the HTML attributes of the item. */ - public $items = array(); + public $items = []; /** * @var boolean whether the labels for header items should be HTML-encoded. */ @@ -64,7 +64,7 @@ class Dropdown extends Widget */ protected function renderItems($items) { - $lines = array(); + $lines = []; foreach ($items as $i => $item) { if (isset($item['visible']) && !$item['visible']) { unset($items[$i]); @@ -78,8 +78,8 @@ class Dropdown extends Widget throw new InvalidConfigException("The 'label' option is required."); } $label = $this->encodeLabels ? Html::encode($item['label']) : $item['label']; - $options = ArrayHelper::getValue($item, 'options', array()); - $linkOptions = ArrayHelper::getValue($item, 'linkOptions', array()); + $options = ArrayHelper::getValue($item, 'options', []); + $linkOptions = ArrayHelper::getValue($item, 'linkOptions', []); $linkOptions['tabindex'] = '-1'; $content = Html::a($label, ArrayHelper::getValue($item, 'url', '#'), $linkOptions); $lines[] = Html::tag('li', $content, $options); diff --git a/framework/yii/bootstrap/Modal.php b/framework/yii/bootstrap/Modal.php index e1f042f..94a3997 100644 --- a/framework/yii/bootstrap/Modal.php +++ b/framework/yii/bootstrap/Modal.php @@ -18,12 +18,10 @@ use yii\helpers\Html; * and [[end()]] calls within the modal window: * * ~~~php - * Modal::begin(array( + * Modal::begin([ * 'header' => '

Hello world

', - * 'toggleButton' => array( - * 'label' => 'click me', - * ), - * )); + * 'toggleButton' => ['label' => 'click me'], + * ]); * * echo 'Say hello...'; * @@ -59,7 +57,7 @@ class Modal extends Widget * Please refer to the [Modal plugin help](http://twitter.github.com/bootstrap/javascript.html#modals) * for the supported HTML attributes. */ - public $closeButton = array(); + public $closeButton = []; /** * @var array the options for rendering the toggle button tag. * The toggle button is used to toggle the visibility of the modal window. @@ -88,8 +86,8 @@ class Modal extends Widget echo $this->renderToggleButton() . "\n"; echo Html::beginTag('div', $this->options) . "\n"; - echo Html::beginTag('div', array('class' => 'modal-dialog')) . "\n"; - echo Html::beginTag('div', array('class' => 'modal-content')) . "\n"; + echo Html::beginTag('div', ['class' => 'modal-dialog']) . "\n"; + echo Html::beginTag('div', ['class' => 'modal-content']) . "\n"; echo $this->renderHeader() . "\n"; echo $this->renderBodyBegin() . "\n"; } @@ -119,7 +117,7 @@ class Modal extends Widget $this->header = $button . "\n" . $this->header; } if ($this->header !== null) { - return Html::tag('div', "\n" . $this->header . "\n", array('class' => 'modal-header')); + return Html::tag('div', "\n" . $this->header . "\n", ['class' => 'modal-header']); } else { return null; } @@ -131,7 +129,7 @@ class Modal extends Widget */ protected function renderBodyBegin() { - return Html::beginTag('div', array('class' => 'modal-body')); + return Html::beginTag('div', ['class' => 'modal-body']); } /** @@ -150,7 +148,7 @@ class Modal extends Widget protected function renderFooter() { if ($this->footer !== null) { - return Html::tag('div', "\n" . $this->footer . "\n", array('class' => 'modal-footer')); + return Html::tag('div', "\n" . $this->footer . "\n", ['class' => 'modal-footer']); } else { return null; } @@ -198,31 +196,29 @@ class Modal extends Widget */ protected function initOptions() { - $this->options = array_merge(array( + $this->options = array_merge([ 'class' => 'fade', 'role' => 'dialog', 'tabindex' => -1, - ), $this->options); + ], $this->options); Html::addCssClass($this->options, 'modal'); if ($this->clientOptions !== false) { - $this->clientOptions = array_merge(array( - 'show' => false, - ), $this->clientOptions); + $this->clientOptions = array_merge(['show' => false], $this->clientOptions); } if ($this->closeButton !== null) { - $this->closeButton = array_merge(array( + $this->closeButton = array_merge([ 'data-dismiss' => 'modal', 'aria-hidden' => 'true', 'class' => 'close', - ), $this->closeButton); + ], $this->closeButton); } if ($this->toggleButton !== null) { - $this->toggleButton = array_merge(array( + $this->toggleButton = array_merge([ 'data-toggle' => 'modal', - ), $this->toggleButton); + ], $this->toggleButton); if (!isset($this->toggleButton['data-target']) && !isset($this->toggleButton['href'])) { $this->toggleButton['data-target'] = '#' . $this->options['id']; } diff --git a/framework/yii/bootstrap/Nav.php b/framework/yii/bootstrap/Nav.php index f24f729..7d07a86 100644 --- a/framework/yii/bootstrap/Nav.php +++ b/framework/yii/bootstrap/Nav.php @@ -18,34 +18,28 @@ use yii\helpers\Html; * For example: * * ```php - * echo Nav::widget(array( - * 'items' => array( - * array( + * echo Nav::widget([ + * 'items' => [ + * [ * 'label' => 'Home', - * 'url' => array('site/index'), - * 'linkOptions' => array(...), + * 'url' => ['site/index'], + * 'linkOptions' => [...], * ), - * array( + * [ * 'label' => 'Dropdown', - * 'items' => array( - * array( + * 'items' => [ + * [ * 'label' => 'Level 1 -DropdownA', * 'url' => '#', - * 'items' => array( - * array( - * 'label' => 'Level 2 -DropdownA', - * 'url' => '#', - * ), - * ), - * ), - * array( - * 'label' => 'Level 1 -DropdownB', - * 'url' => '#', - * ), - * ), - * ), - * ), - * )); + * 'items' => [ + * ['label' => 'Level 2 -DropdownA', 'url' => '#'], + * ], + * ], + * ['label' => 'Level 1 -DropdownB', 'url' => '#'], + * ], + * ], + * ], + * ]); * ``` * * @see http://twitter.github.io/bootstrap/components.html#nav @@ -69,7 +63,7 @@ class Nav extends Widget * * If a menu item is a string, it will be rendered directly without HTML encoding. */ - public $items = array(); + public $items = []; /** * @var boolean whether the nav items labels should be HTML-encoded. */ @@ -125,7 +119,7 @@ class Nav extends Widget */ public function renderItems() { - $items = array(); + $items = []; foreach ($this->items as $i => $item) { if (isset($item['visible']) && !$item['visible']) { unset($items[$i]); @@ -152,10 +146,10 @@ class Nav extends Widget throw new InvalidConfigException("The 'label' option is required."); } $label = $this->encodeLabels ? Html::encode($item['label']) : $item['label']; - $options = ArrayHelper::getValue($item, 'options', array()); + $options = ArrayHelper::getValue($item, 'options', []); $items = ArrayHelper::getValue($item, 'items'); $url = Html::url(ArrayHelper::getValue($item, 'url', '#')); - $linkOptions = ArrayHelper::getValue($item, 'linkOptions', array()); + $linkOptions = ArrayHelper::getValue($item, 'linkOptions', []); if (isset($item['active'])) { $active = ArrayHelper::remove($item, 'active', false); @@ -171,13 +165,13 @@ class Nav extends Widget $linkOptions['data-toggle'] = 'dropdown'; Html::addCssClass($options, 'dropdown'); Html::addCssClass($urlOptions, 'dropdown-toggle'); - $label .= ' ' . Html::tag('b', '', array('class' => 'caret')); + $label .= ' ' . Html::tag('b', '', ['class' => 'caret']); if (is_array($items)) { - $items = Dropdown::widget(array( + $items = Dropdown::widget([ 'items' => $items, 'encodeLabels' => $this->encodeLabels, 'clientOptions' => false, - )); + ]); } } diff --git a/framework/yii/bootstrap/NavBar.php b/framework/yii/bootstrap/NavBar.php index 7aafbbb..620f51e 100644 --- a/framework/yii/bootstrap/NavBar.php +++ b/framework/yii/bootstrap/NavBar.php @@ -20,13 +20,13 @@ use yii\helpers\Html; * use yii\bootstrap\NavBar; * use yii\widgets\Menu; * - * NavBar::begin(array('brandLabel' => 'NavBar Test')); - * echo Nav::widget(array( - * 'items' => array( - * array('label' => 'Home', 'url' => array('/site/index')), - * array('label' => 'About', 'url' => array('/site/about')), - * ), - * )); + * NavBar::begin(['brandLabel' => 'NavBar Test']); + * echo Nav::widget([ + * 'items' => [ + * ['label' => 'Home', 'url' => ['/site/index']], + * ['label' => 'About', 'url' => ['/site/about']], + * ], + * ]); * NavBar::end(); * ``` * @@ -49,7 +49,7 @@ class NavBar extends Widget /** * @var array the HTML attributes of the brand link. */ - public $brandOptions = array(); + public $brandOptions = []; public $screenReaderToggleText = 'Toggle navigation'; @@ -67,16 +67,16 @@ class NavBar extends Widget } echo Html::beginTag('nav', $this->options); - echo Html::beginTag('div', array('class' => 'container')); + echo Html::beginTag('div', ['class' => 'container']); - echo Html::beginTag('div', array('class' => 'navbar-header')); + echo Html::beginTag('div', ['class' => 'navbar-header']); echo $this->renderToggleButton(); if ($this->brandLabel !== null) { echo Html::a($this->brandLabel, $this->brandUrl, $this->brandOptions); } echo Html::endTag('div'); - echo Html::beginTag('div', array('class' => 'collapse navbar-collapse navbar-ex1-collapse')); + echo Html::beginTag('div', ['class' => 'collapse navbar-collapse navbar-ex1-collapse']); } /** @@ -97,12 +97,12 @@ class NavBar extends Widget */ protected function renderToggleButton() { - $bar = Html::tag('span', '', array('class' => 'icon-bar')); + $bar = Html::tag('span', '', ['class' => 'icon-bar']); $screenReader = ''.$this->screenReaderToggleText.''; - return Html::button("{$screenReader}\n{$bar}\n{$bar}\n{$bar}", array( + return Html::button("{$screenReader}\n{$bar}\n{$bar}\n{$bar}", [ 'class' => 'navbar-toggle', 'data-toggle' => 'collapse', 'data-target' => '.navbar-ex1-collapse', - )); + ]); } } diff --git a/framework/yii/bootstrap/Progress.php b/framework/yii/bootstrap/Progress.php index d8e5a69..ed2d37d 100644 --- a/framework/yii/bootstrap/Progress.php +++ b/framework/yii/bootstrap/Progress.php @@ -18,39 +18,39 @@ use yii\helpers\Html; * * ```php * // default with label - * echo Progress::widget(array( + * echo Progress::widget([ * 'percent' => 60, * 'label' => 'test', - * )); + * ]); * * // styled - * echo Progress::widget(array( + * echo Progress::widget([ * 'percent' => 65, - * 'barOptions' => array('class' => 'bar-danger') - * )); + * 'barOptions' => ['class' => 'bar-danger'] + * ]); * * // striped - * echo Progress::widget(array( + * echo Progress::widget([ * 'percent' => 70, - * 'barOptions' => array('class' => 'bar-warning'), - * 'options' => array('class' => 'progress-striped') - * )); + * 'barOptions' => ['class' => 'bar-warning'], + * 'options' => ['class' => 'progress-striped'] + * ]); * * // striped animated - * echo Progress::widget(array( + * echo Progress::widget([ * 'percent' => 70, - * 'barOptions' => array('class' => 'bar-success'), - * 'options' => array('class' => 'active progress-striped') - * )); + * 'barOptions' => ['class' => 'bar-success'], + * 'options' => ['class' => 'active progress-striped'] + * ]); * * // stacked bars - * echo Progress::widget(array( - * 'bars' => array( - * array('percent' => 30, 'options' => array('class' => 'bar-danger')), - * array('percent' => 30, 'label' => 'test', 'options' => array('class' => 'bar-success')), - * array('percent' => 35, 'options' => array('class' => 'bar-warning')) - * ) - * )); + * echo Progress::widget([ + * 'bars' => [ + * ['percent' => 30, 'options' => ['class' => 'bar-danger']], + * ['percent' => 30, 'label' => 'test', 'options' => ['class' => 'bar-success']], + * ['percent' => 35, 'options' => array['class' => 'bar-warning']], + * ] + * ]); * ``` * @see http://twitter.github.io/bootstrap/components.html#progress * @author Antonio Ramirez @@ -69,20 +69,20 @@ class Progress extends Widget /** * @var array the HTML attributes of the */ - public $barOptions = array(); + public $barOptions = []; /** * @var array a set of bars that are stacked together to form a single progress bar. * Each bar is an array of the following structure: * * ```php - * array( + * [ * // required, the amount of progress as a percentage. * 'percent' => 30, * // optional, the label to be displayed on the bar * 'label' => '30%', * // optional, array, additional HTML attributes for the bar tag - * 'options' => array(), - * ) + * 'options' => [], + * ] */ public $bars; @@ -118,13 +118,13 @@ class Progress extends Widget if (empty($this->bars)) { return $this->renderBar($this->percent, $this->label, $this->barOptions); } - $bars = array(); + $bars = []; foreach ($this->bars as $bar) { $label = ArrayHelper::getValue($bar, 'label', ''); if (!isset($bar['percent'])) { throw new InvalidConfigException("The 'percent' option is required."); } - $options = ArrayHelper::getValue($bar, 'options', array()); + $options = ArrayHelper::getValue($bar, 'options', []); $bars[] = $this->renderBar($bar['percent'], $label, $options); } return implode("\n", $bars); @@ -137,7 +137,7 @@ class Progress extends Widget * @param array $options the HTML attributes of the bar * @return string the rendering result. */ - protected function renderBar($percent, $label = '', $options = array()) + protected function renderBar($percent, $label = '', $options = []) { Html::addCssClass($options, 'bar'); $options['style'] = "width:{$percent}%"; diff --git a/framework/yii/bootstrap/Tabs.php b/framework/yii/bootstrap/Tabs.php index d6ddd7b..653ed68 100644 --- a/framework/yii/bootstrap/Tabs.php +++ b/framework/yii/bootstrap/Tabs.php @@ -17,34 +17,34 @@ use yii\helpers\Html; * For example: * * ```php - * echo Tabs::widget(array( - * 'items' => array( - * array( + * echo Tabs::widget([ + * 'items' => [ + * [ * 'label' => 'One', * 'content' => 'Anim pariatur cliche...', * 'active' => true - * ), - * array( + * ], + * [ * 'label' => 'Two', * 'content' => 'Anim pariatur cliche...', - * 'headerOptions' => array(...), - * 'options' => array('id' => 'myveryownID'), - * ), - * array( + * 'headerOptions' => [...], + * 'options' => ['id' => 'myveryownID'], + * ], + * [ * 'label' => 'Dropdown', - * 'items' => array( - * array( + * 'items' => [ + * [ * 'label' => 'DropdownA', * 'content' => 'DropdownA, Anim pariatur cliche...', - * ), - * array( + * ], + * [ * 'label' => 'DropdownB', * 'content' => 'DropdownB, Anim pariatur cliche...', - * ), - * ), - * ), - * ), - * )); + * ], + * ], + * ], + * ], + * ]); * ``` * * @see http://twitter.github.io/bootstrap/javascript.html#tabs @@ -68,19 +68,19 @@ class Tabs extends Widget * * content: string, required if `items` is not set. The content (HTML) of the tab pane. * * contentOptions: optional, array, the HTML attributes of the tab content container. */ - public $items = array(); + public $items = []; /** * @var array list of HTML attributes for the item container tags. This will be overwritten * by the "options" set in individual [[items]]. The following special options are recognized: * * - tag: string, defaults to "div", the tag name of the item container tags. */ - public $itemOptions = array(); + public $itemOptions = []; /** * @var array list of HTML attributes for the header container tags. This will be overwritten * by the "headerOptions" set in individual [[items]]. */ - public $headerOptions = array(); + public $headerOptions = []; /** * @var boolean whether the labels for header items should be HTML-encoded. */ @@ -112,14 +112,14 @@ class Tabs extends Widget */ protected function renderItems() { - $headers = array(); - $panes = array(); + $headers = []; + $panes = []; foreach ($this->items as $n => $item) { if (!isset($item['label'])) { throw new InvalidConfigException("The 'label' option is required."); } $label = $this->encodeLabels ? Html::encode($item['label']) : $item['label']; - $headerOptions = array_merge($this->headerOptions, ArrayHelper::getValue($item, 'headerOptions', array())); + $headerOptions = array_merge($this->headerOptions, ArrayHelper::getValue($item, 'headerOptions', [])); if (isset($item['items'])) { $label .= ' '; @@ -129,10 +129,10 @@ class Tabs extends Widget Html::addCssClass($headerOptions, 'active'); } - $header = Html::a($label, "#", array('class' => 'dropdown-toggle', 'data-toggle' => 'dropdown')) . "\n" - . Dropdown::widget(array('items' => $item['items'], 'clientOptions' => false)); + $header = Html::a($label, "#", ['class' => 'dropdown-toggle', 'data-toggle' => 'dropdown']) . "\n" + . Dropdown::widget(['items' => $item['items'], 'clientOptions' => false]); } elseif (isset($item['content'])) { - $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', array())); + $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', [])); $options['id'] = ArrayHelper::getValue($options, 'id', $this->options['id'] . '-tab' . $n); Html::addCssClass($options, 'tab-pane'); @@ -140,7 +140,7 @@ class Tabs extends Widget Html::addCssClass($options, 'active'); Html::addCssClass($headerOptions, 'active'); } - $header = Html::a($label, '#' . $options['id'], array('data-toggle' => 'tab')); + $header = Html::a($label, '#' . $options['id'], ['data-toggle' => 'tab']); $panes[] = Html::tag('div', $item['content'], $options); } else { throw new InvalidConfigException("Either the 'content' or 'items' option must be set."); @@ -150,7 +150,7 @@ class Tabs extends Widget } return Html::tag('ul', implode("\n", $headers), $this->options) . "\n" - . Html::tag('div', implode("\n", $panes), array('class' => 'tab-content')); + . Html::tag('div', implode("\n", $panes), ['class' => 'tab-content']); } /** @@ -174,7 +174,7 @@ class Tabs extends Widget } $content = ArrayHelper::remove($item, 'content'); - $options = ArrayHelper::remove($item, 'contentOptions', array()); + $options = ArrayHelper::remove($item, 'contentOptions', []); Html::addCssClass($options, 'tab-pane'); if (ArrayHelper::remove($item, 'active')) { Html::addCssClass($options, 'active'); diff --git a/framework/yii/bootstrap/Widget.php b/framework/yii/bootstrap/Widget.php index 2959f09..db7f415 100644 --- a/framework/yii/bootstrap/Widget.php +++ b/framework/yii/bootstrap/Widget.php @@ -23,21 +23,21 @@ class Widget extends \yii\base\Widget /** * @var array the HTML attributes for the widget container tag. */ - public $options = array(); + public $options = []; /** * @var array the options for the underlying Bootstrap JS plugin. * Please refer to the corresponding Bootstrap plugin Web page for possible options. * For example, [this page](http://twitter.github.io/bootstrap/javascript.html#modals) shows * how to use the "Modal" plugin and the supported options (e.g. "remote"). */ - public $clientOptions = array(); + public $clientOptions = []; /** * @var array the event handlers for the underlying Bootstrap JS plugin. * Please refer to the corresponding Bootstrap plugin Web page for possible events. * For example, [this page](http://twitter.github.io/bootstrap/javascript.html#modals) shows * how to use the "Modal" plugin and the supported events (e.g. "shown"). */ - public $clientEvents = array(); + public $clientEvents = []; /** @@ -72,7 +72,7 @@ class Widget extends \yii\base\Widget } if (!empty($this->clientEvents)) { - $js = array(); + $js = []; foreach ($this->clientEvents as $event => $handler) { $js[] = "jQuery('#$id').on('$event', $handler);"; } diff --git a/framework/yii/caching/Cache.php b/framework/yii/caching/Cache.php index 56c6d96..f9d117d 100644 --- a/framework/yii/caching/Cache.php +++ b/framework/yii/caching/Cache.php @@ -163,12 +163,12 @@ abstract class Cache extends Component implements \ArrayAccess */ public function mget($keys) { - $keyMap = array(); + $keyMap = []; foreach ($keys as $key) { $keyMap[$key] = $this->buildKey($key); } $values = $this->getValues(array_values($keyMap)); - $results = array(); + $results = []; foreach ($keyMap as $key => $newKey) { $results[$key] = false; if (isset($values[$newKey])) { @@ -207,9 +207,9 @@ abstract class Cache extends Component implements \ArrayAccess $dependency->evaluateDependency($this); } if ($this->serializer === null) { - $value = serialize(array($value, $dependency)); + $value = serialize([$value, $dependency]); } elseif ($this->serializer !== false) { - $value = call_user_func($this->serializer[0], array($value, $dependency)); + $value = call_user_func($this->serializer[0], [$value, $dependency]); } $key = $this->buildKey($key); return $this->setValue($key, $value, $expire); @@ -233,9 +233,9 @@ abstract class Cache extends Component implements \ArrayAccess $dependency->evaluateDependency($this); } if ($this->serializer === null) { - $value = serialize(array($value, $dependency)); + $value = serialize([$value, $dependency]); } elseif ($this->serializer !== false) { - $value = call_user_func($this->serializer[0], array($value, $dependency)); + $value = call_user_func($this->serializer[0], [$value, $dependency]); } $key = $this->buildKey($key); return $this->addValue($key, $value, $expire); @@ -319,7 +319,7 @@ abstract class Cache extends Component implements \ArrayAccess */ protected function getValues($keys) { - $results = array(); + $results = []; foreach ($keys as $key) { $results[$key] = $this->getValue($key); } diff --git a/framework/yii/caching/ChainedDependency.php b/framework/yii/caching/ChainedDependency.php index d3b9953..20cb632 100644 --- a/framework/yii/caching/ChainedDependency.php +++ b/framework/yii/caching/ChainedDependency.php @@ -38,7 +38,7 @@ class ChainedDependency extends Dependency * Each array element should be a dependency object. * @param array $config name-value pairs that will be used to initialize the object properties */ - public function __construct($dependencies = array(), $config = array()) + public function __construct($dependencies = [], $config = []) { $this->dependencies = $dependencies; parent::__construct($config); diff --git a/framework/yii/caching/DbCache.php b/framework/yii/caching/DbCache.php index b7b6692..cca2c55 100644 --- a/framework/yii/caching/DbCache.php +++ b/framework/yii/caching/DbCache.php @@ -23,11 +23,11 @@ use yii\db\Query; * The following example shows how you can configure the application to use DbCache: * * ~~~ - * 'cache' => array( + * 'cache' => [ * 'class' => 'yii\caching\DbCache', * // 'db' => 'mydb', * // 'cacheTable' => 'my_cache', - * ) + * ] * ~~~ * * @author Qiang Xue @@ -103,9 +103,9 @@ class DbCache extends Cache $key = $this->buildKey($key); $query = new Query; - $query->select(array('COUNT(*)')) + $query->select(['COUNT(*)']) ->from($this->cacheTable) - ->where('[[id]] = :id AND ([[expire]] = 0 OR [[expire]] >' . time() . ')', array(':id' => $key)); + ->where('[[id]] = :id AND ([[expire]] = 0 OR [[expire]] >' . time() . ')', [':id' => $key]); if ($this->db->enableQueryCache) { // temporarily disable and re-enable query caching $this->db->enableQueryCache = false; @@ -126,9 +126,9 @@ class DbCache extends Cache protected function getValue($key) { $query = new Query; - $query->select(array('data')) + $query->select(['data']) ->from($this->cacheTable) - ->where('[[id]] = :id AND ([[expire]] = 0 OR [[expire]] >' . time() . ')', array(':id' => $key)); + ->where('[[id]] = :id AND ([[expire]] = 0 OR [[expire]] >' . time() . ')', [':id' => $key]); if ($this->db->enableQueryCache) { // temporarily disable and re-enable query caching $this->db->enableQueryCache = false; @@ -148,12 +148,12 @@ class DbCache extends Cache protected function getValues($keys) { if (empty($keys)) { - return array(); + return []; } $query = new Query; - $query->select(array('id', 'data')) + $query->select(['id', 'data']) ->from($this->cacheTable) - ->where(array('id' => $keys)) + ->where(['id' => $keys]) ->andWhere('([[expire]] = 0 OR [[expire]] > ' . time() . ')'); if ($this->db->enableQueryCache) { @@ -164,7 +164,7 @@ class DbCache extends Cache $rows = $query->createCommand($this->db)->queryAll(); } - $results = array(); + $results = []; foreach ($keys as $key) { $results[$key] = false; } @@ -186,12 +186,10 @@ class DbCache extends Cache protected function setValue($key, $value, $expire) { $command = $this->db->createCommand() - ->update($this->cacheTable, array( + ->update($this->cacheTable, [ 'expire' => $expire > 0 ? $expire + time() : 0, - 'data' => array($value, \PDO::PARAM_LOB), - ), array( - 'id' => $key, - )); + 'data' => [$value, \PDO::PARAM_LOB], + ], ['id' => $key]); if ($command->execute()) { $this->gc(); @@ -222,11 +220,11 @@ class DbCache extends Cache try { $this->db->createCommand() - ->insert($this->cacheTable, array( + ->insert($this->cacheTable, [ 'id' => $key, 'expire' => $expire, - 'data' => array($value, \PDO::PARAM_LOB), - ))->execute(); + 'data' => [$value, \PDO::PARAM_LOB], + ])->execute(); return true; } catch (\Exception $e) { return false; @@ -242,7 +240,7 @@ class DbCache extends Cache protected function deleteValue($key) { $this->db->createCommand() - ->delete($this->cacheTable, array('id' => $key)) + ->delete($this->cacheTable, ['id' => $key]) ->execute(); return true; } diff --git a/framework/yii/caching/DbDependency.php b/framework/yii/caching/DbDependency.php index 0b559d7..e8e1e68 100644 --- a/framework/yii/caching/DbDependency.php +++ b/framework/yii/caching/DbDependency.php @@ -42,7 +42,7 @@ class DbDependency extends Dependency * @param array $params the parameters (name => value) to be bound to the SQL statement specified by [[sql]]. * @param array $config name-value pairs that will be used to initialize the object properties */ - public function __construct($sql, $params = array(), $config = array()) + public function __construct($sql, $params = [], $config = []) { $this->sql = $sql; $this->params = $params; diff --git a/framework/yii/caching/Dependency.php b/framework/yii/caching/Dependency.php index 91c0568..c84f72d 100644 --- a/framework/yii/caching/Dependency.php +++ b/framework/yii/caching/Dependency.php @@ -34,7 +34,7 @@ abstract class Dependency extends \yii\base\Object /** * @var array static storage of cached data for reusable dependencies. */ - private static $_reusableData = array(); + private static $_reusableData = []; /** * @var string a unique hash value for this cache dependency. */ @@ -86,7 +86,7 @@ abstract class Dependency extends \yii\base\Object */ public static function resetReusableData() { - self::$_reusableData = array(); + self::$_reusableData = []; } /** diff --git a/framework/yii/caching/ExpressionDependency.php b/framework/yii/caching/ExpressionDependency.php index 533c2ab..36250d2 100644 --- a/framework/yii/caching/ExpressionDependency.php +++ b/framework/yii/caching/ExpressionDependency.php @@ -40,7 +40,7 @@ class ExpressionDependency extends Dependency * @param mixed $params the custom parameters associated with this dependency * @param array $config name-value pairs that will be used to initialize the object properties */ - public function __construct($expression = 'true', $params = null, $config = array()) + public function __construct($expression = 'true', $params = null, $config = []) { $this->expression = $expression; $this->params = $params; diff --git a/framework/yii/caching/FileDependency.php b/framework/yii/caching/FileDependency.php index bcc48a8..fa8b147 100644 --- a/framework/yii/caching/FileDependency.php +++ b/framework/yii/caching/FileDependency.php @@ -29,7 +29,7 @@ class FileDependency extends Dependency * @param string $fileName name of the file whose change is to be checked. * @param array $config name-value pairs that will be used to initialize the object properties */ - public function __construct($fileName = null, $config = array()) + public function __construct($fileName = null, $config = []) { $this->fileName = $fileName; parent::__construct($config); diff --git a/framework/yii/caching/GroupDependency.php b/framework/yii/caching/GroupDependency.php index d63cee4..48673f6 100644 --- a/framework/yii/caching/GroupDependency.php +++ b/framework/yii/caching/GroupDependency.php @@ -28,7 +28,7 @@ class GroupDependency extends Dependency * @param string $group the group name * @param array $config name-value pairs that will be used to initialize the object properties */ - public function __construct($group, $config = array()) + public function __construct($group, $config = []) { $this->group = $group; parent::__construct($config); @@ -42,7 +42,7 @@ class GroupDependency extends Dependency */ protected function generateDependencyData($cache) { - $version = $cache->get(array(__CLASS__, $this->group)); + $version = $cache->get([__CLASS__, $this->group]); if ($version === false) { $version = $this->invalidate($cache, $this->group); } @@ -56,7 +56,7 @@ class GroupDependency extends Dependency */ public function getHasChanged($cache) { - $version = $cache->get(array(__CLASS__, $this->group)); + $version = $cache->get([__CLASS__, $this->group]); return $version === false || $version !== $this->data; } @@ -69,7 +69,7 @@ class GroupDependency extends Dependency public static function invalidate($cache, $group) { $version = microtime(); - $cache->set(array(__CLASS__, $group), $version); + $cache->set([__CLASS__, $group], $version); return $version; } } diff --git a/framework/yii/caching/MemCache.php b/framework/yii/caching/MemCache.php index 69a90b4..fc7efb4 100644 --- a/framework/yii/caching/MemCache.php +++ b/framework/yii/caching/MemCache.php @@ -28,25 +28,25 @@ use yii\base\InvalidConfigException; * To use MemCache as the cache application component, configure the application as follows, * * ~~~ - * array( - * 'components' => array( - * 'cache' => array( + * [ + * 'components' => [ + * 'cache' => [ * 'class' => 'MemCache', - * 'servers' => array( - * array( + * 'servers' => [ + * [ * 'host' => 'server1', * 'port' => 11211, * 'weight' => 60, - * ), - * array( + * ], + * [ * 'host' => 'server2', * 'port' => 11211, * 'weight' => 40, - * ), - * ), - * ), - * ), - * ) + * ], + * ], + * ], + * ], + * ] * ~~~ * * In the above, two memcache servers are used: server1 and server2. You can configure more properties of @@ -76,7 +76,7 @@ class MemCache extends Cache /** * @var array list of memcache server configurations */ - private $_servers = array(); + private $_servers = []; /** * Initializes this application component. diff --git a/framework/yii/caching/RedisCache.php b/framework/yii/caching/RedisCache.php index 7cb6451..3a40254 100644 --- a/framework/yii/caching/RedisCache.php +++ b/framework/yii/caching/RedisCache.php @@ -27,16 +27,16 @@ use yii\redis\Connection; * To use RedisCache as the cache application component, configure the application as follows, * * ~~~ - * array( - * 'components'=>array( - * 'cache'=>array( - * 'class'=>'RedisCache', - * 'hostname'=>'localhost', - * 'port'=>6379, - * 'database'=>0, - * ), - * ), - * ) + * [ + * 'components' => [ + * 'cache' => [ + * 'class' => 'RedisCache', + * 'hostname' => 'localhost', + * 'port' => 6379, + * 'database' => 0, + * ], + * ], + * ] * ~~~ * * @property Connection $connection The redis connection object. This property is read-only. @@ -93,12 +93,12 @@ class RedisCache extends Cache public function getConnection() { if ($this->_connection === null) { - $this->_connection = new Connection(array( + $this->_connection = new Connection([ 'dsn' => 'redis://' . $this->hostname . ':' . $this->port . '/' . $this->database, 'password' => $this->password, 'connectionTimeout' => $this->connectionTimeout, 'dataTimeout' => $this->dataTimeout, - )); + ]); } return $this->_connection; } @@ -115,7 +115,7 @@ class RedisCache extends Cache */ public function exists($key) { - return (bool) $this->_connection->executeCommand('EXISTS', array($this->buildKey($key))); + return (bool) $this->_connection->executeCommand('EXISTS', [$this->buildKey($key)]); } /** @@ -126,7 +126,7 @@ class RedisCache extends Cache */ protected function getValue($key) { - return $this->_connection->executeCommand('GET', array($key)); + return $this->_connection->executeCommand('GET', [$key]); } /** @@ -137,7 +137,7 @@ class RedisCache extends Cache protected function getValues($keys) { $response = $this->_connection->executeCommand('MGET', $keys); - $result = array(); + $result = []; $i = 0; foreach($keys as $key) { $result[$key] = $response[$i++]; @@ -158,10 +158,10 @@ class RedisCache extends Cache protected function setValue($key,$value,$expire) { if ($expire == 0) { - return (bool) $this->_connection->executeCommand('SET', array($key, $value)); + return (bool) $this->_connection->executeCommand('SET', [$key, $value]); } else { $expire = (int) ($expire * 1000); - return (bool) $this->_connection->executeCommand('PSETEX', array($key, $expire, $value)); + return (bool) $this->_connection->executeCommand('PSETEX', [$key, $expire, $value]); } } @@ -178,13 +178,13 @@ class RedisCache extends Cache protected function addValue($key,$value,$expire) { if ($expire == 0) { - return (bool) $this->_connection->executeCommand('SETNX', array($key, $value)); + return (bool) $this->_connection->executeCommand('SETNX', [$key, $value]); } else { // TODO consider requiring redis version >= 2.6.12 that supports this in one command $expire = (int) ($expire * 1000); $this->_connection->executeCommand('MULTI'); - $this->_connection->executeCommand('SETNX', array($key, $value)); - $this->_connection->executeCommand('PEXPIRE', array($key, $expire)); + $this->_connection->executeCommand('SETNX', [$key, $value]); + $this->_connection->executeCommand('PEXPIRE', [$key, $expire]); $response = $this->_connection->executeCommand('EXEC'); return (bool) $response[0]; } @@ -198,7 +198,7 @@ class RedisCache extends Cache */ protected function deleteValue($key) { - return (bool) $this->_connection->executeCommand('DEL', array($key)); + return (bool) $this->_connection->executeCommand('DEL', [$key]); } /** diff --git a/framework/yii/captcha/Captcha.php b/framework/yii/captcha/Captcha.php index fc1d881..76090a2 100644 --- a/framework/yii/captcha/Captcha.php +++ b/framework/yii/captcha/Captcha.php @@ -41,11 +41,11 @@ class Captcha extends InputWidget /** * @var array HTML attributes to be applied to the text input field. */ - public $options = array(); + public $options = []; /** * @var array HTML attributes to be applied to the CAPTCHA image tag. */ - public $imageOptions = array(); + public $imageOptions = []; /** * @var string the template for arranging the CAPTCHA image tag and the text input tag. * In this template, the token `{image}` will be replaced with the actual image tag, @@ -81,12 +81,12 @@ class Captcha extends InputWidget } else { $input = Html::textInput($this->name, $this->value, $this->options); } - $url = Yii::$app->getUrlManager()->createUrl($this->captchaAction, array('v' => uniqid())); + $url = Yii::$app->getUrlManager()->createUrl($this->captchaAction, ['v' => uniqid()]); $image = Html::img($url, $this->imageOptions); - echo strtr($this->template, array( + echo strtr($this->template, [ '{input}' => $input, '{image}' => $image, - )); + ]); } /** @@ -108,10 +108,10 @@ class Captcha extends InputWidget */ protected function getClientOptions() { - $options = array( - 'refreshUrl' => Html::url(array($this->captchaAction, CaptchaAction::REFRESH_GET_VAR => 1)), + $options = [ + 'refreshUrl' => Html::url([$this->captchaAction, CaptchaAction::REFRESH_GET_VAR => 1]), 'hashKey' => "yiiCaptcha/{$this->captchaAction}", - ); + ]; return $options; } diff --git a/framework/yii/captcha/CaptchaAction.php b/framework/yii/captcha/CaptchaAction.php index e1761a1..190ec35 100644 --- a/framework/yii/captcha/CaptchaAction.php +++ b/framework/yii/captcha/CaptchaAction.php @@ -119,13 +119,13 @@ class CaptchaAction extends Action $code = $this->getVerifyCode(true); /** @var \yii\web\Controller $controller */ $controller = $this->controller; - return json_encode(array( + return json_encode([ 'hash1' => $this->generateValidationHash($code), 'hash2' => $this->generateValidationHash(strtolower($code)), // we add a random 'v' parameter so that FireFox can refresh the image // when src attribute of image tag is changed - 'url' => $controller->createUrl($this->id, array('v' => uniqid())), - )); + 'url' => $controller->createUrl($this->id, ['v' => uniqid()]), + ]); } else { $this->setHttpHeaders(); return $this->renderImage($this->getVerifyCode()); diff --git a/framework/yii/captcha/CaptchaAsset.php b/framework/yii/captcha/CaptchaAsset.php index 50c75b7..adece3c 100644 --- a/framework/yii/captcha/CaptchaAsset.php +++ b/framework/yii/captcha/CaptchaAsset.php @@ -16,10 +16,10 @@ use yii\web\AssetBundle; class CaptchaAsset extends AssetBundle { public $sourcePath = '@yii/assets'; - public $js = array( + public $js = [ 'yii.captcha.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\web\YiiAsset', - ); + ]; } diff --git a/framework/yii/captcha/CaptchaValidator.php b/framework/yii/captcha/CaptchaValidator.php index 97bfd1b..c613979 100644 --- a/framework/yii/captcha/CaptchaValidator.php +++ b/framework/yii/captcha/CaptchaValidator.php @@ -107,15 +107,15 @@ class CaptchaValidator extends Validator $captcha = $this->getCaptchaAction(); $code = $captcha->getVerifyCode(false); $hash = $captcha->generateValidationHash($this->caseSensitive ? $code : strtolower($code)); - $options = array( + $options = [ 'hash' => $hash, 'hashKey' => 'yiiCaptcha/' . $this->captchaAction, 'caseSensitive' => $this->caseSensitive, - 'message' => Html::encode(strtr($this->message, array( + 'message' => Html::encode(strtr($this->message, [ '{attribute}' => $object->getAttributeLabel($attribute), '{value}' => $object->$attribute, - ))), - ); + ])), + ]; if ($this->skipOnEmpty) { $options['skipOnEmpty'] = 1; } diff --git a/framework/yii/classes.php b/framework/yii/classes.php index 78cce95..1a3824b 100644 --- a/framework/yii/classes.php +++ b/framework/yii/classes.php @@ -10,7 +10,7 @@ * @license http://www.yiiframework.com/license/ */ -return array( +return [ 'yii\base\Action' => YII_PATH . '/base/Action.php', 'yii\base\ActionEvent' => YII_PATH . '/base/ActionEvent.php', 'yii\base\ActionFilter' => YII_PATH . '/base/ActionFilter.php', @@ -241,4 +241,4 @@ return array( 'yii\widgets\MaskedInputAsset' => YII_PATH . '/widgets/MaskedInputAsset.php', 'yii\widgets\Menu' => YII_PATH . '/widgets/Menu.php', 'yii\widgets\Spaceless' => YII_PATH . '/widgets/Spaceless.php', -); +]; diff --git a/framework/yii/console/Application.php b/framework/yii/console/Application.php index 9ca7393..6701304 100644 --- a/framework/yii/console/Application.php +++ b/framework/yii/console/Application.php @@ -125,12 +125,12 @@ class Application extends \yii\base\Application * @return integer the status code returned by the action execution. 0 means normal, and other values mean abnormal. * @throws Exception if the route is invalid */ - public function runAction($route, $params = array()) + public function runAction($route, $params = []) { try { return parent::runAction($route, $params); } catch (InvalidRouteException $e) { - throw new Exception(Yii::t('yii', 'Unknown command "{command}".', array('command' => $route)), 0, $e); + throw new Exception(Yii::t('yii', 'Unknown command "{command}".', ['command' => $route]), 0, $e); } } @@ -140,13 +140,13 @@ class Application extends \yii\base\Application */ public function coreCommands() { - return array( + return [ 'message' => 'yii\console\controllers\MessageController', 'help' => 'yii\console\controllers\HelpController', 'migrate' => 'yii\console\controllers\MigrateController', 'cache' => 'yii\console\controllers\CacheController', 'asset' => 'yii\console\controllers\AssetController', - ); + ]; } /** @@ -156,13 +156,9 @@ class Application extends \yii\base\Application public function registerCoreComponents() { parent::registerCoreComponents(); - $this->setComponents(array( - 'request' => array( - 'class' => 'yii\console\Request', - ), - 'response' => array( - 'class' => 'yii\console\Response', - ), - )); + $this->setComponents([ + 'request' => ['class' => 'yii\console\Request'], + 'response' => ['class' => 'yii\console\Response'], + ]); } } diff --git a/framework/yii/console/Controller.php b/framework/yii/console/Controller.php index 73b74f8..47ac4b0 100644 --- a/framework/yii/console/Controller.php +++ b/framework/yii/console/Controller.php @@ -63,7 +63,7 @@ class Controller extends \yii\base\Controller * @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully. * @see createAction */ - public function runAction($id, $params = array()) + public function runAction($id, $params = []) { if (!empty($params)) { $options = $this->globalOptions(); @@ -89,7 +89,7 @@ class Controller extends \yii\base\Controller */ public function bindActionParams($action, $params) { - $args = array(); + $args = []; if (!empty($params)) { $options = $this->globalOptions(); foreach ($params as $name => $value) { @@ -98,9 +98,7 @@ class Controller extends \yii\base\Controller } elseif (is_int($name)) { $args[] = $value; } else { - throw new Exception(Yii::t('yii', 'Unknown option: --{name}', array( - 'name' => $name, - ))); + throw new Exception(Yii::t('yii', 'Unknown option: --{name}', ['name' => $name])); } } } @@ -111,7 +109,7 @@ class Controller extends \yii\base\Controller $method = new \ReflectionMethod($action, 'run'); } - $missing = array(); + $missing = []; foreach ($method->getParameters() as $i => $param) { $name = $param->getName(); if (!isset($args[$i])) { @@ -124,9 +122,7 @@ class Controller extends \yii\base\Controller } if (!empty($missing)) { - throw new Exception(Yii::t('yii', 'Missing required arguments: {params}', array( - 'params' => implode(', ', $missing), - ))); + throw new Exception(Yii::t('yii', 'Missing required arguments: {params}', ['params' => implode(', ', $missing)])); } return $args; @@ -220,7 +216,7 @@ class Controller extends \yii\base\Controller * - $error: the error value passed by reference if validation failed. * @return string the user input */ - public function prompt($text, $options = array()) + public function prompt($text, $options = []) { if ($this->interactive) { return Console::prompt($text, $options); @@ -255,7 +251,7 @@ class Controller extends \yii\base\Controller * * @return string An option character the user chose */ - public function select($prompt, $options = array()) + public function select($prompt, $options = []) { return Console::select($prompt, $options); } @@ -273,6 +269,6 @@ class Controller extends \yii\base\Controller */ public function globalOptions() { - return array('color', 'interactive'); + return ['color', 'interactive']; } } diff --git a/framework/yii/console/Request.php b/framework/yii/console/Request.php index dca0240..d99c321 100644 --- a/framework/yii/console/Request.php +++ b/framework/yii/console/Request.php @@ -29,7 +29,7 @@ class Request extends \yii\base\Request $this->_params = $_SERVER['argv']; array_shift($this->_params); } else { - $this->_params = array(); + $this->_params = []; } } return $this->_params; @@ -58,7 +58,7 @@ class Request extends \yii\base\Request $route = ''; } - $params = array(); + $params = []; foreach ($rawParams as $param) { if (preg_match('/^--(\w+)(=(.*))?$/', $param, $matches)) { $name = $matches[1]; @@ -68,6 +68,6 @@ class Request extends \yii\base\Request } } - return array($route, $params); + return [$route, $params]; } } diff --git a/framework/yii/console/controllers/AssetController.php b/framework/yii/console/controllers/AssetController.php index a3c5de5..8ce1d46 100644 --- a/framework/yii/console/controllers/AssetController.php +++ b/framework/yii/console/controllers/AssetController.php @@ -43,24 +43,24 @@ class AssetController extends Controller /** * @var array list of asset bundles to be compressed. */ - public $bundles = array(); + public $bundles = []; /** * @var array list of asset bundles, which represents output compressed files. * You can specify the name of the output compressed file using 'css' and 'js' keys: * For example: * * ~~~ - * 'app\config\AllAsset' => array( + * 'app\config\AllAsset' => [ * 'js' => 'js/all-{ts}.js', * 'css' => 'css/all-{ts}.css', - * 'depends' => array( ... ), - * ) + * 'depends' => [ ... ], + * ] * ~~~ * * File names can contain placeholder "{ts}", which will be filled by current timestamp, while * file creation. */ - public $targets = array(); + public $targets = []; /** * @var string|callback JavaScript file compressor. * If a string, it is treated as shell command template, which should contain @@ -86,7 +86,7 @@ class AssetController extends Controller * @var array|\yii\web\AssetManager [[yii\web\AssetManager]] instance or its array configuration, which will be used * for assets processing. */ - private $_assetManager = array(); + private $_assetManager = []; /** * Returns the asset manager instance. @@ -181,7 +181,7 @@ class AssetController extends Controller echo "Collecting source bundles information...\n"; $am = $this->getAssetManager(); - $result = array(); + $result = []; foreach ($bundles as $name) { $result[$name] = $am->getBundle($name); } @@ -223,14 +223,14 @@ class AssetController extends Controller protected function loadTargets($targets, $bundles) { // build the dependency order of bundles - $registered = array(); + $registered = []; foreach ($bundles as $name => $bundle) { $this->registerBundle($bundles, $name, $registered); } $bundleOrders = array_combine(array_keys($registered), range(0, count($bundles) - 1)); // fill up the target which has empty 'depends'. - $referenced = array(); + $referenced = []; foreach ($targets as $name => $target) { if (empty($target['depends'])) { if (!isset($all)) { @@ -284,10 +284,10 @@ class AssetController extends Controller */ protected function buildTarget($target, $type, $bundles, $timestamp) { - $outputFile = strtr($target->$type, array( + $outputFile = strtr($target->$type, [ '{ts}' => $timestamp, - )); - $inputFiles = array(); + ]); + $inputFiles = []; foreach ($target->depends as $name) { if (isset($bundles[$name])) { @@ -303,7 +303,7 @@ class AssetController extends Controller } else { $this->compressCssFiles($inputFiles, $target->basePath . '/' . $outputFile); } - $target->$type = array($outputFile); + $target->$type = [$outputFile]; } /** @@ -316,7 +316,7 @@ class AssetController extends Controller { echo "Creating new bundle configuration...\n"; - $map = array(); + $map = []; foreach ($targets as $name => $target) { foreach ($target->depends as $bundle) { $map[$bundle] = $name; @@ -324,7 +324,7 @@ class AssetController extends Controller } foreach ($targets as $name => $target) { - $depends = array(); + $depends = []; foreach ($target->depends as $bn) { foreach ($bundles[$bn]->depends as $bundle) { $depends[$map[$bundle]] = true; @@ -336,15 +336,15 @@ class AssetController extends Controller // detect possible circular dependencies foreach ($targets as $name => $target) { - $registered = array(); + $registered = []; $this->registerBundle($targets, $name, $registered); } foreach ($map as $bundle => $target) { - $targets[$bundle] = Yii::createObject(array( + $targets[$bundle] = Yii::createObject([ 'class' => 'yii\\web\\AssetBundle', - 'depends' => array($target), - )); + 'depends' => [$target], + ]); } return $targets; } @@ -379,9 +379,9 @@ class AssetController extends Controller */ protected function saveTargets($targets, $bundleFile) { - $array = array(); + $array = []; foreach ($targets as $name => $target) { - foreach (array('js', 'css', 'depends', 'basePath', 'baseUrl') as $prop) { + foreach (['js', 'css', 'depends', 'basePath', 'baseUrl'] as $prop) { if (!empty($target->$prop)) { $array[$name][$prop] = $target->$prop; } @@ -419,10 +419,10 @@ EOD; if (is_string($this->jsCompressor)) { $tmpFile = $outputFile . '.tmp'; $this->combineJsFiles($inputFiles, $tmpFile); - echo shell_exec(strtr($this->jsCompressor, array( + echo shell_exec(strtr($this->jsCompressor, [ '{from}' => escapeshellarg($tmpFile), '{to}' => escapeshellarg($outputFile), - ))); + ])); @unlink($tmpFile); } else { call_user_func($this->jsCompressor, $this, $inputFiles, $outputFile); @@ -448,10 +448,10 @@ EOD; if (is_string($this->cssCompressor)) { $tmpFile = $outputFile . '.tmp'; $this->combineCssFiles($inputFiles, $tmpFile); - echo shell_exec(strtr($this->cssCompressor, array( + echo shell_exec(strtr($this->cssCompressor, [ '{from}' => escapeshellarg($tmpFile), '{to}' => escapeshellarg($outputFile), - ))); + ])); @unlink($tmpFile); } else { call_user_func($this->cssCompressor, $this, $inputFiles, $outputFile); @@ -509,7 +509,7 @@ EOD; */ protected function adjustCssUrl($cssContent, $inputFilePath, $outputFilePath) { - $sharedPathParts = array(); + $sharedPathParts = []; $inputFilePathParts = explode('/', $inputFilePath); $inputFilePathPartsCount = count($inputFilePathParts); $outputFilePathParts = explode('/', $outputFilePath); @@ -575,26 +575,26 @@ EOD; * Note that in the console environment, some path aliases like '@webroot' and '@web' may not exist. * Please define these missing path aliases. */ -return array( +return [ // The list of asset bundles to compress: - 'bundles' => array( + 'bundles' => [ // 'yii\web\YiiAsset', // 'yii\web\JqueryAsset', - ), + ], // Asset bundle for compression output: - 'targets' => array( - 'app\config\AllAsset' => array( + 'targets' => [ + 'app\config\AllAsset' => [ 'basePath' => 'path/to/web', 'baseUrl' => '', 'js' => 'js/all-{ts}.js', 'css' => 'css/all-{ts}.css', - ), - ), + ], + ], // Asset manager configuration: - 'assetManager' => array( + 'assetManager' => [ 'basePath' => __DIR__, 'baseUrl' => '', - ), + ], ); EOD; if (file_exists($configFile)) { diff --git a/framework/yii/console/controllers/CacheController.php b/framework/yii/console/controllers/CacheController.php index 95765fa..1822b73 100644 --- a/framework/yii/console/controllers/CacheController.php +++ b/framework/yii/console/controllers/CacheController.php @@ -25,7 +25,7 @@ class CacheController extends Controller */ public function actionIndex() { - $caches = array(); + $caches = []; $components = Yii::$app->getComponents(); foreach ($components as $name => $component) { if ($component instanceof Cache) { diff --git a/framework/yii/console/controllers/HelpController.php b/framework/yii/console/controllers/HelpController.php index 678d9f9..90e810f 100644 --- a/framework/yii/console/controllers/HelpController.php +++ b/framework/yii/console/controllers/HelpController.php @@ -57,9 +57,9 @@ class HelpController extends Controller if ($command !== null) { $result = Yii::$app->createController($command); if ($result === false) { - throw new Exception(Yii::t('yii', 'No help for unknown command "{command}".', array( + throw new Exception(Yii::t('yii', 'No help for unknown command "{command}".', [ 'command' => $this->ansiFormat($command, Console::FG_YELLOW), - ))); + ])); } list($controller, $actionID) = $result; @@ -114,7 +114,7 @@ class HelpController extends Controller { $prefix = $module instanceof Application ? '' : $module->getUniqueID() . '/'; - $commands = array(); + $commands = []; foreach (array_keys($module->controllerMap) as $id) { $commands[] = $prefix . $id; } @@ -242,9 +242,9 @@ class HelpController extends Controller { $action = $controller->createAction($actionID); if ($action === null) { - throw new Exception(Yii::t('yii', 'No help for unknown sub-command "{command}".', array( + throw new Exception(Yii::t('yii', 'No help for unknown sub-command "{command}".', [ 'command' => rtrim($controller->getUniqueId() . '/' . $actionID, '/'), - ))); + ])); } if ($action instanceof InlineAction) { $method = new \ReflectionMethod($controller, $action->actionMethod); @@ -266,7 +266,7 @@ class HelpController extends Controller } else { echo 'yii ' . $this->ansiFormat($action->getUniqueId(), Console::FG_YELLOW); } - list ($required, $optional) = $this->getArgHelps($method, isset($tags['param']) ? $tags['param'] : array()); + list ($required, $optional) = $this->getArgHelps($method, isset($tags['param']) ? $tags['param'] : []); foreach ($required as $arg => $description) { $this->stdout(' <' . $arg . '>', Console::FG_CYAN); } @@ -298,10 +298,10 @@ class HelpController extends Controller protected function getArgHelps($method, $tags) { if (is_string($tags)) { - $tags = array($tags); + $tags = [$tags]; } $params = $method->getParameters(); - $optional = $required = array(); + $optional = $required = []; foreach ($params as $i => $param) { $name = $param->getName(); $tag = isset($tags[$i]) ? $tags[$i] : ''; @@ -319,7 +319,7 @@ class HelpController extends Controller } } - return array($required, $optional); + return [$required, $optional]; } /** @@ -331,11 +331,11 @@ class HelpController extends Controller { $optionNames = $controller->globalOptions(); if (empty($optionNames)) { - return array(); + return []; } $class = new \ReflectionClass($controller); - $options = array(); + $options = []; foreach ($class->getProperties() as $property) { $name = $property->getName(); if (!in_array($name, $optionNames, true)) { @@ -371,7 +371,7 @@ class HelpController extends Controller */ protected function parseComment($comment) { - $tags = array(); + $tags = []; $comment = "@description \n" . strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($comment, '/'))), "\r", ''); $parts = preg_split('/^\s*@/m', $comment, -1, PREG_SPLIT_NO_EMPTY); foreach ($parts as $part) { @@ -382,7 +382,7 @@ class HelpController extends Controller } elseif (is_array($tags[$name])) { $tags[$name][] = trim($matches[2]); } else { - $tags[$name] = array($tags[$name], trim($matches[2])); + $tags[$name] = [$tags[$name], trim($matches[2])]; } } } diff --git a/framework/yii/console/controllers/MessageController.php b/framework/yii/console/controllers/MessageController.php index 306eb41..8a0f10b 100644 --- a/framework/yii/console/controllers/MessageController.php +++ b/framework/yii/console/controllers/MessageController.php @@ -74,12 +74,12 @@ class MessageController extends Controller throw new Exception("The configuration file does not exist: $configFile"); } - $config = array_merge(array( + $config = array_merge([ 'translator' => 'Yii::t', 'overwrite' => false, 'removeUnused' => false, 'sort' => false, - ), require($configFile)); + ], require($configFile)); if (!isset($config['sourcePath'], $config['messagePath'], $config['languages'])) { throw new Exception('The configuration file must specify "sourcePath", "messagePath" and "languages".'); @@ -96,7 +96,7 @@ class MessageController extends Controller $files = FileHelper::findFiles(realpath($config['sourcePath']), $config); - $messages = array(); + $messages = []; foreach ($files as $file) { $messages = array_merge_recursive($messages, $this->extractMessages($file, $config['translator'])); } @@ -127,9 +127,9 @@ class MessageController extends Controller { echo "Extracting messages from $fileName...\n"; $subject = file_get_contents($fileName); - $messages = array(); + $messages = []; if (!is_array($translator)) { - $translator = array($translator); + $translator = [$translator]; } foreach ($translator as $currentTranslator) { $n = preg_match_all( @@ -168,8 +168,8 @@ class MessageController extends Controller echo "nothing new...skipped.\n"; return; } - $merged = array(); - $untranslated = array(); + $merged = []; + $untranslated = []; foreach ($messages as $message) { if (array_key_exists($message, $translated) && strlen($translated[$message]) > 0) { $merged[$message] = $translated[$message]; @@ -179,7 +179,7 @@ class MessageController extends Controller } ksort($merged); sort($untranslated); - $todo = array(); + $todo = []; foreach ($untranslated as $message) { $todo[$message] = ''; } @@ -202,7 +202,7 @@ class MessageController extends Controller } echo "translation merged.\n"; } else { - $merged = array(); + $merged = []; foreach ($messages as $message) { $merged[$message] = ''; } diff --git a/framework/yii/console/controllers/MigrateController.php b/framework/yii/console/controllers/MigrateController.php index e9e3973..ac941a4 100644 --- a/framework/yii/console/controllers/MigrateController.php +++ b/framework/yii/console/controllers/MigrateController.php @@ -96,9 +96,9 @@ class MigrateController extends Controller */ public function globalOptions() { - return array_merge(parent::globalOptions(), array( + return array_merge(parent::globalOptions(), [ 'migrationPath', 'migrationTable', 'db', 'templateFile', 'interactive', 'color' - )); + ]); } /** @@ -360,10 +360,10 @@ class MigrateController extends Controller if ($this->confirm("Set migration history at $originalVersion?")) { $command = $this->db->createCommand(); for ($j = 0; $j <= $i; ++$j) { - $command->insert($this->migrationTable, array( + $command->insert($this->migrationTable, [ 'version' => $migrations[$j], 'apply_time' => time(), - ))->execute(); + ])->execute(); } echo "The migration history is set at $originalVersion.\nNo actual migration was performed.\n"; } @@ -381,9 +381,9 @@ class MigrateController extends Controller if ($this->confirm("Set migration history at $originalVersion?")) { $command = $this->db->createCommand(); for ($j = 0; $j < $i; ++$j) { - $command->delete($this->migrationTable, array( + $command->delete($this->migrationTable, [ 'version' => $migrations[$j], - ))->execute(); + ])->execute(); } echo "The migration history is set at $originalVersion.\nNo actual migration was performed.\n"; } @@ -490,9 +490,7 @@ class MigrateController extends Controller $file = $this->migrationPath . DIRECTORY_SEPARATOR . $name . '.php'; if ($this->confirm("Create new migration '$file'?")) { - $content = $this->renderFile(Yii::getAlias($this->templateFile), array( - 'className' => $name, - )); + $content = $this->renderFile(Yii::getAlias($this->templateFile), ['className' => $name]); file_put_contents($file, $content); echo "New migration created successfully.\n"; } @@ -513,10 +511,10 @@ class MigrateController extends Controller $start = microtime(true); $migration = $this->createMigration($class); if ($migration->up() !== false) { - $this->db->createCommand()->insert($this->migrationTable, array( + $this->db->createCommand()->insert($this->migrationTable, [ 'version' => $class, 'apply_time' => time(), - ))->execute(); + ])->execute(); $time = microtime(true) - $start; echo "*** applied $class (time: " . sprintf("%.3f", $time) . "s)\n\n"; return true; @@ -542,9 +540,9 @@ class MigrateController extends Controller $start = microtime(true); $migration = $this->createMigration($class); if ($migration->down() !== false) { - $this->db->createCommand()->delete($this->migrationTable, array( + $this->db->createCommand()->delete($this->migrationTable, [ 'version' => $class, - ))->execute(); + ])->execute(); $time = microtime(true) - $start; echo "*** reverted $class (time: " . sprintf("%.3f", $time) . "s)\n\n"; return true; @@ -564,9 +562,7 @@ class MigrateController extends Controller { $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php'; require_once($file); - return new $class(array( - 'db' => $this->db, - )); + return new $class(['db' => $this->db]); } /** @@ -580,7 +576,7 @@ class MigrateController extends Controller $this->createMigrationHistoryTable(); } $query = new Query; - $rows = $query->select(array('version', 'apply_time')) + $rows = $query->select(['version', 'apply_time']) ->from($this->migrationTable) ->orderBy('version DESC') ->limit($limit) @@ -597,14 +593,14 @@ class MigrateController extends Controller protected function createMigrationHistoryTable() { echo 'Creating migration history table "' . $this->migrationTable . '"...'; - $this->db->createCommand()->createTable($this->migrationTable, array( + $this->db->createCommand()->createTable($this->migrationTable, [ 'version' => 'varchar(255) NOT NULL PRIMARY KEY', 'apply_time' => 'integer', - ))->execute(); - $this->db->createCommand()->insert($this->migrationTable, array( + ])->execute(); + $this->db->createCommand()->insert($this->migrationTable, [ 'version' => self::BASE_MIGRATION, 'apply_time' => time(), - ))->execute(); + ])->execute(); echo "done.\n"; } @@ -614,12 +610,12 @@ class MigrateController extends Controller */ protected function getNewMigrations() { - $applied = array(); + $applied = []; foreach ($this->getMigrationHistory(-1) as $version => $time) { $applied[substr($version, 1, 13)] = true; } - $migrations = array(); + $migrations = []; $handle = opendir($this->migrationPath); while (($file = readdir($handle)) !== false) { if ($file === '.' || $file === '..') { diff --git a/framework/yii/data/ActiveDataProvider.php b/framework/yii/data/ActiveDataProvider.php index bd822f9..e95e4b8 100644 --- a/framework/yii/data/ActiveDataProvider.php +++ b/framework/yii/data/ActiveDataProvider.php @@ -22,12 +22,12 @@ use yii\db\Connection; * The following is an example of using ActiveDataProvider to provide ActiveRecord instances: * * ~~~ - * $provider = new ActiveDataProvider(array( + * $provider = new ActiveDataProvider([ * 'query' => Post::find(), - * 'pagination' => array( + * 'pagination' => [ * 'pageSize' => 20, - * ), - * )); + * ], + * ]); * * // get the posts in the current page * $posts = $provider->getModels(); @@ -37,12 +37,12 @@ use yii\db\Connection; * * ~~~ * $query = new Query; - * $provider = new ActiveDataProvider(array( + * $provider = new ActiveDataProvider([ * 'query' => $query->from('tbl_post'), - * 'pagination' => array( + * 'pagination' => [ * 'pageSize' => 20, - * ), - * )); + * ], + * ]); * * // get the posts in the current page * $posts = $provider->getModels(); @@ -115,7 +115,7 @@ class ActiveDataProvider extends BaseDataProvider */ protected function prepareKeys($models) { - $keys = array(); + $keys = []; if ($this->key !== null) { foreach ($models as $model) { if (is_string($this->key)) { @@ -136,7 +136,7 @@ class ActiveDataProvider extends BaseDataProvider } } else { foreach ($models as $model) { - $kk = array(); + $kk = []; foreach ($pks as $pk) { $kk[] = $model[$pk]; } @@ -171,11 +171,11 @@ class ActiveDataProvider extends BaseDataProvider /** @var Model $model */ $model = new $this->query->modelClass; foreach($model->attributes() as $attribute) { - $sort->attributes[$attribute] = array( - 'asc' => array($attribute => Sort::ASC), - 'desc' => array($attribute => Sort::DESC), + $sort->attributes[$attribute] = [ + 'asc' => [$attribute => Sort::ASC], + 'desc' => [$attribute => Sort::DESC], 'label' => $model->getAttributeLabel($attribute), - ); + ]; } } } diff --git a/framework/yii/data/ArrayDataProvider.php b/framework/yii/data/ArrayDataProvider.php index 77f31cd..e3f1b34 100644 --- a/framework/yii/data/ArrayDataProvider.php +++ b/framework/yii/data/ArrayDataProvider.php @@ -29,17 +29,15 @@ use yii\helpers\ArrayHelper; * * ~~~ * $query = new Query; - * $provider = new ArrayDataProvider(array( + * $provider = new ArrayDataProvider([ * 'allModels' => $query->from('tbl_post')->all(), - * 'sort' => array( - * 'attributes' => array( - * 'id', 'username', 'email', - * ), + * 'sort' => [ + * 'attributes' => ['id', 'username', 'email'], * ), - * 'pagination' => array( + * 'pagination' => [ * 'pageSize' => 10, - * ), - * )); + * ], + * ]); * // get the posts in the current page * $posts = $provider->getModels(); * ~~~ @@ -73,7 +71,7 @@ class ArrayDataProvider extends BaseDataProvider protected function prepareModels() { if (($models = $this->allModels) === null) { - return array(); + return []; } if (($sort = $this->getSort()) !== false) { @@ -94,7 +92,7 @@ class ArrayDataProvider extends BaseDataProvider protected function prepareKeys($models) { if ($this->key !== null) { - $keys = array(); + $keys = []; foreach ($models as $model) { if (is_string($this->key)) { $keys[] = $model[$this->key]; diff --git a/framework/yii/data/BaseDataProvider.php b/framework/yii/data/BaseDataProvider.php index 3b0669d..db1e057 100644 --- a/framework/yii/data/BaseDataProvider.php +++ b/framework/yii/data/BaseDataProvider.php @@ -188,9 +188,7 @@ abstract class BaseDataProvider extends Component implements DataProviderInterfa public function setPagination($value) { if (is_array($value)) { - $config = array( - 'class' => Pagination::className(), - ); + $config = ['class' => Pagination::className()]; if ($this->id !== null) { $config['pageVar'] = $this->id . '-page'; } @@ -208,7 +206,7 @@ abstract class BaseDataProvider extends Component implements DataProviderInterfa public function getSort() { if ($this->_sort === null) { - $this->setSort(array()); + $this->setSort([]); } return $this->_sort; } @@ -228,9 +226,7 @@ abstract class BaseDataProvider extends Component implements DataProviderInterfa public function setSort($value) { if (is_array($value)) { - $config = array( - 'class' => Sort::className(), - ); + $config = ['class' => Sort::className()]; if ($this->id !== null) { $config['sortVar'] = $this->id . '-sort'; } diff --git a/framework/yii/data/Pagination.php b/framework/yii/data/Pagination.php index 04af828..5fee61c 100644 --- a/framework/yii/data/Pagination.php +++ b/framework/yii/data/Pagination.php @@ -26,17 +26,17 @@ use yii\base\Object; * ~~~ * function actionIndex() * { - * $query = Article::find()->where(array('status' => 1)); + * $query = Article::find()->where(['status' => 1]); * $countQuery = clone $query; - * $pages = new Pagination(array('totalCount' => $countQuery->count())); + * $pages = new Pagination(['totalCount' => $countQuery->count()]); * $models = $query->offset($pages->offset) * ->limit($pages->limit) * ->all(); * - * return $this->render('index', array( + * return $this->render('index', [ * 'models' => $models, * 'pages' => $pages, - * )); + * ]); * } * ~~~ * @@ -48,9 +48,9 @@ use yii\base\Object; * } * * // display pagination - * echo LinkPager::widget(array( + * echo LinkPager::widget([ * 'pagination' => $pages, - * )); + * ]); * ~~~ * * @property integer $limit The limit of the data. This may be used to set the LIMIT value for a SQL statement diff --git a/framework/yii/data/Sort.php b/framework/yii/data/Sort.php index 5eb031e..156b447 100644 --- a/framework/yii/data/Sort.php +++ b/framework/yii/data/Sort.php @@ -25,27 +25,27 @@ use yii\helpers\Inflector; * ~~~ * function actionIndex() * { - * $sort = new Sort(array( - * 'attributes' => array( + * $sort = new Sort([ + * 'attributes' => [ * 'age', - * 'name' => array( - * 'asc' => array('first_name' => Sort::ASC, 'last_name' => Sort::ASC), - * 'desc' => array('first_name' => Sort::DESC, 'last_name' => Sort::DESC), + * 'name' => [ + * 'asc' => ['first_name' => Sort::ASC, 'last_name' => Sort::ASC], + * 'desc' => ['first_name' => Sort::DESC, 'last_name' => Sort::DESC], * 'default' => Sort::DESC, * 'label' => 'Name', - * ), - * ), - * )); + * ], + * ], + * ]); * * $models = Article::find() - * ->where(array('status' => 1)) + * ->where(['status' => 1]) * ->orderBy($sort->orders) * ->all(); * - * return $this->render('index', array( + * return $this->render('index', [ * 'models' => $models, * 'sort' => $sort, - * )); + * ]); * } * ~~~ * @@ -96,27 +96,27 @@ class Sort extends Object * described using the following example: * * ~~~ - * array( + * [ * 'age', - * 'name' => array( - * 'asc' => array('first_name' => Sort::ASC, 'last_name' => Sort::ASC), - * 'desc' => array('first_name' => Sort::DESC, 'last_name' => Sort::DESC), + * 'name' => [ + * 'asc' => ['first_name' => Sort::ASC, 'last_name' => Sort::ASC], + * 'desc' => ['first_name' => Sort::DESC, 'last_name' => Sort::DESC], * 'default' => Sort::DESC, * 'label' => 'Name', - * ), - * ) + * ], + * ] * ~~~ * * In the above, two attributes are declared: "age" and "user". The "age" attribute is * a simple attribute which is equivalent to the following: * * ~~~ - * 'age' => array( - * 'asc' => array('age' => Sort::ASC), - * 'desc' => array('age' => Sort::DESC), + * 'age' => [ + * 'asc' => ['age' => Sort::ASC], + * 'desc' => ['age' => Sort::DESC], * 'default' => Sort::ASC, * 'label' => Inflector::camel2words('age'), - * ) + * ] * ~~~ * * The "user" attribute is a composite attribute: @@ -135,7 +135,7 @@ class Sort extends Object * Note that if the Sort object is already created, you can only use the full format * to configure every attribute. Each attribute must include these elements: asc and desc. */ - public $attributes = array(); + public $attributes = []; /** * @var string the name of the parameter that specifies which attributes to be sorted * in which direction. Defaults to 'sort'. @@ -152,10 +152,10 @@ class Sort extends Object * The array keys are attribute names and the array values are the corresponding sort directions. For example, * * ~~~ - * array( + * [ * 'name' => Sort::ASC, * 'create_time' => Sort::DESC, - * ) + * ] * ~~~ * * @see attributeOrders @@ -170,9 +170,9 @@ class Sort extends Object * @var array separators used in the generated URL. This must be an array consisting of * two elements. The first element specifies the character separating different * attributes, while the second element specifies the character separating attribute name - * and the corresponding sort direction. Defaults to `array('.', '-')`. + * and the corresponding sort direction. Defaults to `['.', '-']`. */ - public $separators = array('.', '-'); + public $separators = ['.', '-']; /** * @var array parameters (name => value) that should be used to obtain the current sort directions * and to create new sort URLs. If not set, $_GET will be used instead. @@ -195,18 +195,18 @@ class Sort extends Object */ public function init() { - $attributes = array(); + $attributes = []; foreach ($this->attributes as $name => $attribute) { if (!is_array($attribute)) { - $attributes[$attribute] = array( - 'asc' => array($attribute => self::ASC), - 'desc' => array($attribute => self::DESC), - ); + $attributes[$attribute] = [ + 'asc' => [$attribute => self::ASC], + 'desc' => [$attribute => self::DESC], + ]; } elseif (!isset($attribute['asc'], $attribute['desc'])) { - $attributes[$name] = array_merge(array( - 'asc' => array($name => self::ASC), - 'desc' => array($name => self::DESC), - ), $attribute); + $attributes[$name] = array_merge([ + 'asc' => [$name => self::ASC], + 'desc' => [$name => self::DESC], + ], $attribute); } else { $attributes[$name] = $attribute; } @@ -223,7 +223,7 @@ class Sort extends Object public function getOrders($recalculate = false) { $attributeOrders = $this->getAttributeOrders($recalculate); - $orders = array(); + $orders = []; foreach ($attributeOrders as $attribute => $direction) { $definition = $this->attributes[$attribute]; $columns = $definition[$direction === self::ASC ? 'asc' : 'desc']; @@ -249,7 +249,7 @@ class Sort extends Object public function getAttributeOrders($recalculate = false) { if ($this->_attributeOrders === null || $recalculate) { - $this->_attributeOrders = array(); + $this->_attributeOrders = []; $params = $this->params === null ? $_GET : $this->params; if (isset($params[$this->sortVar]) && is_scalar($params[$this->sortVar])) { $attributes = explode($this->separators[0], $params[$this->sortVar]); @@ -302,7 +302,7 @@ class Sort extends Object * @return string the generated hyperlink * @throws InvalidConfigException if the attribute is unknown */ - public function link($attribute, $options = array()) + public function link($attribute, $options = []) { if (($direction = $this->getAttributeOrder($attribute)) !== null) { $class = $direction ? 'desc' : 'asc'; @@ -372,12 +372,12 @@ class Sort extends Object } if ($this->enableMultiSort) { - $directions = array_merge(array($attribute => $descending), $directions); + $directions = array_merge([$attribute => $descending], $directions); } else { - $directions = array($attribute => $descending); + $directions = [$attribute => $descending]; } - $sorts = array(); + $sorts = []; foreach ($directions as $attribute => $descending) { $sorts[] = $descending ? $attribute . $this->separators[1] . $this->descTag : $attribute; } diff --git a/framework/yii/db/ActiveQuery.php b/framework/yii/db/ActiveQuery.php index 375e91f..b7fcdcd 100644 --- a/framework/yii/db/ActiveQuery.php +++ b/framework/yii/db/ActiveQuery.php @@ -78,7 +78,7 @@ class ActiveQuery extends Query { if (method_exists($this->modelClass, $name)) { array_unshift($params, $this); - call_user_func_array(array($this->modelClass, $name), $params); + call_user_func_array([$this->modelClass, $name], $params); return $this; } else { return parent::__call($name, $params); @@ -102,7 +102,7 @@ class ActiveQuery extends Query } return $models; } else { - return array(); + return []; } } @@ -127,7 +127,7 @@ class ActiveQuery extends Query $model = $class::create($row); } if (!empty($this->with)) { - $models = array($model); + $models = [$model]; $this->populateRelations($models, $this->with); $model = $models[0]; } @@ -156,9 +156,9 @@ class ActiveQuery extends Query if ($this->from === null) { $tableName = $modelClass::tableName(); if ($this->select === null && !empty($this->join)) { - $this->select = array("$tableName.*"); + $this->select = ["$tableName.*"]; } - $this->from = array($tableName); + $this->from = [$tableName]; } list ($this->sql, $params) = $db->getQueryBuilder()->build($this); } @@ -188,12 +188,12 @@ class ActiveQuery extends Query * // find customers together with their orders and country * Customer::find()->with('orders', 'country')->all(); * // find customers together with their country and orders of status 1 - * Customer::find()->with(array( + * Customer::find()->with([ * 'orders' => function($query) { * $query->andWhere('status = 1'); * }, * 'country', - * ))->all(); + * ])->all(); * ~~~ * * @return static the query object itself @@ -232,7 +232,7 @@ class ActiveQuery extends Query private function createModels($rows) { - $models = array(); + $models = []; if ($this->asArray) { if ($this->indexBy === null) { return $rows; @@ -287,7 +287,7 @@ class ActiveQuery extends Query */ private function normalizeRelations($model, $with) { - $relations = array(); + $relations = []; foreach ($with as $name => $callback) { if (is_integer($name)) { $name = $callback; diff --git a/framework/yii/db/ActiveRecord.php b/framework/yii/db/ActiveRecord.php index e1c4b4f..3f158cf 100644 --- a/framework/yii/db/ActiveRecord.php +++ b/framework/yii/db/ActiveRecord.php @@ -95,7 +95,7 @@ class ActiveRecord extends Model /** * @var array attribute values indexed by attribute names */ - private $_attributes = array(); + private $_attributes = []; /** * @var array old attribute values indexed by attribute names. */ @@ -144,7 +144,7 @@ class ActiveRecord extends Model // query by primary key $primaryKey = static::primaryKey(); if (isset($primaryKey[0])) { - return $query->where(array($primaryKey[0] => $q))->one(); + return $query->where([$primaryKey[0] => $q])->one(); } else { throw new InvalidConfigException(get_called_class() . ' must have a primary key.'); } @@ -170,7 +170,7 @@ class ActiveRecord extends Model * @param array $params parameters to be bound to the SQL statement during execution. * @return ActiveQuery the newly created [[ActiveQuery]] instance */ - public static function findBySql($sql, $params = array()) + public static function findBySql($sql, $params = []) { $query = static::createQuery(); $query->sql = $sql; @@ -182,7 +182,7 @@ class ActiveRecord extends Model * For example, to change the status to be 1 for all customers whose status is 2: * * ~~~ - * Customer::updateAll(array('status' => 1), 'status = 2'); + * Customer::updateAll(['status' => 1], 'status = 2'); * ~~~ * * @param array $attributes attribute values (name-value pairs) to be saved into the table @@ -191,7 +191,7 @@ class ActiveRecord extends Model * @param array $params the parameters (name => value) to be bound to the query. * @return integer the number of rows updated */ - public static function updateAll($attributes, $condition = '', $params = array()) + public static function updateAll($attributes, $condition = '', $params = []) { $command = static::getDb()->createCommand(); $command->update(static::tableName(), $attributes, $condition, $params); @@ -203,7 +203,7 @@ class ActiveRecord extends Model * For example, to increment all customers' age by 1, * * ~~~ - * Customer::updateAllCounters(array('age' => 1)); + * Customer::updateAllCounters(['age' => 1]); * ~~~ * * @param array $counters the counters to be updated (attribute name => increment value). @@ -214,11 +214,11 @@ class ActiveRecord extends Model * Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method. * @return integer the number of rows updated */ - public static function updateAllCounters($counters, $condition = '', $params = array()) + public static function updateAllCounters($counters, $condition = '', $params = []) { $n = 0; foreach ($counters as $name => $value) { - $counters[$name] = new Expression("[[$name]]+:bp{$n}", array(":bp{$n}" => $value)); + $counters[$name] = new Expression("[[$name]]+:bp{$n}", [":bp{$n}" => $value]); $n++; } $command = static::getDb()->createCommand(); @@ -241,7 +241,7 @@ class ActiveRecord extends Model * @param array $params the parameters (name => value) to be bound to the query. * @return integer the number of rows deleted */ - public static function deleteAll($condition = '', $params = array()) + public static function deleteAll($condition = '', $params = []) { $command = static::getDb()->createCommand(); $command->delete(static::tableName(), $condition, $params); @@ -257,9 +257,7 @@ class ActiveRecord extends Model */ public static function createQuery() { - return new ActiveQuery(array( - 'modelClass' => get_called_class(), - )); + return new ActiveQuery(['modelClass' => get_called_class()]); } /** @@ -346,13 +344,13 @@ class ActiveRecord extends Model * that need to be transactional. For example, * * ~~~ - * return array( + * return [ * 'admin' => self::OP_INSERT, * 'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE, * // the above is equivalent to the following: * // 'api' => self::OP_ALL, * - * ); + * ]; * ~~~ * * The above declaration specifies that in the "admin" scenario, the insert operation ([[insert()]]) @@ -364,7 +362,7 @@ class ActiveRecord extends Model */ public function transactions() { - return array(); + return []; } /** @@ -458,7 +456,7 @@ class ActiveRecord extends Model * ~~~ * public function getCountry() * { - * return $this->hasOne('Country', array('id' => 'country_id')); + * return $this->hasOne('Country', ['id' => 'country_id']); * } * ~~~ * @@ -476,12 +474,12 @@ class ActiveRecord extends Model */ public function hasOne($class, $link) { - return new ActiveRelation(array( + return new ActiveRelation([ 'modelClass' => $this->getNamespacedClass($class), 'primaryModel' => $this, 'link' => $link, 'multiple' => false, - )); + ]); } /** @@ -498,7 +496,7 @@ class ActiveRecord extends Model * ~~~ * public function getOrders() * { - * return $this->hasMany('Order', array('customer_id' => 'id')); + * return $this->hasMany('Order', ['customer_id' => 'id']); * } * ~~~ * @@ -514,12 +512,12 @@ class ActiveRecord extends Model */ public function hasMany($class, $link) { - return new ActiveRelation(array( + return new ActiveRelation([ 'modelClass' => $this->getNamespacedClass($class), 'primaryModel' => $this, 'link' => $link, 'multiple' => true, - )); + ]); } /** @@ -588,7 +586,7 @@ class ActiveRecord extends Model */ public function getOldAttributes() { - return $this->_oldAttributes === null ? array() : $this->_oldAttributes; + return $this->_oldAttributes === null ? [] : $this->_oldAttributes; } /** @@ -657,7 +655,7 @@ class ActiveRecord extends Model $names = $this->attributes(); } $names = array_flip($names); - $attributes = array(); + $attributes = []; if ($this->_oldAttributes === null) { foreach ($this->_attributes as $name => $value) { if (isset($names[$name])) { @@ -924,7 +922,7 @@ class ActiveRecord extends Model * * ~~~ * $post = Post::find($id); - * $post->updateCounters(array('view_count' => 1)); + * $post->updateCounters(['view_count' => 1]); * ~~~ * * @param array $counters the counters to be updated (attribute name => increment value) @@ -1176,7 +1174,7 @@ class ActiveRecord extends Model if (count($keys) === 1 && !$asArray) { return isset($this->_attributes[$keys[0]]) ? $this->_attributes[$keys[0]] : null; } else { - $values = array(); + $values = []; foreach ($keys as $name) { $values[$name] = isset($this->_attributes[$name]) ? $this->_attributes[$name] : null; } @@ -1202,7 +1200,7 @@ class ActiveRecord extends Model if (count($keys) === 1 && !$asArray) { return isset($this->_oldAttributes[$keys[0]]) ? $this->_oldAttributes[$keys[0]] : null; } else { - $values = array(); + $values = []; foreach ($keys as $name) { $values[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null; } @@ -1299,7 +1297,7 @@ class ActiveRecord extends Model * (i.e., a relation set with `[[ActiveRelation::via()]]` or `[[ActiveRelation::viaTable()]]`.) * @throws InvalidCallException if the method is unable to link two models. */ - public function link($name, $model, $extraColumns = array()) + public function link($name, $model, $extraColumns = []) { $relation = $this->getRelation($name); @@ -1319,7 +1317,7 @@ class ActiveRecord extends Model $viaRelation = $relation->via; $viaTable = reset($relation->via->from); } - $columns = array(); + $columns = []; foreach ($viaRelation->link as $a => $b) { $columns[$a] = $this->$b; } @@ -1393,7 +1391,7 @@ class ActiveRecord extends Model $viaRelation = $relation->via; $viaTable = reset($relation->via->from); } - $columns = array(); + $columns = []; foreach ($viaRelation->link as $a => $b) { $columns[$a] = $this->$b; } @@ -1404,7 +1402,7 @@ class ActiveRecord extends Model if ($delete) { $command->delete($viaTable, $columns)->execute(); } else { - $nulls = array(); + $nulls = []; foreach (array_keys($columns) as $a) { $nulls[$a] = null; } diff --git a/framework/yii/db/ActiveRelation.php b/framework/yii/db/ActiveRelation.php index c1c8b2d..1a7541a 100644 --- a/framework/yii/db/ActiveRelation.php +++ b/framework/yii/db/ActiveRelation.php @@ -71,7 +71,7 @@ class ActiveRelation extends ActiveQuery public function via($relationName, $callable = null) { $relation = $this->primaryModel->getRelation($relationName); - $this->via = array($relationName, $relation); + $this->via = [$relationName, $relation]; if ($callable !== null) { call_user_func($callable, $relation); } @@ -90,13 +90,13 @@ class ActiveRelation extends ActiveQuery */ public function viaTable($tableName, $link, $callable = null) { - $relation = new ActiveRelation(array( + $relation = new ActiveRelation([ 'modelClass' => get_class($this->primaryModel), - 'from' => array($tableName), + 'from' => [$tableName], 'link' => $link, 'multiple' => true, 'asArray' => true, - )); + ]); $this->via = $relation; if ($callable !== null) { call_user_func($callable, $relation); @@ -116,7 +116,7 @@ class ActiveRelation extends ActiveQuery // lazy loading if ($this->via instanceof self) { // via pivot table - $viaModels = $this->via->findPivotRows(array($this->primaryModel)); + $viaModels = $this->via->findPivotRows([$this->primaryModel]); $this->filterByModels($viaModels); } elseif (is_array($this->via)) { // via relation @@ -128,11 +128,11 @@ class ActiveRelation extends ActiveQuery } else { $model = $viaQuery->one(); $this->primaryModel->populateRelation($viaName, $model); - $viaModels = $model === null ? array() : array($model); + $viaModels = $model === null ? [] : [$model]; } $this->filterByModels($viaModels); } else { - $this->filterByModels(array($this->primaryModel)); + $this->filterByModels([$this->primaryModel]); } } return parent::createCommand($db); @@ -178,7 +178,7 @@ class ActiveRelation extends ActiveQuery $primaryModels[$i][$name] = $model; } } - return array($model); + return [$model]; } else { $models = $this->all(); if (isset($viaModels, $viaQuery)) { @@ -190,7 +190,7 @@ class ActiveRelation extends ActiveQuery $link = array_values(isset($viaQuery) ? $viaQuery->link : $this->link); foreach ($primaryModels as $i => $primaryModel) { $key = $this->getModelKey($primaryModel, $link); - $value = isset($buckets[$key]) ? $buckets[$key] : ($this->multiple ? array() : null); + $value = isset($buckets[$key]) ? $buckets[$key] : ($this->multiple ? [] : null); if ($primaryModel instanceof ActiveRecord) { $primaryModel->populateRelation($name, $value); } else { @@ -210,7 +210,7 @@ class ActiveRelation extends ActiveQuery */ private function buildBuckets($models, $link, $viaModels = null, $viaLink = null) { - $buckets = array(); + $buckets = []; $linkKeys = array_keys($link); foreach ($models as $i => $model) { $key = $this->getModelKey($model, $linkKeys); @@ -222,7 +222,7 @@ class ActiveRelation extends ActiveQuery } if ($viaModels !== null) { - $viaBuckets = array(); + $viaBuckets = []; $viaLinkKeys = array_keys($viaLink); $linkValues = array_values($link); foreach ($viaModels as $viaModel) { @@ -257,7 +257,7 @@ class ActiveRelation extends ActiveQuery private function getModelKey($model, $attributes) { if (count($attributes) > 1) { - $key = array(); + $key = []; foreach ($attributes as $attribute) { $key[] = $model[$attribute]; } @@ -274,7 +274,7 @@ class ActiveRelation extends ActiveQuery private function filterByModels($models) { $attributes = array_keys($this->link); - $values = array(); + $values = []; if (count($attributes) === 1) { // single key $attribute = reset($this->link); @@ -286,14 +286,14 @@ class ActiveRelation extends ActiveQuery } else { // composite keys foreach ($models as $model) { - $v = array(); + $v = []; foreach ($this->link as $attribute => $link) { $v[$attribute] = $model[$link]; } $values[] = $v; } } - $this->andWhere(array('in', $attributes, array_unique($values, SORT_REGULAR))); + $this->andWhere(['in', $attributes, array_unique($values, SORT_REGULAR)]); } /** @@ -303,7 +303,7 @@ class ActiveRelation extends ActiveQuery private function findPivotRows($primaryModels) { if (empty($primaryModels)) { - return array(); + return []; } $this->filterByModels($primaryModels); /** @var $primaryModel ActiveRecord */ diff --git a/framework/yii/db/Command.php b/framework/yii/db/Command.php index bd18e1f..e1f15b8 100644 --- a/framework/yii/db/Command.php +++ b/framework/yii/db/Command.php @@ -36,10 +36,10 @@ use yii\caching\Cache; * [[update()]], etc. For example, * * ~~~ - * $connection->createCommand()->insert('tbl_user', array( + * $connection->createCommand()->insert('tbl_user', [ * 'name' => 'Sam', * 'age' => 30, - * ))->execute(); + * ])->execute(); * ~~~ * * To build SELECT SQL statements, please use [[QueryBuilder]] instead. @@ -73,7 +73,7 @@ class Command extends \yii\base\Component /** * @var array the parameter log information (name => value) */ - private $_params = array(); + private $_params = []; /** * Returns the SQL statement for this command. @@ -95,7 +95,7 @@ class Command extends \yii\base\Component if ($sql !== $this->_sql) { $this->cancel(); $this->_sql = $this->db->quoteSql($sql); - $this->_params = array(); + $this->_params = []; } return $this; } @@ -111,7 +111,7 @@ class Command extends \yii\base\Component if (empty($this->_params)) { return $this->_sql; } else { - $params = array(); + $params = []; foreach ($this->_params as $name => $value) { if (is_string($value)) { $params[$name] = $this->db->quoteValue($value); @@ -222,9 +222,9 @@ class Command extends \yii\base\Component * Note that the SQL data type of each value is determined by its PHP type. * @param array $values the values to be bound. This must be given in terms of an associative * array with array keys being the parameter names, and array values the corresponding parameter values, - * e.g. `array(':name' => 'John', ':age' => 25)`. By default, the PDO type of each value is determined - * by its PHP type. You may explicitly specify the PDO type by using an array: `array(value, type)`, - * e.g. `array(':name' => 'John', ':profile' => array($profile, \PDO::PARAM_LOB))`. + * e.g. `[':name' => 'John', ':age' => 25]`. By default, the PDO type of each value is determined + * by its PHP type. You may explicitly specify the PDO type by using an array: `[value, type]`, + * e.g. `[':name' => 'John', ':profile' => [$profile, \PDO::PARAM_LOB]]`. * @return static the current command being executed */ public function bindValues($values) @@ -370,12 +370,12 @@ class Command extends \yii\base\Component } if (isset($cache) && $cache instanceof Cache) { - $cacheKey = array( + $cacheKey = [ __CLASS__, $db->dsn, $db->username, $rawSql, - ); + ]; if (($result = $cache->get($cacheKey)) !== false) { Yii::trace('Query result served from cache', __METHOD__); return $result; @@ -395,7 +395,7 @@ class Command extends \yii\base\Component if ($fetchMode === null) { $fetchMode = $this->fetchMode; } - $result = call_user_func_array(array($this->pdoStatement, $method), (array)$fetchMode); + $result = call_user_func_array([$this->pdoStatement, $method], (array)$fetchMode); $this->pdoStatement->closeCursor(); } @@ -420,10 +420,10 @@ class Command extends \yii\base\Component * For example, * * ~~~ - * $connection->createCommand()->insert('tbl_user', array( + * $connection->createCommand()->insert('tbl_user', [ * 'name' => 'Sam', * 'age' => 30, - * ))->execute(); + * ])->execute(); * ~~~ * * The method will properly escape the column names, and bind the values to be inserted. @@ -436,7 +436,7 @@ class Command extends \yii\base\Component */ public function insert($table, $columns) { - $params = array(); + $params = []; $sql = $this->db->getQueryBuilder()->insert($table, $columns, $params); return $this->setSql($sql)->bindValues($params); } @@ -446,11 +446,11 @@ class Command extends \yii\base\Component * For example, * * ~~~ - * $connection->createCommand()->batchInsert('tbl_user', array('name', 'age'), array( - * array('Tom', 30), - * array('Jane', 20), - * array('Linda', 25), - * ))->execute(); + * $connection->createCommand()->batchInsert('tbl_user', ['name', 'age'], [ + * ['Tom', 30], + * ['Jane', 20], + * ['Linda', 25], + * ])->execute(); * ~~~ * * Note that the values in each row must match the corresponding column names. @@ -471,9 +471,7 @@ class Command extends \yii\base\Component * For example, * * ~~~ - * $connection->createCommand()->update('tbl_user', array( - * 'status' => 1, - * ), 'age > 30')->execute(); + * $connection->createCommand()->update('tbl_user', ['status' => 1], 'age > 30')->execute(); * ~~~ * * The method will properly escape the column names and bind the values to be updated. @@ -487,7 +485,7 @@ class Command extends \yii\base\Component * @param array $params the parameters to be bound to the command * @return Command the command object itself */ - public function update($table, $columns, $condition = '', $params = array()) + public function update($table, $columns, $condition = '', $params = []) { $sql = $this->db->getQueryBuilder()->update($table, $columns, $condition, $params); return $this->setSql($sql)->bindValues($params); @@ -511,7 +509,7 @@ class Command extends \yii\base\Component * @param array $params the parameters to be bound to the command * @return Command the command object itself */ - public function delete($table, $condition = '', $params = array()) + public function delete($table, $condition = '', $params = []) { $sql = $this->db->getQueryBuilder()->delete($table, $condition, $params); return $this->setSql($sql)->bindValues($params); diff --git a/framework/yii/db/Connection.php b/framework/yii/db/Connection.php index b080836..ef5be87 100644 --- a/framework/yii/db/Connection.php +++ b/framework/yii/db/Connection.php @@ -28,11 +28,11 @@ use yii\caching\Cache; * the DB connection: * * ~~~ - * $connection = new \yii\db\Connection(array( + * $connection = new \yii\db\Connection([ * 'dsn' => $dsn, * 'username' => $username, * 'password' => $password, - * )); + * ]); * $connection->open(); * ~~~ * @@ -76,17 +76,17 @@ use yii\caching\Cache; * configuration like the following: * * ~~~ - * array( - * 'components' => array( - * 'db' => array( + * [ + * 'components' => [ + * 'db' => [ * 'class' => '\yii\db\Connection', * 'dsn' => 'mysql:host=127.0.0.1;dbname=demo', * 'username' => 'root', * 'password' => '', * 'charset' => 'utf8', - * ), - * ), - * ) + * ], + * ], + * ] * ~~~ * * @property string $driverName Name of the DB driver. This property is read-only. @@ -159,7 +159,7 @@ class Connection extends Component * The table names may contain schema prefix, if any. Do not quote the table names. * @see enableSchemaCache */ - public $schemaCacheExclude = array(); + public $schemaCacheExclude = []; /** * @var Cache|string the cache object or the ID of the cache application component that * is used to cache the table metadata. @@ -233,7 +233,7 @@ class Connection extends Component * You normally do not need to set this property unless you want to use your own * [[Schema]] class to support DBMS that is not supported by Yii. */ - public $schemaMap = array( + public $schemaMap = [ 'pgsql' => 'yii\db\pgsql\Schema', // PostgreSQL 'mysqli' => 'yii\db\mysql\Schema', // MySQL 'mysql' => 'yii\db\mysql\Schema', // MySQL @@ -244,7 +244,7 @@ class Connection extends Component 'mssql' => 'yii\db\mssql\Schema', // older MSSQL driver on MS Windows hosts 'dblib' => 'yii\db\mssql\Schema', // dblib drivers on GNU/Linux (and maybe other OSes) hosts 'cubrid' => 'yii\db\cubrid\Schema', // CUBRID - ); + ]; /** * @var Transaction the currently active transaction */ @@ -361,7 +361,7 @@ class Connection extends Component if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) { $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare); } - if ($this->charset !== null && in_array($this->getDriverName(), array('pgsql', 'mysql', 'mysqli', 'cubrid'))) { + if ($this->charset !== null && in_array($this->getDriverName(), ['pgsql', 'mysql', 'mysqli', 'cubrid'])) { $this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset)); } $this->trigger(self::EVENT_AFTER_OPEN); @@ -373,13 +373,13 @@ class Connection extends Component * @param array $params the parameters to be bound to the SQL statement * @return Command the DB command */ - public function createCommand($sql = null, $params = array()) + public function createCommand($sql = null, $params = []) { $this->open(); - $command = new Command(array( + $command = new Command([ 'db' => $this, 'sql' => $sql, - )); + ]); return $command->bindValues($params); } @@ -399,9 +399,7 @@ class Connection extends Component public function beginTransaction() { $this->open(); - $this->_transaction = new Transaction(array( - 'db' => $this, - )); + $this->_transaction = new Transaction(['db' => $this]); $this->_transaction->begin(); return $this->_transaction; } diff --git a/framework/yii/db/DataReader.php b/framework/yii/db/DataReader.php index f2990c1..213db52 100644 --- a/framework/yii/db/DataReader.php +++ b/framework/yii/db/DataReader.php @@ -62,7 +62,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable * @param Command $command the command generating the query result * @param array $config name-value pairs that will be used to initialize the object properties */ - public function __construct(Command $command, $config = array()) + public function __construct(Command $command, $config = []) { $this->_statement = $command->pdoStatement; $this->_statement->setFetchMode(\PDO::FETCH_ASSOC); @@ -97,7 +97,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable public function setFetchMode($mode) { $params = func_get_args(); - call_user_func_array(array($this->_statement, 'setFetchMode'), $params); + call_user_func_array([$this->_statement, 'setFetchMode'], $params); } /** diff --git a/framework/yii/db/Exception.php b/framework/yii/db/Exception.php index 25ae39f..f502043 100644 --- a/framework/yii/db/Exception.php +++ b/framework/yii/db/Exception.php @@ -19,7 +19,7 @@ class Exception extends \yii\base\Exception * @var array the error info provided by a PDO exception. This is the same as returned * by [PDO::errorInfo](http://www.php.net/manual/en/pdo.errorinfo.php). */ - public $errorInfo = array(); + public $errorInfo = []; /** * Constructor. @@ -28,7 +28,7 @@ class Exception extends \yii\base\Exception * @param integer $code PDO error code * @param \Exception $previous The previous exception used for the exception chaining. */ - public function __construct($message, $errorInfo = array(), $code = 0, \Exception $previous = null) + public function __construct($message, $errorInfo = [], $code = 0, \Exception $previous = null) { $this->errorInfo = $errorInfo; parent::__construct($message, $code, $previous); diff --git a/framework/yii/db/Expression.php b/framework/yii/db/Expression.php index 77e9f60..7fa9124 100644 --- a/framework/yii/db/Expression.php +++ b/framework/yii/db/Expression.php @@ -34,7 +34,7 @@ class Expression extends \yii\base\Object * The keys are placeholders appearing in [[expression]] and the values * are the corresponding parameter values. */ - public $params = array(); + public $params = []; /** * Constructor. @@ -42,7 +42,7 @@ class Expression extends \yii\base\Object * @param array $params parameters * @param array $config name-value pairs that will be used to initialize the object properties */ - public function __construct($expression, $params = array(), $config = array()) + public function __construct($expression, $params = [], $config = []) { $this->expression = $expression; $this->params = $params; diff --git a/framework/yii/db/Migration.php b/framework/yii/db/Migration.php index 7368788..307b02a 100644 --- a/framework/yii/db/Migration.php +++ b/framework/yii/db/Migration.php @@ -135,7 +135,7 @@ class Migration extends \yii\base\Component * @param array $params input parameters (name => value) for the SQL execution. * See [[Command::execute()]] for more details. */ - public function execute($sql, $params = array()) + public function execute($sql, $params = []) { echo " > execute SQL: $sql ..."; $time = microtime(true); @@ -166,7 +166,7 @@ class Migration extends \yii\base\Component * refer to [[Query::where()]] on how to specify conditions. * @param array $params the parameters to be bound to the query. */ - public function update($table, $columns, $condition = '', $params = array()) + public function update($table, $columns, $condition = '', $params = []) { echo " > update $table ..."; $time = microtime(true); @@ -181,7 +181,7 @@ class Migration extends \yii\base\Component * refer to [[Query::where()]] on how to specify conditions. * @param array $params the parameters to be bound to the query. */ - public function delete($table, $condition = '', $params = array()) + public function delete($table, $condition = '', $params = []) { echo " > delete from $table ..."; $time = microtime(true); diff --git a/framework/yii/db/Query.php b/framework/yii/db/Query.php index dbe0424..0839849 100644 --- a/framework/yii/db/Query.php +++ b/framework/yii/db/Query.php @@ -49,7 +49,7 @@ class Query extends Component const SORT_DESC = true; /** - * @var array the columns being selected. For example, `array('id', 'name')`. + * @var array the columns being selected. For example, `['id', 'name']`. * This is used to construct the SELECT clause in a SQL statement. If not set, if means selecting all columns. * @see select() */ @@ -65,7 +65,7 @@ class Query extends Component */ public $distinct; /** - * @var array the table(s) to be selected from. For example, `array('tbl_user', 'tbl_post')`. + * @var array the table(s) to be selected from. For example, `['tbl_user', 'tbl_post']`. * This is used to construct the FROM clause in a SQL statement. * @see from() */ @@ -93,7 +93,7 @@ class Query extends Component */ public $orderBy; /** - * @var array how to group the query results. For example, `array('company', 'department')`. + * @var array how to group the query results. For example, `['company', 'department']`. * This is used to construct the GROUP BY clause in a SQL statement. */ public $groupBy; @@ -102,16 +102,16 @@ class Query extends Component * of one join which has the following structure: * * ~~~ - * array($joinType, $tableName, $joinCondition) + * [$joinType, $tableName, $joinCondition] * ~~~ * * For example, * * ~~~ - * array( - * array('INNER JOIN', 'tbl_user', 'tbl_user.id = author_id'), - * array('LEFT JOIN', 'tbl_team', 'tbl_team.id = team_id'), - * ) + * [ + * ['INNER JOIN', 'tbl_user', 'tbl_user.id = author_id'], + * ['LEFT JOIN', 'tbl_team', 'tbl_team.id = team_id'], + * ] * ~~~ */ public $join; @@ -127,7 +127,7 @@ class Query extends Component public $union; /** * @var array list of query parameter values indexed by parameter placeholders. - * For example, `array(':name' => 'Dan', ':age' => 31)`. + * For example, `[':name' => 'Dan', ':age' => 31]`. */ public $params; /** @@ -186,7 +186,7 @@ class Query extends Component if ($this->indexBy === null) { return $rows; } - $result = array(); + $result = []; foreach ($rows as $row) { if (is_string($this->indexBy)) { $key = $row[$this->indexBy]; @@ -244,7 +244,7 @@ class Query extends Component */ public function count($q = '*', $db = null) { - $this->select = array("COUNT($q)"); + $this->select = ["COUNT($q)"]; return $this->createCommand($db)->queryScalar(); } @@ -258,7 +258,7 @@ class Query extends Component */ public function sum($q, $db = null) { - $this->select = array("SUM($q)"); + $this->select = ["SUM($q)"]; return $this->createCommand($db)->queryScalar(); } @@ -272,7 +272,7 @@ class Query extends Component */ public function average($q, $db = null) { - $this->select = array("AVG($q)"); + $this->select = ["AVG($q)"]; return $this->createCommand($db)->queryScalar(); } @@ -286,7 +286,7 @@ class Query extends Component */ public function min($q, $db = null) { - $this->select = array("MIN($q)"); + $this->select = ["MIN($q)"]; return $this->createCommand($db)->queryScalar(); } @@ -300,7 +300,7 @@ class Query extends Component */ public function max($q, $db = null) { - $this->select = array("MAX($q)"); + $this->select = ["MAX($q)"]; return $this->createCommand($db)->queryScalar(); } @@ -312,14 +312,14 @@ class Query extends Component */ public function exists($db = null) { - $this->select = array(new Expression('1')); + $this->select = [new Expression('1')]; return $this->scalar($db) !== false; } /** * Sets the SELECT part of the query. * @param string|array $columns the columns to be selected. - * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. array('id', 'name')). + * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']). * Columns can contain table prefixes (e.g. "tbl_user.id") and/or column aliases (e.g. "tbl_user.id AS user_id"). * The method will automatically quote the column names unless a column contains some parenthesis * (which means the column contains a DB expression). @@ -351,7 +351,7 @@ class Query extends Component /** * Sets the FROM part of the query. * @param string|array $tables the table(s) to be selected from. This can be either a string (e.g. `'tbl_user'`) - * or an array (e.g. `array('tbl_user', 'tbl_profile')`) specifying one or several table names. + * or an array (e.g. `['tbl_user', 'tbl_profile']`) specifying one or several table names. * Table names can contain schema prefixes (e.g. `'public.tbl_user'`) and/or table aliases (e.g. `'tbl_user u'`). * The method will automatically quote the table names unless it contains some parenthesis * (which means the table is given as a sub-query or DB expression). @@ -375,48 +375,48 @@ class Query extends Component * The $condition parameter should be either a string (e.g. 'id=1') or an array. * If the latter, it must be in one of the following two formats: * - * - hash format: `array('column1' => value1, 'column2' => value2, ...)` - * - operator format: `array(operator, operand1, operand2, ...)` + * - hash format: `['column1' => value1, 'column2' => value2, ...]` + * - operator format: `[operator, operand1, operand2, ...]` * * A condition in hash format represents the following SQL expression in general: * `column1=value1 AND column2=value2 AND ...`. In case when a value is an array, * an `IN` expression will be generated. And if a value is null, `IS NULL` will be used * in the generated expression. Below are some examples: * - * - `array('type' => 1, 'status' => 2)` generates `(type = 1) AND (status = 2)`. - * - `array('id' => array(1, 2, 3), 'status' => 2)` generates `(id IN (1, 2, 3)) AND (status = 2)`. - * - `array('status' => null) generates `status IS NULL`. + * - `['type' => 1, 'status' => 2]` generates `(type = 1) AND (status = 2)`. + * - `['id' => [1, 2, 3], 'status' => 2]` generates `(id IN (1, 2, 3)) AND (status = 2)`. + * - `['status' => null] generates `status IS NULL`. * * A condition in operator format generates the SQL expression according to the specified operator, which * can be one of the followings: * * - `and`: the operands should be concatenated together using `AND`. For example, - * `array('and', 'id=1', 'id=2')` will generate `id=1 AND id=2`. If an operand is an array, + * `['and', 'id=1', 'id=2']` will generate `id=1 AND id=2`. If an operand is an array, * it will be converted into a string using the rules described here. For example, - * `array('and', 'type=1', array('or', 'id=1', 'id=2'))` will generate `type=1 AND (id=1 OR id=2)`. + * `['and', 'type=1', ['or', 'id=1', 'id=2']]` will generate `type=1 AND (id=1 OR id=2)`. * The method will NOT do any quoting or escaping. * * - `or`: similar to the `and` operator except that the operands are concatenated using `OR`. * * - `between`: operand 1 should be the column name, and operand 2 and 3 should be the * starting and ending values of the range that the column is in. - * For example, `array('between', 'id', 1, 10)` will generate `id BETWEEN 1 AND 10`. + * For example, `['between', 'id', 1, 10]` will generate `id BETWEEN 1 AND 10`. * * - `not between`: similar to `between` except the `BETWEEN` is replaced with `NOT BETWEEN` * in the generated condition. * * - `in`: operand 1 should be a column or DB expression, and operand 2 be an array representing * the range of the values that the column or DB expression should be in. For example, - * `array('in', 'id', array(1, 2, 3))` will generate `id IN (1, 2, 3)`. + * `['in', 'id', [1, 2, 3]]` will generate `id IN (1, 2, 3)`. * The method will properly quote the column name and escape values in the range. * * - `not in`: similar to the `in` operator except that `IN` is replaced with `NOT IN` in the generated condition. * * - `like`: operand 1 should be a column or DB expression, and operand 2 be a string or an array representing * the values that the column or DB expression should be like. - * For example, `array('like', 'name', '%tester%')` will generate `name LIKE '%tester%'`. + * For example, `['like', 'name', '%tester%']` will generate `name LIKE '%tester%'`. * When the value range is given as an array, multiple `LIKE` predicates will be generated and concatenated - * using `AND`. For example, `array('like', 'name', array('%test%', '%sample%'))` will generate + * using `AND`. For example, `['like', 'name', ['%test%', '%sample%']]` will generate * `name LIKE '%test%' AND name LIKE '%sample%'`. * The method will properly quote the column name and escape values in the range. * @@ -435,7 +435,7 @@ class Query extends Component * @see andWhere() * @see orWhere() */ - public function where($condition, $params = array()) + public function where($condition, $params = []) { $this->where = $condition; $this->addParams($params); @@ -452,12 +452,12 @@ class Query extends Component * @see where() * @see orWhere() */ - public function andWhere($condition, $params = array()) + public function andWhere($condition, $params = []) { if ($this->where === null) { $this->where = $condition; } else { - $this->where = array('and', $this->where, $condition); + $this->where = ['and', $this->where, $condition]; } $this->addParams($params); return $this; @@ -473,12 +473,12 @@ class Query extends Component * @see where() * @see andWhere() */ - public function orWhere($condition, $params = array()) + public function orWhere($condition, $params = []) { if ($this->where === null) { $this->where = $condition; } else { - $this->where = array('or', $this->where, $condition); + $this->where = ['or', $this->where, $condition]; } $this->addParams($params); return $this; @@ -497,9 +497,9 @@ class Query extends Component * @param array $params the parameters (name => value) to be bound to the query. * @return Query the query object itself */ - public function join($type, $table, $on = '', $params = array()) + public function join($type, $table, $on = '', $params = []) { - $this->join[] = array($type, $table, $on); + $this->join[] = [$type, $table, $on]; return $this->addParams($params); } @@ -514,9 +514,9 @@ class Query extends Component * @param array $params the parameters (name => value) to be bound to the query. * @return Query the query object itself */ - public function innerJoin($table, $on = '', $params = array()) + public function innerJoin($table, $on = '', $params = []) { - $this->join[] = array('INNER JOIN', $table, $on); + $this->join[] = ['INNER JOIN', $table, $on]; return $this->addParams($params); } @@ -531,9 +531,9 @@ class Query extends Component * @param array $params the parameters (name => value) to be bound to the query * @return Query the query object itself */ - public function leftJoin($table, $on = '', $params = array()) + public function leftJoin($table, $on = '', $params = []) { - $this->join[] = array('LEFT JOIN', $table, $on); + $this->join[] = ['LEFT JOIN', $table, $on]; return $this->addParams($params); } @@ -548,16 +548,16 @@ class Query extends Component * @param array $params the parameters (name => value) to be bound to the query * @return Query the query object itself */ - public function rightJoin($table, $on = '', $params = array()) + public function rightJoin($table, $on = '', $params = []) { - $this->join[] = array('RIGHT JOIN', $table, $on); + $this->join[] = ['RIGHT JOIN', $table, $on]; return $this->addParams($params); } /** * Sets the GROUP BY part of the query. * @param string|array $columns the columns to be grouped by. - * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. array('id', 'name')). + * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']). * The method will automatically quote the column names unless a column contains some parenthesis * (which means the column contains a DB expression). * @return static the query object itself @@ -575,7 +575,7 @@ class Query extends Component /** * Adds additional group-by columns to the existing ones. * @param string|array $columns additional columns to be grouped by. - * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. array('id', 'name')). + * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']). * The method will automatically quote the column names unless a column contains some parenthesis * (which means the column contains a DB expression). * @return static the query object itself @@ -603,7 +603,7 @@ class Query extends Component * @see andHaving() * @see orHaving() */ - public function having($condition, $params = array()) + public function having($condition, $params = []) { $this->having = $condition; $this->addParams($params); @@ -620,12 +620,12 @@ class Query extends Component * @see having() * @see orHaving() */ - public function andHaving($condition, $params = array()) + public function andHaving($condition, $params = []) { if ($this->having === null) { $this->having = $condition; } else { - $this->having = array('and', $this->having, $condition); + $this->having = ['and', $this->having, $condition]; } $this->addParams($params); return $this; @@ -641,12 +641,12 @@ class Query extends Component * @see having() * @see andHaving() */ - public function orHaving($condition, $params = array()) + public function orHaving($condition, $params = []) { if ($this->having === null) { $this->having = $condition; } else { - $this->having = array('or', $this->having, $condition); + $this->having = ['or', $this->having, $condition]; } $this->addParams($params); return $this; @@ -656,7 +656,7 @@ class Query extends Component * Sets the ORDER BY part of the query. * @param string|array $columns the columns (and the directions) to be ordered by. * Columns can be specified in either a string (e.g. "id ASC, name DESC") or an array - * (e.g. `array('id' => Query::SORT_ASC, 'name' => Query::SORT_DESC)`). + * (e.g. `['id' => Query::SORT_ASC, 'name' => Query::SORT_DESC]`). * The method will automatically quote the column names unless a column contains some parenthesis * (which means the column contains a DB expression). * @return static the query object itself @@ -672,7 +672,7 @@ class Query extends Component * Adds additional ORDER BY columns to the query. * @param string|array $columns the columns (and the directions) to be ordered by. * Columns can be specified in either a string (e.g. "id ASC, name DESC") or an array - * (e.g. `array('id' => Query::SORT_ASC, 'name' => Query::SORT_DESC)`). + * (e.g. `['id' => Query::SORT_ASC, 'name' => Query::SORT_DESC]`). * The method will automatically quote the column names unless a column contains some parenthesis * (which means the column contains a DB expression). * @return static the query object itself @@ -695,7 +695,7 @@ class Query extends Component return $columns; } else { $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY); - $result = array(); + $result = []; foreach ($columns as $column) { if (preg_match('/^(.*?)\s+(asc|desc)$/i', $column, $matches)) { $result[$matches[1]] = strcasecmp($matches[2], 'desc') ? self::SORT_ASC : self::SORT_DESC; @@ -743,7 +743,7 @@ class Query extends Component /** * Sets the parameters to be bound to the query. * @param array $params list of query parameter values indexed by parameter placeholders. - * For example, `array(':name' => 'Dan', ':age' => 31)`. + * For example, `[':name' => 'Dan', ':age' => 31]`. * @return static the query object itself * @see addParams() */ @@ -756,7 +756,7 @@ class Query extends Component /** * Adds additional parameters to be bound to the query. * @param array $params list of query parameter values indexed by parameter placeholders. - * For example, `array(':name' => 'Dan', ':age' => 31)`. + * For example, `[':name' => 'Dan', ':age' => 31]`. * @return static the query object itself * @see params() */ diff --git a/framework/yii/db/QueryBuilder.php b/framework/yii/db/QueryBuilder.php index f210f65..e41fc4d 100644 --- a/framework/yii/db/QueryBuilder.php +++ b/framework/yii/db/QueryBuilder.php @@ -39,14 +39,14 @@ class QueryBuilder extends \yii\base\Object * This is mainly used to support creating/modifying tables using DB-independent data type specifications. * Child classes should override this property to declare supported type mappings. */ - public $typeMap = array(); + public $typeMap = []; /** * Constructor. * @param Connection $connection the database connection. * @param array $config name-value pairs that will be used to initialize the object properties */ - public function __construct($connection, $config = array()) + public function __construct($connection, $config = []) { $this->db = $connection; parent::__construct($config); @@ -61,7 +61,7 @@ class QueryBuilder extends \yii\base\Object public function build($query) { $params = $query->params; - $clauses = array( + $clauses = [ $this->buildSelect($query->select, $query->distinct, $query->selectOption), $this->buildFrom($query->from), $this->buildJoin($query->join, $params), @@ -71,8 +71,8 @@ class QueryBuilder extends \yii\base\Object $this->buildUnion($query->union, $params), $this->buildOrderBy($query->orderBy), $this->buildLimit($query->limit, $query->offset), - ); - return array(implode($this->separator, array_filter($clauses)), $params); + ]; + return [implode($this->separator, array_filter($clauses)), $params]; } /** @@ -80,10 +80,10 @@ class QueryBuilder extends \yii\base\Object * For example, * * ~~~ - * $sql = $queryBuilder->insert('tbl_user', array( + * $sql = $queryBuilder->insert('tbl_user', [ * 'name' => 'Sam', * 'age' => 30, - * ), $params); + * ], $params); * ~~~ * * The method will properly escape the table and column names. @@ -99,10 +99,10 @@ class QueryBuilder extends \yii\base\Object if (($tableSchema = $this->db->getTableSchema($table)) !== null) { $columnSchemas = $tableSchema->columns; } else { - $columnSchemas = array(); + $columnSchemas = []; } - $names = array(); - $placeholders = array(); + $names = []; + $placeholders = []; foreach ($columns as $name => $value) { $names[] = $this->db->quoteColumnName($name); if ($value instanceof Expression) { @@ -127,11 +127,11 @@ class QueryBuilder extends \yii\base\Object * For example, * * ~~~ - * $connection->createCommand()->batchInsert('tbl_user', array('name', 'age'), array( - * array('Tom', 30), - * array('Jane', 20), - * array('Linda', 25), - * ))->execute(); + * $connection->createCommand()->batchInsert('tbl_user', ['name', 'age'], [ + * ['Tom', 30], + * ['Jane', 20], + * ['Linda', 25], + * ])->execute(); * ~~~ * * Note that the values in each row must match the corresponding column names. @@ -153,10 +153,8 @@ class QueryBuilder extends \yii\base\Object * For example, * * ~~~ - * $params = array(); - * $sql = $queryBuilder->update('tbl_user', array( - * 'status' => 1, - * ), 'age > 30', $params); + * $params = []; + * $sql = $queryBuilder->update('tbl_user', ['status' => 1], 'age > 30', $params); * ~~~ * * The method will properly escape the table and column names. @@ -174,10 +172,10 @@ class QueryBuilder extends \yii\base\Object if (($tableSchema = $this->db->getTableSchema($table)) !== null) { $columnSchemas = $tableSchema->columns; } else { - $columnSchemas = array(); + $columnSchemas = []; } - $lines = array(); + $lines = []; foreach ($columns as $name => $value) { if ($value instanceof Expression) { $lines[] = $this->db->quoteColumnName($name) . '=' . $value->expression; @@ -234,11 +232,11 @@ class QueryBuilder extends \yii\base\Object * For example, * * ~~~ - * $sql = $queryBuilder->createTable('tbl_user', array( + * $sql = $queryBuilder->createTable('tbl_user', [ * 'id' => 'pk', * 'name' => 'string', * 'age' => 'integer', - * )); + * ]); * ~~~ * * @param string $table the name of the table to be created. The name will be properly quoted by the method. @@ -248,7 +246,7 @@ class QueryBuilder extends \yii\base\Object */ public function createTable($table, $columns, $options = null) { - $cols = array(); + $cols = []; foreach ($columns as $name => $type) { if (is_string($name)) { $cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type); @@ -680,7 +678,7 @@ class QueryBuilder extends \yii\base\Object if (empty($columns)) { return ''; } - $orders = array(); + $orders = []; foreach ($columns as $name => $direction) { if (is_object($direction)) { $orders[] = (string)$direction; @@ -767,7 +765,7 @@ class QueryBuilder extends \yii\base\Object */ public function buildCondition($condition, &$params) { - static $builders = array( + static $builders = [ 'AND' => 'buildAndCondition', 'OR' => 'buildAndCondition', 'BETWEEN' => 'buildBetweenCondition', @@ -778,7 +776,7 @@ class QueryBuilder extends \yii\base\Object 'NOT LIKE' => 'buildLikeCondition', 'OR LIKE' => 'buildLikeCondition', 'OR NOT LIKE' => 'buildLikeCondition', - ); + ]; if (!is_array($condition)) { return (string)$condition; @@ -801,10 +799,10 @@ class QueryBuilder extends \yii\base\Object private function buildHashCondition($condition, &$params) { - $parts = array(); + $parts = []; foreach ($condition as $column => $value) { if (is_array($value)) { // IN condition - $parts[] = $this->buildInCondition('IN', array($column, $value), $params); + $parts[] = $this->buildInCondition('IN', [$column, $value], $params); } else { if (strpos($column, '(') === false) { $column = $this->db->quoteColumnName($column); @@ -828,7 +826,7 @@ class QueryBuilder extends \yii\base\Object private function buildAndCondition($operator, $operands, &$params) { - $parts = array(); + $parts = []; foreach ($operands as $operand) { if (is_array($operand)) { $operand = $this->buildCondition($operand, $params); @@ -873,7 +871,7 @@ class QueryBuilder extends \yii\base\Object $values = (array)$values; - if (empty($values) || $column === array()) { + if (empty($values) || $column === []) { return $operator === 'IN' ? '0=1' : ''; } @@ -913,9 +911,9 @@ class QueryBuilder extends \yii\base\Object protected function buildCompositeInCondition($operator, $columns, $values, &$params) { - $vss = array(); + $vss = []; foreach ($values as $value) { - $vs = array(); + $vs = []; foreach ($columns as $column) { if (isset($value[$column])) { $phName = self::PARAM_PREFIX . count($params); @@ -960,7 +958,7 @@ class QueryBuilder extends \yii\base\Object $column = $this->db->quoteColumnName($column); } - $parts = array(); + $parts = []; foreach ($values as $value) { $phName = self::PARAM_PREFIX . count($params); $params[$phName] = $value; diff --git a/framework/yii/db/Schema.php b/framework/yii/db/Schema.php index e32917f..2b3a187 100644 --- a/framework/yii/db/Schema.php +++ b/framework/yii/db/Schema.php @@ -58,11 +58,11 @@ abstract class Schema extends Object /** * @var array list of ALL table names in the database */ - private $_tableNames = array(); + private $_tableNames = []; /** * @var array list of loaded table metadata (table name => TableSchema) */ - private $_tables = array(); + private $_tables = []; /** * @var QueryBuilder the query builder for this database */ @@ -115,12 +115,12 @@ abstract class Schema extends Object */ protected function getCacheKey($name) { - return array( + return [ __CLASS__, $this->db->dsn, $this->db->username, $name, - ); + ]; } /** @@ -130,11 +130,11 @@ abstract class Schema extends Object */ protected function getCacheGroup() { - return md5(serialize(array( + return md5(serialize([ __CLASS__, $this->db->dsn, $this->db->username, - ))); + ])); } /** @@ -147,7 +147,7 @@ abstract class Schema extends Object */ public function getTableSchemas($schema = '', $refresh = false) { - $tables = array(); + $tables = []; foreach ($this->getTableNames($schema, $refresh) as $name) { if ($schema !== '') { $name = $schema . '.' . $name; @@ -194,14 +194,14 @@ abstract class Schema extends Object */ public function getPdoType($data) { - static $typeMap = array( + static $typeMap = [ // php type => PDO type 'boolean' => \PDO::PARAM_BOOL, 'integer' => \PDO::PARAM_INT, 'string' => \PDO::PARAM_STR, 'resource' => \PDO::PARAM_LOB, 'NULL' => \PDO::PARAM_NULL, - ); + ]; $type = gettype($data); return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR; } @@ -218,8 +218,8 @@ abstract class Schema extends Object if ($this->db->enableSchemaCache && $cache instanceof Cache) { GroupDependency::invalidate($cache, $this->getCacheGroup()); } - $this->_tableNames = array(); - $this->_tables = array(); + $this->_tableNames = []; + $this->_tables = []; } /** @@ -378,13 +378,13 @@ abstract class Schema extends Object */ protected function getColumnPhpType($column) { - static $typeMap = array( // abstract type => php type + static $typeMap = [ // abstract type => php type 'smallint' => 'integer', 'integer' => 'integer', 'bigint' => 'integer', 'boolean' => 'boolean', 'float' => 'double', - ); + ]; if (isset($typeMap[$column->type])) { if ($column->type === 'bigint') { return PHP_INT_SIZE == 8 && !$column->unsigned ? 'integer' : 'string'; diff --git a/framework/yii/db/TableSchema.php b/framework/yii/db/TableSchema.php index 910061d..91ce78d 100644 --- a/framework/yii/db/TableSchema.php +++ b/framework/yii/db/TableSchema.php @@ -31,7 +31,7 @@ class TableSchema extends Object /** * @var string[] primary keys of this table. */ - public $primaryKey = array(); + public $primaryKey = []; /** * @var string sequence name for the primary key. Null if no sequence. */ @@ -40,18 +40,18 @@ class TableSchema extends Object * @var array foreign keys of this table. Each array element is of the following structure: * * ~~~ - * array( + * [ * 'ForeignTableName', * 'fk1' => 'pk1', // pk1 is in foreign table * 'fk2' => 'pk2', // if composite foreign key - * ) + * ] * ~~~ */ - public $foreignKeys = array(); + public $foreignKeys = []; /** * @var ColumnSchema[] column metadata of this table. Each array element is a [[ColumnSchema]] object, indexed by column names. */ - public $columns = array(); + public $columns = []; /** * Gets the named column metadata. @@ -81,7 +81,7 @@ class TableSchema extends Object public function fixPrimaryKey($keys) { if (!is_array($keys)) { - $keys = array($keys); + $keys = [$keys]; } $this->primaryKey = $keys; foreach ($this->columns as $column) { diff --git a/framework/yii/db/cubrid/QueryBuilder.php b/framework/yii/db/cubrid/QueryBuilder.php index 4b7ef43..e80e1d6 100644 --- a/framework/yii/db/cubrid/QueryBuilder.php +++ b/framework/yii/db/cubrid/QueryBuilder.php @@ -20,7 +20,7 @@ class QueryBuilder extends \yii\db\QueryBuilder /** * @var array mapping from abstract column types (keys) to physical column types (values). */ - public $typeMap = array( + public $typeMap = [ Schema::TYPE_PK => 'int NOT NULL AUTO_INCREMENT PRIMARY KEY', Schema::TYPE_BIGPK => 'bigint NOT NULL AUTO_INCREMENT PRIMARY KEY', Schema::TYPE_STRING => 'varchar(255)', @@ -37,7 +37,7 @@ class QueryBuilder extends \yii\db\QueryBuilder Schema::TYPE_BINARY => 'blob', Schema::TYPE_BOOLEAN => 'smallint', Schema::TYPE_MONEY => 'decimal(19,4)', - ); + ]; /** * Creates a SQL statement for resetting the sequence value of a table's primary key. @@ -73,11 +73,11 @@ class QueryBuilder extends \yii\db\QueryBuilder * For example, * * ~~~ - * $connection->createCommand()->batchInsert('tbl_user', array('name', 'age'), array( - * array('Tom', 30), - * array('Jane', 20), - * array('Linda', 25), - * ))->execute(); + * $connection->createCommand()->batchInsert('tbl_user', ['name', 'age'], [ + * ['Tom', 30], + * ['Jane', 20], + * ['Linda', 25], + * ])->execute(); * ~~~ * * Note that the values in each row must match the corresponding column names. @@ -92,16 +92,16 @@ class QueryBuilder extends \yii\db\QueryBuilder if (($tableSchema = $this->db->getTableSchema($table)) !== null) { $columnSchemas = $tableSchema->columns; } else { - $columnSchemas = array(); + $columnSchemas = []; } foreach ($columns as $i => $name) { $columns[$i] = $this->db->quoteColumnName($name); } - $values = array(); + $values = []; foreach ($rows as $row) { - $vs = array(); + $vs = []; foreach ($row as $i => $value) { if (!is_array($value) && isset($columnSchemas[$columns[$i]])) { $value = $columnSchemas[$columns[$i]]->typecast($value); diff --git a/framework/yii/db/cubrid/Schema.php b/framework/yii/db/cubrid/Schema.php index a789694..68aa8ee 100644 --- a/framework/yii/db/cubrid/Schema.php +++ b/framework/yii/db/cubrid/Schema.php @@ -24,7 +24,7 @@ class Schema extends \yii\db\Schema * Please refer to [CUBRID manual](http://www.cubrid.org/manual/91/en/sql/datatype.html) for * details on data types. */ - public $typeMap = array( + public $typeMap = [ // Numeric data types 'short' => self::TYPE_SMALLINT, 'smallint' => self::TYPE_SMALLINT, @@ -62,7 +62,7 @@ class Schema extends \yii\db\Schema 'list' => self::TYPE_STRING, 'sequence' => self::TYPE_STRING, 'enum' => self::TYPE_STRING, - ); + ]; /** * Quotes a table name for use in a query. @@ -151,10 +151,10 @@ class Schema extends \yii\db\Schema if (isset($table->foreignKeys[$key['FK_NAME']])) { $table->foreignKeys[$key['FK_NAME']][$key['FKCOLUMN_NAME']] = $key['PKCOLUMN_NAME']; } else { - $table->foreignKeys[$key['FK_NAME']] = array( + $table->foreignKeys[$key['FK_NAME']] = [ $key['PKTABLE_NAME'], $key['FKCOLUMN_NAME'] => $key['PKCOLUMN_NAME'] - ); + ]; } } $table->foreignKeys = array_values($table->foreignKeys); @@ -229,7 +229,7 @@ class Schema extends \yii\db\Schema { $this->db->open(); $tables = $this->db->pdo->cubrid_schema(\PDO::CUBRID_SCH_TABLE); - $tableNames = array(); + $tableNames = []; foreach($tables as $table) { // do not list system tables if ($table['TYPE'] != 0) { @@ -247,14 +247,14 @@ class Schema extends \yii\db\Schema */ public function getPdoType($data) { - static $typeMap = array( + static $typeMap = [ // php type => PDO type 'boolean' => \PDO::PARAM_INT, // PARAM_BOOL is not supported by CUBRID PDO 'integer' => \PDO::PARAM_INT, 'string' => \PDO::PARAM_STR, 'resource' => \PDO::PARAM_LOB, 'NULL' => \PDO::PARAM_NULL, - ); + ]; $type = gettype($data); return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR; } diff --git a/framework/yii/db/mssql/QueryBuilder.php b/framework/yii/db/mssql/QueryBuilder.php index aeb5be8..c9bf7ca 100644 --- a/framework/yii/db/mssql/QueryBuilder.php +++ b/framework/yii/db/mssql/QueryBuilder.php @@ -20,7 +20,7 @@ class QueryBuilder extends \yii\db\QueryBuilder /** * @var array mapping from abstract column types (keys) to physical column types (values). */ - public $typeMap = array( + public $typeMap = [ Schema::TYPE_PK => 'int IDENTITY PRIMARY KEY', Schema::TYPE_BIGPK => 'bigint IDENTITY PRIMARY KEY', Schema::TYPE_STRING => 'varchar(255)', @@ -37,7 +37,7 @@ class QueryBuilder extends \yii\db\QueryBuilder Schema::TYPE_BINARY => 'binary', Schema::TYPE_BOOLEAN => 'tinyint(1)', Schema::TYPE_MONEY => 'decimal(19,4)', - ); + ]; // public function update($table, $columns, $condition, &$params) // { diff --git a/framework/yii/db/mssql/Schema.php b/framework/yii/db/mssql/Schema.php index 9def3b4..0bb5924 100644 --- a/framework/yii/db/mssql/Schema.php +++ b/framework/yii/db/mssql/Schema.php @@ -25,7 +25,7 @@ class Schema extends \yii\db\Schema /** * @var array mapping from physical column types (keys) to abstract column types (values) */ - public $typeMap = array( + public $typeMap = [ // exact numerics 'bigint' => self::TYPE_BIGINT, 'numeric' => self::TYPE_DECIMAL, @@ -72,7 +72,7 @@ class Schema extends \yii\db\Schema 'sql_variant' => self::TYPE_STRING, 'xml' => self::TYPE_STRING, 'table' => self::TYPE_STRING, - ); + ]; /** * Quotes a table name for use in a query. @@ -128,7 +128,7 @@ class Schema extends \yii\db\Schema */ protected function resolveTableNames($table, $name) { - $parts = explode('.', str_replace(array('[', ']'), '', $name)); + $parts = explode('.', str_replace(['[', ']'], '', $name)); $partCount = count($parts); if ($partCount == 3) { // catalog name, schema name and table name passed @@ -158,7 +158,7 @@ class Schema extends \yii\db\Schema $column->name = $info['column_name']; $column->allowNull = $info['is_nullable'] == 'YES'; $column->dbType = $info['data_type']; - $column->enumValues = array(); // mssql has only vague equivalents to enum + $column->enumValues = []; // mssql has only vague equivalents to enum $column->isPrimaryKey = null; // primary key will be determined in findColumns() method $column->autoIncrement = $info['is_identity'] == 1; $column->unsigned = stripos($column->dbType, 'unsigned') !== false; @@ -283,7 +283,7 @@ WHERE SQL; $table->primaryKey = $this->db - ->createCommand($sql, array(':tableName' => $table->name, ':schemaName' => $table->schemaName)) + ->createCommand($sql, [':tableName' => $table->name, ':schemaName' => $table->schemaName]) ->queryColumn(); } @@ -322,10 +322,10 @@ JOIN {$keyColumnUsageTableName} AS [kcu2] ON WHERE [kcu1].[table_name] = :tableName SQL; - $rows = $this->db->createCommand($sql, array(':tableName' => $table->name))->queryAll(); - $table->foreignKeys = array(); + $rows = $this->db->createCommand($sql, [':tableName' => $table->name])->queryAll(); + $table->foreignKeys = []; foreach ($rows as $row) { - $table->foreignKeys[] = array($row['uq_table_name'], $row['fk_column_name'] => $row['uq_column_name']); + $table->foreignKeys[] = [$row['uq_table_name'], $row['fk_column_name'] => $row['uq_column_name']]; } } @@ -346,7 +346,7 @@ FROM [information_schema].[tables] AS [t] WHERE [t].[table_schema] = :schema AND [t].[table_type] = 'BASE TABLE' SQL; - $names = $this->db->createCommand($sql, array(':schema' => $schema))->queryColumn(); + $names = $this->db->createCommand($sql, [':schema' => $schema])->queryColumn(); if ($schema !== static::DEFAULT_SCHEMA) { foreach ($names as $index => $name) { $names[$index] = $schema . '.' . $name; diff --git a/framework/yii/db/mysql/QueryBuilder.php b/framework/yii/db/mysql/QueryBuilder.php index 386de2f..50e717c 100644 --- a/framework/yii/db/mysql/QueryBuilder.php +++ b/framework/yii/db/mysql/QueryBuilder.php @@ -21,7 +21,7 @@ class QueryBuilder extends \yii\db\QueryBuilder /** * @var array mapping from abstract column types (keys) to physical column types (values). */ - public $typeMap = array( + public $typeMap = [ Schema::TYPE_PK => 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY', Schema::TYPE_BIGPK => 'bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY', Schema::TYPE_STRING => 'varchar(255)', @@ -38,7 +38,7 @@ class QueryBuilder extends \yii\db\QueryBuilder Schema::TYPE_BINARY => 'blob', Schema::TYPE_BOOLEAN => 'tinyint(1)', Schema::TYPE_MONEY => 'decimal(19,4)', - ); + ]; /** * Builds a SQL statement for renaming a column. @@ -146,11 +146,11 @@ class QueryBuilder extends \yii\db\QueryBuilder * For example, * * ~~~ - * $connection->createCommand()->batchInsert('tbl_user', array('name', 'age'), array( - * array('Tom', 30), - * array('Jane', 20), - * array('Linda', 25), - * ))->execute(); + * $connection->createCommand()->batchInsert('tbl_user', ['name', 'age'], [ + * ['Tom', 30], + * ['Jane', 20], + * ['Linda', 25], + * ])->execute(); * ~~~ * * Note that the values in each row must match the corresponding column names. @@ -165,16 +165,16 @@ class QueryBuilder extends \yii\db\QueryBuilder if (($tableSchema = $this->db->getTableSchema($table)) !== null) { $columnSchemas = $tableSchema->columns; } else { - $columnSchemas = array(); + $columnSchemas = []; } foreach ($columns as $i => $name) { $columns[$i] = $this->db->quoteColumnName($name); } - $values = array(); + $values = []; foreach ($rows as $row) { - $vs = array(); + $vs = []; foreach ($row as $i => $value) { if (!is_array($value) && isset($columnSchemas[$columns[$i]])) { $value = $columnSchemas[$columns[$i]]->typecast($value); diff --git a/framework/yii/db/mysql/Schema.php b/framework/yii/db/mysql/Schema.php index 998f49a..f55d38f 100644 --- a/framework/yii/db/mysql/Schema.php +++ b/framework/yii/db/mysql/Schema.php @@ -21,7 +21,7 @@ class Schema extends \yii\db\Schema /** * @var array mapping from physical column types (keys) to abstract column types (values) */ - public $typeMap = array( + public $typeMap = [ 'tinyint' => self::TYPE_SMALLINT, 'bit' => self::TYPE_SMALLINT, 'smallint' => self::TYPE_SMALLINT, @@ -47,7 +47,7 @@ class Schema extends \yii\db\Schema 'time' => self::TYPE_TIME, 'timestamp' => self::TYPE_TIMESTAMP, 'enum' => self::TYPE_STRING, - ); + ]; /** * Quotes a table name for use in a query. @@ -225,7 +225,7 @@ class Schema extends \yii\db\Schema foreach ($matches as $match) { $fks = array_map('trim', explode(',', str_replace('`', '', $match[1]))); $pks = array_map('trim', explode(',', str_replace('`', '', $match[3]))); - $constraint = array(str_replace('`', '', $match[2])); + $constraint = [str_replace('`', '', $match[2])]; foreach ($fks as $k => $name) { $constraint[$name] = $pks[$k]; } diff --git a/framework/yii/db/pgsql/QueryBuilder.php b/framework/yii/db/pgsql/QueryBuilder.php index 667fa43..09a620d 100644 --- a/framework/yii/db/pgsql/QueryBuilder.php +++ b/framework/yii/db/pgsql/QueryBuilder.php @@ -20,7 +20,7 @@ class QueryBuilder extends \yii\db\QueryBuilder /** * @var array mapping from abstract column types (keys) to physical column types (values). */ - public $typeMap = array( + public $typeMap = [ Schema::TYPE_PK => 'serial NOT NULL PRIMARY KEY', Schema::TYPE_BIGPK => 'bigserial NOT NULL PRIMARY KEY', Schema::TYPE_STRING => 'varchar(255)', @@ -37,7 +37,7 @@ class QueryBuilder extends \yii\db\QueryBuilder Schema::TYPE_BINARY => 'bytea', Schema::TYPE_BOOLEAN => 'boolean', Schema::TYPE_MONEY => 'numeric(19,4)', - ); + ]; /** * Builds a SQL statement for dropping an index. diff --git a/framework/yii/db/pgsql/Schema.php b/framework/yii/db/pgsql/Schema.php index d131342..a5c59f4 100644 --- a/framework/yii/db/pgsql/Schema.php +++ b/framework/yii/db/pgsql/Schema.php @@ -31,7 +31,7 @@ class Schema extends \yii\db\Schema * @var array mapping from physical column types (keys) to abstract * column types (values) */ - public $typeMap = array( + public $typeMap = [ 'abstime' => self::TYPE_TIMESTAMP, 'bit' => self::TYPE_STRING, 'boolean' => self::TYPE_BOOLEAN, @@ -70,7 +70,7 @@ class Schema extends \yii\db\Schema 'bit varying' => self::TYPE_STRING, 'character varying' => self::TYPE_STRING, 'xml' => self::TYPE_STRING - ); + ]; /** * Creates a query builder for the PostgreSQL database. @@ -146,7 +146,7 @@ EOD; $command = $this->db->createCommand($sql); $command->bindParam(':schema', $schema); $rows = $command->queryAll(); - $names = array(); + $names = []; foreach ($rows as $row) { if ($schema === $this->defaultSchema) { $names[] = $row['table_name']; @@ -198,7 +198,7 @@ SQL; } else { $foreignTable = $constraint['foreign_table_name']; } - $citem = array($foreignTable); + $citem = [$foreignTable]; foreach ($columns as $idx => $column) { $citem[$fcolumns[$idx]] = $column; } @@ -281,7 +281,7 @@ SQL; if ($column->isPrimaryKey === true) { $table->primaryKey[] = $column->name; if ($table->sequenceName === null && preg_match("/nextval\('\w+'(::regclass)?\)/", $column->defaultValue) === 1) { - $table->sequenceName = preg_replace(array('/nextval/', '/::/', '/regclass/', '/\'\)/', '/\(\'/'), '', $column->defaultValue); + $table->sequenceName = preg_replace(['/nextval/', '/::/', '/regclass/', '/\'\)/', '/\(\'/'], '', $column->defaultValue); } } } @@ -301,7 +301,7 @@ SQL; $column->comment = $info['column_comment']; $column->dbType = $info['data_type']; $column->defaultValue = $info['column_default']; - $column->enumValues = explode(',', str_replace(array("''"), array("'"), $info['enum_values'])); + $column->enumValues = explode(',', str_replace(["''"], ["'"], $info['enum_values'])); $column->unsigned = false; // has no meanining in PG $column->isPrimaryKey = $info['is_pkey']; $column->name = $info['column_name']; diff --git a/framework/yii/db/sqlite/QueryBuilder.php b/framework/yii/db/sqlite/QueryBuilder.php index 4e210f8..2a6f345 100644 --- a/framework/yii/db/sqlite/QueryBuilder.php +++ b/framework/yii/db/sqlite/QueryBuilder.php @@ -22,7 +22,7 @@ class QueryBuilder extends \yii\db\QueryBuilder /** * @var array mapping from abstract column types (keys) to physical column types (values). */ - public $typeMap = array( + public $typeMap = [ Schema::TYPE_PK => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL', Schema::TYPE_BIGPK => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL', Schema::TYPE_STRING => 'varchar(255)', @@ -39,7 +39,7 @@ class QueryBuilder extends \yii\db\QueryBuilder Schema::TYPE_BINARY => 'blob', Schema::TYPE_BOOLEAN => 'boolean', Schema::TYPE_MONEY => 'decimal(19,4)', - ); + ]; /** * Creates a SQL statement for resetting the sequence value of a table's primary key. diff --git a/framework/yii/db/sqlite/Schema.php b/framework/yii/db/sqlite/Schema.php index bca26c1..294c97e 100644 --- a/framework/yii/db/sqlite/Schema.php +++ b/framework/yii/db/sqlite/Schema.php @@ -21,7 +21,7 @@ class Schema extends \yii\db\Schema /** * @var array mapping from physical column types (keys) to abstract column types (values) */ - public $typeMap = array( + public $typeMap = [ 'tinyint' => self::TYPE_SMALLINT, 'bit' => self::TYPE_SMALLINT, 'smallint' => self::TYPE_SMALLINT, @@ -47,7 +47,7 @@ class Schema extends \yii\db\Schema 'time' => self::TYPE_TIME, 'timestamp' => self::TYPE_TIMESTAMP, 'enum' => self::TYPE_STRING, - ); + ]; /** * Creates a query builder for the MySQL database. @@ -128,7 +128,7 @@ class Schema extends \yii\db\Schema foreach ($keys as $key) { $id = (int)$key['id']; if (!isset($table->foreignKeys[$id])) { - $table->foreignKeys[$id] = array($key['table'], $key['from'] => $key['to']); + $table->foreignKeys[$id] = [$key['table'], $key['from'] => $key['to']]; } else { // composite FK $table->foreignKeys[$id][$key['from']] = $key['to']; diff --git a/framework/yii/debug/DebugAsset.php b/framework/yii/debug/DebugAsset.php index 4f3ee89..5b459a3 100644 --- a/framework/yii/debug/DebugAsset.php +++ b/framework/yii/debug/DebugAsset.php @@ -15,11 +15,11 @@ use yii\web\AssetBundle; class DebugAsset extends AssetBundle { public $sourcePath = '@yii/debug/assets'; - public $css = array( + public $css = [ 'main.css', - ); - public $depends = array( + ]; + public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', - ); + ]; } diff --git a/framework/yii/debug/LogTarget.php b/framework/yii/debug/LogTarget.php index 30392f0..4b75cfa 100644 --- a/framework/yii/debug/LogTarget.php +++ b/framework/yii/debug/LogTarget.php @@ -28,7 +28,7 @@ class LogTarget extends Target * @param \yii\debug\Module $module * @param array $config */ - public function __construct($module, $config = array()) + public function __construct($module, $config = []) { parent::__construct($config); $this->module = $module; @@ -47,23 +47,23 @@ class LogTarget extends Target } $indexFile = "$path/index.data"; if (!is_file($indexFile)) { - $manifest = array(); + $manifest = []; } else { $manifest = unserialize(file_get_contents($indexFile)); } $request = Yii::$app->getRequest(); - $manifest[$this->tag] = $summary = array( + $manifest[$this->tag] = $summary = [ 'tag' => $this->tag, 'url' => $request->getAbsoluteUrl(), 'ajax' => $request->getIsAjax(), 'method' => $request->getMethod(), 'ip' => $request->getUserIP(), 'time' => time(), - ); + ]; $this->gc($manifest); $dataFile = "$path/{$this->tag}.data"; - $data = array(); + $data = []; foreach ($this->module->panels as $id => $panel) { $data[$id] = $panel->save(); } diff --git a/framework/yii/debug/Module.php b/framework/yii/debug/Module.php index 260a981..e75d14b 100644 --- a/framework/yii/debug/Module.php +++ b/framework/yii/debug/Module.php @@ -24,10 +24,10 @@ class Module extends \yii\base\Module * @var array the list of IPs that are allowed to access this module. * Each array element represents a single IP filter which can be either an IP address * or an address with wildcard (e.g. 192.168.0.*) to represent a network segment. - * The default value is `array('127.0.0.1', '::1')`, which means the module can only be accessed + * The default value is `['127.0.0.1', '::1']`, which means the module can only be accessed * by localhost. */ - public $allowedIPs = array('127.0.0.1', '::1'); + public $allowedIPs = ['127.0.0.1', '::1']; /** * @var string the namespace that controller classes are in. */ @@ -39,7 +39,7 @@ class Module extends \yii\base\Module /** * @var array|Panel[] */ - public $panels = array(); + public $panels = []; /** * @var string the directory storing the debugger data files. This can be specified using a path alias. */ @@ -58,7 +58,7 @@ class Module extends \yii\base\Module $this->logTarget = Yii::$app->getLog()->targets['debug'] = new LogTarget($this); // do not initialize view component before application is ready (needed when debug in preload) Yii::$app->on(Application::EVENT_BEFORE_ACTION, function() { - Yii::$app->getView()->on(View::EVENT_END_BODY, array($this, 'renderToolbar')); + Yii::$app->getView()->on(View::EVENT_END_BODY, [$this, 'renderToolbar']); }); foreach (array_merge($this->corePanels(), $this->panels) as $id => $config) { @@ -70,7 +70,7 @@ class Module extends \yii\base\Module public function beforeAction($action) { - Yii::$app->getView()->off(View::EVENT_END_BODY, array($this, 'renderToolbar')); + Yii::$app->getView()->off(View::EVENT_END_BODY, [$this, 'renderToolbar']); unset(Yii::$app->getLog()->targets['debug']); $this->logTarget = null; @@ -88,9 +88,9 @@ class Module extends \yii\base\Module if (!$this->checkAccess()) { return; } - $url = Yii::$app->getUrlManager()->createUrl($this->id . '/default/toolbar', array( + $url = Yii::$app->getUrlManager()->createUrl($this->id . '/default/toolbar', [ 'tag' => $this->logTarget->tag, - )); + ]); echo ''; /** @var View $view */ $view = $event->sender; @@ -111,22 +111,12 @@ class Module extends \yii\base\Module protected function corePanels() { - return array( - 'config' => array( - 'class' => 'yii\debug\panels\ConfigPanel', - ), - 'request' => array( - 'class' => 'yii\debug\panels\RequestPanel', - ), - 'log' => array( - 'class' => 'yii\debug\panels\LogPanel', - ), - 'profiling' => array( - 'class' => 'yii\debug\panels\ProfilingPanel', - ), - 'db' => array( - 'class' => 'yii\debug\panels\DbPanel', - ), - ); + return [ + 'config' => ['class' => 'yii\debug\panels\ConfigPanel'], + 'request' => ['class' => 'yii\debug\panels\RequestPanel'], + 'log' => ['class' => 'yii\debug\panels\LogPanel'], + 'profiling' => ['class' => 'yii\debug\panels\ProfilingPanel'], + 'db' => ['class' => 'yii\debug\panels\DbPanel'], + ]; } } diff --git a/framework/yii/debug/Panel.php b/framework/yii/debug/Panel.php index 6782264..055dbba 100644 --- a/framework/yii/debug/Panel.php +++ b/framework/yii/debug/Panel.php @@ -77,9 +77,9 @@ class Panel extends Component */ public function getUrl() { - return Yii::$app->getUrlManager()->createUrl($this->module->id . '/default/view', array( + return Yii::$app->getUrlManager()->createUrl($this->module->id . '/default/view', [ 'panel' => $this->id, 'tag' => $this->tag, - )); + ]); } } diff --git a/framework/yii/debug/controllers/DefaultController.php b/framework/yii/debug/controllers/DefaultController.php index 62fe61a..a4ac633 100644 --- a/framework/yii/debug/controllers/DefaultController.php +++ b/framework/yii/debug/controllers/DefaultController.php @@ -29,9 +29,7 @@ class DefaultController extends Controller public function actionIndex() { - return $this->render('index', array( - 'manifest' => $this->getManifest(), - )); + return $this->render('index', ['manifest' => $this->getManifest()]); } public function actionView($tag = null, $panel = null) @@ -46,22 +44,22 @@ class DefaultController extends Controller } else { $activePanel = $this->module->panels['request']; } - return $this->render('view', array( + return $this->render('view', [ 'tag' => $tag, 'summary' => $this->summary, 'manifest' => $this->getManifest(), 'panels' => $this->module->panels, 'activePanel' => $activePanel, - )); + ]); } public function actionToolbar($tag) { $this->loadData($tag); - return $this->renderPartial('toolbar', array( + return $this->renderPartial('toolbar', [ 'tag' => $tag, 'panels' => $this->module->panels, - )); + ]); } public function actionPhpinfo() @@ -78,7 +76,7 @@ class DefaultController extends Controller if (is_file($indexFile)) { $this->_manifest = array_reverse(unserialize(file_get_contents($indexFile)), true); } else { - $this->_manifest = array(); + $this->_manifest = []; } } return $this->_manifest; diff --git a/framework/yii/debug/panels/ConfigPanel.php b/framework/yii/debug/panels/ConfigPanel.php index eb0d325..3ed5b06 100644 --- a/framework/yii/debug/panels/ConfigPanel.php +++ b/framework/yii/debug/panels/ConfigPanel.php @@ -49,18 +49,18 @@ EOD; public function getDetail() { - $app = array( + $app = [ 'Yii Version' => $this->data['application']['yii'], 'Application Name' => $this->data['application']['name'], 'Environment' => $this->data['application']['env'], 'Debug Mode' => $this->data['application']['debug'] ? 'Yes' : 'No', - ); - $php = array( + ]; + $php = [ 'PHP Version' => $this->data['php']['version'], 'Xdebug' => $this->data['php']['xdebug'] ? 'Enabled' : 'Disabled', 'APC' => $this->data['php']['apc'] ? 'Enabled' : 'Disabled', 'Memcache' => $this->data['php']['memcache'] ? 'Enabled' : 'Disabled', - ); + ]; return "

Configuration

\n" . $this->renderData('Application Configuration', $app) . "\n" . $this->renderData('PHP Configuration', $php) . "\n" @@ -69,7 +69,7 @@ EOD; protected function getPhpInfo() { - return '
' . Html::a('Show phpinfo »', array('phpinfo'), array('class' => 'btn btn-primary')) . "
\n"; + return '
' . Html::a('Show phpinfo »', ['phpinfo'], ['class' => 'btn btn-primary']) . "
\n"; } protected function renderData($caption, $values) @@ -77,7 +77,7 @@ EOD; if (empty($values)) { return "

$caption

\n

Empty.

"; } - $rows = array(); + $rows = []; foreach ($values as $name => $value) { $rows[] = '' . Html::encode($name) . '' . Html::encode($value) . ''; } @@ -95,21 +95,21 @@ EOD; public function save() { - return array( + return [ 'phpVersion' => PHP_VERSION, 'yiiVersion' => Yii::getVersion(), - 'application' => array( + 'application' => [ 'yii' => Yii::getVersion(), 'name' => Yii::$app->name, 'env' => YII_ENV, 'debug' => YII_DEBUG, - ), - 'php' => array( + ], + 'php' => [ 'version' => PHP_VERSION, 'xdebug' => extension_loaded('xdebug'), 'apc' => extension_loaded('apc'), 'memcache' => extension_loaded('memcache'), - ), - ); + ], + ]; } } diff --git a/framework/yii/debug/panels/DbPanel.php b/framework/yii/debug/panels/DbPanel.php index 8dd2c9e..e24da93 100644 --- a/framework/yii/debug/panels/DbPanel.php +++ b/framework/yii/debug/panels/DbPanel.php @@ -49,18 +49,18 @@ EOD; { $timings = $this->calculateTimings(); ArrayHelper::multisort($timings, 3, true); - $rows = array(); + $rows = []; foreach ($timings as $timing) { $duration = sprintf('%.1f ms', $timing[3] * 1000); $procedure = Html::encode($timing[1]); $traces = $timing[4]; if (!empty($traces)) { - $procedure .= Html::ul($traces, array( + $procedure .= Html::ul($traces, [ 'class' => 'trace', 'item' => function ($trace) { return "
  • {$trace['file']}({$trace['line']})
  • "; }, - )); + ]); } $rows[] = "$duration$procedure"; } @@ -91,8 +91,8 @@ EOD; return $this->_timings; } $messages = $this->data['messages']; - $timings = array(); - $stack = array(); + $timings = []; + $stack = []; foreach ($messages as $i => $log) { list($token, $level, $category, $timestamp) = $log; $log[5] = $i; @@ -100,7 +100,7 @@ EOD; $stack[] = $log; } elseif ($level == Logger::LEVEL_PROFILE_END) { if (($last = array_pop($stack)) !== null && $last[0] === $token) { - $timings[$last[5]] = array(count($stack), $token, $last[3], $timestamp - $last[3], $last[4]); + $timings[$last[5]] = [count($stack), $token, $last[3], $timestamp - $last[3], $last[4]]; } } } @@ -108,7 +108,7 @@ EOD; $now = microtime(true); while (($last = array_pop($stack)) !== null) { $delta = $now - $last[3]; - $timings[$last[5]] = array(count($stack), $last[0], $last[2], $delta, $last[4]); + $timings[$last[5]] = [count($stack), $last[0], $last[2], $delta, $last[4]]; } ksort($timings); return $this->_timings = $timings; @@ -117,9 +117,7 @@ EOD; public function save() { $target = $this->module->logTarget; - $messages = $target->filterMessages($target->messages, Logger::LEVEL_PROFILE, array('yii\db\Command::queryInternal')); - return array( - 'messages' => $messages, - ); + $messages = $target->filterMessages($target->messages, Logger::LEVEL_PROFILE, ['yii\db\Command::queryInternal']); + return ['messages' => $messages]; } } diff --git a/framework/yii/debug/panels/LogPanel.php b/framework/yii/debug/panels/LogPanel.php index c562006..ccf4402 100644 --- a/framework/yii/debug/panels/LogPanel.php +++ b/framework/yii/debug/panels/LogPanel.php @@ -28,7 +28,7 @@ class LogPanel extends Panel public function getSummary() { - $output = array('' . count($this->data['messages']) . ''); + $output = ['' . count($this->data['messages']) . '']; $title = 'Logged ' . count($this->data['messages']) . ' messages'; $errorCount = count(Target::filterMessages($this->data['messages'], Logger::LEVEL_ERROR)); if ($errorCount) { @@ -51,18 +51,18 @@ EOD; public function getDetail() { - $rows = array(); + $rows = []; foreach ($this->data['messages'] as $log) { list ($message, $level, $category, $time, $traces) = $log; $time = date('H:i:s.', $time) . sprintf('%03d', (int)(($time - (int)$time) * 1000)); $message = nl2br(Html::encode($message)); if (!empty($traces)) { - $message .= Html::ul($traces, array( + $message .= Html::ul($traces, [ 'class' => 'trace', 'item' => function ($trace) { return "
  • {$trace['file']}({$trace['line']})
  • "; }, - )); + ]); } if ($level == Logger::LEVEL_ERROR) { $class = ' class="danger"'; @@ -100,8 +100,6 @@ EOD; { $target = $this->module->logTarget; $messages = $target->filterMessages($target->messages, Logger::LEVEL_ERROR | Logger::LEVEL_INFO | Logger::LEVEL_WARNING | Logger::LEVEL_TRACE); - return array( - 'messages' => $messages, - ); + return ['messages' => $messages]; } } diff --git a/framework/yii/debug/panels/ProfilingPanel.php b/framework/yii/debug/panels/ProfilingPanel.php index c462e40..49cf081 100644 --- a/framework/yii/debug/panels/ProfilingPanel.php +++ b/framework/yii/debug/panels/ProfilingPanel.php @@ -44,25 +44,25 @@ EOD; public function getDetail() { $messages = $this->data['messages']; - $timings = array(); - $stack = array(); + $timings = []; + $stack = []; foreach ($messages as $i => $log) { list($token, $level, $category, $timestamp, $traces) = $log; if ($level == Logger::LEVEL_PROFILE_BEGIN) { $stack[] = $log; } elseif ($level == Logger::LEVEL_PROFILE_END) { if (($last = array_pop($stack)) !== null && $last[0] === $token) { - $timings[] = array(count($stack), $token, $category, $timestamp - $last[3], $traces); + $timings[] = [count($stack), $token, $category, $timestamp - $last[3], $traces]; } } } $now = microtime(true); while (($last = array_pop($stack)) !== null) { - $timings[] = array(count($stack), $last[0], $last[2], $now - $last[3], $last[4]); + $timings[] = [count($stack), $last[0], $last[2], $now - $last[3], $last[4]]; } - $rows = array(); + $rows = []; foreach ($timings as $timing) { $time = sprintf('%.1f ms', $timing[3] * 1000); $procedure = str_repeat('', $timing[0]) . Html::encode($timing[1]); @@ -98,10 +98,10 @@ EOD; { $target = $this->module->logTarget; $messages = $target->filterMessages($target->messages, Logger::LEVEL_PROFILE); - return array( + return [ 'memory' => memory_get_peak_usage(), 'time' => microtime(true) - YII_BEGIN_TIME, 'messages' => $messages, - ); + ]; } } diff --git a/framework/yii/debug/panels/RequestPanel.php b/framework/yii/debug/panels/RequestPanel.php index 58256e4..9d9cb02 100644 --- a/framework/yii/debug/panels/RequestPanel.php +++ b/framework/yii/debug/panels/RequestPanel.php @@ -55,14 +55,14 @@ EOD; public function getDetail() { - $data = array( + $data = [ 'Route' => $this->data['route'], 'Action' => $this->data['action'], 'Parameters' => $this->data['actionParams'], - ); - return Tabs::widget(array( - 'items' => array( - array( + ]; + return Tabs::widget([ + 'items' => [ + [ 'label' => 'Parameters', 'content' => $this->renderData('Routing', $data) . $this->renderData('$_GET', $this->data['GET']) @@ -70,23 +70,23 @@ EOD; . $this->renderData('$_FILES', $this->data['FILES']) . $this->renderData('$_COOKIE', $this->data['COOKIE']), 'active' => true, - ), - array( + ], + [ 'label' => 'Headers', 'content' => $this->renderData('Request Headers', $this->data['requestHeaders']) . $this->renderData('Response Headers', $this->data['responseHeaders']), - ), - array( + ], + [ 'label' => 'Session', 'content' => $this->renderData('$_SESSION', $this->data['SESSION']) . $this->renderData('Flashes', $this->data['flashes']), - ), - array( + ], + [ 'label' => '$_SERVER', 'content' => $this->renderData('$_SERVER', $this->data['SERVER']), - ), - ), - )); + ], + ], + ]); } public function save() @@ -96,16 +96,16 @@ EOD; } elseif (function_exists('http_get_request_headers')) { $requestHeaders = http_get_request_headers(); } else { - $requestHeaders = array(); + $requestHeaders = []; } - $responseHeaders = array(); + $responseHeaders = []; foreach (headers_list() as $header) { if (($pos = strpos($header, ':')) !== false) { $name = substr($header, 0, $pos); $value = trim(substr($header, $pos + 1)); if (isset($responseHeaders[$name])) { if (!is_array($responseHeaders[$name])) { - $responseHeaders[$name] = array($responseHeaders[$name], $value); + $responseHeaders[$name] = [$responseHeaders[$name], $value]; } else { $responseHeaders[$name][] = $value; } @@ -127,21 +127,21 @@ EOD; } /** @var \yii\web\Session $session */ $session = Yii::$app->getComponent('session', false); - return array( - 'flashes' => $session ? $session->getAllFlashes() : array(), + return [ + 'flashes' => $session ? $session->getAllFlashes() : [], 'statusCode' => Yii::$app->getResponse()->getStatusCode(), 'requestHeaders' => $requestHeaders, 'responseHeaders' => $responseHeaders, 'route' => Yii::$app->requestedAction ? Yii::$app->requestedAction->getUniqueId() : Yii::$app->requestedRoute, 'action' => $action, 'actionParams' => Yii::$app->requestedParams, - 'SERVER' => empty($_SERVER) ? array() : $_SERVER, - 'GET' => empty($_GET) ? array() : $_GET, - 'POST' => empty($_POST) ? array() : $_POST, - 'COOKIE' => empty($_COOKIE) ? array() : $_COOKIE, - 'FILES' => empty($_FILES) ? array() : $_FILES, - 'SESSION' => empty($_SESSION) ? array() : $_SESSION, - ); + 'SERVER' => empty($_SERVER) ? [] : $_SERVER, + 'GET' => empty($_GET) ? [] : $_GET, + 'POST' => empty($_POST) ? [] : $_POST, + 'COOKIE' => empty($_COOKIE) ? [] : $_COOKIE, + 'FILES' => empty($_FILES) ? [] : $_FILES, + 'SESSION' => empty($_SESSION) ? [] : $_SESSION, + ]; } protected function renderData($caption, $values) @@ -149,7 +149,7 @@ EOD; if (empty($values)) { return "

    $caption

    \n

    Empty.

    "; } - $rows = array(); + $rows = []; foreach ($values as $name => $value) { $rows[] = '' . Html::encode($name) . '' . htmlspecialchars(var_export($value, true), ENT_QUOTES|ENT_SUBSTITUTE, \Yii::$app->charset, TRUE) . ''; } diff --git a/framework/yii/debug/views/default/index.php b/framework/yii/debug/views/default/index.php index 5630e80..325267d 100644 --- a/framework/yii/debug/views/default/index.php +++ b/framework/yii/debug/views/default/index.php @@ -32,7 +32,7 @@ $this->title = 'Yii Debugger'; $data): ?> - $tag)); ?> + $tag]); ?> diff --git a/framework/yii/debug/views/default/view.php b/framework/yii/debug/views/default/view.php index a455008..8fe7199 100644 --- a/framework/yii/debug/views/default/view.php +++ b/framework/yii/debug/views/default/view.php @@ -32,9 +32,9 @@ $this->title = 'Yii Debugger'; $panel) { $label = '' . Html::encode($panel->getName()); - echo Html::a($label, array('view', 'tag' => $tag, 'panel' => $id), array( + echo Html::a($label, ['view', 'tag' => $tag, 'panel' => $id], [ 'class' => $panel === $activePanel ? 'list-group-item active' : 'list-group-item', - )); + ]); } ?> @@ -43,30 +43,30 @@ $this->title = 'Yii Debugger';
    $meta['tag'], 'panel' => $activePanel->id); - $items[] = array( + $url = ['view', 'tag' => $meta['tag'], 'panel' => $activePanel->id]; + $items[] = [ 'label' => $label, 'url' => $url, - ); + ]; if (++$count >= 10) { break; } } - echo ButtonGroup::widget(array( - 'buttons' => array( - Html::a('All', array('index'), array('class' => 'btn btn-default')), - ButtonDropdown::widget(array( + echo ButtonGroup::widget([ + 'buttons' => [ + Html::a('All', ['index'], ['class' => 'btn btn-default']), + ButtonDropdown::widget([ 'label' => 'Last 10', - 'options' => array('class' => 'btn-default'), - 'dropdown' => array('items' => $items), - )), - ), - )); + 'options' => ['class' => 'btn-default'], + 'dropdown' => ['items' => $items], + ]), + ], + ]); echo "\n" . $summary['tag'] . ': ' . $summary['method'] . ' ' . Html::a(Html::encode($summary['url']), $summary['url']); echo ' at ' . date('Y-m-d h:i:s a', $summary['time']) . ' by ' . $summary['ip']; ?> diff --git a/framework/yii/gii/CodeFile.php b/framework/yii/gii/CodeFile.php index 2f21b4c..2676c38 100644 --- a/framework/yii/gii/CodeFile.php +++ b/framework/yii/gii/CodeFile.php @@ -62,7 +62,7 @@ class CodeFile extends Object */ public function __construct($path, $content) { - $this->path = strtr($path, array('/' => DIRECTORY_SEPARATOR, '\\' => DIRECTORY_SEPARATOR)); + $this->path = strtr($path, ['/' => DIRECTORY_SEPARATOR, '\\' => DIRECTORY_SEPARATOR]); $this->content = $content; $this->id = md5($this->path); if (is_file($path)) { @@ -134,7 +134,7 @@ class CodeFile extends Object if ($type === 'php') { return highlight_string($this->content, true); - } elseif (!in_array($type, array('jpg', 'gif', 'png', 'exe'))) { + } elseif (!in_array($type, ['jpg', 'gif', 'png', 'exe'])) { return nl2br(Html::encode($this->content)); } else { return false; @@ -144,7 +144,7 @@ class CodeFile extends Object public function diff() { $type = strtolower($this->getType()); - if (in_array($type, array('jpg', 'gif', 'png', 'exe'))) { + if (in_array($type, ['jpg', 'gif', 'png', 'exe'])) { return false; } elseif ($this->operation === self::OP_OVERWRITE) { return StringHelper::diff(file($this->path), $this->content); diff --git a/framework/yii/gii/Generator.php b/framework/yii/gii/Generator.php index eb5b8b4..5c74567 100644 --- a/framework/yii/gii/Generator.php +++ b/framework/yii/gii/Generator.php @@ -42,7 +42,7 @@ abstract class Generator extends Model * @var array a list of available code templates. The array keys are the template names, * and the array values are the corresponding template paths or path aliases. */ - public $templates = array(); + public $templates = []; /** * @var string the name of the code template that the user has selected. * The value of this property is internally managed by this class. @@ -85,7 +85,7 @@ abstract class Generator extends Model */ public function requiredTemplates() { - return array(); + return []; } /** @@ -96,7 +96,7 @@ abstract class Generator extends Model */ public function stickyAttributes() { - return array('template'); + return ['template']; } /** @@ -107,7 +107,7 @@ abstract class Generator extends Model */ public function hints() { - return array(); + return []; } /** @@ -159,17 +159,17 @@ abstract class Generator extends Model * rules are included: * * ~~~ - * return array_merge(parent::rules(), array( + * return array_merge(parent::rules(), [ * ...rules for the child class... - * )); + * ]); * ~~~ */ public function rules() { - return array( - array('template', 'required', 'message' => 'A code template must be selected.'), - array('template', 'validateTemplate'), - ); + return [ + ['template', 'required', 'message' => 'A code template must be selected.'], + ['template', 'validateTemplate'], + ]; } /** @@ -201,7 +201,7 @@ abstract class Generator extends Model { $stickyAttributes = $this->stickyAttributes(); $stickyAttributes[] = 'template'; - $values = array(); + $values = []; foreach ($stickyAttributes as $name) { $values[$name] = $this->$name; } @@ -229,7 +229,7 @@ abstract class Generator extends Model */ public function save($files, $answers, &$results) { - $lines = array('Generating code using template "' . $this->getTemplatePath() . '"...'); + $lines = ['Generating code using template "' . $this->getTemplatePath() . '"...']; $hasError = false; foreach ($files as $file) { $relativePath = $file->getRelativePath(); @@ -272,7 +272,7 @@ abstract class Generator extends Model * @param array $params list of parameters to be passed to the template file. * @return string the generated code */ - public function render($template, $params = array()) + public function render($template, $params = []) { $view = new View; $params['generator'] = $this; @@ -352,7 +352,7 @@ abstract class Generator extends Model */ public function isReservedKeyword($value) { - static $keywords = array( + static $keywords = [ '__class__', '__dir__', '__file__', @@ -432,7 +432,7 @@ abstract class Generator extends Model 'var', 'while', 'xor', - ); + ]; return in_array(strtolower($value), $keywords, true); } } diff --git a/framework/yii/gii/GiiAsset.php b/framework/yii/gii/GiiAsset.php index a5fc0d0..26b6412 100644 --- a/framework/yii/gii/GiiAsset.php +++ b/framework/yii/gii/GiiAsset.php @@ -24,21 +24,21 @@ class GiiAsset extends AssetBundle /** * @inheritdoc */ - public $css = array( + public $css = [ 'main.css', - ); + ]; /** * @inheritdoc */ - public $js = array( + public $js = [ 'gii.js', - ); + ]; /** * @inheritdoc */ - public $depends = array( + public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', 'yii\bootstrap\BootstrapPluginAsset', - ); + ]; } diff --git a/framework/yii/gii/Module.php b/framework/yii/gii/Module.php index f82e3dd..ab840a0 100644 --- a/framework/yii/gii/Module.php +++ b/framework/yii/gii/Module.php @@ -16,14 +16,12 @@ use yii\web\HttpException; * To use Gii, include it as a module in the application configuration like the following: * * ~~~ - * return array( + * return [ * ...... - * 'modules' => array( - * 'gii' => array( - * 'class' => 'yii\gii\Module', - * ), - * ), - * ) + * 'modules' => [ + * 'gii' => ['class' => 'yii\gii\Module'], + * ], + * ] * ~~~ * * Because Gii generates new code files on the server, you should only use it on your own @@ -40,12 +38,12 @@ use yii\web\HttpException; * in order to access Gii: * * ~~~ - * 'rules'=>array( + * 'rules' => [ * 'gii' => 'gii', * 'gii/' => 'gii/', * 'gii//' => 'gii//', * ... - * ), + * ], * ~~~ * * You can then access Gii via URL: `http://localhost/path/to/index.php/gii` @@ -63,10 +61,10 @@ class Module extends \yii\base\Module * @var array the list of IPs that are allowed to access this module. * Each array element represents a single IP filter which can be either an IP address * or an address with wildcard (e.g. 192.168.0.*) to represent a network segment. - * The default value is `array('127.0.0.1', '::1')`, which means the module can only be accessed + * The default value is `['127.0.0.1', '::1']`, which means the module can only be accessed * by localhost. */ - public $allowedIPs = array('127.0.0.1', '::1'); + public $allowedIPs = ['127.0.0.1', '::1']; /** * @var array|Generator[] a list of generator configurations or instances. The array keys * are the generator IDs (e.g. "crud"), and the array elements are the corresponding generator @@ -78,7 +76,7 @@ class Module extends \yii\base\Module * Newly assigned generators will be merged with the [[coreGenerators()|core ones]], and the former * takes precedence in case when they have the same generator ID. */ - public $generators = array(); + public $generators = []; /** * @var integer the permission to be set for newly generated code files. * This value will be used by PHP chmod function. @@ -136,22 +134,12 @@ class Module extends \yii\base\Module */ protected function coreGenerators() { - return array( - 'model' => array( - 'class' => 'yii\gii\generators\model\Generator', - ), - 'crud' => array( - 'class' => 'yii\gii\generators\crud\Generator', - ), - 'controller' => array( - 'class' => 'yii\gii\generators\controller\Generator', - ), - 'form' => array( - 'class' => 'yii\gii\generators\form\Generator', - ), - 'module' => array( - 'class' => 'yii\gii\generators\module\Generator', - ), - ); + return [ + 'model' => ['class' => 'yii\gii\generators\model\Generator'], + 'crud' => ['class' => 'yii\gii\generators\crud\Generator'], + 'controller' => ['class' => 'yii\gii\generators\controller\Generator'], + 'form' => ['class' => 'yii\gii\generators\form\Generator'], + 'module' => ['class' => 'yii\gii\generators\module\Generator'], + ]; } } diff --git a/framework/yii/gii/controllers/DefaultController.php b/framework/yii/gii/controllers/DefaultController.php index 305ef35..ef104c3 100644 --- a/framework/yii/gii/controllers/DefaultController.php +++ b/framework/yii/gii/controllers/DefaultController.php @@ -36,7 +36,7 @@ class DefaultController extends Controller public function actionView($id) { $generator = $this->loadGenerator($id); - $params = array('generator' => $generator, 'id' => $id); + $params = ['generator' => $generator, 'id' => $id]; if (isset($_POST['preview']) || isset($_POST['generate'])) { if ($generator->validate()) { $generator->saveStickyAttributes(); @@ -78,9 +78,9 @@ class DefaultController extends Controller if ($generator->validate()) { foreach ($generator->generate() as $f) { if ($f->id === $file) { - return $this->renderPartial('diff', array( + return $this->renderPartial('diff', [ 'diff' => $f->diff(), - )); + ]); } } } @@ -107,7 +107,7 @@ class DefaultController extends Controller } } - public function createUrl($route, $params = array()) + public function createUrl($route, $params = []) { if (!isset($params['id']) && $this->generator !== null) { foreach ($this->module->generators as $id => $generator) { @@ -120,7 +120,7 @@ class DefaultController extends Controller return parent::createUrl($route, $params); } - public function createActionUrl($name, $params = array()) + public function createActionUrl($name, $params = []) { foreach ($this->module->generators as $id => $generator) { if ($generator === $this->generator) { diff --git a/framework/yii/gii/generators/controller/Generator.php b/framework/yii/gii/generators/controller/Generator.php index b7c4095..660ffb4 100644 --- a/framework/yii/gii/generators/controller/Generator.php +++ b/framework/yii/gii/generators/controller/Generator.php @@ -59,14 +59,14 @@ class Generator extends \yii\gii\Generator */ public function rules() { - return array_merge(parent::rules(), array( - array('controller, actions, baseClass, ns', 'filter', 'filter' => 'trim'), - array('controller, baseClass', 'required'), - array('controller', 'match', 'pattern' => '/^[a-z\\-\\/]*$/', 'message' => 'Only a-z, dashes (-) and slashes (/) are allowed.'), - array('actions', 'match', 'pattern' => '/^[a-z\\-,\\s]*$/', 'message' => 'Only a-z, dashes (-), spaces and commas are allowed.'), - array('baseClass', 'match', 'pattern' => '/^[\w\\\\]*$/', 'message' => 'Only word characters and backslashes are allowed.'), - array('ns', 'match', 'pattern' => '/^[\w\\\\]*$/', 'message' => 'Only word characters and backslashes are allowed.'), - )); + return array_merge(parent::rules(), [ + ['controller, actions, baseClass, ns', 'filter', 'filter' => 'trim'], + ['controller, baseClass', 'required'], + ['controller', 'match', 'pattern' => '/^[a-z\\-\\/]*$/', 'message' => 'Only a-z, dashes (-) and slashes (/) are allowed.'], + ['actions', 'match', 'pattern' => '/^[a-z\\-,\\s]*$/', 'message' => 'Only a-z, dashes (-), spaces and commas are allowed.'], + ['baseClass', 'match', 'pattern' => '/^[\w\\\\]*$/', 'message' => 'Only word characters and backslashes are allowed.'], + ['ns', 'match', 'pattern' => '/^[\w\\\\]*$/', 'message' => 'Only word characters and backslashes are allowed.'], + ]); } /** @@ -74,12 +74,12 @@ class Generator extends \yii\gii\Generator */ public function attributeLabels() { - return array( + return [ 'baseClass' => 'Base Class', 'controller' => 'Controller ID', 'actions' => 'Action IDs', 'ns' => 'Controller Namespace', - ); + ]; } /** @@ -87,10 +87,10 @@ class Generator extends \yii\gii\Generator */ public function requiredTemplates() { - return array( + return [ 'controller.php', 'view.php', - ); + ]; } /** @@ -98,7 +98,7 @@ class Generator extends \yii\gii\Generator */ public function stickyAttributes() { - return array('ns', 'baseClass'); + return ['ns', 'baseClass']; } /** @@ -106,7 +106,7 @@ class Generator extends \yii\gii\Generator */ public function hints() { - return array( + return [ 'controller' => 'Controller ID should be in lower case and may contain module ID(s) separated by slashes. For example:
    • order generates OrderController.php
    • @@ -121,7 +121,7 @@ class Generator extends \yii\gii\Generator
    ', 'ns' => 'This is the namespace that the new controller class will use.', 'baseClass' => 'This is the class that the new controller class will extend from. Please make sure the class exists and can be autoloaded.', - ); + ]; } /** @@ -135,7 +135,7 @@ class Generator extends \yii\gii\Generator } else { $route = $this->controller . '/' . reset($actions); } - $link = Html::a('try it now', Yii::$app->getUrlManager()->createUrl($route), array('target' => '_blank')); + $link = Html::a('try it now', Yii::$app->getUrlManager()->createUrl($route), ['target' => '_blank']); return "The controller has been generated successfully. You may $link."; } @@ -144,7 +144,7 @@ class Generator extends \yii\gii\Generator */ public function generate() { - $files = array(); + $files = []; $files[] = new CodeFile( $this->getControllerFile(), @@ -154,7 +154,7 @@ class Generator extends \yii\gii\Generator foreach ($this->getActionIDs() as $action) { $files[] = new CodeFile( $this->getViewFile($action), - $this->render('view.php', array('action' => $action)) + $this->render('view.php', ['action' => $action]) ); } diff --git a/framework/yii/gii/generators/crud/Generator.php b/framework/yii/gii/generators/crud/Generator.php index 9bce7ff..ae59102 100644 --- a/framework/yii/gii/generators/crud/Generator.php +++ b/framework/yii/gii/generators/crud/Generator.php @@ -42,30 +42,30 @@ class Generator extends \yii\gii\Generator public function rules() { - return array_merge(parent::rules(), array( - array('moduleID, controllerClass, modelClass, searchModelClass, baseControllerClass', 'filter', 'filter' => 'trim'), - array('modelClass, searchModelClass, controllerClass, baseControllerClass, indexWidgetType', 'required'), - array('modelClass, controllerClass, baseControllerClass, searchModelClass', 'match', 'pattern' => '/^[\w\\\\]*$/', 'message' => 'Only word characters and backslashes are allowed.'), - array('modelClass', 'validateClass', 'params' => array('extends' => ActiveRecord::className())), - array('baseControllerClass', 'validateClass', 'params' => array('extends' => Controller::className())), - array('controllerClass', 'match', 'pattern' => '/Controller$/', 'message' => 'Controller class name must be suffixed with "Controller".'), - array('controllerClass, searchModelClass', 'validateNewClass'), - array('indexWidgetType', 'in', 'range' => array('grid', 'list')), - array('modelClass', 'validateModelClass'), - array('moduleID', 'validateModuleID'), - )); + return array_merge(parent::rules(), [ + ['moduleID, controllerClass, modelClass, searchModelClass, baseControllerClass', 'filter', 'filter' => 'trim'], + ['modelClass, searchModelClass, controllerClass, baseControllerClass, indexWidgetType', 'required'], + ['modelClass, controllerClass, baseControllerClass, searchModelClass', 'match', 'pattern' => '/^[\w\\\\]*$/', 'message' => 'Only word characters and backslashes are allowed.'], + ['modelClass', 'validateClass', 'params' => ['extends' => ActiveRecord::className()]], + ['baseControllerClass', 'validateClass', 'params' => ['extends' => Controller::className()]], + ['controllerClass', 'match', 'pattern' => '/Controller$/', 'message' => 'Controller class name must be suffixed with "Controller".'], + ['controllerClass, searchModelClass', 'validateNewClass'], + ['indexWidgetType', 'in', 'range' => ['grid', 'list']], + ['modelClass', 'validateModelClass'], + ['moduleID', 'validateModuleID'], + ]); } public function attributeLabels() { - return array_merge(parent::attributeLabels(), array( + return array_merge(parent::attributeLabels(), [ 'modelClass' => 'Model Class', 'moduleID' => 'Module ID', 'controllerClass' => 'Controller Class', 'baseControllerClass' => 'Base Controller Class', 'indexWidgetType' => 'Widget Used in Index Page', 'searchModelClass' => 'Search Model Class', - )); + ]); } /** @@ -73,7 +73,7 @@ class Generator extends \yii\gii\Generator */ public function hints() { - return array( + return [ 'modelClass' => 'This is the ActiveRecord class associated with the table that CRUD will be built upon. You should provide a fully qualified class name, e.g., app\models\Post.', 'controllerClass' => 'This is the name of the controller class to be generated. You should @@ -86,14 +86,12 @@ class Generator extends \yii\gii\Generator You may choose either GridView or ListView', 'searchModelClass' => 'This is the class representing the data being collecting in the search form. A fully qualified namespaced class name is required, e.g., app\models\search\PostSearch.', - ); + ]; } public function requiredTemplates() { - return array( - 'controller.php', - ); + return ['controller.php']; } /** @@ -101,7 +99,7 @@ class Generator extends \yii\gii\Generator */ public function stickyAttributes() { - return array('baseControllerClass', 'moduleID', 'indexWidgetType'); + return ['baseControllerClass', 'moduleID', 'indexWidgetType']; } public function validateModelClass() @@ -131,10 +129,10 @@ class Generator extends \yii\gii\Generator { $controllerFile = Yii::getAlias('@' . str_replace('\\', '/', ltrim($this->controllerClass, '\\')) . '.php'); $searchModel = Yii::getAlias('@' . str_replace('\\', '/', ltrim($this->searchModelClass, '\\') . '.php')); - $files = array( + $files = [ new CodeFile($controllerFile, $this->render('controller.php')), new CodeFile($searchModel, $this->render('search.php')), - ); + ]; $viewPath = $this->getViewPath(); $templatePath = $this->getTemplatePath() . '/views'; @@ -194,7 +192,7 @@ class Generator extends \yii\gii\Generator if ($column->phpType === 'boolean') { return "\$form->field(\$model, '$attribute')->checkbox();"; } elseif ($column->type === 'text') { - return "\$form->field(\$model, '$attribute')->textarea(array('rows' => 6));"; + return "\$form->field(\$model, '$attribute')->textarea(['rows' => 6]);"; } else { if (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name)) { $input = 'passwordInput'; @@ -204,7 +202,7 @@ class Generator extends \yii\gii\Generator if ($column->phpType !== 'string' || $column->size === null) { return "\$form->field(\$model, '$attribute')->$input();"; } else { - return "\$form->field(\$model, '$attribute')->$input(array('maxlength' => $column->size));"; + return "\$form->field(\$model, '$attribute')->$input(['maxlength' => $column->size]);"; } } } @@ -252,7 +250,7 @@ class Generator extends \yii\gii\Generator public function generateSearchRules() { $table = $this->getTableSchema(); - $types = array(); + $types = []; foreach ($table->columns as $column) { switch ($column->type) { case Schema::TYPE_SMALLINT: @@ -278,9 +276,9 @@ class Generator extends \yii\gii\Generator } } - $rules = array(); + $rules = []; foreach ($types as $type => $columns) { - $rules[] = "array('" . implode(', ', $columns) . "', '$type')"; + $rules[] = "['" . implode(', ', $columns) . "', '$type']"; } return $rules; @@ -298,7 +296,7 @@ class Generator extends \yii\gii\Generator public function generateSearchLabels() { $table = $this->getTableSchema(); - $labels = array(); + $labels = []; foreach ($table->columns as $column) { if (!strcasecmp($column->name, 'id')) { $labels[$column->name] = 'ID'; @@ -316,7 +314,7 @@ class Generator extends \yii\gii\Generator public function generateSearchConditions() { $table = $this->getTableSchema(); - $conditions = array(); + $conditions = []; foreach ($table->columns as $column) { switch ($column->type) { case Schema::TYPE_SMALLINT: @@ -347,7 +345,7 @@ class Generator extends \yii\gii\Generator if (count($pks) === 1) { return "'id' => \$model->{$pks[0]}"; } else { - $params = array(); + $params = []; foreach ($pks as $pk) { $params[] = "'$pk' => \$model->$pk"; } @@ -370,9 +368,9 @@ class Generator extends \yii\gii\Generator $table = $this->getTableSchema(); $pks = $table->primaryKey; if (count($pks) === 1) { - return array('@param ' . $table->columns[$pks[0]]->phpType . ' $id'); + return ['@param ' . $table->columns[$pks[0]]->phpType . ' $id']; } else { - $params = array(); + $params = []; foreach ($pks as $pk) { $params[] = '@param ' . $table->columns[$pk]->phpType . ' $' . $pk; } diff --git a/framework/yii/gii/generators/crud/form.php b/framework/yii/gii/generators/crud/form.php index 829b8a3..fd7df05 100644 --- a/framework/yii/gii/generators/crud/form.php +++ b/framework/yii/gii/generators/crud/form.php @@ -10,7 +10,7 @@ echo $form->field($generator, 'searchModelClass'); echo $form->field($generator, 'controllerClass'); echo $form->field($generator, 'baseControllerClass'); echo $form->field($generator, 'moduleID'); -echo $form->field($generator, 'indexWidgetType')->dropDownList(array( +echo $form->field($generator, 'indexWidgetType')->dropDownList([ 'grid' => 'GridView', 'list' => 'ListView', -)); +]); diff --git a/framework/yii/gii/generators/crud/templates/controller.php b/framework/yii/gii/generators/crud/templates/controller.php index c992b81..0aaead6 100644 --- a/framework/yii/gii/generators/crud/templates/controller.php +++ b/framework/yii/gii/generators/crud/templates/controller.php @@ -37,14 +37,14 @@ class extends base { public function behaviors() { - return array( - 'verbs' => array( + return [ + 'verbs' => [ 'class' => VerbFilter::className(), - 'actions' => array( - 'delete' => array('post'), - ), - ), - ); + 'actions' => [ + 'delete' => ['post'], + ], + ], + ]; } /** @@ -56,10 +56,10 @@ class extends base $searchModel = new ; $dataProvider = $searchModel->search($_GET); - return $this->render('index', array( + return $this->render('index', [ 'dataProvider' => $dataProvider, 'searchModel' => $searchModel, - )); + ]); } /** @@ -69,9 +69,9 @@ class extends base */ public function actionView() { - return $this->render('view', array( + return $this->render('view', [ 'model' => $this->findModel(), - )); + ]); } /** @@ -84,11 +84,11 @@ class extends base $model = new ; if ($model->load($_POST) && $model->save()) { - return $this->redirect(array('view', )); + return $this->redirect(['view', ]); } else { - return $this->render('create', array( + return $this->render('create', [ 'model' => $model, - )); + ]); } } @@ -103,11 +103,11 @@ class extends base $model = $this->findModel(); if ($model->load($_POST) && $model->save()) { - return $this->redirect(array('view', )); + return $this->redirect(['view', ]); } else { - return $this->render('update', array( + return $this->render('update', [ 'model' => $model, - )); + ]); } } @@ -120,7 +120,7 @@ class extends base public function actionDelete() { $this->findModel()->delete(); - return $this->redirect(array('index')); + return $this->redirect(['index']); } /** @@ -136,11 +136,11 @@ class extends base if (count($pks) === 1) { $condition = '$id'; } else { - $condition = array(); + $condition = []; foreach ($pks as $pk) { $condition[] = "'$pk' => \$$pk"; } - $condition = 'array(' . implode(', ', $condition) . ')'; + $condition = '[' . implode(', ', $condition) . ']'; } ?> if (($model = ::find()) !== null) { diff --git a/framework/yii/gii/generators/crud/templates/search.php b/framework/yii/gii/generators/crud/templates/search.php index a3caf83..cd8e156 100644 --- a/framework/yii/gii/generators/crud/templates/search.php +++ b/framework/yii/gii/generators/crud/templates/search.php @@ -34,9 +34,9 @@ class extends Model public function rules() { - return array( + return [ , - ); + ]; } /** @@ -44,19 +44,19 @@ class extends Model */ public function attributeLabels() { - return array( + return [ $label): ?> '" . addslashes($label) . "',\n"; ?> - ); + ]; } public function search($params) { $query = ::find(); - $dataProvider = new ActiveDataProvider(array( + $dataProvider = new ActiveDataProvider([ 'query' => $query, - )); + ]); if (!($this->load($params) && $this->validate())) { return $dataProvider; @@ -74,10 +74,10 @@ class extends Model return; } if ($partialMatch) { - $value = '%' . strtr($value, array('%'=>'\%', '_'=>'\_', '\\'=>'\\\\')) . '%'; - $query->andWhere(array('like', $attribute, $value)); + $value = '%' . strtr($value, ['%'=>'\%', '_'=>'\_', '\\'=>'\\\\']) . '%'; + $query->andWhere(['like', $attribute, $value]); } else { - $query->andWhere(array($attribute => $value)); + $query->andWhere([$attribute => $value]); } } } diff --git a/framework/yii/gii/generators/crud/templates/views/_form.php b/framework/yii/gii/generators/crud/templates/views/_form.php index 7e092c1..024006e 100644 --- a/framework/yii/gii/generators/crud/templates/views/_form.php +++ b/framework/yii/gii/generators/crud/templates/views/_form.php @@ -36,7 +36,7 @@ use yii\widgets\ActiveForm; echo "\t\tgenerateActiveField($attribute) . " ?>\n\n"; } ?>
    - echo Html::submitButton($model->isNewRecord ? 'Create' : 'Update', array('class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary')); ?> + echo Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']); ?>
    ActiveForm::end(); ?> diff --git a/framework/yii/gii/generators/crud/templates/views/_search.php b/framework/yii/gii/generators/crud/templates/views/_search.php index 263fbd0..14bd1af 100644 --- a/framework/yii/gii/generators/crud/templates/views/_search.php +++ b/framework/yii/gii/generators/crud/templates/views/_search.php @@ -23,10 +23,10 @@ use yii\widgets\ActiveForm; diff --git a/framework/yii/gii/generators/crud/templates/views/update.php b/framework/yii/gii/generators/crud/templates/views/update.php index 8518490..0b881ec 100644 --- a/framework/yii/gii/generators/crud/templates/views/update.php +++ b/framework/yii/gii/generators/crud/templates/views/update.php @@ -21,16 +21,16 @@ use yii\helpers\Html; */ $this->title = 'Update modelClass)); ?>: ' . $model->getNameAttribute(); ?>; -$this->params['breadcrumbs'][] = array('label' => 'modelClass))); ?>', 'url' => array('index')); -$this->params['breadcrumbs'][] = array('label' => $model->getNameAttribute(); ?>, 'url' => array('view', )); +$this->params['breadcrumbs'][] = ['label' => 'modelClass))); ?>', 'url' => ['index']]; +$this->params['breadcrumbs'][] = ['label' => $model->getNameAttribute(); ?>, 'url' => ['view', ]]; $this->params['breadcrumbs'][] = 'Update'; ?>

    echo Html::encode($this->title); ?>

    - echo $this->render('_form', array( + echo $this->render('_form', [ 'model' => $model, - )); ?> + ]); ?>
    diff --git a/framework/yii/gii/generators/crud/templates/views/view.php b/framework/yii/gii/generators/crud/templates/views/view.php index 18821af..9e8f28d 100644 --- a/framework/yii/gii/generators/crud/templates/views/view.php +++ b/framework/yii/gii/generators/crud/templates/views/view.php @@ -22,7 +22,7 @@ use yii\widgets\DetailView; */ $this->title = $model->getNameAttribute(); ?>; -$this->params['breadcrumbs'][] = array('label' => 'modelClass))); ?>', 'url' => array('index')); +$this->params['breadcrumbs'][] = ['label' => 'modelClass))); ?>', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?>
    @@ -30,24 +30,24 @@ $this->params['breadcrumbs'][] = $this->title;

    echo Html::encode($this->title); ?>

    - echo Html::a('Update', array('update', ), array('class' => 'btn btn-primary')); ?> - echo Html::a('Delete', array('delete', ), array( + echo Html::a('Update', ['update', ], ['class' => 'btn btn-primary']); ?> + echo Html::a('Delete', ['delete', ], [ 'class' => 'btn btn-danger', 'data-confirm' => Yii::t('app', 'Are you sure to delete this item?'), 'data-method' => 'post', - )); ?> + ]); ?>

    - echo DetailView::widget(array( + echo DetailView::widget([ 'model' => $model, - 'attributes' => array( + 'attributes' => [ getTableSchema()->columns as $column) { $format = $generator->generateColumnFormat($column); echo "\t\t\t'" . $column->name . ($format === 'text' ? '' : ':' . $format) . "',\n"; } ?> - ), - )); ?> + ], + ]); ?>
    diff --git a/framework/yii/gii/generators/form/Generator.php b/framework/yii/gii/generators/form/Generator.php index b0edb2a..749f9d8 100644 --- a/framework/yii/gii/generators/form/Generator.php +++ b/framework/yii/gii/generators/form/Generator.php @@ -46,7 +46,7 @@ class Generator extends \yii\gii\Generator */ public function generate() { - $files = array(); + $files = []; $files[] = new CodeFile( Yii::getAlias($this->viewPath) . '/' . $this->viewName . '.php', $this->render('form.php') @@ -59,16 +59,16 @@ class Generator extends \yii\gii\Generator */ public function rules() { - return array_merge(parent::rules(), array( - array('modelClass, viewName, scenarioName, viewPath', 'filter', 'filter' => 'trim'), - array('modelClass, viewName, viewPath', 'required'), - array('modelClass', 'match', 'pattern' => '/^[\w\\\\]*$/', 'message' => 'Only word characters and backslashes are allowed.'), - array('modelClass', 'validateClass', 'params' => array('extends' => Model::className())), - array('viewName', 'match', 'pattern' => '/^\w+[\\-\\/\w]*$/', 'message' => 'Only word characters, dashes and slashes are allowed.'), - array('viewPath', 'match', 'pattern' => '/^@?\w+[\\-\\/\w]*$/', 'message' => 'Only word characters, dashes, slashes and @ are allowed.'), - array('viewPath', 'validateViewPath'), - array('scenarioName', 'match', 'pattern' => '/^[\w\\-]+$/', 'message' => 'Only word characters and dashes are allowed.'), - )); + return array_merge(parent::rules(), [ + ['modelClass, viewName, scenarioName, viewPath', 'filter', 'filter' => 'trim'], + ['modelClass, viewName, viewPath', 'required'], + ['modelClass', 'match', 'pattern' => '/^[\w\\\\]*$/', 'message' => 'Only word characters and backslashes are allowed.'], + ['modelClass', 'validateClass', 'params' => ['extends' => Model::className()]], + ['viewName', 'match', 'pattern' => '/^\w+[\\-\\/\w]*$/', 'message' => 'Only word characters, dashes and slashes are allowed.'], + ['viewPath', 'match', 'pattern' => '/^@?\w+[\\-\\/\w]*$/', 'message' => 'Only word characters, dashes, slashes and @ are allowed.'], + ['viewPath', 'validateViewPath'], + ['scenarioName', 'match', 'pattern' => '/^[\w\\-]+$/', 'message' => 'Only word characters and dashes are allowed.'], + ]); } /** @@ -76,12 +76,12 @@ class Generator extends \yii\gii\Generator */ public function attributeLabels() { - return array( + return [ 'modelClass' => 'Model Class', 'viewName' => 'View Name', 'viewPath' => 'View Path', 'scenarioName' => 'Scenario', - ); + ]; } /** @@ -89,10 +89,7 @@ class Generator extends \yii\gii\Generator */ public function requiredTemplates() { - return array( - 'form.php', - 'action.php', - ); + return ['form.php', 'action.php']; } /** @@ -100,7 +97,7 @@ class Generator extends \yii\gii\Generator */ public function stickyAttributes() { - return array('viewPath', 'scenarioName'); + return ['viewPath', 'scenarioName']; } /** @@ -108,12 +105,12 @@ class Generator extends \yii\gii\Generator */ public function hints() { - return array( + return [ 'modelClass' => 'This is the model class for collecting the form input. You should provide a fully qualified class name, e.g., app\models\Post.', 'viewName' => 'This is the view name with respect to the view path. For example, site/index would generate a site/index.php view file under the view path.', 'viewPath' => 'This is the root view path to keep the generated view files. You may provide either a directory or a path alias, e.g., @app/views.', 'scenarioName' => 'This is the scenario to be used by the model when collecting the form input. If empty, the default scenario will be used.', - ); + ]; } /** diff --git a/framework/yii/gii/generators/form/templates/action.php b/framework/yii/gii/generators/form/templates/action.php index 0d1adac..184c60f 100644 --- a/framework/yii/gii/generators/form/templates/action.php +++ b/framework/yii/gii/generators/form/templates/action.php @@ -14,7 +14,7 @@ echo "viewName), '_')); ?>() { - $model = new modelClass; ?>scenarioName) ? '' : "(array('scenario' => '{$generator->scenarioName}'))"; ?>; + $model = new modelClass; ?>scenarioName) ? '' : "(['scenario' => '{$generator->scenarioName}'])"; ?>; if ($model->load($_POST)) { if($model->validate()) { @@ -22,7 +22,7 @@ public function actionviewName) return; } } - return $this->render('viewName; ?>', array( + return $this->render('viewName; ?>', [ 'model' => $model, - )); + ]); } diff --git a/framework/yii/gii/generators/form/templates/form.php b/framework/yii/gii/generators/form/templates/form.php index 7569fc0..f365ebc 100644 --- a/framework/yii/gii/generators/form/templates/form.php +++ b/framework/yii/gii/generators/form/templates/form.php @@ -28,7 +28,7 @@ use yii\widgets\ActiveForm;
    - echo Html::submitButton('Submit', array('class' => 'btn btn-primary')); ?> + echo Html::submitButton('Submit', ['class' => 'btn btn-primary']); ?>
    ActiveForm::end(); ?> diff --git a/framework/yii/gii/generators/model/Generator.php b/framework/yii/gii/generators/model/Generator.php index 69edb5f..de9cc2f 100644 --- a/framework/yii/gii/generators/model/Generator.php +++ b/framework/yii/gii/generators/model/Generator.php @@ -52,19 +52,19 @@ class Generator extends \yii\gii\Generator */ public function rules() { - return array_merge(parent::rules(), array( - array('db, ns, tableName, modelClass, baseClass', 'filter', 'filter' => 'trim'), - array('db, ns, tableName, baseClass', 'required'), - array('db, modelClass', 'match', 'pattern' => '/^\w+$/', 'message' => 'Only word characters are allowed.'), - array('ns, baseClass', 'match', 'pattern' => '/^[\w\\\\]+$/', 'message' => 'Only word characters and backslashes are allowed.'), - array('tableName', 'match', 'pattern' => '/^(\w+\.)?([\w\*]+)$/', 'message' => 'Only word characters, and optionally an asterisk and/or a dot are allowed.'), - array('db', 'validateDb'), - array('ns', 'validateNamespace'), - array('tableName', 'validateTableName'), - array('modelClass', 'validateModelClass'), - array('baseClass', 'validateClass', 'params' => array('extends' => ActiveRecord::className())), - array('generateRelations, generateLabelsFromComments', 'boolean'), - )); + return array_merge(parent::rules(), [ + ['db, ns, tableName, modelClass, baseClass', 'filter', 'filter' => 'trim'], + ['db, ns, tableName, baseClass', 'required'], + ['db, modelClass', 'match', 'pattern' => '/^\w+$/', 'message' => 'Only word characters are allowed.'], + ['ns, baseClass', 'match', 'pattern' => '/^[\w\\\\]+$/', 'message' => 'Only word characters and backslashes are allowed.'], + ['tableName', 'match', 'pattern' => '/^(\w+\.)?([\w\*]+)$/', 'message' => 'Only word characters, and optionally an asterisk and/or a dot are allowed.'], + ['db', 'validateDb'], + ['ns', 'validateNamespace'], + ['tableName', 'validateTableName'], + ['modelClass', 'validateModelClass'], + ['baseClass', 'validateClass', 'params' => ['extends' => ActiveRecord::className()]], + ['generateRelations, generateLabelsFromComments', 'boolean'], + ]); } /** @@ -72,7 +72,7 @@ class Generator extends \yii\gii\Generator */ public function attributeLabels() { - return array( + return [ 'ns' => 'Namespace', 'db' => 'Database Connection ID', 'tableName' => 'Table Name', @@ -80,7 +80,7 @@ class Generator extends \yii\gii\Generator 'baseClass' => 'Base Class', 'generateRelations' => 'Generate Relations', 'generateLabelsFromComments' => 'Generate Labels from DB Comments', - ); + ]; } /** @@ -88,7 +88,7 @@ class Generator extends \yii\gii\Generator */ public function hints() { - return array( + return [ 'ns' => 'This is the namespace of the ActiveRecord class to be generated, e.g., app\models', 'db' => 'This is the ID of the DB application component.', 'tableName' => 'This is the name of the DB table that the new ActiveRecord class is associated with, e.g. tbl_post. @@ -107,7 +107,7 @@ class Generator extends \yii\gii\Generator you may want to uncheck this option to accelerate the code generation proc ess.', 'generateLabelsFromComments' => 'This indicates whether the generator should generate attribute labels by using the comments of the corresponding DB columns.', - ); + ]; } /** @@ -115,9 +115,7 @@ class Generator extends \yii\gii\Generator */ public function requiredTemplates() { - return array( - 'model.php', - ); + return ['model.php']; } /** @@ -125,7 +123,7 @@ class Generator extends \yii\gii\Generator */ public function stickyAttributes() { - return array('ns', 'db', 'baseClass', 'generateRelations', 'generateLabelsFromComments'); + return ['ns', 'db', 'baseClass', 'generateRelations', 'generateLabelsFromComments']; } /** @@ -133,20 +131,20 @@ class Generator extends \yii\gii\Generator */ public function generate() { - $files = array(); + $files = []; $relations = $this->generateRelations(); $db = $this->getDbConnection(); foreach ($this->getTableNames() as $tableName) { $className = $this->generateClassName($tableName); $tableSchema = $db->getTableSchema($tableName); - $params = array( + $params = [ 'tableName' => $tableName, 'className' => $className, 'tableSchema' => $tableSchema, 'labels' => $this->generateLabels($tableSchema), 'rules' => $this->generateRules($tableSchema), - 'relations' => isset($relations[$className]) ? $relations[$className] : array(), - ); + 'relations' => isset($relations[$className]) ? $relations[$className] : [], + ]; $files[] = new CodeFile( Yii::getAlias('@' . str_replace('\\', '/', $this->ns)) . '/' . $className . '.php', $this->render('model.php', $params) @@ -163,7 +161,7 @@ class Generator extends \yii\gii\Generator */ public function generateLabels($table) { - $labels = array(); + $labels = []; foreach ($table->columns as $column) { if ($this->generateLabelsFromComments && !empty($column->comment)) { $labels[$column->name] = $column->comment; @@ -187,8 +185,8 @@ class Generator extends \yii\gii\Generator */ public function generateRules($table) { - $types = array(); - $lengths = array(); + $types = []; + $lengths = []; foreach ($table->columns as $column) { if ($column->autoIncrement) { continue; @@ -225,12 +223,12 @@ class Generator extends \yii\gii\Generator } } - $rules = array(); + $rules = []; foreach ($types as $type => $columns) { - $rules[] = "array('" . implode(', ', $columns) . "', '$type')"; + $rules[] = "['" . implode(', ', $columns) . "', '$type']"; } foreach ($lengths as $length => $columns) { - $rules[] = "array('" . implode(', ', $columns) . "', 'string', 'max' => $length)"; + $rules[] = "['" . implode(', ', $columns) . "', 'string', 'max' => $length]"; } return $rules; @@ -242,7 +240,7 @@ class Generator extends \yii\gii\Generator protected function generateRelations() { if (!$this->generateRelations) { - return array(); + return []; } $db = $this->getDbConnection(); @@ -253,7 +251,7 @@ class Generator extends \yii\gii\Generator $schemaName = ''; } - $relations = array(); + $relations = []; foreach ($db->getSchema()->getTableSchemas($schemaName) as $table) { $tableName = $table->name; $className = $this->generateClassName($tableName); @@ -266,11 +264,11 @@ class Generator extends \yii\gii\Generator // Add relation for this table $link = $this->generateRelationLink(array_flip($refs)); $relationName = $this->generateRelationName($relations, $className, $table, $fks[0], false); - $relations[$className][$relationName] = array( + $relations[$className][$relationName] = [ "return \$this->hasOne('$refClassName', $link);", $refClassName, false, - ); + ]; // Add relation for the referenced table $hasMany = false; @@ -282,11 +280,11 @@ class Generator extends \yii\gii\Generator } $link = $this->generateRelationLink($refs); $relationName = $this->generateRelationName($relations, $refClassName, $refTable, $className, $hasMany); - $relations[$refClassName][$relationName] = array( + $relations[$refClassName][$relationName] = [ "return \$this->" . ($hasMany ? 'hasMany' : 'hasOne') . "('$className', $link);", $className, $hasMany, - ); + ]; } if (($fks = $this->checkPivotTable($table)) === false) { @@ -297,23 +295,23 @@ class Generator extends \yii\gii\Generator $className0 = $this->generateClassName($table0); $className1 = $this->generateClassName($table1); - $link = $this->generateRelationLink(array($fks[$table->primaryKey[1]][1] => $table->primaryKey[1])); - $viaLink = $this->generateRelationLink(array($table->primaryKey[0] => $fks[$table->primaryKey[0]][1])); + $link = $this->generateRelationLink([$fks[$table->primaryKey[1]][1] => $table->primaryKey[1]]); + $viaLink = $this->generateRelationLink([$table->primaryKey[0] => $fks[$table->primaryKey[0]][1]]); $relationName = $this->generateRelationName($relations, $className0, $db->getTableSchema($table0), $table->primaryKey[1], true); - $relations[$className0][$relationName] = array( + $relations[$className0][$relationName] = [ "return \$this->hasMany('$className1', $link)->viaTable('{$table->name}', $viaLink);", $className0, true, - ); + ]; - $link = $this->generateRelationLink(array($fks[$table->primaryKey[0]][1] => $table->primaryKey[0])); - $viaLink = $this->generateRelationLink(array($table->primaryKey[1] => $fks[$table->primaryKey[1]][1])); + $link = $this->generateRelationLink([$fks[$table->primaryKey[0]][1] => $table->primaryKey[0]]); + $viaLink = $this->generateRelationLink([$table->primaryKey[1] => $fks[$table->primaryKey[1]][1]]); $relationName = $this->generateRelationName($relations, $className1, $db->getTableSchema($table1), $table->primaryKey[0], true); - $relations[$className1][$relationName] = array( + $relations[$className1][$relationName] = [ "return \$this->hasMany('$className0', $link)->viaTable('{$table->name}', $viaLink);", $className1, true, - ); + ]; } return $relations; } @@ -325,11 +323,11 @@ class Generator extends \yii\gii\Generator */ protected function generateRelationLink($refs) { - $pairs = array(); + $pairs = []; foreach ($refs as $a => $b) { $pairs[] = "'$a' => '$b'"; } - return 'array(' . implode(', ', $pairs) . ')'; + return '[' . implode(', ', $pairs) . ']'; } /** @@ -346,13 +344,13 @@ class Generator extends \yii\gii\Generator if (count($pk) !== 2) { return false; } - $fks = array(); + $fks = []; foreach ($table->foreignKeys as $refs) { if (count($refs) === 2) { if (isset($refs[$pk[0]])) { - $fks[$pk[0]] = array($refs[0], $refs[$pk[0]]); + $fks[$pk[0]] = [$refs[0], $refs[$pk[0]]]; } elseif (isset($refs[$pk[1]])) { - $fks[$pk[1]] = array($refs[0], $refs[$pk[1]]); + $fks[$pk[1]] = [$refs[0], $refs[$pk[1]]]; } } } @@ -465,9 +463,9 @@ class Generator extends \yii\gii\Generator } $db = $this->getDbConnection(); if ($db === null) { - return array(); + return []; } - $tableNames = array(); + $tableNames = []; if (strpos($this->tableName, '*') !== false) { if (($pos = strrpos($this->tableName, '.')) !== false) { $schema = substr($this->tableName, 0, $pos); @@ -505,7 +503,7 @@ class Generator extends \yii\gii\Generator } $db = $this->getDbConnection(); - $patterns = array(); + $patterns = []; if (strpos($this->tableName, '*') !== false) { $pattern = $this->tableName; if (($pos = strrpos($pattern, '.')) !== false) { diff --git a/framework/yii/gii/generators/model/templates/model.php b/framework/yii/gii/generators/model/templates/model.php index d5f0a18..b5fc4ad 100644 --- a/framework/yii/gii/generators/model/templates/model.php +++ b/framework/yii/gii/generators/model/templates/model.php @@ -45,7 +45,7 @@ class extends baseClass, '\\') . " */ public function rules() { - return array(); + return []; } /** @@ -53,11 +53,11 @@ class extends baseClass, '\\') . " */ public function attributeLabels() { - return array( + return [ $label): ?> '" . addslashes($label) . "',\n"; ?> - ); + ]; } $relation): ?> diff --git a/framework/yii/gii/generators/module/Generator.php b/framework/yii/gii/generators/module/Generator.php index 39c68f0..fcb385d 100644 --- a/framework/yii/gii/generators/module/Generator.php +++ b/framework/yii/gii/generators/module/Generator.php @@ -44,13 +44,13 @@ class Generator extends \yii\gii\Generator */ public function rules() { - return array_merge(parent::rules(), array( - array('moduleID, moduleClass', 'filter', 'filter' => 'trim'), - array('moduleID, moduleClass', 'required'), - array('moduleID', 'match', 'pattern' => '/^[\w\\-]+$/', 'message' => 'Only word characters and dashes are allowed.'), - array('moduleClass', 'match', 'pattern' => '/^[\w\\\\]*$/', 'message' => 'Only word characters and backslashes are allowed.'), - array('moduleClass', 'validateModuleClass'), - )); + return array_merge(parent::rules(), [ + ['moduleID, moduleClass', 'filter', 'filter' => 'trim'], + ['moduleID, moduleClass', 'required'], + ['moduleID', 'match', 'pattern' => '/^[\w\\-]+$/', 'message' => 'Only word characters and dashes are allowed.'], + ['moduleClass', 'match', 'pattern' => '/^[\w\\\\]*$/', 'message' => 'Only word characters and backslashes are allowed.'], + ['moduleClass', 'validateModuleClass'], + ]); } /** @@ -58,10 +58,10 @@ class Generator extends \yii\gii\Generator */ public function attributeLabels() { - return array( + return [ 'moduleID' => 'Module ID', 'moduleClass' => 'Module Class', - ); + ]; } /** @@ -69,10 +69,10 @@ class Generator extends \yii\gii\Generator */ public function hints() { - return array( + return [ 'moduleID' => 'This refers to the ID of the module, e.g., admin.', 'moduleClass' => 'This is the fully qualified class name of the module, e.g., app\modules\admin\Module.', - ); + ]; } /** @@ -81,7 +81,7 @@ class Generator extends \yii\gii\Generator public function successMessage() { if (Yii::$app->hasModule($this->moduleID)) { - $link = Html::a('try it now', Yii::$app->getUrlManager()->createUrl($this->moduleID), array('target' => '_blank')); + $link = Html::a('try it now', Yii::$app->getUrlManager()->createUrl($this->moduleID), ['target' => '_blank']); return "The module has been generated successfully. You may $link."; } @@ -92,11 +92,11 @@ EOD; $code = << array( - '{$this->moduleID}' => array( + 'modules' => [ + '{$this->moduleID}' => [ 'class' => '{$this->moduleClass}', - ), - ), + ], + ], ...... EOD; @@ -108,11 +108,7 @@ EOD; */ public function requiredTemplates() { - return array( - 'module.php', - 'controller.php', - 'view.php', - ); + return ['module.php', 'controller.php', 'view.php']; } /** @@ -120,7 +116,7 @@ EOD; */ public function generate() { - $files = array(); + $files = []; $modulePath = $this->getModulePath(); $files[] = new CodeFile( $modulePath . '/' . StringHelper::basename($this->moduleClass) . '.php', diff --git a/framework/yii/gii/views/default/index.php b/framework/yii/gii/views/default/index.php index c727691..26ba583 100644 --- a/framework/yii/gii/views/default/index.php +++ b/framework/yii/gii/views/default/index.php @@ -23,7 +23,7 @@ $this->title = 'Welcome to Gii';

    getName()); ?>

    getDescription(); ?>

    -

    $id), array('class' => 'btn btn-default')); ?>

    +

    $id], ['class' => 'btn btn-default']); ?>

    diff --git a/framework/yii/gii/views/default/view.php b/framework/yii/gii/views/default/view.php index d26c97d..7899275 100644 --- a/framework/yii/gii/views/default/view.php +++ b/framework/yii/gii/views/default/view.php @@ -18,7 +18,7 @@ use yii\gii\CodeFile; */ $this->title = $generator->getName(); -$templates = array(); +$templates = []; foreach ($generator->templates as $name => $path) { $templates[$name] = "$name ($path)"; } @@ -28,27 +28,27 @@ foreach ($generator->templates as $name => $path) {

    getDescription(); ?>

    - "$id-generator", 'successCssClass' => '', - 'fieldConfig' => array('class' => ActiveField::className()), - )); ?> + 'fieldConfig' => ['class' => ActiveField::className()], + ]); ?>
    - renderFile($generator->formView(), array( + renderFile($generator->formView(), [ 'generator' => $generator, 'form' => $form, - )); ?> + ]); ?> field($generator, 'template')->sticky() ->label('Code Template') ->dropDownList($templates)->hint(' Please select which set of the templates should be used to generated the code. '); ?>
    - 'preview', 'class' => 'btn btn-primary')); ?> + 'preview', 'class' => 'btn btn-primary']); ?> - 'generate', 'class' => 'btn btn-success')); ?> + 'generate', 'class' => 'btn btn-success']); ?>
    @@ -56,17 +56,17 @@ foreach ($generator->templates as $name => $path) { render('view/results', array( + echo $this->render('view/results', [ 'generator' => $generator, 'results' => $results, 'hasError' => $hasError, - )); + ]); } elseif (isset($files)) { - echo $this->render('view/files', array( + echo $this->render('view/files', [ 'generator' => $generator, 'files' => $files, 'answers' => $answers, - )); + ]); } ?> diff --git a/framework/yii/gii/views/default/view/files.php b/framework/yii/gii/views/default/view/files.php index 21794c3..dae0274 100644 --- a/framework/yii/gii/views/default/view/files.php +++ b/framework/yii/gii/views/default/view/files.php @@ -35,9 +35,9 @@ use yii\gii\CodeFile; - getRelativePath()), array('preview', 'file' => $file->id), array('class' => 'preview-code', 'data-title' => $file->getRelativePath())); ?> + getRelativePath()), ['preview', 'file' => $file->id], ['class' => 'preview-code', 'data-title' => $file->getRelativePath()]); ?> operation === CodeFile::OP_OVERWRITE): ?> - $file->id), array('class' => 'diff-code label label-warning', 'data-title' => $file->getRelativePath())); ?> + $file->id], ['class' => 'diff-code label label-warning', 'data-title' => $file->getRelativePath()]); ?> diff --git a/framework/yii/gii/views/layouts/generator.php b/framework/yii/gii/views/layouts/generator.php index 7ec6905..7d51e65 100644 --- a/framework/yii/gii/views/layouts/generator.php +++ b/framework/yii/gii/views/layouts/generator.php @@ -17,9 +17,9 @@ $activeGenerator = Yii::$app->controller->generator; $generator) { $label = '' . Html::encode($generator->getName()); - echo Html::a($label, array('default/view', 'id' => $id), array( + echo Html::a($label, ['default/view', 'id' => $id], [ 'class' => $generator === $activeGenerator ? 'list-group-item active' : 'list-group-item', - )); + ]); } ?>
    diff --git a/framework/yii/gii/views/layouts/main.php b/framework/yii/gii/views/layouts/main.php index 406fefe..1d6c2f4 100644 --- a/framework/yii/gii/views/layouts/main.php +++ b/framework/yii/gii/views/layouts/main.php @@ -20,21 +20,19 @@ $asset = yii\gii\GiiAsset::register($this); beginBody(); ?> Html::img($asset->baseUrl . '/logo.png'), - 'brandUrl' => array('default/index'), - 'options' => array( - 'class' => 'navbar-inverse navbar-fixed-top', - ), -)); -echo Nav::widget(array( - 'options' => array('class' => 'nav navbar-nav pull-right'), - 'items' => array( - array('label' => 'Home', 'url' => array('default/index')), - array('label' => 'Help', 'url' => 'http://www.yiiframework.com/doc/guide/topics.gii'), - array('label' => 'Application', 'url' => Yii::$app->homeUrl), - ), -)); + 'brandUrl' => ['default/index'], + 'options' => ['class' => 'navbar-inverse navbar-fixed-top'], +]); +echo Nav::widget([ + 'options' => ['class' => 'nav navbar-nav pull-right'], + 'items' => [ + ['label' => 'Home', 'url' => ['default/index']], + ['label' => 'Help', 'url' => 'http://www.yiiframework.com/doc/guide/topics.gii'], + ['label' => 'Application', 'url' => Yii::$app->homeUrl], + ], +]); NavBar::end(); ?> diff --git a/framework/yii/grid/ActionColumn.php b/framework/yii/grid/ActionColumn.php index b4b0960..598457f 100644 --- a/framework/yii/grid/ActionColumn.php +++ b/framework/yii/grid/ActionColumn.php @@ -20,7 +20,7 @@ use yii\helpers\StringHelper; class ActionColumn extends Column { public $template = '{view} {update} {delete}'; - public $buttons = array(); + public $buttons = []; public $urlCreator; public function init() @@ -35,29 +35,29 @@ class ActionColumn extends Column $this->buttons['view'] = function ($model, $column) { /** @var ActionColumn $column */ $url = $column->createUrl($model, 'view'); - return Html::a('', $url, array( + return Html::a('', $url, [ 'title' => Yii::t('yii', 'View'), - )); + ]); }; } if (!isset($this->buttons['update'])) { $this->buttons['update'] = function ($model, $column) { /** @var ActionColumn $column */ $url = $column->createUrl($model, 'update'); - return Html::a('', $url, array( + return Html::a('', $url, [ 'title' => Yii::t('yii', 'Update'), - )); + ]); }; } if (!isset($this->buttons['delete'])) { $this->buttons['delete'] = function ($model, $column) { /** @var ActionColumn $column */ $url = $column->createUrl($model, 'delete'); - return Html::a('', $url, array( + return Html::a('', $url, [ 'title' => Yii::t('yii', 'Delete'), 'data-confirm' => Yii::t('yii', 'Are you sure to delete this item?'), 'data-method' => 'post', - )); + ]); }; } } @@ -74,7 +74,7 @@ class ActionColumn extends Column } else { $params = $model->getPrimaryKey(true); if (count($params) === 1) { - $params = array('id' => reset($params)); + $params = ['id' => reset($params)]; } return Yii::$app->controller->createUrl($action, $params); } diff --git a/framework/yii/grid/CheckboxColumn.php b/framework/yii/grid/CheckboxColumn.php index e9170f4..d029648 100644 --- a/framework/yii/grid/CheckboxColumn.php +++ b/framework/yii/grid/CheckboxColumn.php @@ -27,7 +27,7 @@ use yii\helpers\Html; class CheckboxColumn extends Column { public $name = 'selection'; - public $checkboxOptions = array(); + public $checkboxOptions = []; public $multiple = true; @@ -52,17 +52,17 @@ class CheckboxColumn extends Column { $name = rtrim($this->name, '[]') . '_all'; $id = $this->grid->options['id']; - $options = json_encode(array( + $options = json_encode([ 'name' => $this->name, 'multiple' => $this->multiple, 'checkAll' => $name, - )); + ]); $this->grid->getView()->registerJs("jQuery('#$id').yiiGridView('setSelectionColumn', $options);"); if ($this->header !== null || !$this->multiple) { return parent::renderHeaderCellContent(); } else { - return Html::checkBox($name, false, array('class' => 'select-on-check-all')); + return Html::checkBox($name, false, ['class' => 'select-on-check-all']); } } diff --git a/framework/yii/grid/Column.php b/framework/yii/grid/Column.php index b49f73e..ec0c886 100644 --- a/framework/yii/grid/Column.php +++ b/framework/yii/grid/Column.php @@ -39,17 +39,17 @@ class Column extends Object * @var boolean whether this column is visible. Defaults to true. */ public $visible = true; - public $options = array(); - public $headerOptions = array(); + public $options = []; + public $headerOptions = []; /** * @var array|\Closure */ - public $contentOptions = array(); - public $footerOptions = array(); + public $contentOptions = []; + public $footerOptions = []; /** * @var array the HTML attributes for the filter cell tag. */ - public $filterOptions=array(); + public $filterOptions=[]; /** diff --git a/framework/yii/grid/DataColumn.php b/framework/yii/grid/DataColumn.php index 478394b..9459aae 100644 --- a/framework/yii/grid/DataColumn.php +++ b/framework/yii/grid/DataColumn.php @@ -57,7 +57,7 @@ class DataColumn extends Column * @var array the HTML attributes for the link tag in the header cell * generated by [[Sort::link]] when sorting is enabled for this column. */ - public $sortLinkOptions = array(); + public $sortLinkOptions = []; /** * @var string|array|boolean the HTML code representing a filter input (e.g. a text field, a dropdown list) * that is used for this data column. This property is effective only when [[GridView::filterModel]] is set. @@ -73,7 +73,7 @@ class DataColumn extends Column * the [[filter]] property. When [[filter]] is not set or is an array, this property will be used to * render the HTML attributes for the generated filter input fields. */ - public $filterInputOptions = array('class' => 'form-control', 'id' => null); + public $filterInputOptions = ['class' => 'form-control', 'id' => null]; protected function renderHeaderCellContent() @@ -105,7 +105,7 @@ class DataColumn extends Column if ($this->attribute !== null && $this->enableSorting && ($sort = $provider->getSort()) !== false && $sort->hasAttribute($this->attribute)) { - return $sort->link($this->attribute, array_merge($this->sortLinkOptions, array('label' => Html::encode($label)))); + return $sort->link($this->attribute, array_merge($this->sortLinkOptions, ['label' => Html::encode($label)])); } else { return Html::encode($label); } @@ -119,7 +119,7 @@ class DataColumn extends Column $this->attribute !== null && $this->grid->filterModel->isAttributeActive($this->attribute)) { if (is_array($this->filter)) { - $options = array_merge(array('prompt' => ''), $this->filterInputOptions); + $options = array_merge(['prompt' => ''], $this->filterInputOptions); return Html::activeDropDownList($this->grid->filterModel, $this->attribute, $this->filter, $options); } else { return Html::activeTextInput($this->grid->filterModel, $this->attribute, $this->filterInputOptions); diff --git a/framework/yii/grid/GridView.php b/framework/yii/grid/GridView.php index 4bf7a39..4895781 100644 --- a/framework/yii/grid/GridView.php +++ b/framework/yii/grid/GridView.php @@ -41,19 +41,19 @@ class GridView extends BaseListView * @var array the HTML attributes for the caption element * @see caption */ - public $captionOptions = array(); + public $captionOptions = []; /** * @var array the HTML attributes for the grid table element */ - public $tableOptions = array('class' => 'table table-striped table-bordered'); + public $tableOptions = ['class' => 'table table-striped table-bordered']; /** * @var array the HTML attributes for the table header row */ - public $headerRowOptions = array(); + public $headerRowOptions = []; /** * @var array the HTML attributes for the table footer row */ - public $footerRowOptions = array(); + public $footerRowOptions = []; /** * @var array|Closure the HTML attributes for the table body rows. This can be either an array * specifying the common HTML attributes for all body rows, or an anonymous function that @@ -69,7 +69,7 @@ class GridView extends BaseListView * - `$index`: the zero-based index of the data model in the model array returned by [[dataProvider]] * - `$grid`: the GridView object */ - public $rowOptions = array(); + public $rowOptions = []; /** * @var Closure an anonymous function that is called once BEFORE rendering each data model. * It should have the similar signature as [[rowOptions]]. The return result of the function @@ -101,20 +101,16 @@ class GridView extends BaseListView * for one particular grid column. For example, * * ~~~php - * array( - * array( - * 'class' => SerialColumn::className(), - * ), - * array( + * [ + * ['class' => SerialColumn::className()], + * [ * 'class' => DataColumn::className(), * 'attribute' => 'name', * 'format' => 'text', * 'label' => 'Name', - * ), - * array( - * 'class' => CheckboxColumn::className(), - * ), - * ) + * ], + * ['class' => CheckboxColumn::className()], + * ] * ~~~ * * If a column is of class [[DataColumn]], the "class" element can be omitted. @@ -124,7 +120,7 @@ class GridView extends BaseListView * For example, the above "name" column can also be specified as: `"name:text:Name"`. * Both "format" and "label" are optional. They will take default values if absent. */ - public $columns = array(); + public $columns = []; public $emptyCell = ' '; /** * @var \yii\base\Model the model that keeps the user-entered filter data. When this property is set, @@ -156,7 +152,7 @@ class GridView extends BaseListView /** * @var array the HTML attributes for the filter row element */ - public $filterRowOptions = array('class' => 'filters'); + public $filterRowOptions = ['class' => 'filters']; /** * Initializes the grid view. @@ -203,17 +199,17 @@ class GridView extends BaseListView */ protected function getClientOptions() { - $filterUrl = isset($this->filterUrl) ? $this->filterUrl : array(Yii::$app->controller->action->id); + $filterUrl = isset($this->filterUrl) ? $this->filterUrl : [Yii::$app->controller->action->id]; $id = $this->filterRowOptions['id']; $filterSelector = "#$id input, #$id select"; if (isset($this->filterSelector)) { $filterSelector .= ', ' . $this->filterSelector; } - return array( + return [ 'filterUrl' => Html::url($filterUrl), 'filterSelector' => $filterSelector, - ); + ]; } /** @@ -221,13 +217,13 @@ class GridView extends BaseListView */ public function renderItems() { - $content = array_filter(array( + $content = array_filter([ $this->renderCaption(), $this->renderColumnGroup(), $this->showHeader ? $this->renderTableHeader() : false, $this->showFooter ? $this->renderTableFooter() : false, $this->renderTableBody(), - )); + ]); return Html::tag('table', implode("\n", $content), $this->tableOptions); } @@ -251,7 +247,7 @@ class GridView extends BaseListView } } if ($requireColumnGroup) { - $cols = array(); + $cols = []; foreach ($this->columns as $column) { $cols[] = Html::tag('col', '', $column->options); } @@ -267,7 +263,7 @@ class GridView extends BaseListView */ public function renderTableHeader() { - $cells = array(); + $cells = []; foreach ($this->columns as $column) { /** @var Column $column */ $cells[] = $column->renderHeaderCell(); @@ -287,7 +283,7 @@ class GridView extends BaseListView */ public function renderTableFooter() { - $cells = array(); + $cells = []; foreach ($this->columns as $column) { /** @var Column $column */ $cells[] = $column->renderFooterCell(); @@ -305,7 +301,7 @@ class GridView extends BaseListView public function renderFilters() { if ($this->filterModel !== null) { - $cells = array(); + $cells = []; foreach ($this->columns as $column) { /** @var Column $column */ $cells[] = $column->renderFilterCell(); @@ -324,7 +320,7 @@ class GridView extends BaseListView { $models = array_values($this->dataProvider->getModels()); $keys = $this->dataProvider->getKeys(); - $rows = array(); + $rows = []; foreach ($models as $index => $model) { $key = $keys[$index]; if ($this->beforeRow !== null) { @@ -355,7 +351,7 @@ class GridView extends BaseListView */ public function renderTableRow($model, $key, $index) { - $cells = array(); + $cells = []; /** @var Column $column */ foreach ($this->columns as $column) { $cells[] = $column->renderDataCell($model, $index); @@ -381,10 +377,10 @@ class GridView extends BaseListView if (is_string($column)) { $column = $this->createDataColumn($column); } else { - $column = Yii::createObject(array_merge(array( + $column = Yii::createObject(array_merge([ 'class' => $this->dataColumnClass ?: DataColumn::className(), 'grid' => $this, - ), $column)); + ], $column)); } if (!$column->visible) { unset($this->columns[$i]); @@ -405,13 +401,13 @@ class GridView extends BaseListView if (!preg_match('/^([\w\.]+)(:(\w*))?(:(.*))?$/', $text, $matches)) { throw new InvalidConfigException('The column must be specified in the format of "attribute", "attribute:format" or "attribute:format:label'); } - return Yii::createObject(array( + return Yii::createObject([ 'class' => $this->dataColumnClass ?: DataColumn::className(), 'grid' => $this, 'attribute' => $matches[1], 'format' => isset($matches[3]) ? $matches[3] : 'text', 'label' => isset($matches[5]) ? $matches[5] : null, - )); + ]); } protected function guessColumns() diff --git a/framework/yii/grid/GridViewAsset.php b/framework/yii/grid/GridViewAsset.php index decf674..ae49070 100644 --- a/framework/yii/grid/GridViewAsset.php +++ b/framework/yii/grid/GridViewAsset.php @@ -17,10 +17,10 @@ use yii\web\AssetBundle; class GridViewAsset extends AssetBundle { public $sourcePath = '@yii/assets'; - public $js = array( + public $js = [ 'yii.gridView.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\web\YiiAsset', - ); + ]; } diff --git a/framework/yii/helpers/BaseArrayHelper.php b/framework/yii/helpers/BaseArrayHelper.php index 0ed584f..b7d0a2f 100644 --- a/framework/yii/helpers/BaseArrayHelper.php +++ b/framework/yii/helpers/BaseArrayHelper.php @@ -28,8 +28,8 @@ class BaseArrayHelper * The properties specified for each class is an array of the following format: * * ~~~ - * array( - * 'app\models\Post' => array( + * [ + * 'app\models\Post' => [ * 'id', * 'title', * // the key name in array result => property name @@ -38,30 +38,30 @@ class BaseArrayHelper * 'length' => function ($post) { * return strlen($post->content); * }, - * ), - * ) + * ], + * ] * ~~~ * * The result of `ArrayHelper::toArray($post, $properties)` could be like the following: * * ~~~ - * array( + * [ * 'id' => 123, * 'title' => 'test', * 'createTime' => '2013-01-01 12:00AM', * 'length' => 301, - * ) + * ] * ~~~ * * @param boolean $recursive whether to recursively converts properties which are objects into arrays. * @return array the array representation of the object */ - public static function toArray($object, $properties = array(), $recursive = true) + public static function toArray($object, $properties = [], $recursive = true) { if (!empty($properties) && is_object($object)) { $className = get_class($object); if (!empty($properties[$className])) { - $result = array(); + $result = []; foreach ($properties[$className] as $key => $name) { if (is_int($key)) { $result[$name] = $object->$name; @@ -78,7 +78,7 @@ class BaseArrayHelper return $object; } } - $result = array(); + $result = []; foreach ($object as $key => $value) { if ($recursive && (is_array($value) || is_object($value))) { $result[$key] = static::toArray($value, true); @@ -163,11 +163,11 @@ class BaseArrayHelper * Usage examples, * * ~~~ - * // $array = array('type' => 'A', 'options' => array(1, 2)); + * // $array = ['type' => 'A', 'options' => [1, 2]]; * // working with array * $type = \yii\helpers\ArrayHelper::remove($array, 'type'); * // $array content - * // $array = array('options' => array(1, 2)); + * // $array = ['options' => [1, 2]]; * ~~~ * * @param array $array the array to extract value from @@ -197,16 +197,16 @@ class BaseArrayHelper * For example, * * ~~~ - * $array = array( - * array('id' => '123', 'data' => 'abc'), - * array('id' => '345', 'data' => 'def'), - * ); + * $array = [ + * ['id' => '123', 'data' => 'abc'], + * ['id' => '345', 'data' => 'def'], + * ]; * $result = ArrayHelper::index($array, 'id'); * // the result is: - * // array( - * // '123' => array('id' => '123', 'data' => 'abc'), - * // '345' => array('id' => '345', 'data' => 'def'), - * // ) + * // [ + * // '123' => ['id' => '123', 'data' => 'abc'], + * // '345' => ['id' => '345', 'data' => 'def'], + * // ] * * // using anonymous function * $result = ArrayHelper::index($array, function ($element) { @@ -220,7 +220,7 @@ class BaseArrayHelper */ public static function index($array, $key) { - $result = array(); + $result = []; foreach ($array as $element) { $value = static::getValue($element, $key); $result[$value] = $element; @@ -235,12 +235,12 @@ class BaseArrayHelper * For example, * * ~~~ - * $array = array( - * array('id' => '123', 'data' => 'abc'), - * array('id' => '345', 'data' => 'def'), - * ); + * $array = [ + * ['id' => '123', 'data' => 'abc'], + * ['id' => '345', 'data' => 'def'], + * ]; * $result = ArrayHelper::getColumn($array, 'id'); - * // the result is: array( '123', '345') + * // the result is: ['123', '345'] * * // using anonymous function * $result = ArrayHelper::getColumn($array, function ($element) { @@ -256,7 +256,7 @@ class BaseArrayHelper */ public static function getColumn($array, $name, $keepKeys = true) { - $result = array(); + $result = []; if ($keepKeys) { foreach ($array as $k => $element) { $result[$k] = static::getValue($element, $name); @@ -278,31 +278,31 @@ class BaseArrayHelper * For example, * * ~~~ - * $array = array( - * array('id' => '123', 'name' => 'aaa', 'class' => 'x'), - * array('id' => '124', 'name' => 'bbb', 'class' => 'x'), - * array('id' => '345', 'name' => 'ccc', 'class' => 'y'), + * $array = [ + * ['id' => '123', 'name' => 'aaa', 'class' => 'x'], + * ['id' => '124', 'name' => 'bbb', 'class' => 'x'], + * ['id' => '345', 'name' => 'ccc', 'class' => 'y'], * ); * * $result = ArrayHelper::map($array, 'id', 'name'); * // the result is: - * // array( + * // [ * // '123' => 'aaa', * // '124' => 'bbb', * // '345' => 'ccc', - * // ) + * // ] * * $result = ArrayHelper::map($array, 'id', 'name', 'class'); * // the result is: - * // array( - * // 'x' => array( + * // [ + * // 'x' => [ * // '123' => 'aaa', * // '124' => 'bbb', - * // ), - * // 'y' => array( + * // ], + * // 'y' => [ * // '345' => 'ccc', - * // ), - * // ) + * // ], + * // ] * ~~~ * * @param array $array @@ -313,7 +313,7 @@ class BaseArrayHelper */ public static function map($array, $from, $to, $group = null) { - $result = array(); + $result = []; foreach ($array as $element) { $key = static::getValue($element, $from); $value = static::getValue($element, $to); @@ -347,7 +347,7 @@ class BaseArrayHelper */ public static function multisort(&$array, $key, $descending = false, $sortFlag = SORT_REGULAR, $caseSensitive = true) { - $keys = is_array($key) ? $key : array($key); + $keys = is_array($key) ? $key : [$key]; if (empty($keys) || empty($array)) { return; } @@ -367,7 +367,7 @@ class BaseArrayHelper } elseif (count($caseSensitive) !== $n) { throw new InvalidParamException('The length of $caseSensitive parameter must be the same as that of $keys.'); } - $args = array(); + $args = []; foreach ($keys as $i => $key) { $flag = $sortFlag[$i]; $cs = $caseSensitive[$i]; @@ -376,7 +376,7 @@ class BaseArrayHelper $flag = $flag | SORT_FLAG_CASE; $args[] = static::getColumn($array, $key); } else { - $column = array(); + $column = []; foreach (static::getColumn($array, $key) as $k => $value) { $column[$k] = mb_strtolower($value); } @@ -409,7 +409,7 @@ class BaseArrayHelper if ($charset === null) { $charset = Yii::$app->charset; } - $d = array(); + $d = []; foreach ($data as $key => $value) { if (!$valuesOnly && is_string($key)) { $key = htmlspecialchars($key, ENT_QUOTES, $charset); @@ -435,7 +435,7 @@ class BaseArrayHelper */ public static function htmlDecode($data, $valuesOnly = true) { - $d = array(); + $d = []; foreach ($data as $key => $value) { if (!$valuesOnly && is_string($key)) { $key = htmlspecialchars_decode($key, ENT_QUOTES); diff --git a/framework/yii/helpers/BaseConsole.php b/framework/yii/helpers/BaseConsole.php index 3f11031..480badf 100644 --- a/framework/yii/helpers/BaseConsole.php +++ b/framework/yii/helpers/BaseConsole.php @@ -263,7 +263,7 @@ class BaseConsole * This is equal to calling * * ```php - * echo Console::ansiFormatCode(array(Console::RESET)) + * echo Console::ansiFormatCode([Console::RESET]) * ``` */ public static function endAnsiFormat() @@ -280,7 +280,7 @@ class BaseConsole * and also [[xtermFgColor]] and [[xtermBgColor]] to specify a format. * @return string */ - public static function ansiFormat($string, $format = array()) + public static function ansiFormat($string, $format = []) { $code = implode(';', $format); return "\033[0m" . ($code !== '' ? "\033[" . $code . "m" : '') . $string . "\033[0m"; @@ -337,74 +337,74 @@ class BaseConsole return preg_replace_callback( '/\033\[[\d;]+m/', function ($ansi) use (&$tags) { - $styleA = array(); + $styleA = []; foreach (explode(';', $ansi) as $controlCode) { switch ($controlCode) { case self::FG_BLACK: - $style = array('color' => '#000000'); + $style = ['color' => '#000000']; break; case self::FG_BLUE: - $style = array('color' => '#000078'); + $style = ['color' => '#000078']; break; case self::FG_CYAN: - $style = array('color' => '#007878'); + $style = ['color' => '#007878']; break; case self::FG_GREEN: - $style = array('color' => '#007800'); + $style = ['color' => '#007800']; break; case self::FG_GREY: - $style = array('color' => '#787878'); + $style = ['color' => '#787878']; break; case self::FG_PURPLE: - $style = array('color' => '#780078'); + $style = ['color' => '#780078']; break; case self::FG_RED: - $style = array('color' => '#780000'); + $style = ['color' => '#780000']; break; case self::FG_YELLOW: - $style = array('color' => '#787800'); + $style = ['color' => '#787800']; break; case self::BG_BLACK: - $style = array('background-color' => '#000000'); + $style = ['background-color' => '#000000']; break; case self::BG_BLUE: - $style = array('background-color' => '#000078'); + $style = ['background-color' => '#000078']; break; case self::BG_CYAN: - $style = array('background-color' => '#007878'); + $style = ['background-color' => '#007878']; break; case self::BG_GREEN: - $style = array('background-color' => '#007800'); + $style = ['background-color' => '#007800']; break; case self::BG_GREY: - $style = array('background-color' => '#787878'); + $style = ['background-color' => '#787878']; break; case self::BG_PURPLE: - $style = array('background-color' => '#780078'); + $style = ['background-color' => '#780078']; break; case self::BG_RED: - $style = array('background-color' => '#780000'); + $style = ['background-color' => '#780000']; break; case self::BG_YELLOW: - $style = array('background-color' => '#787800'); + $style = ['background-color' => '#787800']; break; case self::BOLD: - $style = array('font-weight' => 'bold'); + $style = ['font-weight' => 'bold']; break; case self::ITALIC: - $style = array('font-style' => 'italic'); + $style = ['font-style' => 'italic']; break; case self::UNDERLINE: - $style = array('text-decoration' => array('underline')); + $style = ['text-decoration' => ['underline']]; break; case self::OVERLINED: - $style = array('text-decoration' => array('overline')); + $style = ['text-decoration' => ['overline']]; break; case self::CROSSED_OUT: - $style = array('text-decoration' => array('line-through')); + $style = ['text-decoration' => ['line-through']]; break; case self::BLINK: - $style = array('text-decoration' => array('blink')); + $style = ['text-decoration' => ['blink']]; break; case self::NEGATIVE: // ??? case self::CONCEALED: @@ -422,7 +422,7 @@ class BaseConsole $styleA = ArrayHelper::merge($styleA, $style); } - $styleString[] = array(); + $styleString[] = []; foreach ($styleA as $name => $content) { if ($name === 'text-decoration') { $content = implode(' ', $content); @@ -480,41 +480,41 @@ class BaseConsole // TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746 public static function renderColoredString($string, $colored = true) { - static $conversions = array( - '%y' => array(self::FG_YELLOW), - '%g' => array(self::FG_GREEN), - '%b' => array(self::FG_BLUE), - '%r' => array(self::FG_RED), - '%p' => array(self::FG_PURPLE), - '%m' => array(self::FG_PURPLE), - '%c' => array(self::FG_CYAN), - '%w' => array(self::FG_GREY), - '%k' => array(self::FG_BLACK), - '%n' => array(0), // reset - '%Y' => array(self::FG_YELLOW, self::BOLD), - '%G' => array(self::FG_GREEN, self::BOLD), - '%B' => array(self::FG_BLUE, self::BOLD), - '%R' => array(self::FG_RED, self::BOLD), - '%P' => array(self::FG_PURPLE, self::BOLD), - '%M' => array(self::FG_PURPLE, self::BOLD), - '%C' => array(self::FG_CYAN, self::BOLD), - '%W' => array(self::FG_GREY, self::BOLD), - '%K' => array(self::FG_BLACK, self::BOLD), - '%N' => array(0, self::BOLD), - '%3' => array(self::BG_YELLOW), - '%2' => array(self::BG_GREEN), - '%4' => array(self::BG_BLUE), - '%1' => array(self::BG_RED), - '%5' => array(self::BG_PURPLE), - '%6' => array(self::BG_PURPLE), - '%7' => array(self::BG_CYAN), - '%0' => array(self::BG_GREY), - '%F' => array(self::BLINK), - '%U' => array(self::UNDERLINE), - '%8' => array(self::NEGATIVE), - '%9' => array(self::BOLD), - '%_' => array(self::BOLD) - ); + static $conversions = [ + '%y' => [self::FG_YELLOW], + '%g' => [self::FG_GREEN], + '%b' => [self::FG_BLUE], + '%r' => [self::FG_RED], + '%p' => [self::FG_PURPLE], + '%m' => [self::FG_PURPLE], + '%c' => [self::FG_CYAN], + '%w' => [self::FG_GREY], + '%k' => [self::FG_BLACK], + '%n' => [0], // reset + '%Y' => [self::FG_YELLOW, self::BOLD], + '%G' => [self::FG_GREEN, self::BOLD], + '%B' => [self::FG_BLUE, self::BOLD], + '%R' => [self::FG_RED, self::BOLD], + '%P' => [self::FG_PURPLE, self::BOLD], + '%M' => [self::FG_PURPLE, self::BOLD], + '%C' => [self::FG_CYAN, self::BOLD], + '%W' => [self::FG_GREY, self::BOLD], + '%K' => [self::FG_BLACK, self::BOLD], + '%N' => [0, self::BOLD], + '%3' => [self::BG_YELLOW], + '%2' => [self::BG_GREEN], + '%4' => [self::BG_BLUE], + '%1' => [self::BG_RED], + '%5' => [self::BG_PURPLE], + '%6' => [self::BG_PURPLE], + '%7' => [self::BG_CYAN], + '%0' => [self::BG_GREY], + '%F' => [self::BLINK], + '%U' => [self::UNDERLINE], + '%8' => [self::NEGATIVE], + '%9' => [self::BOLD], + '%_' => [self::BOLD], + ]; if ($colored) { $string = str_replace('%%', '% ', $string); @@ -588,26 +588,26 @@ class BaseConsole } if (static::isRunningOnWindows()) { - $output = array(); + $output = []; exec('mode con', $output); if (isset($output) && strpos($output[1], 'CON') !== false) { - return $size = array((int)preg_replace('~[^0-9]~', '', $output[3]), (int)preg_replace('~[^0-9]~', '', $output[4])); + return $size = [(int)preg_replace('~[^0-9]~', '', $output[3]), (int)preg_replace('~[^0-9]~', '', $output[4])]; } } else { // try stty if available - $stty = array(); + $stty = []; if (exec('stty -a 2>&1', $stty) && preg_match('/rows\s+(\d+);\s*columns\s+(\d+);/mi', implode(' ', $stty), $matches)) { - return $size = array($matches[2], $matches[1]); + return $size = [$matches[2], $matches[1]]; } // fallback to tput, which may not be updated on terminal resize if (($width = (int) exec('tput cols 2>&1')) > 0 && ($height = (int) exec('tput lines 2>&1')) > 0) { - return $size = array($width, $height); + return $size = [$width, $height]; } // fallback to ENV variables, which may not be updated on terminal resize if (($width = (int) getenv('COLUMNS')) > 0 && ($height = (int) getenv('LINES')) > 0) { - return $size = array($width, $height); + return $size = [$width, $height]; } } @@ -697,16 +697,16 @@ class BaseConsole * - $error: the error value passed by reference if validation failed. * @return string the user input */ - public static function prompt($text, $options = array()) + public static function prompt($text, $options = []) { $options = ArrayHelper::merge( - array( + [ 'required' => false, 'default' => null, 'pattern' => null, 'validator' => null, 'error' => 'Invalid input.', - ), + ], $options ); $error = null; @@ -727,7 +727,7 @@ class BaseConsole static::output($options['error']); goto top; } elseif ($options['validator'] && - !call_user_func_array($options['validator'], array($input, &$error)) + !call_user_func_array($options['validator'], [$input, &$error]) ) { static::output(isset($error) ? $error : $options['error']); goto top; @@ -759,7 +759,7 @@ class BaseConsole * * @return string An option character the user chose */ - public static function select($prompt, $options = array()) + public static function select($prompt, $options = []) { top: static::stdout("$prompt [" . implode(',', array_keys($options)) . ",?]: "); diff --git a/framework/yii/helpers/BaseFileHelper.php b/framework/yii/helpers/BaseFileHelper.php index 7540168..9533b95 100644 --- a/framework/yii/helpers/BaseFileHelper.php +++ b/framework/yii/helpers/BaseFileHelper.php @@ -33,7 +33,7 @@ class BaseFileHelper */ public static function normalizePath($path, $ds = DIRECTORY_SEPARATOR) { - return rtrim(strtr($path, array('/' => $ds, '\\' => $ds)), $ds); + return rtrim(strtr($path, ['/' => $ds, '\\' => $ds]), $ds); } /** @@ -110,7 +110,7 @@ class BaseFileHelper */ public static function getMimeTypeByExtension($file, $magicFile = null) { - static $mimeTypes = array(); + static $mimeTypes = []; if ($magicFile === null) { $magicFile = __DIR__ . '/mimeTypes.php'; } @@ -163,7 +163,7 @@ class BaseFileHelper * The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or * file copied from, while `$to` is the copy target. */ - public static function copyDirectory($src, $dst, $options = array()) + public static function copyDirectory($src, $dst, $options = []) { if (!is_dir($dst)) { static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true); @@ -247,9 +247,9 @@ class BaseFileHelper * - recursive: boolean, whether the files under the subdirectories should also be looked for. Defaults to true. * @return array files found under the directory. The file list is sorted. */ - public static function findFiles($dir, $options = array()) + public static function findFiles($dir, $options = []) { - $list = array(); + $list = []; $handle = opendir($dir); while (($file = readdir($handle)) !== false) { if ($file === '.' || $file === '..') { diff --git a/framework/yii/helpers/BaseHtml.php b/framework/yii/helpers/BaseHtml.php index ff12cd5..9f3df0e 100644 --- a/framework/yii/helpers/BaseHtml.php +++ b/framework/yii/helpers/BaseHtml.php @@ -26,7 +26,7 @@ class BaseHtml * @var array list of void elements (element name => 1) * @see http://www.w3.org/TR/html-markup/syntax.html#void-element */ - public static $voidElements = array( + public static $voidElements = [ 'area' => 1, 'base' => 1, 'br' => 1, @@ -43,12 +43,12 @@ class BaseHtml 'source' => 1, 'track' => 1, 'wbr' => 1, - ); + ]; /** * @var array the preferred order of attributes in a tag. This mainly affects the order of the attributes * that are rendered by [[renderTagAttributes()]]. */ - public static $attributeOrder = array( + public static $attributeOrder = [ 'type', 'id', 'class', @@ -77,7 +77,7 @@ class BaseHtml 'title', 'rel', 'media', - ); + ]; /** * Encodes special characters into HTML entities. @@ -119,7 +119,7 @@ class BaseHtml * @see beginTag * @see endTag */ - public static function tag($name, $content = '', $options = array()) + public static function tag($name, $content = '', $options = []) { $html = "<$name" . static::renderTagAttributes($options) . '>'; return isset(static::$voidElements[strtolower($name)]) ? $html : "$html$content"; @@ -135,7 +135,7 @@ class BaseHtml * @see endTag * @see tag */ - public static function beginTag($name, $options = array()) + public static function beginTag($name, $options = []) { return "<$name" . static::renderTagAttributes($options) . '>'; } @@ -161,7 +161,7 @@ class BaseHtml * If the options does not contain "type", a "type" attribute with value "text/css" will be used. * @return string the generated style tag */ - public static function style($content, $options = array()) + public static function style($content, $options = []) { return static::tag('style', $content, $options); } @@ -175,7 +175,7 @@ class BaseHtml * If the options does not contain "type", a "type" attribute with value "text/javascript" will be rendered. * @return string the generated script tag */ - public static function script($content, $options = array()) + public static function script($content, $options = []) { return static::tag('script', $content, $options); } @@ -189,7 +189,7 @@ class BaseHtml * @return string the generated link tag * @see url */ - public static function cssFile($url, $options = array()) + public static function cssFile($url, $options = []) { $options['rel'] = 'stylesheet'; $options['href'] = static::url($url); @@ -205,7 +205,7 @@ class BaseHtml * @return string the generated script tag * @see url */ - public static function jsFile($url, $options = array()) + public static function jsFile($url, $options = []) { $options['src'] = static::url($url); return static::tag('script', '', $options); @@ -224,11 +224,11 @@ class BaseHtml * @return string the generated form start tag. * @see endForm */ - public static function beginForm($action = '', $method = 'post', $options = array()) + public static function beginForm($action = '', $method = 'post', $options = []) { $action = static::url($action); - $hiddenInputs = array(); + $hiddenInputs = []; $request = Yii::$app->getRequest(); if ($request instanceof Request) { @@ -292,7 +292,7 @@ class BaseHtml * @return string the generated hyperlink * @see url */ - public static function a($text, $url = null, $options = array()) + public static function a($text, $url = null, $options = []) { if ($url !== null) { $options['href'] = static::url($url); @@ -312,7 +312,7 @@ class BaseHtml * If a value is null, the corresponding attribute will not be rendered. * @return string the generated mailto link */ - public static function mailto($text, $email = null, $options = array()) + public static function mailto($text, $email = null, $options = []) { $options['href'] = 'mailto:' . ($email === null ? $text : $email); return static::tag('a', $text, $options); @@ -326,7 +326,7 @@ class BaseHtml * If a value is null, the corresponding attribute will not be rendered. * @return string the generated image tag */ - public static function img($src, $options = array()) + public static function img($src, $options = []) { $options['src'] = static::url($src); if (!isset($options['alt'])) { @@ -347,7 +347,7 @@ class BaseHtml * If a value is null, the corresponding attribute will not be rendered. * @return string the generated label tag */ - public static function label($content, $for = null, $options = array()) + public static function label($content, $for = null, $options = []) { $options['for'] = $for; return static::tag('label', $content, $options); @@ -363,7 +363,7 @@ class BaseHtml * If a value is null, the corresponding attribute will not be rendered. * @return string the generated button tag */ - public static function button($content = 'Button', $options = array()) + public static function button($content = 'Button', $options = []) { return static::tag('button', $content, $options); } @@ -378,7 +378,7 @@ class BaseHtml * If a value is null, the corresponding attribute will not be rendered. * @return string the generated submit button tag */ - public static function submitButton($content = 'Submit', $options = array()) + public static function submitButton($content = 'Submit', $options = []) { $options['type'] = 'submit'; return static::button($content, $options); @@ -394,7 +394,7 @@ class BaseHtml * If a value is null, the corresponding attribute will not be rendered. * @return string the generated reset button tag */ - public static function resetButton($content = 'Reset', $options = array()) + public static function resetButton($content = 'Reset', $options = []) { $options['type'] = 'reset'; return static::button($content, $options); @@ -410,7 +410,7 @@ class BaseHtml * If a value is null, the corresponding attribute will not be rendered. * @return string the generated input tag */ - public static function input($type, $name = null, $value = null, $options = array()) + public static function input($type, $name = null, $value = null, $options = []) { $options['type'] = $type; $options['name'] = $name; @@ -426,7 +426,7 @@ class BaseHtml * If a value is null, the corresponding attribute will not be rendered. * @return string the generated button tag */ - public static function buttonInput($label = 'Button', $options = array()) + public static function buttonInput($label = 'Button', $options = []) { $options['type'] = 'button'; $options['value'] = $label; @@ -441,7 +441,7 @@ class BaseHtml * If a value is null, the corresponding attribute will not be rendered. * @return string the generated button tag */ - public static function submitInput($label = 'Submit', $options = array()) + public static function submitInput($label = 'Submit', $options = []) { $options['type'] = 'submit'; $options['value'] = $label; @@ -455,7 +455,7 @@ class BaseHtml * Attributes whose value is null will be ignored and not put in the tag returned. * @return string the generated button tag */ - public static function resetInput($label = 'Reset', $options = array()) + public static function resetInput($label = 'Reset', $options = []) { $options['type'] = 'reset'; $options['value'] = $label; @@ -471,7 +471,7 @@ class BaseHtml * If a value is null, the corresponding attribute will not be rendered. * @return string the generated button tag */ - public static function textInput($name, $value = null, $options = array()) + public static function textInput($name, $value = null, $options = []) { return static::input('text', $name, $value, $options); } @@ -485,7 +485,7 @@ class BaseHtml * If a value is null, the corresponding attribute will not be rendered. * @return string the generated button tag */ - public static function hiddenInput($name, $value = null, $options = array()) + public static function hiddenInput($name, $value = null, $options = []) { return static::input('hidden', $name, $value, $options); } @@ -499,7 +499,7 @@ class BaseHtml * If a value is null, the corresponding attribute will not be rendered. * @return string the generated button tag */ - public static function passwordInput($name, $value = null, $options = array()) + public static function passwordInput($name, $value = null, $options = []) { return static::input('password', $name, $value, $options); } @@ -516,7 +516,7 @@ class BaseHtml * If a value is null, the corresponding attribute will not be rendered. * @return string the generated button tag */ - public static function fileInput($name, $value = null, $options = array()) + public static function fileInput($name, $value = null, $options = []) { return static::input('file', $name, $value, $options); } @@ -530,7 +530,7 @@ class BaseHtml * If a value is null, the corresponding attribute will not be rendered. * @return string the generated text area tag */ - public static function textarea($name, $value = '', $options = array()) + public static function textarea($name, $value = '', $options = []) { $options['name'] = $name; return static::tag('textarea', static::encode($value), $options); @@ -555,7 +555,7 @@ class BaseHtml * * @return string the generated radio button tag */ - public static function radio($name, $checked = false, $options = array()) + public static function radio($name, $checked = false, $options = []) { $options['checked'] = (boolean)$checked; $value = array_key_exists('value', $options) ? $options['value'] : '1'; @@ -568,10 +568,10 @@ class BaseHtml } if (isset($options['label'])) { $label = $options['label']; - $labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : array(); + $labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : []; unset($options['label'], $options['labelOptions']); $content = static::label(static::input('radio', $name, $value, $options) . ' ' . $label, null, $labelOptions); - return $hidden . static::tag('div', $content, array('class' => 'radio')); + return $hidden . static::tag('div', $content, ['class' => 'radio']); } else { return $hidden . static::input('radio', $name, $value, $options); } @@ -596,7 +596,7 @@ class BaseHtml * * @return string the generated checkbox tag */ - public static function checkbox($name, $checked = false, $options = array()) + public static function checkbox($name, $checked = false, $options = []) { $options['checked'] = (boolean)$checked; $value = array_key_exists('value', $options) ? $options['value'] : '1'; @@ -609,10 +609,10 @@ class BaseHtml } if (isset($options['label'])) { $label = $options['label']; - $labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : array(); + $labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : []; unset($options['label'], $options['labelOptions']); $content = static::label(static::input('checkbox', $name, $value, $options) . ' ' . $label, null, $labelOptions); - return $hidden . static::tag('div', $content, array('class' => 'checkbox')); + return $hidden . static::tag('div', $content, ['class' => 'checkbox']); } else { return $hidden . static::input('checkbox', $name, $value, $options); } @@ -637,10 +637,10 @@ class BaseHtml * and the array values are the extra attributes for the corresponding option tags. For example, * * ~~~ - * array( - * 'value1' => array('disabled' => true), - * 'value2' => array('label' => 'value 2'), - * ); + * [ + * 'value1' => ['disabled' => true], + * 'value2' => ['label' => 'value 2'], + * ]; * ~~~ * * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options', @@ -651,7 +651,7 @@ class BaseHtml * * @return string the generated drop-down list tag */ - public static function dropDownList($name, $selection = null, $items = array(), $options = array()) + public static function dropDownList($name, $selection = null, $items = [], $options = []) { $options['name'] = $name; $selectOptions = static::renderSelectOptions($selection, $items, $options); @@ -677,10 +677,10 @@ class BaseHtml * and the array values are the extra attributes for the corresponding option tags. For example, * * ~~~ - * array( - * 'value1' => array('disabled' => true), - * 'value2' => array('label' => 'value 2'), - * ); + * [ + * 'value1' => ['disabled' => true], + * 'value2' => ['label' => 'value 2'], + * ]; * ~~~ * * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options', @@ -694,7 +694,7 @@ class BaseHtml * * @return string the generated list box tag */ - public static function listBox($name, $selection = null, $items = array(), $options = array()) + public static function listBox($name, $selection = null, $items = [], $options = []) { if (!isset($options['size'])) { $options['size'] = 4; @@ -746,7 +746,7 @@ class BaseHtml * value and the checked status of the checkbox input, respectively. * @return string the generated checkbox list */ - public static function checkboxList($name, $selection = null, $items = array(), $options = array()) + public static function checkboxList($name, $selection = null, $items = [], $options = []) { if (substr($name, -2) !== '[]') { $name .= '[]'; @@ -754,7 +754,7 @@ class BaseHtml $formatter = isset($options['item']) ? $options['item'] : null; $encode = !isset($options['encode']) || $options['encode']; - $lines = array(); + $lines = []; $index = 0; foreach ($items as $value => $label) { $checked = $selection !== null && @@ -763,10 +763,10 @@ class BaseHtml if ($formatter !== null) { $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value); } else { - $lines[] = static::checkbox($name, $checked, array( + $lines[] = static::checkbox($name, $checked, [ 'value' => $value, 'label' => $encode ? static::encode($label) : $label, - )); + ]); } $index++; } @@ -812,11 +812,11 @@ class BaseHtml * value and the checked status of the radio button input, respectively. * @return string the generated radio button list */ - public static function radioList($name, $selection = null, $items = array(), $options = array()) + public static function radioList($name, $selection = null, $items = [], $options = []) { $encode = !isset($options['encode']) || $options['encode']; $formatter = isset($options['item']) ? $options['item'] : null; - $lines = array(); + $lines = []; $index = 0; foreach ($items as $value => $label) { $checked = $selection !== null && @@ -825,10 +825,10 @@ class BaseHtml if ($formatter !== null) { $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value); } else { - $lines[] = static::radio($name, $checked, array( + $lines[] = static::radio($name, $checked, [ 'value' => $value, 'label' => $encode ? static::encode($label) : $label, - )); + ]); } $index++; } @@ -868,7 +868,7 @@ class BaseHtml * * @return string the generated unordered list. An empty string is returned if `$items` is empty. */ - public static function ul($items, $options = array()) + public static function ul($items, $options = []) { if (empty($items)) { return ''; @@ -876,9 +876,9 @@ class BaseHtml $tag = isset($options['tag']) ? $options['tag'] : 'ul'; $encode = !isset($options['encode']) || $options['encode']; $formatter = isset($options['item']) ? $options['item'] : null; - $itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : array(); + $itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : []; unset($options['tag'], $options['encode'], $options['item'], $options['itemOptions']); - $results = array(); + $results = []; foreach ($items as $index => $item) { if ($formatter !== null) { $results[] = call_user_func($formatter, $item, $index); @@ -910,7 +910,7 @@ class BaseHtml * * @return string the generated ordered list. An empty string is returned if `$items` is empty. */ - public static function ol($items, $options = array()) + public static function ol($items, $options = []) { $options['tag'] = 'ol'; return static::ul($items, $options); @@ -933,7 +933,7 @@ class BaseHtml * * @return string the generated label tag */ - public static function activeLabel($model, $attribute, $options = array()) + public static function activeLabel($model, $attribute, $options = []) { $attribute = static::getAttributeName($attribute); $label = isset($options['label']) ? $options['label'] : static::encode($model->getAttributeLabel($attribute)); @@ -957,7 +957,7 @@ class BaseHtml * * @return string the generated label tag */ - public static function error($model, $attribute, $options = array()) + public static function error($model, $attribute, $options = []) { $attribute = static::getAttributeName($attribute); $error = $model->getFirstError($attribute); @@ -978,7 +978,7 @@ class BaseHtml * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * @return string the generated input tag */ - public static function activeInput($type, $model, $attribute, $options = array()) + public static function activeInput($type, $model, $attribute, $options = []) { $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute); $value = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute); @@ -999,7 +999,7 @@ class BaseHtml * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * @return string the generated input tag */ - public static function activeTextInput($model, $attribute, $options = array()) + public static function activeTextInput($model, $attribute, $options = []) { return static::activeInput('text', $model, $attribute, $options); } @@ -1015,7 +1015,7 @@ class BaseHtml * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * @return string the generated input tag */ - public static function activeHiddenInput($model, $attribute, $options = array()) + public static function activeHiddenInput($model, $attribute, $options = []) { return static::activeInput('hidden', $model, $attribute, $options); } @@ -1031,7 +1031,7 @@ class BaseHtml * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * @return string the generated input tag */ - public static function activePasswordInput($model, $attribute, $options = array()) + public static function activePasswordInput($model, $attribute, $options = []) { return static::activeInput('password', $model, $attribute, $options); } @@ -1047,11 +1047,11 @@ class BaseHtml * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * @return string the generated input tag */ - public static function activeFileInput($model, $attribute, $options = array()) + public static function activeFileInput($model, $attribute, $options = []) { // add a hidden field so that if a model only has a file field, we can // still use isset($_POST[$modelClass]) to detect if the input is submitted - return static::activeHiddenInput($model, $attribute, array('id' => null, 'value' => '')) + return static::activeHiddenInput($model, $attribute, ['id' => null, 'value' => '']) . static::activeInput('file', $model, $attribute, $options); } @@ -1065,7 +1065,7 @@ class BaseHtml * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * @return string the generated textarea tag */ - public static function activeTextarea($model, $attribute, $options = array()) + public static function activeTextarea($model, $attribute, $options = []) { $name = static::getInputName($model, $attribute); $value = static::getAttributeValue($model, $attribute); @@ -1097,7 +1097,7 @@ class BaseHtml * * @return string the generated radio button tag */ - public static function activeRadio($model, $attribute, $options = array()) + public static function activeRadio($model, $attribute, $options = []) { $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute); $checked = static::getAttributeValue($model, $attribute); @@ -1132,7 +1132,7 @@ class BaseHtml * * @return string the generated checkbox tag */ - public static function activeCheckbox($model, $attribute, $options = array()) + public static function activeCheckbox($model, $attribute, $options = []) { $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute); $checked = static::getAttributeValue($model, $attribute); @@ -1166,10 +1166,10 @@ class BaseHtml * and the array values are the extra attributes for the corresponding option tags. For example, * * ~~~ - * array( - * 'value1' => array('disabled' => true), - * 'value2' => array('label' => 'value 2'), - * ); + * [ + * 'value1' => ['disabled' => true], + * 'value2' => ['label' => 'value 2'], + * ]; * ~~~ * * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options', @@ -1180,7 +1180,7 @@ class BaseHtml * * @return string the generated drop-down list tag */ - public static function activeDropDownList($model, $attribute, $items, $options = array()) + public static function activeDropDownList($model, $attribute, $items, $options = []) { $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute); $checked = static::getAttributeValue($model, $attribute); @@ -1211,10 +1211,10 @@ class BaseHtml * and the array values are the extra attributes for the corresponding option tags. For example, * * ~~~ - * array( - * 'value1' => array('disabled' => true), - * 'value2' => array('label' => 'value 2'), - * ); + * [ + * 'value1' => ['disabled' => true], + * 'value2' => ['label' => 'value 2'], + * ]; * ~~~ * * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options', @@ -1228,7 +1228,7 @@ class BaseHtml * * @return string the generated list box tag */ - public static function activeListBox($model, $attribute, $items, $options = array()) + public static function activeListBox($model, $attribute, $items, $options = []) { $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute); $checked = static::getAttributeValue($model, $attribute); @@ -1269,7 +1269,7 @@ class BaseHtml * value and the checked status of the checkbox input. * @return string the generated checkbox list */ - public static function activeCheckboxList($model, $attribute, $items, $options = array()) + public static function activeCheckboxList($model, $attribute, $items, $options = []) { $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute); $checked = static::getAttributeValue($model, $attribute); @@ -1309,7 +1309,7 @@ class BaseHtml * value and the checked status of the radio button input. * @return string the generated radio button list */ - public static function activeRadioList($model, $attribute, $items, $options = array()) + public static function activeRadioList($model, $attribute, $items, $options = []) { $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute); $checked = static::getAttributeValue($model, $attribute); @@ -1340,27 +1340,27 @@ class BaseHtml * * @return string the generated list options */ - public static function renderSelectOptions($selection, $items, &$tagOptions = array()) + public static function renderSelectOptions($selection, $items, &$tagOptions = []) { - $lines = array(); + $lines = []; if (isset($tagOptions['prompt'])) { $prompt = str_replace(' ', ' ', static::encode($tagOptions['prompt'])); - $lines[] = static::tag('option', $prompt, array('value' => '')); + $lines[] = static::tag('option', $prompt, ['value' => '']); } - $options = isset($tagOptions['options']) ? $tagOptions['options'] : array(); - $groups = isset($tagOptions['groups']) ? $tagOptions['groups'] : array(); + $options = isset($tagOptions['options']) ? $tagOptions['options'] : []; + $groups = isset($tagOptions['groups']) ? $tagOptions['groups'] : []; unset($tagOptions['prompt'], $tagOptions['options'], $tagOptions['groups']); foreach ($items as $key => $value) { if (is_array($value)) { - $groupAttrs = isset($groups[$key]) ? $groups[$key] : array(); + $groupAttrs = isset($groups[$key]) ? $groups[$key] : []; $groupAttrs['label'] = $key; - $attrs = array('options' => $options, 'groups' => $groups); + $attrs = ['options' => $options, 'groups' => $groups]; $content = static::renderSelectOptions($selection, $value, $attrs); $lines[] = static::tag('optgroup', "\n" . $content . "\n", $groupAttrs); } else { - $attrs = isset($options[$key]) ? $options[$key] : array(); + $attrs = isset($options[$key]) ? $options[$key] : []; $attrs['value'] = (string)$key; $attrs['selected'] = $selection !== null && (!is_array($selection) && !strcmp($key, $selection) @@ -1385,7 +1385,7 @@ class BaseHtml public static function renderTagAttributes($attributes) { if (count($attributes) > 1) { - $sorted = array(); + $sorted = []; foreach (static::$attributeOrder as $name) { if (isset($attributes[$name])) { $sorted[$name] = $attributes[$name]; @@ -1418,7 +1418,7 @@ class BaseHtml * will be prefixed with [[\yii\web\Request::baseUrl]] and returned. * - is an array: the first array element is considered a route, while the rest of the name-value * pairs are treated as the parameters to be used for URL creation using [[\yii\web\Controller::createUrl()]]. - * For example: `array('post/index', 'page' => 2)`, `array('index')`. + * For example: `['post/index', 'page' => 2]`, `['index']`. * In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used. * * @param array|string $url the parameter to be used to generate a valid URL @@ -1594,6 +1594,6 @@ class BaseHtml public static function getInputId($model, $attribute) { $name = strtolower(static::getInputName($model, $attribute)); - return str_replace(array('[]', '][', '[', ']', ' '), array('', '-', '-', '', '-'), $name); + return str_replace(['[]', '][', '[', ']', ' '], ['', '-', '-', '', '-'], $name); } } diff --git a/framework/yii/helpers/BaseInflector.php b/framework/yii/helpers/BaseInflector.php index affd3dd..8d5fe28 100644 --- a/framework/yii/helpers/BaseInflector.php +++ b/framework/yii/helpers/BaseInflector.php @@ -23,7 +23,7 @@ class BaseInflector * @var array the rules for converting a word into its plural form. * The keys are the regular expressions and the values are the corresponding replacements. */ - public static $plurals = array( + public static $plurals = [ '/([nrlm]ese|deer|fish|sheep|measles|ois|pox|media)$/i' => '\1', '/^(sea[- ]bass)$/i' => '\1', '/(m)ove$/i' => '\1oves', @@ -53,12 +53,12 @@ class BaseInflector '/s$/' => 's', '/^$/' => '', '/$/' => 's', - ); + ]; /** * @var array the rules for converting a word into its singular form. * The keys are the regular expressions and the values are the corresponding replacements. */ - public static $singulars = array( + public static $singulars = [ '/([nrlm]ese|deer|fish|sheep|measles|ois|pox|media|ss)$/i' => '\1', '/^(sea[- ]bass)$/i' => '\1', '/(s)tatuses$/i' => '\1tatus', @@ -97,12 +97,12 @@ class BaseInflector '/eaus$/' => 'eau', '/^(.*us)$/' => '\\1', '/s$/i' => '', - ); + ]; /** * @var array the special rules for converting a word between its plural form and singular form. * The keys are the special words in singular form, and the values are the corresponding plural form. */ - public static $specials = array( + public static $specials = [ 'atlas' => 'atlases', 'beef' => 'beefs', 'brother' => 'brothers', @@ -214,11 +214,11 @@ class BaseInflector 'whiting' => 'whiting', 'wildebeest' => 'wildebeest', 'Yengeese' => 'Yengeese', - ); + ]; /** * @var array map of special chars and its translation. This is used by [[slug()]]. */ - public static $transliteration = array( + public static $transliteration = [ '/ä|æ|ǽ/' => 'ae', '/ö|œ/' => 'oe', '/ü/' => 'ue', @@ -269,7 +269,7 @@ class BaseInflector '/ij/' => 'ij', '/Œ/' => 'OE', '/ƒ/' => 'f' - ); + ]; /** * Converts a word to its plural form. @@ -346,11 +346,11 @@ class BaseInflector */ public static function camel2words($name, $ucwords = true) { - $label = trim(strtolower(str_replace(array( + $label = trim(strtolower(str_replace([ '-', '_', '.' - ), ' ', preg_replace('/(? ' ', '/\\s+/' => $replacement, '/(?<=[a-z])([A-Z])/' => $replacement . '\\1', str_replace(':rep', preg_quote($replacement, '/'), '/^[:rep]+|[:rep]+$/') => '' - ); + ]; return preg_replace(array_keys($map), array_values($map), $string); } diff --git a/framework/yii/helpers/BaseJson.php b/framework/yii/helpers/BaseJson.php index 80224d5..35b35ff 100644 --- a/framework/yii/helpers/BaseJson.php +++ b/framework/yii/helpers/BaseJson.php @@ -33,7 +33,7 @@ class BaseJson */ public static function encode($value, $options = 0) { - $expressions = array(); + $expressions = []; $value = static::processData($value, $expressions, uniqid()); $json = json_encode($value, $options); return empty($expressions) ? $json : strtr($json, $expressions); @@ -88,7 +88,7 @@ class BaseJson return $token; } $data = $data instanceof Arrayable ? $data->toArray() : get_object_vars($data); - if ($data === array() && !$data instanceof Arrayable) { + if ($data === [] && !$data instanceof Arrayable) { return new \stdClass(); } } diff --git a/framework/yii/helpers/BaseMarkdown.php b/framework/yii/helpers/BaseMarkdown.php index 40a1dc4..5258534 100644 --- a/framework/yii/helpers/BaseMarkdown.php +++ b/framework/yii/helpers/BaseMarkdown.php @@ -31,7 +31,7 @@ class BaseMarkdown * @param array $config * @return string */ - public static function process($content, $config = array()) + public static function process($content, $config = []) { if (static::$markdown === null) { static::$markdown = new MarkdownExtra(); diff --git a/framework/yii/helpers/BaseSecurity.php b/framework/yii/helpers/BaseSecurity.php index a1b0ec4..6b7f1cf 100644 --- a/framework/yii/helpers/BaseSecurity.php +++ b/framework/yii/helpers/BaseSecurity.php @@ -186,7 +186,7 @@ class BaseSecurity static $keys; $keyFile = Yii::$app->getRuntimePath() . '/keys.php'; if ($keys === null) { - $keys = array(); + $keys = []; if (is_file($keyFile)) { $keys = require($keyFile); } diff --git a/framework/yii/helpers/BaseVarDumper.php b/framework/yii/helpers/BaseVarDumper.php index f109125..b11757b 100644 --- a/framework/yii/helpers/BaseVarDumper.php +++ b/framework/yii/helpers/BaseVarDumper.php @@ -47,7 +47,7 @@ class BaseVarDumper public static function dumpAsString($var, $depth = 10, $highlight = false) { self::$_output = ''; - self::$_objects = array(); + self::$_objects = []; self::$_depth = $depth; self::dumpInternal($var, 0); if ($highlight) { @@ -87,20 +87,20 @@ class BaseVarDumper break; case 'array': if (self::$_depth <= $level) { - self::$_output .= 'array(...)'; + self::$_output .= '[...]'; } elseif (empty($var)) { - self::$_output .= 'array()'; + self::$_output .= '[]'; } else { $keys = array_keys($var); $spaces = str_repeat(' ', $level * 4); - self::$_output .= "array\n" . $spaces . '('; + self::$_output .= '['; foreach ($keys as $key) { self::$_output .= "\n" . $spaces . ' '; self::dumpInternal($key, 0); self::$_output .= ' => '; self::dumpInternal($var[$key], $level + 1); } - self::$_output .= "\n" . $spaces . ')'; + self::$_output .= "\n" . $spaces . ']'; } break; case 'object': @@ -115,7 +115,7 @@ class BaseVarDumper $spaces = str_repeat(' ', $level * 4); self::$_output .= "$className#$id\n" . $spaces . '('; foreach ($members as $key => $value) { - $keyDisplay = strtr(trim($key), array("\0" => ':')); + $keyDisplay = strtr(trim($key), ["\0" => ':']); self::$_output .= "\n" . $spaces . " [$keyDisplay] => "; self::dumpInternal($value, $level + 1); } diff --git a/framework/yii/helpers/HtmlPurifier.php b/framework/yii/helpers/HtmlPurifier.php index e1511e4..f2852ad 100644 --- a/framework/yii/helpers/HtmlPurifier.php +++ b/framework/yii/helpers/HtmlPurifier.php @@ -19,9 +19,9 @@ namespace yii\helpers; * If you want to configure it: * * ```php - * echo HtmlPurifier::process($html, array( + * echo HtmlPurifier::process($html, [ * 'Attr.EnableID' => true, - * )); + * ]); * ``` * * For more details please refer to HTMLPurifier documentation](http://htmlpurifier.org/). diff --git a/framework/yii/helpers/Markdown.php b/framework/yii/helpers/Markdown.php index 3dcc750..326cd34 100644 --- a/framework/yii/helpers/Markdown.php +++ b/framework/yii/helpers/Markdown.php @@ -19,9 +19,9 @@ namespace yii\helpers; * If you want to configure the parser: * * ```php - * $myHtml = Markdown::process($myText, array( + * $myHtml = Markdown::process($myText, [ * 'fn_id_prefix' => 'footnote_', - * )); + * ]); * ``` * * Note that in order to use this helper you need to install "michelf/php-markdown" Composer package. diff --git a/framework/yii/helpers/mimeTypes.php b/framework/yii/helpers/mimeTypes.php index ffdba4b..4e9f61a 100644 --- a/framework/yii/helpers/mimeTypes.php +++ b/framework/yii/helpers/mimeTypes.php @@ -11,7 +11,7 @@ * @since 2.0 */ -return array( +return [ 'ai' => 'application/postscript', 'aif' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', @@ -184,4 +184,4 @@ return array( 'xwd' => 'image/x-xwindowdump', 'xyz' => 'chemical/x-pdb', 'zip' => 'application/zip', -); +]; diff --git a/framework/yii/i18n/DbMessageSource.php b/framework/yii/i18n/DbMessageSource.php index 14cf0b9..b660a86 100644 --- a/framework/yii/i18n/DbMessageSource.php +++ b/framework/yii/i18n/DbMessageSource.php @@ -121,11 +121,11 @@ class DbMessageSource extends MessageSource protected function loadMessages($category, $language) { if ($this->enableCaching) { - $key = array( + $key = [ __CLASS__, $category, $language, - ); + ]; $messages = $this->cache->get($key); if ($messages === false) { $messages = $this->loadMessagesFromDb($category, $language); @@ -147,10 +147,10 @@ class DbMessageSource extends MessageSource protected function loadMessagesFromDb($category, $language) { $query = new Query(); - $messages = $query->select(array('t1.message message', 't2.translation translation')) - ->from(array($this->sourceMessageTable . ' t1', $this->messageTable . ' t2')) + $messages = $query->select(['t1.message message', 't2.translation translation']) + ->from([$this->sourceMessageTable . ' t1', $this->messageTable . ' t2']) ->where('t1.id = t2.id AND t1.category = :category AND t2.language = :language') - ->params(array(':category' => $category, ':language' => $language)) + ->params([':category' => $category, ':language' => $language]) ->createCommand($this->db) ->queryAll(); return ArrayHelper::map($messages, 'message', 'translation'); diff --git a/framework/yii/i18n/Formatter.php b/framework/yii/i18n/Formatter.php index 979a46f..3fcc189 100644 --- a/framework/yii/i18n/Formatter.php +++ b/framework/yii/i18n/Formatter.php @@ -53,7 +53,7 @@ class Formatter extends \yii\base\Formatter * for the possible options. This property is used by [[createNumberFormatter]] when * creating a new number formatter to format decimals, currencies, etc. */ - public $numberFormatOptions = array(); + public $numberFormatOptions = []; /** * @var string the character displayed as the decimal point when formatting a number. * If not set, the decimal separator corresponding to [[locale]] will be used. @@ -93,12 +93,12 @@ class Formatter extends \yii\base\Formatter parent::init(); } - private $_dateFormats = array( + private $_dateFormats = [ 'short' => IntlDateFormatter::SHORT, 'medium' => IntlDateFormatter::MEDIUM, 'long' => IntlDateFormatter::LONG, 'full' => IntlDateFormatter::FULL, - ); + ]; /** * Formats the value as a date. diff --git a/framework/yii/i18n/GettextMessageSource.php b/framework/yii/i18n/GettextMessageSource.php index 745eb38..66704c4 100644 --- a/framework/yii/i18n/GettextMessageSource.php +++ b/framework/yii/i18n/GettextMessageSource.php @@ -68,18 +68,18 @@ class GettextMessageSource extends MessageSource if (is_file($messageFile)) { if ($this->useMoFile) { - $gettextFile = new GettextMoFile(array('useBigEndian' => $this->useBigEndian)); + $gettextFile = new GettextMoFile(['useBigEndian' => $this->useBigEndian]); } else { $gettextFile = new GettextPoFile(); } $messages = $gettextFile->load($messageFile, $category); if (!is_array($messages)) { - $messages = array(); + $messages = []; } return $messages; } else { Yii::error("The message file for category '$category' does not exist: $messageFile", __METHOD__); - return array(); + return []; } } } diff --git a/framework/yii/i18n/GettextMoFile.php b/framework/yii/i18n/GettextMoFile.php index c12aebe..a92293c 100644 --- a/framework/yii/i18n/GettextMoFile.php +++ b/framework/yii/i18n/GettextMoFile.php @@ -85,23 +85,23 @@ class GettextMoFile extends GettextFile $sourceOffset = $this->readInteger($fileHandle); $targetOffset = $this->readInteger($fileHandle); - $sourceLengths = array(); - $sourceOffsets = array(); + $sourceLengths = []; + $sourceOffsets = []; fseek($fileHandle, $sourceOffset); for ($i = 0; $i < $count; ++$i) { $sourceLengths[] = $this->readInteger($fileHandle); $sourceOffsets[] = $this->readInteger($fileHandle); } - $targetLengths = array(); - $targetOffsets = array(); + $targetLengths = []; + $targetOffsets = []; fseek($fileHandle, $targetOffset); for ($i = 0; $i < $count; ++$i) { $targetLengths[] = $this->readInteger($fileHandle); $targetOffsets[] = $this->readInteger($fileHandle); } - $messages = array(); + $messages = []; for ($i = 0; $i < $count; ++$i) { $id = $this->readString($fileHandle, $sourceLengths[$i], $sourceOffsets[$i]); $separatorPosition = strpos($id, chr(4)); diff --git a/framework/yii/i18n/GettextPoFile.php b/framework/yii/i18n/GettextPoFile.php index cac075b..8fb618c 100644 --- a/framework/yii/i18n/GettextPoFile.php +++ b/framework/yii/i18n/GettextPoFile.php @@ -30,10 +30,10 @@ class GettextPoFile extends GettextFile . 'msgid\s+((?:".*(?decode($matches[3][$i]); @@ -74,8 +74,8 @@ class GettextPoFile extends GettextFile protected function encode($string) { return str_replace( - array('"', "\n", "\t", "\r"), - array('\\"', '\\n', '\\t', '\\r'), + ['"', "\n", "\t", "\r"], + ['\\"', '\\n', '\\t', '\\r'], $string ); } @@ -88,8 +88,8 @@ class GettextPoFile extends GettextFile protected function decode($string) { $string = preg_replace( - array('/"\s+"/', '/\\\\n/', '/\\\\r/', '/\\\\t/', '/\\\\"/'), - array('', "\n", "\r", "\t", '"'), + ['/"\s+"/', '/\\\\n/', '/\\\\r/', '/\\\\t/', '/\\\\"/'], + ['', "\n", "\r", "\t", '"'], $string ); return substr(rtrim($string), 1, -1); diff --git a/framework/yii/i18n/I18N.php b/framework/yii/i18n/I18N.php index 625ba5c..779d89f 100644 --- a/framework/yii/i18n/I18N.php +++ b/framework/yii/i18n/I18N.php @@ -45,18 +45,18 @@ class I18N extends Component { parent::init(); if (!isset($this->translations['yii'])) { - $this->translations['yii'] = array( + $this->translations['yii'] = [ 'class' => 'yii\i18n\PhpMessageSource', 'sourceLanguage' => 'en_US', 'basePath' => '@yii/messages', - ); + ]; } if (!isset($this->translations['app'])) { - $this->translations['app'] = array( + $this->translations['app'] = [ 'class' => 'yii\i18n\PhpMessageSource', 'sourceLanguage' => 'en_US', 'basePath' => '@app/messages', - ); + ]; } } @@ -74,7 +74,7 @@ class I18N extends Component $message = $this->getMessageSource($category)->translate($category, $message, $language); $params = (array)$params; - if ($params === array()) { + if ($params === []) { return $message; } @@ -94,7 +94,7 @@ class I18N extends Component } } - $p = array(); + $p = []; foreach($params as $name => $value) { $p['{' . $name . '}'] = $value; } diff --git a/framework/yii/i18n/MessageFormatter.php b/framework/yii/i18n/MessageFormatter.php index 2325573..93c4563 100644 --- a/framework/yii/i18n/MessageFormatter.php +++ b/framework/yii/i18n/MessageFormatter.php @@ -30,7 +30,7 @@ class MessageFormatter extends \MessageFormatter */ public function format($args) { - if ($args === array()) { + if ($args === []) { return $this->getPattern(); } @@ -53,7 +53,7 @@ class MessageFormatter extends \MessageFormatter */ public static function formatMessage($locale, $pattern, $args) { - if ($args === array()) { + if ($args === []) { return $pattern; } @@ -81,7 +81,7 @@ class MessageFormatter extends \MessageFormatter $c = count($parts); $pattern = $parts[0]; $d = 0; - $stack = array(); + $stack = []; for($i = 1; $i < $c; $i++) { if (preg_match('~^(\s*)([\d\w]+)(\s*)([},])(\s*)(.*)$~us', $parts[$i], $matches)) { // if we are not inside a plural or select this is a message diff --git a/framework/yii/i18n/MessageSource.php b/framework/yii/i18n/MessageSource.php index 90adbfb..95f907d 100644 --- a/framework/yii/i18n/MessageSource.php +++ b/framework/yii/i18n/MessageSource.php @@ -38,7 +38,7 @@ class MessageSource extends Component */ public $sourceLanguage; - private $_messages = array(); + private $_messages = []; /** * Initializes this component. @@ -62,7 +62,7 @@ class MessageSource extends Component */ protected function loadMessages($category, $language) { - return array(); + return []; } /** @@ -106,11 +106,11 @@ class MessageSource extends Component if (isset($this->_messages[$key][$message]) && $this->_messages[$key][$message] !== '') { return $this->_messages[$key][$message]; } elseif ($this->hasEventHandlers('missingTranslation')) { - $event = new MissingTranslationEvent(array( + $event = new MissingTranslationEvent([ 'category' => $category, 'message' => $message, 'language' => $language, - )); + ]); $this->trigger(self::EVENT_MISSING_TRANSLATION, $event); return $this->_messages[$key] = $event->message; } else { diff --git a/framework/yii/i18n/PhpMessageSource.php b/framework/yii/i18n/PhpMessageSource.php index 1cd2103..e105083 100644 --- a/framework/yii/i18n/PhpMessageSource.php +++ b/framework/yii/i18n/PhpMessageSource.php @@ -20,10 +20,10 @@ use Yii; * - Within each PHP script, the message translations are returned as an array like the following: * * ~~~ - * return array( + * return [ * 'original message 1' => 'translated message 1', * 'original message 2' => 'translated message 2', - * ); + * ]; * ~~~ * * You may use [[fileMap]] to customize the association between category names and the file names. @@ -43,10 +43,10 @@ class PhpMessageSource extends MessageSource * The file paths are relative to [[basePath]]. For example, * * ~~~ - * array( + * [ * 'core' => 'core.php', * 'ext' => 'extensions.php', - * ) + * ] * ~~~ */ public $fileMap; @@ -68,12 +68,12 @@ class PhpMessageSource extends MessageSource if (is_file($messageFile)) { $messages = include($messageFile); if (!is_array($messages)) { - $messages = array(); + $messages = []; } return $messages; } else { Yii::error("The message file for category '$category' does not exist: $messageFile", __METHOD__); - return array(); + return []; } } } diff --git a/framework/yii/log/DbTarget.php b/framework/yii/log/DbTarget.php index a828a72..b649e9e 100644 --- a/framework/yii/log/DbTarget.php +++ b/framework/yii/log/DbTarget.php @@ -80,12 +80,12 @@ class DbTarget extends Target VALUES (:level, :category, :log_time, :message)"; $command = $this->db->createCommand($sql); foreach ($this->messages as $message) { - $command->bindValues(array( + $command->bindValues([ ':level' => $message[1], ':category' => $message[2], ':log_time' => $message[3], ':message' => $message[0], - ))->execute(); + ])->execute(); } } } diff --git a/framework/yii/log/EmailTarget.php b/framework/yii/log/EmailTarget.php index 8ae1a88..8ca3d97 100644 --- a/framework/yii/log/EmailTarget.php +++ b/framework/yii/log/EmailTarget.php @@ -22,7 +22,7 @@ class EmailTarget extends Target /** * @var array list of destination email addresses. */ - public $emails = array(); + public $emails = []; /** * @var string email subject */ @@ -34,7 +34,7 @@ class EmailTarget extends Target /** * @var array list of additional headers to use when sending an email. */ - public $headers = array(); + public $headers = []; /** * Sends log messages to specified email addresses. diff --git a/framework/yii/log/Logger.php b/framework/yii/log/Logger.php index 2046ecc..ad0ab8d 100644 --- a/framework/yii/log/Logger.php +++ b/framework/yii/log/Logger.php @@ -31,24 +31,24 @@ use yii\base\InvalidConfigException; * You may configure the targets in application configuration, like the following: * * ~~~ - * array( - * 'components' => array( - * 'log' => array( - * 'targets' => array( - * 'file' => array( + * [ + * 'components' => [ + * 'log' => [ + * 'targets' => [ + * 'file' => [ * 'class' => 'yii\log\FileTarget', - * 'levels' => array('trace', 'info'), - * 'categories' => array('yii\*'), + * 'levels' => ['trace', 'info'], + * 'categories' => ['yii\*'], * ), - * 'email' => array( + * 'email' => [ * 'class' => 'yii\log\EmailTarget', - * 'levels' => array('error', 'warning'), - * 'emails' => array('admin@example.com'), - * ), - * ), - * ), - * ), - * ) + * 'levels' => ['error', 'warning'], + * 'emails' => ['admin@example.com'], + * ], + * ], + * ], + * ], + * ] * ~~~ * * Each log target can have a name and can be referenced via the [[targets]] property @@ -66,7 +66,7 @@ use yii\base\InvalidConfigException; * @property float $elapsedTime The total elapsed time in seconds for current request. This property is * read-only. * @property array $profiling The profiling results. Each array element has the following structure: - * `array($token, $category, $time)`. This property is read-only. + * `[$token, $category, $time]`. This property is read-only. * * @author Qiang Xue * @since 2.0 @@ -113,26 +113,26 @@ class Logger extends Component * Each log message is of the following structure: * * ~~~ - * array( + * [ * [0] => message (mixed, can be a string or some complex data, such as an exception object) * [1] => level (integer) * [2] => category (string) * [3] => timestamp (float, obtained by microtime(true)) * [4] => traces (array, debug backtrace, contains the application code call stacks) - * ) + * ] * ~~~ */ - public $messages = array(); + public $messages = []; /** * @var array debug data. This property stores various types of debug data reported at * different instrument places. */ - public $data = array(); + public $data = []; /** * @var array|Target[] the log targets. Each array element represents a single [[Target|log target]] instance * or the configuration for creating the log target instance. */ - public $targets = array(); + public $targets = []; /** * @var integer how many messages should be logged before they are flushed from memory and sent to targets. * Defaults to 1000, meaning the [[flush]] method will be invoked once every 1000 messages logged. @@ -164,7 +164,7 @@ class Logger extends Component $this->targets[$name] = Yii::createObject($target); } } - register_shutdown_function(array($this, 'flush'), true); + register_shutdown_function([$this, 'flush'], true); } /** @@ -180,7 +180,7 @@ class Logger extends Component public function log($message, $level, $category = 'application') { $time = microtime(true); - $traces = array(); + $traces = []; if ($this->traceLevel > 0) { $count = 0; $ts = debug_backtrace(); @@ -195,7 +195,7 @@ class Logger extends Component } } } - $this->messages[] = array($message, $level, $category, $time, $traces); + $this->messages[] = [$message, $level, $category, $time, $traces]; if ($this->flushInterval > 0 && count($this->messages) >= $this->flushInterval) { $this->flush(); } @@ -213,7 +213,7 @@ class Logger extends Component $target->collect($this->messages, $final); } } - $this->messages = array(); + $this->messages = []; } /** @@ -241,9 +241,9 @@ class Logger extends Component * such as 'yii\db\Connection'. * @param array $excludeCategories list of categories that you want to exclude * @return array the profiling results. Each array element has the following structure: - * `array($token, $category, $time)`. + * `[$token, $category, $time]`. */ - public function getProfiling($categories = array(), $excludeCategories = array()) + public function getProfiling($categories = [], $excludeCategories = []) { $timings = $this->calculateTimings(); if (empty($categories) && empty($excludeCategories)) { @@ -288,27 +288,26 @@ class Logger extends Component */ public function getDbProfiling() { - $timings = $this->getProfiling(array('yii\db\Command::query', 'yii\db\Command::execute')); + $timings = $this->getProfiling(['yii\db\Command::query', 'yii\db\Command::execute']); $count = count($timings); $time = 0; foreach ($timings as $timing) { $time += $timing[1]; } - return array($count, $time); + return [$count, $time]; } private function calculateTimings() { - $timings = array(); - - $stack = array(); + $timings = []; + $stack = []; foreach ($this->messages as $log) { list($token, $level, $category, $timestamp) = $log; if ($level == self::LEVEL_PROFILE_BEGIN) { $stack[] = $log; } elseif ($level == self::LEVEL_PROFILE_END) { if (($last = array_pop($stack)) !== null && $last[0] === $token) { - $timings[] = array($token, $category, $timestamp - $last[3]); + $timings[] = [$token, $category, $timestamp - $last[3]]; } else { throw new InvalidConfigException("Unmatched profiling block: $token"); } @@ -318,7 +317,7 @@ class Logger extends Component $now = microtime(true); while (($last = array_pop($stack)) !== null) { $delta = $now - $last[3]; - $timings[] = array($last[0], $last[2], $delta); + $timings[] = [$last[0], $last[2], $delta]; } return $timings; @@ -331,14 +330,14 @@ class Logger extends Component */ public static function getLevelName($level) { - static $levels = array( + static $levels = [ self::LEVEL_ERROR => 'error', self::LEVEL_WARNING => 'warning', self::LEVEL_INFO => 'info', self::LEVEL_TRACE => 'trace', self::LEVEL_PROFILE_BEGIN => 'profile begin', self::LEVEL_PROFILE_END => 'profile end', - ); + ]; return isset($levels[$level]) ? $levels[$level] : 'unknown'; } } diff --git a/framework/yii/log/Target.php b/framework/yii/log/Target.php index 0cb72ef..cd1256a 100644 --- a/framework/yii/log/Target.php +++ b/framework/yii/log/Target.php @@ -41,7 +41,7 @@ abstract class Target extends Component * match those categories sharing the same common prefix. For example, 'yii\db\*' will match * categories starting with 'yii\db\', such as 'yii\db\Connection'. */ - public $categories = array(); + public $categories = []; /** * @var array list of message categories that this target is NOT interested in. Defaults to empty, meaning no uninteresting messages. * If this property is not empty, then any category listed here will be excluded from [[categories]]. @@ -50,7 +50,7 @@ abstract class Target extends Component * categories starting with 'yii\db\', such as 'yii\db\Connection'. * @see categories */ - public $except = array(); + public $except = []; /** * @var boolean whether to log a message containing the current user name and ID. Defaults to false. * @see \yii\web\User @@ -59,9 +59,9 @@ abstract class Target extends Component /** * @var array list of the PHP predefined variables that should be logged in a message. * Note that a variable must be accessible via `$GLOBALS`. Otherwise it won't be logged. - * Defaults to `array('_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER')`. + * Defaults to `['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER']`. */ - public $logVars = array('_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER'); + public $logVars = ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER']; /** * @var integer how many messages should be accumulated before they are exported. * Defaults to 1000. Note that messages will always be exported when the application terminates. @@ -72,7 +72,7 @@ abstract class Target extends Component * @var array the messages that are retrieved from the logger so far by this log target. * Please refer to [[Logger::messages]] for the details about the message structure. */ - public $messages = array(); + public $messages = []; private $_levels = 0; @@ -96,10 +96,10 @@ abstract class Target extends Component $count = count($this->messages); if ($count > 0 && ($final || $this->exportInterval > 0 && $count >= $this->exportInterval)) { if (($context = $this->getContextMessage()) !== '') { - $this->messages[] = array($context, Logger::LEVEL_INFO, 'application', YII_BEGIN_TIME); + $this->messages[] = [$context, Logger::LEVEL_INFO, 'application', YII_BEGIN_TIME]; } $this->export(); - $this->messages = array(); + $this->messages = []; } } @@ -110,7 +110,7 @@ abstract class Target extends Component */ protected function getContextMessage() { - $context = array(); + $context = []; if ($this->logUser && ($user = Yii::$app->getComponent('user', false)) !== null) { /** @var $user \yii\web\User */ $context[] = 'User: ' . $user->getId(); @@ -146,7 +146,7 @@ abstract class Target extends Component * For example, * * ~~~ - * array('error', 'warning') + * ['error', 'warning'] * // which is equivalent to: * Logger::LEVEL_ERROR | Logger::LEVEL_WARNING * ~~~ @@ -156,13 +156,13 @@ abstract class Target extends Component */ public function setLevels($levels) { - static $levelMap = array( + static $levelMap = [ 'error' => Logger::LEVEL_ERROR, 'warning' => Logger::LEVEL_WARNING, 'info' => Logger::LEVEL_INFO, 'trace' => Logger::LEVEL_TRACE, 'profile' => Logger::LEVEL_PROFILE, - ); + ]; if (is_array($levels)) { $this->_levels = 0; foreach ($levels as $level) { @@ -186,7 +186,7 @@ abstract class Target extends Component * @param array $except the message categories to exclude. If empty, it means all categories are allowed. * @return array the filtered messages. */ - public static function filterMessages($messages, $levels = 0, $categories = array(), $except = array()) + public static function filterMessages($messages, $levels = 0, $categories = [], $except = []) { foreach ($messages as $i => $message) { if ($levels && !($levels & $message[1])) { diff --git a/framework/yii/messages/config.php b/framework/yii/messages/config.php index e1c79ff..0f724ba 100644 --- a/framework/yii/messages/config.php +++ b/framework/yii/messages/config.php @@ -1,13 +1,13 @@ __DIR__ . '/..', // string, required, root directory containing message translations. 'messagePath' => __DIR__, // array, required, list of language codes that the extracted messages - // should be translated to. For example, array('zh_cn', 'de'). - 'languages' => array('de'), + // should be translated to. For example, ['zh_cn', 'de']. + 'languages' => ['de'], // string, the name of the function for translating messages. // Defaults to 'Yii::t'. This is used as a mark to find the messages to be // translated. You may use a string for single function name or an array for @@ -29,11 +29,11 @@ return array( // and the '.svn' will match all files and directories whose name ends with '.svn'. // Note, the '/' characters in a pattern matches both '/' and '\'. // If a file/directory matches both a pattern in "only" and "except", it will NOT be processed. - 'only' => array('.php'), + 'only' => ['.php'], // array, list of patterns that specify which files/directories should NOT be processed. // If empty or not set, all files/directories will be processed. // Please refer to "only" for details about the patterns. - 'except' => array( + 'except' => [ '.svn', '.git', '.gitignore', @@ -41,5 +41,5 @@ return array( '.hgignore', '.hgkeep', '/messages', - ), -); + ], +]; diff --git a/framework/yii/rbac/DbManager.php b/framework/yii/rbac/DbManager.php index 46c375f..0e1f8cc 100644 --- a/framework/yii/rbac/DbManager.php +++ b/framework/yii/rbac/DbManager.php @@ -79,7 +79,7 @@ class DbManager extends Manager * which holds the value of `$userId`. * @return boolean whether the operations can be performed by the user. */ - public function checkAccess($userId, $itemName, $params = array()) + public function checkAccess($userId, $itemName, $params = []) { $assignments = $this->getAssignments($userId); return $this->checkAccessRecursive($userId, $itemName, $params, $assignments); @@ -117,9 +117,9 @@ class DbManager extends Manager } } $query = new Query; - $parents = $query->select(array('parent')) + $parents = $query->select(['parent']) ->from($this->itemChildTable) - ->where(array('child' => $itemName)) + ->where(['child' => $itemName]) ->createCommand($this->db) ->queryColumn(); foreach ($parents as $parent) { @@ -146,7 +146,7 @@ class DbManager extends Manager } $query = new Query; $rows = $query->from($this->itemTable) - ->where(array('or', 'name=:name1', 'name=:name2'), array(':name1' => $itemName, ':name2' => $childName)) + ->where(['or', 'name=:name1', 'name=:name2'], [':name1' => $itemName, ':name2' => $childName]) ->createCommand($this->db) ->queryAll(); if (count($rows) == 2) { @@ -162,7 +162,7 @@ class DbManager extends Manager throw new InvalidCallException("Cannot add '$childName' as a child of '$itemName'. A loop has been detected."); } $this->db->createCommand() - ->insert($this->itemChildTable, array('parent' => $itemName, 'child' => $childName)) + ->insert($this->itemChildTable, ['parent' => $itemName, 'child' => $childName]) ->execute(); return true; } else { @@ -180,7 +180,7 @@ class DbManager extends Manager public function removeItemChild($itemName, $childName) { return $this->db->createCommand() - ->delete($this->itemChildTable, array('parent' => $itemName, 'child' => $childName)) + ->delete($this->itemChildTable, ['parent' => $itemName, 'child' => $childName]) ->execute() > 0; } @@ -193,9 +193,9 @@ class DbManager extends Manager public function hasItemChild($itemName, $childName) { $query = new Query; - return $query->select(array('parent')) + return $query->select(['parent']) ->from($this->itemChildTable) - ->where(array('parent' => $itemName, 'child' => $childName)) + ->where(['parent' => $itemName, 'child' => $childName]) ->createCommand($this->db) ->queryScalar() !== false; } @@ -209,24 +209,24 @@ class DbManager extends Manager public function getItemChildren($names) { $query = new Query; - $rows = $query->select(array('name', 'type', 'description', 'biz_rule', 'data')) - ->from(array($this->itemTable, $this->itemChildTable)) - ->where(array('parent' => $names, 'name' => new Expression('child'))) + $rows = $query->select(['name', 'type', 'description', 'biz_rule', 'data']) + ->from([$this->itemTable, $this->itemChildTable]) + ->where(['parent' => $names, 'name' => new Expression('child')]) ->createCommand($this->db) ->queryAll(); - $children = array(); + $children = []; foreach ($rows as $row) { if (($data = @unserialize($row['data'])) === false) { $data = null; } - $children[$row['name']] = new Item(array( + $children[$row['name']] = new Item([ 'manager' => $this, 'name' => $row['name'], 'type' => $row['type'], 'description' => $row['description'], 'bizRule' => $row['biz_rule'], 'data' => $data, - )); + ]); } return $children; } @@ -247,20 +247,20 @@ class DbManager extends Manager throw new InvalidParamException("The item '$itemName' does not exist."); } $this->db->createCommand() - ->insert($this->assignmentTable, array( + ->insert($this->assignmentTable, [ 'user_id' => $userId, 'item_name' => $itemName, 'biz_rule' => $bizRule, 'data' => serialize($data), - )) + ]) ->execute(); - return new Assignment(array( + return new Assignment([ 'manager' => $this, 'userId' => $userId, 'itemName' => $itemName, 'bizRule' => $bizRule, 'data' => $data, - )); + ]); } /** @@ -272,7 +272,7 @@ class DbManager extends Manager public function revoke($userId, $itemName) { return $this->db->createCommand() - ->delete($this->assignmentTable, array('user_id' => $userId, 'item_name' => $itemName)) + ->delete($this->assignmentTable, ['user_id' => $userId, 'item_name' => $itemName]) ->execute() > 0; } @@ -285,9 +285,9 @@ class DbManager extends Manager public function isAssigned($userId, $itemName) { $query = new Query; - return $query->select(array('item_name')) + return $query->select(['item_name']) ->from($this->assignmentTable) - ->where(array('user_id' => $userId, 'item_name' => $itemName)) + ->where(['user_id' => $userId, 'item_name' => $itemName]) ->createCommand($this->db) ->queryScalar() !== false; } @@ -303,20 +303,20 @@ class DbManager extends Manager { $query = new Query; $row = $query->from($this->assignmentTable) - ->where(array('user_id' => $userId, 'item_name' => $itemName)) + ->where(['user_id' => $userId, 'item_name' => $itemName]) ->createCommand($this->db) ->queryOne(); if ($row !== false) { if (($data = @unserialize($row['data'])) === false) { $data = null; } - return new Assignment(array( + return new Assignment([ 'manager' => $this, 'userId' => $row['user_id'], 'itemName' => $row['item_name'], 'bizRule' => $row['biz_rule'], 'data' => $data, - )); + ]); } else { return null; } @@ -332,21 +332,21 @@ class DbManager extends Manager { $query = new Query; $rows = $query->from($this->assignmentTable) - ->where(array('user_id' => $userId)) + ->where(['user_id' => $userId]) ->createCommand($this->db) ->queryAll(); - $assignments = array(); + $assignments = []; foreach ($rows as $row) { if (($data = @unserialize($row['data'])) === false) { $data = null; } - $assignments[$row['item_name']] = new Assignment(array( + $assignments[$row['item_name']] = new Assignment([ 'manager' => $this, 'userId' => $row['user_id'], 'itemName' => $row['item_name'], 'bizRule' => $row['biz_rule'], 'data' => $data, - )); + ]); } return $assignments; } @@ -358,13 +358,13 @@ class DbManager extends Manager public function saveAssignment($assignment) { $this->db->createCommand() - ->update($this->assignmentTable, array( + ->update($this->assignmentTable, [ 'biz_rule' => $assignment->bizRule, 'data' => serialize($assignment->data), - ), array( + ], [ 'user_id' => $assignment->userId, 'item_name' => $assignment->itemName, - )) + ]) ->execute(); } @@ -384,32 +384,32 @@ class DbManager extends Manager ->createCommand($this->db); } elseif ($userId === null) { $command = $query->from($this->itemTable) - ->where(array('type' => $type)) + ->where(['type' => $type]) ->createCommand($this->db); } elseif ($type === null) { - $command = $query->select(array('name', 'type', 'description', 't1.biz_rule', 't1.data')) - ->from(array($this->itemTable . ' t1', $this->assignmentTable . ' t2')) - ->where(array('user_id' => $userId, 'name' => new Expression('item_name'))) + $command = $query->select(['name', 'type', 'description', 't1.biz_rule', 't1.data']) + ->from([$this->itemTable . ' t1', $this->assignmentTable . ' t2']) + ->where(['user_id' => $userId, 'name' => new Expression('item_name')]) ->createCommand($this->db); } else { $command = $query->select('name', 'type', 'description', 't1.biz_rule', 't1.data') - ->from(array($this->itemTable . ' t1', $this->assignmentTable . ' t2')) - ->where(array('user_id' => $userId, 'type' => $type, 'name' => new Expression('item_name'))) + ->from([$this->itemTable . ' t1', $this->assignmentTable . ' t2']) + ->where(['user_id' => $userId, 'type' => $type, 'name' => new Expression('item_name')]) ->createCommand($this->db); } - $items = array(); + $items = []; foreach ($command->queryAll() as $row) { if (($data = @unserialize($row['data'])) === false) { $data = null; } - $items[$row['name']] = new Item(array( + $items[$row['name']] = new Item([ 'manager' => $this, 'name' => $row['name'], 'type' => $row['type'], 'description' => $row['description'], 'bizRule' => $row['biz_rule'], 'data' => $data, - )); + ]); } return $items; } @@ -432,22 +432,22 @@ class DbManager extends Manager public function createItem($name, $type, $description = '', $bizRule = null, $data = null) { $this->db->createCommand() - ->insert($this->itemTable, array( + ->insert($this->itemTable, [ 'name' => $name, 'type' => $type, 'description' => $description, 'biz_rule' => $bizRule, 'data' => serialize($data), - )) + ]) ->execute(); - return new Item(array( + return new Item([ 'manager' => $this, 'name' => $name, 'type' => $type, 'description' => $description, 'bizRule' => $bizRule, 'data' => $data, - )); + ]); } /** @@ -459,14 +459,14 @@ class DbManager extends Manager { if ($this->usingSqlite()) { $this->db->createCommand() - ->delete($this->itemChildTable, array('or', 'parent=:name', 'child=:name'), array(':name' => $name)) + ->delete($this->itemChildTable, ['or', 'parent=:name', 'child=:name'], [':name' => $name]) ->execute(); $this->db->createCommand() - ->delete($this->assignmentTable, array('item_name' => $name)) + ->delete($this->assignmentTable, ['item_name' => $name]) ->execute(); } return $this->db->createCommand() - ->delete($this->itemTable, array('name' => $name)) + ->delete($this->itemTable, ['name' => $name]) ->execute() > 0; } @@ -479,7 +479,7 @@ class DbManager extends Manager { $query = new Query; $row = $query->from($this->itemTable) - ->where(array('name' => $name)) + ->where(['name' => $name]) ->createCommand($this->db) ->queryOne(); @@ -487,14 +487,14 @@ class DbManager extends Manager if (($data = @unserialize($row['data'])) === false) { $data = null; } - return new Item(array( + return new Item([ 'manager' => $this, 'name' => $row['name'], 'type' => $row['type'], 'description' => $row['description'], 'bizRule' => $row['biz_rule'], 'data' => $data, - )); + ]); } else { return null; } @@ -509,26 +509,26 @@ class DbManager extends Manager { if ($this->usingSqlite() && $oldName !== null && $item->getName() !== $oldName) { $this->db->createCommand() - ->update($this->itemChildTable, array('parent' => $item->getName()), array('parent' => $oldName)) + ->update($this->itemChildTable, ['parent' => $item->getName()], ['parent' => $oldName]) ->execute(); $this->db->createCommand() - ->update($this->itemChildTable, array('child' => $item->getName()), array('child' => $oldName)) + ->update($this->itemChildTable, ['child' => $item->getName()], ['child' => $oldName]) ->execute(); $this->db->createCommand() - ->update($this->assignmentTable, array('item_name' => $item->getName()), array('item_name' => $oldName)) + ->update($this->assignmentTable, ['item_name' => $item->getName()], ['item_name' => $oldName]) ->execute(); } $this->db->createCommand() - ->update($this->itemTable, array( + ->update($this->itemTable, [ 'name' => $item->getName(), 'type' => $item->type, 'description' => $item->description, 'biz_rule' => $item->bizRule, 'data' => serialize($item->data), - ), array( + ], [ 'name' => $oldName === null ? $item->getName() : $oldName, - )) + ]) ->execute(); } diff --git a/framework/yii/rbac/Item.php b/framework/yii/rbac/Item.php index f7930c1..ae9214e 100644 --- a/framework/yii/rbac/Item.php +++ b/framework/yii/rbac/Item.php @@ -64,7 +64,7 @@ class Item extends Object * @param array $params the parameters to be passed to business rule evaluation * @return boolean whether the specified item is within the hierarchy starting from this item. */ - public function checkAccess($itemName, $params = array()) + public function checkAccess($itemName, $params = []) { Yii::trace('Checking permission: ' . $this->_name, __METHOD__); if ($this->manager->executeBizRule($this->bizRule, $params, $this->data)) { diff --git a/framework/yii/rbac/Manager.php b/framework/yii/rbac/Manager.php index 3d3aafc..1710a77 100644 --- a/framework/yii/rbac/Manager.php +++ b/framework/yii/rbac/Manager.php @@ -58,7 +58,7 @@ abstract class Manager extends Component * And then declare 'authenticated' in this property so that it can be applied to * every authenticated user. */ - public $defaultRoles = array(); + public $defaultRoles = []; /** * Creates a role. @@ -159,7 +159,7 @@ abstract class Manager extends Component */ protected function checkItemChildType($parentType, $childType) { - static $types = array('operation', 'task', 'role'); + static $types = ['operation', 'task', 'role']; if ($parentType < $childType) { throw new InvalidParamException("Cannot add an item of type '{$types[$childType]}' to an item of type '{$types[$parentType]}'."); } @@ -174,7 +174,7 @@ abstract class Manager extends Component * with the tasks and roles assigned to the user. * @return boolean whether the operations can be performed by the user. */ - abstract public function checkAccess($userId, $itemName, $params = array()); + abstract public function checkAccess($userId, $itemName, $params = []); /** * Creates an authorization item. diff --git a/framework/yii/rbac/PhpManager.php b/framework/yii/rbac/PhpManager.php index 203b17e..a91d9bd 100644 --- a/framework/yii/rbac/PhpManager.php +++ b/framework/yii/rbac/PhpManager.php @@ -41,9 +41,9 @@ class PhpManager extends Manager */ public $authFile; - private $_items = array(); // itemName => item - private $_children = array(); // itemName, childName => child - private $_assignments = array(); // userId, itemName => assignment + private $_items = []; // itemName => item + private $_children = []; // itemName, childName => child + private $_assignments = []; // userId, itemName => assignment /** * Initializes the application component. @@ -69,7 +69,7 @@ class PhpManager extends Manager * this array, which holds the value of `$userId`. * @return boolean whether the operations can be performed by the user. */ - public function checkAccess($userId, $itemName, $params = array()) + public function checkAccess($userId, $itemName, $params = []) { if (!isset($this->_items[$itemName])) { return false; @@ -165,10 +165,10 @@ class PhpManager extends Manager public function getItemChildren($names) { if (is_string($names)) { - return isset($this->_children[$names]) ? $this->_children[$names] : array(); + return isset($this->_children[$names]) ? $this->_children[$names] : []; } - $children = array(); + $children = []; foreach ($names as $name) { if (isset($this->_children[$name])) { $children = array_merge($children, $this->_children[$name]); @@ -194,13 +194,13 @@ class PhpManager extends Manager } elseif (isset($this->_assignments[$userId][$itemName])) { throw new InvalidParamException("Authorization item '$itemName' has already been assigned to user '$userId'."); } else { - return $this->_assignments[$userId][$itemName] = new Assignment(array( + return $this->_assignments[$userId][$itemName] = new Assignment([ 'manager' => $this, 'userId' => $userId, 'itemName' => $itemName, 'bizRule' => $bizRule, 'data' => $data, - )); + ]); } } @@ -251,7 +251,7 @@ class PhpManager extends Manager */ public function getAssignments($userId) { - return isset($this->_assignments[$userId]) ? $this->_assignments[$userId] : array(); + return isset($this->_assignments[$userId]) ? $this->_assignments[$userId] : []; } /** @@ -267,7 +267,7 @@ class PhpManager extends Manager if ($userId === null && $type === null) { return $this->_items; } - $items = array(); + $items = []; if ($userId === null) { foreach ($this->_items as $name => $item) { /** @var $item Item */ @@ -307,14 +307,14 @@ class PhpManager extends Manager if (isset($this->_items[$name])) { throw new Exception('Unable to add an item whose name is the same as an existing item.'); } - return $this->_items[$name] = new Item(array( + return $this->_items[$name] = new Item([ 'manager' => $this, 'name' => $name, 'type' => $type, 'description' => $description, 'bizRule' => $bizRule, 'data' => $data, - )); + ]); } /** @@ -398,15 +398,15 @@ class PhpManager extends Manager */ public function save() { - $items = array(); + $items = []; foreach ($this->_items as $name => $item) { /** @var $item Item */ - $items[$name] = array( + $items[$name] = [ 'type' => $item->type, 'description' => $item->description, 'bizRule' => $item->bizRule, 'data' => $item->data, - ); + ]; if (isset($this->_children[$name])) { foreach ($this->_children[$name] as $child) { /** @var $child Item */ @@ -419,10 +419,10 @@ class PhpManager extends Manager foreach ($assignments as $name => $assignment) { /** @var $assignment Assignment */ if (isset($items[$name])) { - $items[$name]['assignments'][$userId] = array( + $items[$name]['assignments'][$userId] = [ 'bizRule' => $assignment->bizRule, 'data' => $assignment->data, - ); + ]; } } } @@ -440,14 +440,14 @@ class PhpManager extends Manager $items = $this->loadFromFile($this->authFile); foreach ($items as $name => $item) { - $this->_items[$name] = new Item(array( + $this->_items[$name] = new Item([ 'manager' => $this, 'name' => $name, 'type' => $item['type'], 'description' => $item['description'], 'bizRule' => $item['bizRule'], 'data' => $item['data'], - )); + ]); } foreach ($items as $name => $item) { @@ -460,13 +460,13 @@ class PhpManager extends Manager } if (isset($item['assignments'])) { foreach ($item['assignments'] as $userId => $assignment) { - $this->_assignments[$userId][$name] = new Assignment(array( + $this->_assignments[$userId][$name] = new Assignment([ 'manager' => $this, 'userId' => $userId, 'itemName' => $name, 'bizRule' => $assignment['bizRule'], 'data' => $assignment['data'], - )); + ]); } } } @@ -478,8 +478,8 @@ class PhpManager extends Manager public function clearAll() { $this->clearAssignments(); - $this->_children = array(); - $this->_items = array(); + $this->_children = []; + $this->_items = []; } /** @@ -487,7 +487,7 @@ class PhpManager extends Manager */ public function clearAssignments() { - $this->_assignments = array(); + $this->_assignments = []; } /** @@ -524,7 +524,7 @@ class PhpManager extends Manager if (is_file($file)) { return require($file); } else { - return array(); + return []; } } diff --git a/framework/yii/redis/Connection.php b/framework/yii/redis/Connection.php index 848b408..a5da73e 100644 --- a/framework/yii/redis/Connection.php +++ b/framework/yii/redis/Connection.php @@ -61,7 +61,7 @@ class Connection extends Component /** * @var array List of available redis commands http://redis.io/commands */ - public $redisCommands = array( + public $redisCommands = [ 'BRPOP', // key [key ...] timeout Remove and get the last element in a list, or block until one is available 'BRPOPLPUSH', // source destination timeout Pop a value from a list, push it to another list and return it; or block until one is available 'CLIENT KILL', // ip:port Kill the connection of a client @@ -201,7 +201,7 @@ class Connection extends Component 'ZREVRANK', // key member Determine the index of a member in a sorted set, with scores ordered from high to low 'ZSCORE', // key member Get the score associated with the given member in a sorted set 'ZUNIONSTORE', // destination numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX] Add multiple sorted sets and store the resulting sorted set in a new key - ); + ]; /** * @var Transaction the currently active transaction */ @@ -260,9 +260,9 @@ class Connection extends Component stream_set_timeout($this->_socket, $timeout=(int)$this->dataTimeout, (int) (($this->dataTimeout - $timeout) * 1000000)); } if ($this->password !== null) { - $this->executeCommand('AUTH', array($this->password)); + $this->executeCommand('AUTH', [$this->password]); } - $this->executeCommand('SELECT', array($db)); + $this->executeCommand('SELECT', [$db]); $this->initConnection(); } else { \Yii::error("Failed to open DB connection ({$this->dsn}): " . $errorNumber . ' - ' . $errorDescription, __CLASS__); @@ -313,9 +313,7 @@ class Connection extends Component public function beginTransaction() { $this->open(); - $this->_transaction = new Transaction(array( - 'db' => $this, - )); + $this->_transaction = new Transaction(['db' => $this]); $this->_transaction->begin(); return $this->_transaction; } @@ -368,7 +366,7 @@ class Connection extends Component * for details on the mentioned reply types. * @trows Exception for commands that return [error reply](http://redis.io/topics/protocol#error-reply). */ - public function executeCommand($name, $params=array()) + public function executeCommand($name, $params=[]) { $this->open(); @@ -416,7 +414,7 @@ class Connection extends Component return mb_substr($data, 0, -2, '8bit'); case '*': // Multi-bulk replies $count = (int) $line; - $data = array(); + $data = []; for($i = 0; $i < $count; $i++) { $data[] = $this->parseResponse($command); } diff --git a/framework/yii/requirements/YiiRequirementChecker.php b/framework/yii/requirements/YiiRequirementChecker.php index c8ad45d..77e98d7 100644 --- a/framework/yii/requirements/YiiRequirementChecker.php +++ b/framework/yii/requirements/YiiRequirementChecker.php @@ -19,15 +19,15 @@ if (version_compare(PHP_VERSION, '4.3', '<')) { * ~~~php * require_once('path/to/YiiRequirementChecker.php'); * $requirementsChecker = new YiiRequirementChecker(); - * $requirements = array( - * array( + * $requirements = [ + * [ * 'name' => 'PHP Some Extension', * 'mandatory' => true, * 'condition' => extension_loaded('some_extension'), * 'by' => 'Some application feature', * 'memo' => 'PHP extension "some_extension" required', - * ), - * ); + * ], + * ]; * $requirementsChecker->checkYii()->check($requirements)->render(); * ~~~ * @@ -38,12 +38,12 @@ if (version_compare(PHP_VERSION, '4.3', '<')) { * For example: * * ~~~ - * $requirements = array( - * array( + * $requirements = [ + * [ * 'name' => 'Upload max file size', * 'condition' => 'eval:$this->checkUploadMaxFileSize("5M")', - * ), - * ); + * ], + * ]; * ~~~ * * Note: this class definition does not match ordinary Yii style, because it should match PHP 4.3 @@ -74,14 +74,14 @@ class YiiRequirementChecker $this->usageError('Requirements must be an array, "' . gettype($requirements) . '" has been given!'); } if (!isset($this->result) || !is_array($this->result)) { - $this->result = array( - 'summary' => array( + $this->result = [ + 'summary' => [ 'total' => 0, 'errors' => 0, 'warnings' => 0, - ), - 'requirements' => array(), - ); + ], + 'requirements' => [], + ]; } foreach ($requirements as $key => $rawRequirement) { $requirement = $this->normalizeRequirement($rawRequirement, $key); @@ -118,21 +118,21 @@ class YiiRequirementChecker * Return the check results. * @return array|null check results in format: * - * array( - * 'summary' => array( + * [ + * 'summary' => [ * 'total' => total number of checks, * 'errors' => number of errors, * 'warnings' => number of warnings, - * ), - * 'requirements' => array( - * array( + * ], + * 'requirements' => [ + * [ * ... * 'error' => is there an error, * 'warning' => is there a warning, - * ), + * ], * ... - * ), - * ) + * ], + * ] * */ function getResult() diff --git a/framework/yii/requirements/requirements.php b/framework/yii/requirements/requirements.php index f70f414..9f9f582 100644 --- a/framework/yii/requirements/requirements.php +++ b/framework/yii/requirements/requirements.php @@ -5,40 +5,40 @@ * * @var $this YiiRequirementChecker */ -return array( - array( +return [ + [ 'name' => 'PHP version', 'mandatory' => true, 'condition' => version_compare(PHP_VERSION, '5.4.0', '>='), 'by' => 'Yii Framework', 'memo' => 'PHP 5.4.0 or higher is required.', - ), - array( + ], + [ 'name' => 'Reflection extension', 'mandatory' => true, 'condition' => class_exists('Reflection', false), 'by' => 'Yii Framework', - ), - array( + ], + [ 'name' => 'PCRE extension', 'mandatory' => true, 'condition' => extension_loaded('pcre'), 'by' => 'Yii Framework', - ), - array( + ], + [ 'name' => 'SPL extension', 'mandatory' => true, 'condition' => extension_loaded('SPL'), 'by' => 'Yii Framework', - ), - array( + ], + [ 'name' => 'MBString extension', 'mandatory' => true, 'condition' => extension_loaded('mbstring'), 'by' => 'Multibyte string processing', 'memo' => 'Required for multibyte encoding string processing.' - ), - array( + ], + [ 'name' => 'Intl extension', 'mandatory' => false, 'condition' => $this->checkPhpExtensionVersion('intl', '1.0.2', '>='), @@ -46,5 +46,5 @@ return array( 'memo' => 'PHP Intl extension 1.0.2 or higher is required when you want to use advanced parameters formatting in \Yii::t(), IDN-feature of EmailValidator or UrlValidator or the yii\i18n\Formatter class.' - ), -); + ], +]; diff --git a/framework/yii/test/TestCase.php b/framework/yii/test/TestCase.php index 2e9b480..a6806b3 100644 --- a/framework/yii/test/TestCase.php +++ b/framework/yii/test/TestCase.php @@ -10,9 +10,9 @@ namespace yii\test; require_once('PHPUnit/Runner/Version.php'); -spl_autoload_unregister(array('Yii', 'autoload')); +spl_autoload_unregister(['Yii', 'autoload']); require_once('PHPUnit/Autoload.php'); -spl_autoload_register(array('Yii', 'autoload')); // put yii's autoloader at the end +spl_autoload_register(['Yii', 'autoload']); // put yii's autoloader at the end /** * TestCase is the base class for all test case classes. diff --git a/framework/yii/test/WebTestCase.php b/framework/yii/test/WebTestCase.php index 39162c9..4308454 100644 --- a/framework/yii/test/WebTestCase.php +++ b/framework/yii/test/WebTestCase.php @@ -10,9 +10,9 @@ namespace yii\test; require_once('PHPUnit/Runner/Version.php'); -spl_autoload_unregister(array('Yii','autoload')); +spl_autoload_unregister(['Yii','autoload']); require_once('PHPUnit/Autoload.php'); -spl_autoload_register(array('Yii','autoload')); // put yii's autoloader at the end +spl_autoload_register(['Yii','autoload']); // put yii's autoloader at the end /** * WebTestCase is the base class for all test case classes. diff --git a/framework/yii/validators/BooleanValidator.php b/framework/yii/validators/BooleanValidator.php index 7eb1427..2504b8a 100644 --- a/framework/yii/validators/BooleanValidator.php +++ b/framework/yii/validators/BooleanValidator.php @@ -57,10 +57,10 @@ class BooleanValidator extends Validator { $value = $object->$attribute; if (!$this->validateValue($value)) { - $this->addError($object, $attribute, $this->message, array( + $this->addError($object, $attribute, $this->message, [ '{true}' => $this->trueValue, '{false}' => $this->falseValue, - )); + ]); } } @@ -85,15 +85,15 @@ class BooleanValidator extends Validator */ public function clientValidateAttribute($object, $attribute, $view) { - $options = array( + $options = [ 'trueValue' => $this->trueValue, 'falseValue' => $this->falseValue, - 'message' => Html::encode(strtr($this->message, array( + 'message' => Html::encode(strtr($this->message, [ '{attribute}' => $object->getAttributeLabel($attribute), '{true}' => $this->trueValue, '{false}' => $this->falseValue, - ))), - ); + ])), + ]; if ($this->skipOnEmpty) { $options['skipOnEmpty'] = 1; } diff --git a/framework/yii/validators/CompareValidator.php b/framework/yii/validators/CompareValidator.php index 35e044a..3ff459b 100644 --- a/framework/yii/validators/CompareValidator.php +++ b/framework/yii/validators/CompareValidator.php @@ -142,10 +142,10 @@ class CompareValidator extends Validator default: $valid = false; break; } if (!$valid) { - $this->addError($object, $attribute, $this->message, array( + $this->addError($object, $attribute, $this->message, [ '{compareAttribute}' => $compareLabel, '{compareValue}' => $compareValue, - )); + ]); } } @@ -185,7 +185,7 @@ class CompareValidator extends Validator */ public function clientValidateAttribute($object, $attribute, $view) { - $options = array('operator' => $this->operator); + $options = ['operator' => $this->operator]; if ($this->compareValue !== null) { $options['compareValue'] = $this->compareValue; @@ -200,11 +200,11 @@ class CompareValidator extends Validator $options['skipOnEmpty'] = 1; } - $options['message'] = Html::encode(strtr($this->message, array( + $options['message'] = Html::encode(strtr($this->message, [ '{attribute}' => $object->getAttributeLabel($attribute), '{compareAttribute}' => $compareValue, '{compareValue}' => $compareValue, - ))); + ])); ValidationAsset::register($view); return 'yii.validation.compare(value, messages, ' . json_encode($options) . ');'; diff --git a/framework/yii/validators/EmailValidator.php b/framework/yii/validators/EmailValidator.php index 7081cfb..7e28738 100644 --- a/framework/yii/validators/EmailValidator.php +++ b/framework/yii/validators/EmailValidator.php @@ -125,15 +125,15 @@ class EmailValidator extends Validator */ public function clientValidateAttribute($object, $attribute, $view) { - $options = array( + $options = [ 'pattern' => new JsExpression($this->pattern), 'fullPattern' => new JsExpression($this->fullPattern), 'allowName' => $this->allowName, - 'message' => Html::encode(strtr($this->message, array( + 'message' => Html::encode(strtr($this->message, [ '{attribute}' => $object->getAttributeLabel($attribute), - ))), + ])), 'enableIDN' => (boolean)$this->enableIDN, - ); + ]; if ($this->skipOnEmpty) { $options['skipOnEmpty'] = 1; } diff --git a/framework/yii/validators/ExistValidator.php b/framework/yii/validators/ExistValidator.php index 8cbce5f..2746b06 100644 --- a/framework/yii/validators/ExistValidator.php +++ b/framework/yii/validators/ExistValidator.php @@ -69,7 +69,7 @@ class ExistValidator extends Validator $className = $this->className === null ? get_class($object) : $this->className; $attributeName = $this->attributeName === null ? $attribute : $this->attributeName; $query = $className::find(); - $query->where(array($attributeName => $value)); + $query->where([$attributeName => $value]); if (!$query->exists()) { $this->addError($object, $attribute, $this->message); } @@ -95,7 +95,7 @@ class ExistValidator extends Validator /** @var $className \yii\db\ActiveRecord */ $className = $this->className; $query = $className::find(); - $query->where(array($this->attributeName => $value)); + $query->where([$this->attributeName => $value]); return $query->exists(); } } diff --git a/framework/yii/validators/FileValidator.php b/framework/yii/validators/FileValidator.php index e2880af..8024d10 100644 --- a/framework/yii/validators/FileValidator.php +++ b/framework/yii/validators/FileValidator.php @@ -144,7 +144,7 @@ class FileValidator extends Validator $this->addError($object, $attribute, $this->uploadRequired); } if (count($files) > $this->maxFiles) { - $this->addError($object, $attribute, $this->tooMany, array('{attribute}' => $attribute, '{limit}' => $this->maxFiles)); + $this->addError($object, $attribute, $this->tooMany, ['{attribute}' => $attribute, '{limit}' => $this->maxFiles]); } else { foreach ($files as $file) { $this->validateFile($object, $attribute, $file); @@ -171,18 +171,18 @@ class FileValidator extends Validator switch ($file->error) { case UPLOAD_ERR_OK: if ($this->maxSize !== null && $file->size > $this->maxSize) { - $this->addError($object, $attribute, $this->tooBig, array('{file}' => $file->name, '{limit}' => $this->getSizeLimit())); + $this->addError($object, $attribute, $this->tooBig, ['{file}' => $file->name, '{limit}' => $this->getSizeLimit()]); } if ($this->minSize !== null && $file->size < $this->minSize) { - $this->addError($object, $attribute, $this->tooSmall, array('{file}' => $file->name, '{limit}' => $this->minSize)); + $this->addError($object, $attribute, $this->tooSmall, ['{file}' => $file->name, '{limit}' => $this->minSize]); } if (!empty($this->types) && !in_array(strtolower(pathinfo($file->name, PATHINFO_EXTENSION)), $this->types, true)) { - $this->addError($object, $attribute, $this->wrongType, array('{file}' => $file->name, '{extensions}' => implode(', ', $this->types))); + $this->addError($object, $attribute, $this->wrongType, ['{file}' => $file->name, '{extensions}' => implode(', ', $this->types)]); } break; case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: - $this->addError($object, $attribute, $this->tooBig, array('{file}' => $file->name, '{limit}' => $this->getSizeLimit())); + $this->addError($object, $attribute, $this->tooBig, ['{file}' => $file->name, '{limit}' => $this->getSizeLimit()]); break; case UPLOAD_ERR_PARTIAL: $this->addError($object, $attribute, $this->message); diff --git a/framework/yii/validators/InlineValidator.php b/framework/yii/validators/InlineValidator.php index dd951aa..8099977 100644 --- a/framework/yii/validators/InlineValidator.php +++ b/framework/yii/validators/InlineValidator.php @@ -60,7 +60,7 @@ class InlineValidator extends Validator { $method = $this->method; if (is_string($method)) { - $method = array($object, $method); + $method = [$object, $method]; } call_user_func($method, $attribute, $this->params); } @@ -91,7 +91,7 @@ class InlineValidator extends Validator if ($this->clientValidate !== null) { $method = $this->clientValidate; if (is_string($method)) { - $method = array($object, $method); + $method = [$object, $method]; } return call_user_func($method, $attribute); } else { diff --git a/framework/yii/validators/NumberValidator.php b/framework/yii/validators/NumberValidator.php index 960828d..ec72dcf 100644 --- a/framework/yii/validators/NumberValidator.php +++ b/framework/yii/validators/NumberValidator.php @@ -91,10 +91,10 @@ class NumberValidator extends Validator $this->addError($object, $attribute, $this->message); } if ($this->min !== null && $value < $this->min) { - $this->addError($object, $attribute, $this->tooSmall, array('{min}' => $this->min)); + $this->addError($object, $attribute, $this->tooSmall, ['{min}' => $this->min]); } if ($this->max !== null && $value > $this->max) { - $this->addError($object, $attribute, $this->tooBig, array('{max}' => $this->max)); + $this->addError($object, $attribute, $this->tooBig, ['{max}' => $this->max]); } } @@ -122,26 +122,26 @@ class NumberValidator extends Validator { $label = $object->getAttributeLabel($attribute); - $options = array( + $options = [ 'pattern' => new JsExpression($this->integerOnly ? $this->integerPattern : $this->numberPattern), - 'message' => Html::encode(strtr($this->message, array( + 'message' => Html::encode(strtr($this->message, [ '{attribute}' => $label, - ))), - ); + ])), + ]; if ($this->min !== null) { $options['min'] = $this->min; - $options['tooSmall'] = Html::encode(strtr($this->tooSmall, array( + $options['tooSmall'] = Html::encode(strtr($this->tooSmall, [ '{attribute}' => $label, '{min}' => $this->min, - ))); + ])); } if ($this->max !== null) { $options['max'] = $this->max; - $options['tooBig'] = Html::encode(strtr($this->tooBig, array( + $options['tooBig'] = Html::encode(strtr($this->tooBig, [ '{attribute}' => $label, '{max}' => $this->max, - ))); + ])); } if ($this->skipOnEmpty) { $options['skipOnEmpty'] = 1; diff --git a/framework/yii/validators/PunycodeAsset.php b/framework/yii/validators/PunycodeAsset.php index 08d3fb4..08439bf 100644 --- a/framework/yii/validators/PunycodeAsset.php +++ b/framework/yii/validators/PunycodeAsset.php @@ -15,7 +15,7 @@ use yii\web\AssetBundle; class PunycodeAsset extends AssetBundle { public $sourcePath = '@yii/assets'; - public $js = array( + public $js = [ 'punycode/punycode.js', - ); + ]; } diff --git a/framework/yii/validators/RangeValidator.php b/framework/yii/validators/RangeValidator.php index fedc027..7abc41d 100644 --- a/framework/yii/validators/RangeValidator.php +++ b/framework/yii/validators/RangeValidator.php @@ -87,17 +87,17 @@ class RangeValidator extends Validator */ public function clientValidateAttribute($object, $attribute, $view) { - $range = array(); + $range = []; foreach ($this->range as $value) { $range[] = (string)$value; } - $options = array( + $options = [ 'range' => $range, 'not' => $this->not, - 'message' => Html::encode(strtr($this->message, array( + 'message' => Html::encode(strtr($this->message, [ '{attribute}' => $object->getAttributeLabel($attribute), - ))), - ); + ])), + ]; if ($this->skipOnEmpty) { $options['skipOnEmpty'] = 1; } diff --git a/framework/yii/validators/RegularExpressionValidator.php b/framework/yii/validators/RegularExpressionValidator.php index f5c5d02..ae79d32 100644 --- a/framework/yii/validators/RegularExpressionValidator.php +++ b/framework/yii/validators/RegularExpressionValidator.php @@ -98,13 +98,13 @@ class RegularExpressionValidator extends Validator $pattern .= preg_replace('/[^igm]/', '', $flag); } - $options = array( + $options = [ 'pattern' => new JsExpression($pattern), 'not' => $this->not, - 'message' => Html::encode(strtr($this->message, array( + 'message' => Html::encode(strtr($this->message, [ '{attribute}' => $object->getAttributeLabel($attribute), - ))), - ); + ])), + ]; if ($this->skipOnEmpty) { $options['skipOnEmpty'] = 1; } diff --git a/framework/yii/validators/RequiredValidator.php b/framework/yii/validators/RequiredValidator.php index 68968be..88bd03d 100644 --- a/framework/yii/validators/RequiredValidator.php +++ b/framework/yii/validators/RequiredValidator.php @@ -74,9 +74,9 @@ class RequiredValidator extends Validator if ($this->requiredValue === null) { $this->addError($object, $attribute, $this->message); } else { - $this->addError($object, $attribute, $this->message, array( + $this->addError($object, $attribute, $this->message, [ '{requiredValue}' => $this->requiredValue, - )); + ]); } } } @@ -108,11 +108,11 @@ class RequiredValidator extends Validator */ public function clientValidateAttribute($object, $attribute, $view) { - $options = array(); + $options = []; if ($this->requiredValue !== null) { - $options['message'] = strtr($this->message, array( + $options['message'] = strtr($this->message, [ '{requiredValue}' => $this->requiredValue, - )); + ]); $options['requiredValue'] = $this->requiredValue; } else { $options['message'] = $this->message; @@ -121,9 +121,9 @@ class RequiredValidator extends Validator $options['strict'] = 1; } - $options['message'] = Html::encode(strtr($options['message'], array( + $options['message'] = Html::encode(strtr($options['message'], [ '{attribute}' => $object->getAttributeLabel($attribute), - ))); + ])); ValidationAsset::register($view); return 'yii.validation.required(value, messages, ' . json_encode($options) . ');'; diff --git a/framework/yii/validators/StringValidator.php b/framework/yii/validators/StringValidator.php index 166d2d6..a6383b9 100644 --- a/framework/yii/validators/StringValidator.php +++ b/framework/yii/validators/StringValidator.php @@ -25,10 +25,10 @@ class StringValidator extends Validator * This can be specified in one of the following forms: * * - an integer: the exact length that the value should be of; - * - an array of one element: the minimum length that the value should be of. For example, `array(8)`. + * - an array of one element: the minimum length that the value should be of. For example, `[8]`. * This will overwrite [[min]]. * - an array of two elements: the minimum and maximum lengths that the value should be of. - * For example, `array(8, 128)`. This will overwrite both [[min]] and [[max]]. + * For example, `[8, 128]`. This will overwrite both [[min]] and [[max]]. */ public $length; /** @@ -112,13 +112,13 @@ class StringValidator extends Validator $length = mb_strlen($value, $this->encoding); if ($this->min !== null && $length < $this->min) { - $this->addError($object, $attribute, $this->tooShort, array('{min}' => $this->min)); + $this->addError($object, $attribute, $this->tooShort, ['{min}' => $this->min]); } if ($this->max !== null && $length > $this->max) { - $this->addError($object, $attribute, $this->tooLong, array('{max}' => $this->max)); + $this->addError($object, $attribute, $this->tooLong, ['{max}' => $this->max]); } if ($this->length !== null && $length !== $this->length) { - $this->addError($object, $attribute, $this->notEqual, array('{length}' => $this->length)); + $this->addError($object, $attribute, $this->notEqual, ['{length}' => $this->length]); } } @@ -150,32 +150,32 @@ class StringValidator extends Validator { $label = $object->getAttributeLabel($attribute); - $options = array( - 'message' => Html::encode(strtr($this->message, array( + $options = [ + 'message' => Html::encode(strtr($this->message, [ '{attribute}' => $label, - ))), - ); + ])), + ]; if ($this->min !== null) { $options['min'] = $this->min; - $options['tooShort'] = Html::encode(strtr($this->tooShort, array( + $options['tooShort'] = Html::encode(strtr($this->tooShort, [ '{attribute}' => $label, '{min}' => $this->min, - ))); + ])); } if ($this->max !== null) { $options['max'] = $this->max; - $options['tooLong'] = Html::encode(strtr($this->tooLong, array( + $options['tooLong'] = Html::encode(strtr($this->tooLong, [ '{attribute}' => $label, '{max}' => $this->max, - ))); + ])); } if ($this->length !== null) { $options['is'] = $this->length; - $options['notEqual'] = Html::encode(strtr($this->notEqual, array( + $options['notEqual'] = Html::encode(strtr($this->notEqual, [ '{attribute}' => $label, '{length}' => $this->is, - ))); + ])); } if ($this->skipOnEmpty) { $options['skipOnEmpty'] = 1; diff --git a/framework/yii/validators/UniqueValidator.php b/framework/yii/validators/UniqueValidator.php index c3876e8..a698d96 100644 --- a/framework/yii/validators/UniqueValidator.php +++ b/framework/yii/validators/UniqueValidator.php @@ -70,7 +70,7 @@ class UniqueValidator extends Validator } $query = $className::find(); - $query->where(array($column->name => $value)); + $query->where([$column->name => $value]); if (!$object instanceof ActiveRecord || $object->getIsNewRecord()) { // if current $object isn't in the database yet then it's OK just to call exists() diff --git a/framework/yii/validators/UrlValidator.php b/framework/yii/validators/UrlValidator.php index 9230b36..f65c347 100644 --- a/framework/yii/validators/UrlValidator.php +++ b/framework/yii/validators/UrlValidator.php @@ -31,7 +31,7 @@ class UrlValidator extends Validator * @var array list of URI schemes which should be considered valid. By default, http and https * are considered to be valid schemes. **/ - public $validSchemes = array('http', 'https'); + public $validSchemes = ['http', 'https']; /** * @var string the default URI scheme. If the input doesn't contain the scheme part, the default * scheme will be prepended to it (thus changing the input). Defaults to null, meaning a URL must @@ -128,13 +128,13 @@ class UrlValidator extends Validator $pattern = $this->pattern; } - $options = array( + $options = [ 'pattern' => new JsExpression($pattern), - 'message' => Html::encode(strtr($this->message, array( + 'message' => Html::encode(strtr($this->message, [ '{attribute}' => $object->getAttributeLabel($attribute), - ))), + ])), 'enableIDN' => (boolean)$this->enableIDN, - ); + ]; if ($this->skipOnEmpty) { $options['skipOnEmpty'] = 1; } diff --git a/framework/yii/validators/ValidationAsset.php b/framework/yii/validators/ValidationAsset.php index 625e580..8ff1b2d 100644 --- a/framework/yii/validators/ValidationAsset.php +++ b/framework/yii/validators/ValidationAsset.php @@ -15,10 +15,10 @@ use yii\web\AssetBundle; class ValidationAsset extends AssetBundle { public $sourcePath = '@yii/assets'; - public $js = array( + public $js = [ 'yii.validation.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\web\YiiAsset', - ); + ]; } diff --git a/framework/yii/validators/Validator.php b/framework/yii/validators/Validator.php index ec9afc4..46ab673 100644 --- a/framework/yii/validators/Validator.php +++ b/framework/yii/validators/Validator.php @@ -48,7 +48,7 @@ abstract class Validator extends Component /** * @var array list of built-in validators (name => class or configuration) */ - public static $builtInValidators = array( + public static $builtInValidators = [ 'boolean' => 'yii\validators\BooleanValidator', 'captcha' => 'yii\captcha\CaptchaValidator', 'compare' => 'yii\validators\CompareValidator', @@ -60,10 +60,10 @@ abstract class Validator extends Component 'file' => 'yii\validators\FileValidator', 'filter' => 'yii\validators\FilterValidator', 'in' => 'yii\validators\RangeValidator', - 'integer' => array( + 'integer' => [ 'class' => 'yii\validators\NumberValidator', 'integerOnly' => true, - ), + ], 'match' => 'yii\validators\RegularExpressionValidator', 'number' => 'yii\validators\NumberValidator', 'required' => 'yii\validators\RequiredValidator', @@ -71,12 +71,12 @@ abstract class Validator extends Component 'string' => 'yii\validators\StringValidator', 'unique' => 'yii\validators\UniqueValidator', 'url' => 'yii\validators\UrlValidator', - ); + ]; /** * @var array list of attributes to be validated. */ - public $attributes = array(); + public $attributes = []; /** * @var string the user-defined error message. It may contain the following placeholders which * will be replaced accordingly by the validator: @@ -88,11 +88,11 @@ abstract class Validator extends Component /** * @var array list of scenarios that the validator can be applied to. */ - public $on = array(); + public $on = []; /** * @var array list of scenarios that the validator should not be applied to. */ - public $except = array(); + public $except = []; /** * @var boolean whether this validation rule should be skipped if the attribute being validated * already has some validation error according to some previous rules. Defaults to true. @@ -129,7 +129,7 @@ abstract class Validator extends Component * @param array $params initial values to be applied to the validator properties * @return Validator the validator */ - public static function createValidator($type, $object, $attributes, $params = array()) + public static function createValidator($type, $object, $attributes, $params = []) { if (!is_array($attributes)) { $attributes = preg_split('/[\s,]+/', $attributes, -1, PREG_SPLIT_NO_EMPTY); @@ -248,7 +248,7 @@ abstract class Validator extends Component * @param string $message the error message * @param array $params values for the placeholders in the error message */ - public function addError($object, $attribute, $message, $params = array()) + public function addError($object, $attribute, $message, $params = []) { $value = $object->$attribute; $params['{attribute}'] = $object->getAttributeLabel($attribute); @@ -266,7 +266,7 @@ abstract class Validator extends Component */ public function isEmpty($value, $trim = false) { - return $value === null || $value === array() || $value === '' + return $value === null || $value === [] || $value === '' || $trim && is_scalar($value) && trim($value) === ''; } } diff --git a/framework/yii/views/messageConfig.php b/framework/yii/views/messageConfig.php index d0d515a..9babb0c 100644 --- a/framework/yii/views/messageConfig.php +++ b/framework/yii/views/messageConfig.php @@ -1,13 +1,13 @@ __DIR__, // string, required, root directory containing message translations. 'messagePath' => __DIR__ . DIRECTORY_SEPARATOR . 'messages', // array, required, list of language codes that the extracted messages - // should be translated to. For example, array('zh_cn', 'de'). - 'languages' => array('de'), + // should be translated to. For example, ['zh_cn', 'de']. + 'languages' => ['de'], // string, the name of the function for translating messages. // Defaults to 'Yii::t'. This is used as a mark to find the messages to be // translated. You may use a string for single function name or an array for @@ -29,11 +29,11 @@ return array( // and the '.svn' will match all files and directories whose name ends with '.svn'. // Note, the '/' characters in a pattern matches both '/' and '\'. // If a file/directory matches both a pattern in "only" and "except", it will NOT be processed. - 'only' => array('.php'), + 'only' => ['.php'], // array, list of patterns that specify which files/directories should NOT be processed. // If empty or not set, all files/directories will be processed. // Please refer to "only" for details about the patterns. - 'except' => array( + 'except' => [ '.svn', '.git', '.gitignore', @@ -41,5 +41,5 @@ return array( '.hgignore', '.hgkeep', '/messages', - ), -); + ], +]; diff --git a/framework/yii/web/AccessControl.php b/framework/yii/web/AccessControl.php index 75e2dc9..f9b82df 100644 --- a/framework/yii/web/AccessControl.php +++ b/framework/yii/web/AccessControl.php @@ -26,21 +26,21 @@ use yii\base\ActionFilter; * ~~~ * public function behaviors() * { - * return array( - * 'access' => array( + * return [ + * 'access' => [ * 'class' => \yii\web\AccessControl::className(), - * 'only' => array('create', 'update'), - * 'rules' => array( + * 'only' => ['create', 'update'], + * 'rules' => [ * // deny all POST requests - * array( + * [ * 'allow' => false, - * 'verbs' => array('POST') - * ), + * 'verbs' => ['POST'] + * ], * // allow authenticated users - * array( + * [ * 'allow' => true, - * 'roles' => array('@'), - * ), + * 'roles' => ['@'], + * ], * // everything else is denied * ), * ), @@ -70,16 +70,14 @@ class AccessControl extends ActionFilter * @var array the default configuration of access rules. Individual rule configurations * specified via [[rules]] will take precedence when the same property of the rule is configured. */ - public $ruleConfig = array( - 'class' => 'yii\web\AccessRule', - ); + public $ruleConfig = ['class' => 'yii\web\AccessRule']; /** * @var array a list of access rule objects or configuration arrays for creating the rule objects. * If a rule is specified via a configuration array, it will be merged with [[ruleConfig]] first * before it is used for creating the rule object. * @see ruleConfig */ - public $rules = array(); + public $rules = []; /** * Initializes the [[rules]] array by instantiating rule objects from configurations. diff --git a/framework/yii/web/Application.php b/framework/yii/web/Application.php index b0638a7..13b5588 100644 --- a/framework/yii/web/Application.php +++ b/framework/yii/web/Application.php @@ -38,11 +38,11 @@ class Application extends \yii\base\Application * to the action. For example, * * ~~~ - * array( + * [ * 'offline/notice', * 'param1' => 'value1', * 'param2' => 'value2', - * ) + * ] * ~~~ * * Defaults to null, meaning catch-all is not used. @@ -167,22 +167,12 @@ class Application extends \yii\base\Application public function registerCoreComponents() { parent::registerCoreComponents(); - $this->setComponents(array( - 'request' => array( - 'class' => 'yii\web\Request', - ), - 'response' => array( - 'class' => 'yii\web\Response', - ), - 'session' => array( - 'class' => 'yii\web\Session', - ), - 'user' => array( - 'class' => 'yii\web\User', - ), - 'assetManager' => array( - 'class' => 'yii\web\AssetManager', - ), - )); + $this->setComponents([ + 'request' => ['class' => 'yii\web\Request'], + 'response' => ['class' => 'yii\web\Response'], + 'session' => ['class' => 'yii\web\Session'], + 'user' => ['class' => 'yii\web\User'], + 'assetManager' => ['class' => 'yii\web\AssetManager'], + ]); } } diff --git a/framework/yii/web/AssetBundle.php b/framework/yii/web/AssetBundle.php index 6bd7bff..2cc59d5 100644 --- a/framework/yii/web/AssetBundle.php +++ b/framework/yii/web/AssetBundle.php @@ -69,7 +69,7 @@ class AssetBundle extends Object /** * @var array list of the bundle names that this bundle depends on */ - public $depends = array(); + public $depends = []; /** * @var array list of JavaScript files that this bundle contains. Each JavaScript file can * be either a file path (without leading slash) relative to [[basePath]] or a URL representing @@ -77,7 +77,7 @@ class AssetBundle extends Object * * Note that only forward slash "/" can be used as directory separator. */ - public $js = array(); + public $js = []; /** * @var array list of CSS files that this bundle contains. Each CSS file can * be either a file path (without leading slash) relative to [[basePath]] or a URL representing @@ -85,22 +85,22 @@ class AssetBundle extends Object * * Note that only forward slash "/" can be used as directory separator. */ - public $css = array(); + public $css = []; /** * @var array the options that will be passed to [[\yii\base\View::registerJsFile()]] * when registering the JS files in this bundle. */ - public $jsOptions = array(); + public $jsOptions = []; /** * @var array the options that will be passed to [[\yii\base\View::registerCssFile()]] * when registering the CSS files in this bundle. */ - public $cssOptions = array(); + public $cssOptions = []; /** * @var array the options to be passed to [[AssetManager::publish()]] when the asset bundle * is being published. */ - public $publishOptions = array(); + public $publishOptions = []; /** * @param View $view diff --git a/framework/yii/web/AssetConverter.php b/framework/yii/web/AssetConverter.php index 420a5bc..b7f406d 100644 --- a/framework/yii/web/AssetConverter.php +++ b/framework/yii/web/AssetConverter.php @@ -23,12 +23,12 @@ 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. */ - public $commands = array( - 'less' => array('css', 'lessc {from} {to}'), - 'scss' => array('css', 'sass {from} {to}'), - 'sass' => array('css', 'sass {from} {to}'), - 'styl' => array('js', 'stylus < {from} > {to}'), - ); + public $commands = [ + 'less' => ['css', 'lessc {from} {to}'], + 'scss' => ['css', 'sass {from} {to}'], + 'sass' => ['css', 'sass {from} {to}'], + 'styl' => ['js', 'stylus < {from} > {to}'], + ]; /** * Converts a given asset file into a CSS or JS file. @@ -45,11 +45,11 @@ class AssetConverter extends Component implements AssetConverterInterface list ($ext, $command) = $this->commands[$ext]; $result = substr($asset, 0, $pos + 1) . $ext; if (@filemtime("$basePath/$result") < filemtime("$basePath/$asset")) { - $output = array(); - $command = strtr($command, array( + $output = []; + $command = strtr($command, [ '{from}' => escapeshellarg("$basePath/$asset"), '{to}' => escapeshellarg("$basePath/$result"), - )); + ]); exec($command, $output); Yii::trace("Converted $asset into $result: " . implode("\n", $output), __METHOD__); } diff --git a/framework/yii/web/AssetManager.php b/framework/yii/web/AssetManager.php index 5b47214..85b378a 100644 --- a/framework/yii/web/AssetManager.php +++ b/framework/yii/web/AssetManager.php @@ -29,7 +29,7 @@ class AssetManager extends Component * and the values are either the configuration arrays for creating the [[AssetBundle]] objects * or the corresponding asset bundle instances. */ - public $bundles = array(); + public $bundles = []; /** * @return string the root directory storing the published asset files. */ @@ -146,7 +146,7 @@ class AssetManager extends Component /** * @var array published assets */ - private $_published = array(); + private $_published = []; /** * Publishes a file or a directory. @@ -192,7 +192,7 @@ class AssetManager extends Component * @return array the path (directory or file path) and the URL that the asset is published as. * @throws InvalidParamException if the asset to be published does not exist. */ - public function publish($path, $options = array()) + public function publish($path, $options = []) { if (isset($this->_published[$path])) { return $this->_published[$path]; @@ -224,7 +224,7 @@ class AssetManager extends Component } } - return $this->_published[$path] = array($dstFile, $this->baseUrl . "/$dir/$fileName"); + return $this->_published[$path] = [$dstFile, $this->baseUrl . "/$dir/$fileName"]; } else { $dir = $this->hash($src . filemtime($src)); $dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir; @@ -233,10 +233,10 @@ class AssetManager extends Component symlink($src, $dstDir); } } elseif (!is_dir($dstDir) || !empty($options['forceCopy'])) { - $opts = array( + $opts = [ 'dirMode' => $this->dirMode, 'fileMode' => $this->fileMode, - ); + ]; if (isset($options['beforeCopy'])) { $opts['beforeCopy'] = $options['beforeCopy']; } else { @@ -250,7 +250,7 @@ class AssetManager extends Component FileHelper::copyDirectory($src, $dstDir, $opts); } - return $this->_published[$path] = array($dstDir, $this->baseUrl . '/' . $dir); + return $this->_published[$path] = [$dstDir, $this->baseUrl . '/' . $dir]; } } diff --git a/framework/yii/web/CacheSession.php b/framework/yii/web/CacheSession.php index b4ce2ae..84033b7 100644 --- a/framework/yii/web/CacheSession.php +++ b/framework/yii/web/CacheSession.php @@ -103,6 +103,6 @@ class CacheSession extends Session */ protected function calculateKey($id) { - return array(__CLASS__, $id); + return [__CLASS__, $id]; } } diff --git a/framework/yii/web/Controller.php b/framework/yii/web/Controller.php index a6eaf3f..9d22d01 100644 --- a/framework/yii/web/Controller.php +++ b/framework/yii/web/Controller.php @@ -44,8 +44,8 @@ class Controller extends \yii\base\Controller $method = new \ReflectionMethod($action, 'run'); } - $args = array(); - $missing = array(); + $args = []; + $missing = []; foreach ($method->getParameters() as $param) { $name = $param->getName(); if (array_key_exists($name, $params)) { @@ -59,9 +59,9 @@ class Controller extends \yii\base\Controller } if (!empty($missing)) { - throw new HttpException(400, Yii::t('yii', 'Missing required parameters: {params}', array( + throw new HttpException(400, Yii::t('yii', 'Missing required parameters: {params}', [ 'params' => implode(', ', $missing), - ))); + ])); } return $args; @@ -100,7 +100,7 @@ class Controller extends \yii\base\Controller * @param array $params the parameters (name-value pairs) to be included in the generated URL * @return string the created URL */ - public function createUrl($route, $params = array()) + public function createUrl($route, $params = []) { if (strpos($route, '/') === false) { // empty or an action ID @@ -120,7 +120,7 @@ class Controller extends \yii\base\Controller * * - a string representing a URL (e.g. "http://example.com") * - a string representing a URL alias (e.g. "@example.com") - * - an array in the format of `array($route, ...name-value pairs...)` (e.g. `array('site/index', 'ref' => 1)`) + * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`) * [[Html::url()]] will be used to convert the array into a URL. * * Any relative URL will be converted into an absolute one by prepending it with the host info diff --git a/framework/yii/web/CookieCollection.php b/framework/yii/web/CookieCollection.php index 6940493..3cf80ff 100644 --- a/framework/yii/web/CookieCollection.php +++ b/framework/yii/web/CookieCollection.php @@ -32,7 +32,7 @@ class CookieCollection extends Object implements \IteratorAggregate, \ArrayAcces /** * @var Cookie[] the cookies in this collection (indexed by the cookie names) */ - private $_cookies = array(); + private $_cookies = []; /** * Constructor. @@ -40,7 +40,7 @@ class CookieCollection extends Object implements \IteratorAggregate, \ArrayAcces * an array of name-value pairs.s * @param array $config name-value pairs that will be used to initialize the object properties */ - public function __construct($cookies = array(), $config = array()) + public function __construct($cookies = [], $config = []) { $this->_cookies = $cookies; parent::__construct($config); @@ -141,10 +141,10 @@ class CookieCollection extends Object implements \IteratorAggregate, \ArrayAcces $cookie->expire = 1; $cookie->value = ''; } else { - $cookie = new Cookie(array( + $cookie = new Cookie([ 'name' => $cookie, 'expire' => 1, - )); + ]); } if ($removeFromBrowser) { $this->_cookies[$cookie->name] = $cookie; @@ -162,7 +162,7 @@ class CookieCollection extends Object implements \IteratorAggregate, \ArrayAcces if ($this->readOnly) { throw new InvalidCallException('The cookie collection is read only.'); } - $this->_cookies = array(); + $this->_cookies = []; } /** diff --git a/framework/yii/web/DbSession.php b/framework/yii/web/DbSession.php index c508bb8..410439b 100644 --- a/framework/yii/web/DbSession.php +++ b/framework/yii/web/DbSession.php @@ -21,11 +21,11 @@ use yii\base\InvalidConfigException; * The following example shows how you can configure the application to use DbSession: * * ~~~ - * 'session' => array( + * 'session' => [ * 'class' => 'yii\web\DbSession', * // 'db' => 'mydb', * // 'sessionTable' => 'my_session', - * ) + * ] * ~~~ * * @property boolean $useCustomStorage Whether to use custom storage. This property is read-only. @@ -111,13 +111,13 @@ class DbSession extends Session $query = new Query; $row = $query->from($this->sessionTable) - ->where(array('id' => $oldID)) + ->where(['id' => $oldID]) ->createCommand($this->db) ->queryOne(); if ($row !== false) { if ($deleteOldSession) { $this->db->createCommand() - ->update($this->sessionTable, array('id' => $newID), array('id' => $oldID)) + ->update($this->sessionTable, ['id' => $newID], ['id' => $oldID]) ->execute(); } else { $row['id'] = $newID; @@ -128,10 +128,10 @@ class DbSession extends Session } else { // shouldn't reach here normally $this->db->createCommand() - ->insert($this->sessionTable, array( + ->insert($this->sessionTable, [ 'id' => $newID, 'expire' => time() + $this->getTimeout(), - ))->execute(); + ])->execute(); } } @@ -144,9 +144,9 @@ class DbSession extends Session public function readSession($id) { $query = new Query; - $data = $query->select(array('data')) + $data = $query->select(['data']) ->from($this->sessionTable) - ->where('[[expire]]>:expire AND [[id]]=:id', array(':expire' => time(), ':id' => $id)) + ->where('[[expire]]>:expire AND [[id]]=:id', [':expire' => time(), ':id' => $id]) ->createCommand($this->db) ->queryScalar(); return $data === false ? '' : $data; @@ -166,21 +166,21 @@ class DbSession extends Session try { $expire = time() + $this->getTimeout(); $query = new Query; - $exists = $query->select(array('id')) + $exists = $query->select(['id']) ->from($this->sessionTable) - ->where(array('id' => $id)) + ->where(['id' => $id]) ->createCommand($this->db) ->queryScalar(); if ($exists === false) { $this->db->createCommand() - ->insert($this->sessionTable, array( + ->insert($this->sessionTable, [ 'id' => $id, 'data' => $data, 'expire' => $expire, - ))->execute(); + ])->execute(); } else { $this->db->createCommand() - ->update($this->sessionTable, array('data' => $data, 'expire' => $expire), array('id' => $id)) + ->update($this->sessionTable, ['data' => $data, 'expire' => $expire], ['id' => $id]) ->execute(); } } catch (\Exception $e) { @@ -202,7 +202,7 @@ class DbSession extends Session public function destroySession($id) { $this->db->createCommand() - ->delete($this->sessionTable, array('id' => $id)) + ->delete($this->sessionTable, ['id' => $id]) ->execute(); return true; } @@ -216,7 +216,7 @@ class DbSession extends Session public function gcSession($maxLifetime) { $this->db->createCommand() - ->delete($this->sessionTable, '[[expire]]<:expire', array(':expire' => time())) + ->delete($this->sessionTable, '[[expire]]<:expire', [':expire' => time()]) ->execute(); return true; } diff --git a/framework/yii/web/ErrorAction.php b/framework/yii/web/ErrorAction.php index 3dd2823..bdbb4c5 100644 --- a/framework/yii/web/ErrorAction.php +++ b/framework/yii/web/ErrorAction.php @@ -23,11 +23,9 @@ use yii\base\UserException; * ```php * public function actions() * { - * return array( - * 'error' => array( - * 'class' => 'yii\web\ErrorAction', - * ), - * ); + * return [ + * 'error' => ['class' => 'yii\web\ErrorAction'], + * ]; * } * ``` * @@ -41,9 +39,9 @@ use yii\base\UserException; * Finally, configure the "errorHandler" application component as follows, * * ```php - * 'errorHandler' => array( + * 'errorHandler' => [ * 'errorAction' => 'site/error', - * ) + * ] * ``` * * @author Qiang Xue @@ -98,11 +96,11 @@ class ErrorAction extends Action if (Yii::$app->getRequest()->getIsAjax()) { return "$name: $message"; } else { - return $this->controller->render($this->view ?: $this->id, array( + return $this->controller->render($this->view ?: $this->id, [ 'name' => $name, 'message' => $message, 'exception' => $exception, - )); + ]); } } } diff --git a/framework/yii/web/HeaderCollection.php b/framework/yii/web/HeaderCollection.php index a729f6b..e8e4f9c 100644 --- a/framework/yii/web/HeaderCollection.php +++ b/framework/yii/web/HeaderCollection.php @@ -26,7 +26,7 @@ class HeaderCollection extends Object implements \IteratorAggregate, \ArrayAcces /** * @var array the headers in this collection (indexed by the header names) */ - private $_headers = array(); + private $_headers = []; /** * Returns an iterator for traversing the headers in the collection. @@ -156,7 +156,7 @@ class HeaderCollection extends Object implements \IteratorAggregate, \ArrayAcces */ public function removeAll() { - $this->_headers = array(); + $this->_headers = []; } /** diff --git a/framework/yii/web/JqueryAsset.php b/framework/yii/web/JqueryAsset.php index 9991eb4..f1324ab 100644 --- a/framework/yii/web/JqueryAsset.php +++ b/framework/yii/web/JqueryAsset.php @@ -16,7 +16,7 @@ namespace yii\web; class JqueryAsset extends AssetBundle { public $sourcePath = '@yii/assets'; - public $js = array( + public $js = [ 'jquery.js', - ); + ]; } diff --git a/framework/yii/web/JsExpression.php b/framework/yii/web/JsExpression.php index 7daac08..1d05b57 100644 --- a/framework/yii/web/JsExpression.php +++ b/framework/yii/web/JsExpression.php @@ -30,7 +30,7 @@ class JsExpression extends Object * @param string $expression the JavaScript expression represented by this object * @param array $config additional configurations for this object */ - public function __construct($expression, $config = array()) + public function __construct($expression, $config = []) { $this->expression = $expression; parent::__construct($config); diff --git a/framework/yii/web/PageCache.php b/framework/yii/web/PageCache.php index 9bc8981..a97659c 100644 --- a/framework/yii/web/PageCache.php +++ b/framework/yii/web/PageCache.php @@ -41,10 +41,10 @@ class PageCache extends ActionFilter * For example, * * ~~~ - * array( + * [ * 'class' => 'yii\caching\DbDependency', * 'sql' => 'SELECT MAX(lastModified) FROM Post', - * ) + * ] * ~~~ * * would make the output cache depends on the last modified time of all posts. @@ -58,9 +58,9 @@ class PageCache extends ActionFilter * according to the current application language: * * ~~~ - * array( + * [ * Yii::$app->language, - * ) + * ] */ public $variations; /** @@ -91,8 +91,8 @@ class PageCache extends ActionFilter */ public function beforeAction($action) { - $properties = array(); - foreach (array('cache', 'duration', 'dependency', 'variations', 'enabled') as $name) { + $properties = []; + foreach (['cache', 'duration', 'dependency', 'variations', 'enabled'] as $name) { $properties[$name] = $this->$name; } $id = $this->varyByRoute ? $action->getUniqueId() : __CLASS__; diff --git a/framework/yii/web/Request.php b/framework/yii/web/Request.php index 312adc1..f326f6e 100644 --- a/framework/yii/web/Request.php +++ b/framework/yii/web/Request.php @@ -103,7 +103,7 @@ class Request extends \yii\base\Request * @var array the configuration of the CSRF cookie. This property is used only when [[enableCsrfValidation]] is true. * @see Cookie */ - public $csrfCookie = array('httpOnly' => true); + public $csrfCookie = ['httpOnly' => true]; /** * @var boolean whether cookies should be validated to ensure they are not tampered. Defaults to true. */ @@ -130,7 +130,7 @@ class Request extends \yii\base\Request if ($result !== false) { list ($route, $params) = $result; $_GET = array_merge($_GET, $params); - return array($route, $_GET); + return [$route, $_GET]; } else { throw new HttpException(404, Yii::t('yii', 'Page not found.')); } @@ -245,7 +245,7 @@ class Request extends \yii\base\Request if (isset($_POST[$this->restVar])) { $this->_restParams = $_POST; } else { - $this->_restParams = array(); + $this->_restParams = []; if (function_exists('mb_parse_str')) { mb_parse_str($this->getRawBody(), $this->_restParams); } else { @@ -783,7 +783,7 @@ class Request extends \yii\base\Request if (isset($_SERVER['HTTP_ACCEPT'])) { $this->_contentTypes = $this->parseAcceptHeader($_SERVER['HTTP_ACCEPT']); } else { - $this->_contentTypes = array(); + $this->_contentTypes = []; } } return $this->_contentTypes; @@ -812,7 +812,7 @@ class Request extends \yii\base\Request if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $this->_languages = $this->parseAcceptHeader($_SERVER['HTTP_ACCEPT_LANGUAGE']); } else { - $this->_languages = array(); + $this->_languages = []; } } return $this->_languages; @@ -835,11 +835,11 @@ class Request extends \yii\base\Request */ protected function parseAcceptHeader($header) { - $accepts = array(); + $accepts = []; $n = preg_match_all('/\s*([\w\/\-\*]+)\s*(?:;\s*q\s*=\s*([\d\.]+))?[^,]*/', $header, $matches, PREG_SET_ORDER); for ($i = 0; $i < $n; ++$i) { if (!empty($matches[$i][1])) { - $accepts[] = array($matches[$i][1], isset($matches[$i][2]) ? (float)$matches[$i][2] : 1, $i); + $accepts[] = [$matches[$i][1], isset($matches[$i][2]) ? (float)$matches[$i][2] : 1, $i]; } } usort($accepts, function ($a, $b) { @@ -863,7 +863,7 @@ class Request extends \yii\base\Request } } }); - $result = array(); + $result = []; foreach ($accepts as $accept) { $result[] = $accept[0]; } @@ -879,7 +879,7 @@ class Request extends \yii\base\Request * @return string the language that the application should use. Null is returned if both [[getAcceptedLanguages()]] * and `$languages` are empty. */ - public function getPreferredLanguage($languages = array()) + public function getPreferredLanguage($languages = []) { $acceptedLanguages = $this->getAcceptedLanguages(); if (empty($languages)) { @@ -917,9 +917,9 @@ class Request extends \yii\base\Request public function getCookies() { if ($this->_cookies === null) { - $this->_cookies = new CookieCollection($this->loadCookies(), array( + $this->_cookies = new CookieCollection($this->loadCookies(), [ 'readOnly' => true, - )); + ]); } return $this->_cookies; } @@ -930,23 +930,23 @@ class Request extends \yii\base\Request */ protected function loadCookies() { - $cookies = array(); + $cookies = []; if ($this->enableCookieValidation) { $key = $this->getCookieValidationKey(); foreach ($_COOKIE as $name => $value) { if (is_string($value) && ($value = Security::validateData($value, $key)) !== false) { - $cookies[$name] = new Cookie(array( + $cookies[$name] = new Cookie([ 'name' => $name, 'value' => @unserialize($value), - )); + ]); } } } else { foreach ($_COOKIE as $name => $value) { - $cookies[$name] = new Cookie(array( + $cookies[$name] = new Cookie([ 'name' => $name, 'value' => $value, - )); + ]); } } return $cookies; @@ -1032,7 +1032,7 @@ class Request extends \yii\base\Request public function validateCsrfToken() { $method = $this->getMethod(); - if (!$this->enableCsrfValidation || !in_array($method, array('POST', 'PUT', 'PATCH', 'DELETE'), true)) { + if (!$this->enableCsrfValidation || !in_array($method, ['POST', 'PUT', 'PATCH', 'DELETE'], true)) { return true; } $trueToken = $this->getCookies()->getValue($this->csrfVar); diff --git a/framework/yii/web/Response.php b/framework/yii/web/Response.php index 2dc8721..ea1f0d9 100644 --- a/framework/yii/web/Response.php +++ b/framework/yii/web/Response.php @@ -123,7 +123,7 @@ class Response extends \yii\base\Response /** * @var array list of HTTP status codes and the corresponding texts */ - public static $httpStatuses = array( + public static $httpStatuses = [ 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', @@ -189,7 +189,7 @@ class Response extends \yii\base\Response 509 => 'Bandwidth Limit Exceeded', 510 => 'Not Extended', 511 => 'Network Authentication Required', - ); + ]; /** * @var integer the HTTP status code to send with the response. @@ -463,7 +463,7 @@ class Response extends \yii\base\Response protected function getHttpRange($fileSize) { if (!isset($_SERVER['HTTP_RANGE']) || $_SERVER['HTTP_RANGE'] === '-') { - return array(0, $fileSize - 1); + return [0, $fileSize - 1]; } if (!preg_match('/^bytes=(\d*)-(\d*)$/', $_SERVER['HTTP_RANGE'], $matches)) { return false; @@ -484,7 +484,7 @@ class Response extends \yii\base\Response if ($start < 0 || $start > $end) { return false; } else { - return array($start, $end); + return [$start, $end]; } } @@ -595,7 +595,7 @@ class Response extends \yii\base\Response * * - a string representing a URL (e.g. "http://example.com") * - a string representing a URL alias (e.g. "@example.com") - * - an array in the format of `array($route, ...name-value pairs...)` (e.g. `array('site/index', 'ref' => 1)`). + * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`). * Note that the route is with respect to the whole application, instead of relative to a controller or module. * [[Html::url()]] will be used to convert the array into a URL. * @@ -656,10 +656,10 @@ class Response extends \yii\base\Response * * ~~~ * // add a cookie - * $response->cookies->add(new Cookie(array( + * $response->cookies->add(new Cookie([ * 'name' => $name, * 'value' => $value, - * )); + * ]); * * // remove a cookie * $response->cookies->remove('name'); @@ -754,7 +754,7 @@ class Response extends \yii\base\Response */ public function getIsEmpty() { - return in_array($this->getStatusCode(), array(201, 204, 304)); + return in_array($this->getStatusCode(), [201, 204, 304]); } /** diff --git a/framework/yii/web/ResponseEvent.php b/framework/yii/web/ResponseEvent.php index e5d4210..dabaf2f 100644 --- a/framework/yii/web/ResponseEvent.php +++ b/framework/yii/web/ResponseEvent.php @@ -31,7 +31,7 @@ class ResponseEvent extends Event * @param Response $response the response object associated with this event. * @param array $config the configuration array for initializing the newly created object. */ - public function __construct($response, $config = array()) + public function __construct($response, $config = []) { $this->response = $response; parent::__construct($config); diff --git a/framework/yii/web/Session.php b/framework/yii/web/Session.php index 92ec3ad..d081cc9 100644 --- a/framework/yii/web/Session.php +++ b/framework/yii/web/Session.php @@ -84,9 +84,7 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co /** * @var array parameter-value pairs to override default session cookie parameters */ - public $cookieParams = array( - 'httpOnly' => true - ); + public $cookieParams = ['httpOnly' => true]; /** * Initializes the application component. @@ -98,7 +96,7 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co if ($this->autoStart) { $this->open(); } - register_shutdown_function(array($this, 'close')); + register_shutdown_function([$this, 'close']); } /** @@ -131,12 +129,12 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co if (!$this->_opened) { if ($this->getUseCustomStorage()) { @session_set_save_handler( - array($this, 'openSession'), - array($this, 'closeSession'), - array($this, 'readSession'), - array($this, 'writeSession'), - array($this, 'destroySession'), - array($this, 'gcSession') + [$this, 'openSession'], + [$this, 'closeSession'], + [$this, 'readSession'], + [$this, 'writeSession'], + [$this, 'destroySession'], + [$this, 'gcSession'] ); } @@ -561,7 +559,7 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co */ protected function updateFlashCounters() { - $counters = $this->get($this->flashVar, array()); + $counters = $this->get($this->flashVar, []); if (is_array($counters)) { foreach ($counters as $key => $count) { if ($count) { @@ -588,7 +586,7 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co */ public function getFlash($key, $defaultValue = null, $delete = false) { - $counters = $this->get($this->flashVar, array()); + $counters = $this->get($this->flashVar, []); if (isset($counters[$key])) { $value = $this->get($key, $defaultValue); if ($delete) { @@ -606,8 +604,8 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co */ public function getAllFlashes() { - $counters = $this->get($this->flashVar, array()); - $flashes = array(); + $counters = $this->get($this->flashVar, []); + $flashes = []; foreach (array_keys($counters) as $key) { if (isset($_SESSION[$key])) { $flashes[$key] = $_SESSION[$key]; @@ -626,7 +624,7 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co */ public function setFlash($key, $value = true) { - $counters = $this->get($this->flashVar, array()); + $counters = $this->get($this->flashVar, []); $counters[$key] = 0; $_SESSION[$key] = $value; $_SESSION[$this->flashVar] = $counters; @@ -642,7 +640,7 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co */ public function removeFlash($key) { - $counters = $this->get($this->flashVar, array()); + $counters = $this->get($this->flashVar, []); $value = isset($_SESSION[$key], $counters[$key]) ? $_SESSION[$key] : null; unset($counters[$key], $_SESSION[$key]); $_SESSION[$this->flashVar] = $counters; @@ -657,7 +655,7 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co */ public function removeAllFlashes() { - $counters = $this->get($this->flashVar, array()); + $counters = $this->get($this->flashVar, []); foreach (array_keys($counters) as $key) { unset($_SESSION[$key]); } diff --git a/framework/yii/web/UploadedFile.php b/framework/yii/web/UploadedFile.php index c4e2f0f..3cb6813 100644 --- a/framework/yii/web/UploadedFile.php +++ b/framework/yii/web/UploadedFile.php @@ -122,9 +122,9 @@ class UploadedFile extends Object { $files = static::loadFiles(); if (isset($files[$name])) { - return array($files[$name]); + return [$files[$name]]; } - $results = array(); + $results = []; foreach ($files as $key => $file) { if (strpos($key, "{$name}[") === 0) { $results[] = self::$_files[$key]; @@ -180,7 +180,7 @@ class UploadedFile extends Object private static function loadFiles() { if (self::$_files === null) { - self::$_files = array(); + self::$_files = []; if (isset($_FILES) && is_array($_FILES)) { foreach ($_FILES as $class => $info) { self::loadFilesRecursive($class, $info['name'], $info['tmp_name'], $info['type'], $info['size'], $info['error']); @@ -206,13 +206,13 @@ class UploadedFile extends Object self::loadFilesRecursive($key . '[' . $i . ']', $name, $tempNames[$i], $types[$i], $sizes[$i], $errors[$i]); } } else { - self::$_files[$key] = new static(array( + self::$_files[$key] = new static([ 'name' => $names, 'tempName' => $tempNames, 'type' => $types, 'size' => $sizes, 'error' => $errors, - )); + ]); } } } diff --git a/framework/yii/web/UrlManager.php b/framework/yii/web/UrlManager.php index 0d9547f..c5f4c28 100644 --- a/framework/yii/web/UrlManager.php +++ b/framework/yii/web/UrlManager.php @@ -61,7 +61,7 @@ class UrlManager extends Component * Here is an example configuration for RESTful CRUD controller: * * ~~~php - * array( + * [ * 'dashboard' => 'site/index', * * 'POST s' => '/create', @@ -70,13 +70,13 @@ class UrlManager extends Component * 'PUT /' => '/update', * 'DELETE /' => '/delete', * '/' => '/view', - * ); + * ]; * ~~~ * * Note that if you modify this property after the UrlManager object is created, make sure * you populate the array with rule objects instead of rule configurations. */ - public $rules = array(); + public $rules = []; /** * @var string the URL suffix used when in 'path' format. * For example, ".html" can be used so that the URL looks like pointing to a static HTML page. @@ -105,9 +105,7 @@ class UrlManager extends Component * @var array the default configuration of URL rules. Individual rule configurations * specified via [[rules]] will take precedence when the same property of the rule is configured. */ - public $ruleConfig = array( - 'class' => 'yii\web\UrlRule', - ); + public $ruleConfig = ['class' => 'yii\web\UrlRule']; private $_baseUrl; private $_hostInfo; @@ -141,12 +139,10 @@ class UrlManager extends Component } } - $rules = array(); + $rules = []; foreach ($this->rules as $key => $rule) { if (!is_array($rule)) { - $rule = array( - 'route' => $rule, - ); + $rule = ['route' => $rule]; if (preg_match('/^((?:(GET|HEAD|POST|PUT|PATCH|DELETE),)*(GET|HEAD|POST|PUT|PATCH|DELETE))\s+(.*)$/', $key, $matches)) { $rule['verb'] = explode(',', $matches[1]); $rule['mode'] = UrlRule::PARSING_ONLY; @@ -159,7 +155,7 @@ class UrlManager extends Component $this->rules = $rules; if (isset($key, $hash)) { - $this->cache->set($key, array($this->rules, $hash)); + $this->cache->set($key, [$this->rules, $hash]); } } @@ -201,14 +197,14 @@ class UrlManager extends Component } Yii::trace('No matching URL rules. Using default URL parsing logic.', __METHOD__); - return array($pathInfo, array()); + return [$pathInfo, []]; } else { $route = $request->get($this->routeVar); if (is_array($route)) { $route = ''; } Yii::trace('Pretty URL not enabled. Using default URL parsing logic.', __METHOD__); - return array((string)$route, array()); + return [(string)$route, []]; } } @@ -219,7 +215,7 @@ class UrlManager extends Component * @param array $params the parameters (name-value pairs) * @return string the created URL */ - public function createUrl($route, $params = array()) + public function createUrl($route, $params = []) { $anchor = isset($params['#']) ? '#' . $params['#'] : ''; unset($params['#'], $params[$this->routeVar]); @@ -267,7 +263,7 @@ class UrlManager extends Component * @return string the created URL * @see createUrl() */ - public function createAbsoluteUrl($route, $params = array()) + public function createAbsoluteUrl($route, $params = []) { $url = $this->createUrl($route, $params); if (strpos($url, '://') !== false) { diff --git a/framework/yii/web/UrlRule.php b/framework/yii/web/UrlRule.php index 10f0627..6ebc615 100644 --- a/framework/yii/web/UrlRule.php +++ b/framework/yii/web/UrlRule.php @@ -50,7 +50,7 @@ class UrlRule extends Object * When this rule is used to parse the incoming request, the values declared in this property * will be injected into $_GET. */ - public $defaults = array(); + public $defaults = []; /** * @var string the URL suffix used for this rule. * For example, ".html" can be used so that the URL looks like pointing to a static HTML page. @@ -84,11 +84,11 @@ class UrlRule extends Object /** * @var array list of regex for matching parameters. This is used in generating URL. */ - private $_paramRules = array(); + private $_paramRules = []; /** * @var array list of parameters used in the route. */ - private $_routeParams = array(); + private $_routeParams = []; /** * Initializes this rule. @@ -107,7 +107,7 @@ class UrlRule extends Object $this->verb[$i] = strtoupper($verb); } } else { - $this->verb = array(strtoupper($this->verb)); + $this->verb = [strtoupper($this->verb)]; } } if ($this->name === null) { @@ -133,7 +133,7 @@ class UrlRule extends Object } } - $tr = $tr2 = array(); + $tr = $tr2 = []; if (preg_match_all('/<(\w+):?([^>]+)?>/', $this->pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) { foreach ($matches as $match) { $name = $match[1][0]; @@ -211,7 +211,7 @@ class UrlRule extends Object } } $params = $this->defaults; - $tr = array(); + $tr = []; foreach ($matches as $name => $value) { if (isset($this->_routeParams[$name])) { $tr[$this->_routeParams[$name]] = $value; @@ -225,7 +225,7 @@ class UrlRule extends Object } else { $route = $this->route; } - return array($route, $params); + return [$route, $params]; } /** @@ -241,7 +241,7 @@ class UrlRule extends Object return false; } - $tr = array(); + $tr = []; // match the route part first if ($route !== $this->route) { diff --git a/framework/yii/web/User.php b/framework/yii/web/User.php index 0dd16d0..4aa7c67 100644 --- a/framework/yii/web/User.php +++ b/framework/yii/web/User.php @@ -54,17 +54,17 @@ class User extends Component * the name-value pairs are GET parameters used to construct the login URL. For example, * * ~~~ - * array('site/login', 'ref' => 1) + * ['site/login', 'ref' => 1] * ~~~ * * If this property is null, a 403 HTTP exception will be raised when [[loginRequired()]] is called. */ - public $loginUrl = array('site/login'); + public $loginUrl = ['site/login']; /** * @var array the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is true. * @see Cookie */ - public $identityCookie = array('name' => '_identity', 'httpOnly' => true); + public $identityCookie = ['name' => '_identity', 'httpOnly' => true]; /** * @var integer the number of seconds in which the user will be logged out automatically if he * remains inactive. If this property is not set, the user will be logged out after @@ -94,7 +94,7 @@ class User extends Component */ public $returnUrlVar = '__returnUrl'; - private $_access = array(); + private $_access = []; /** @@ -282,7 +282,7 @@ class User extends Component * the name-value pairs are GET parameters used to construct the URL. For example, * * ~~~ - * array('admin/index', 'ref' => 1) + * ['admin/index', 'ref' => 1] * ~~~ */ public function setReturnUrl($url) @@ -324,10 +324,10 @@ class User extends Component */ protected function beforeLogin($identity, $cookieBased) { - $event = new UserEvent(array( + $event = new UserEvent([ 'identity' => $identity, 'cookieBased' => $cookieBased, - )); + ]); $this->trigger(self::EVENT_BEFORE_LOGIN, $event); return $event->isValid; } @@ -342,10 +342,10 @@ class User extends Component */ protected function afterLogin($identity, $cookieBased) { - $this->trigger(self::EVENT_AFTER_LOGIN, new UserEvent(array( + $this->trigger(self::EVENT_AFTER_LOGIN, new UserEvent([ 'identity' => $identity, 'cookieBased' => $cookieBased, - ))); + ])); } /** @@ -358,9 +358,9 @@ class User extends Component */ protected function beforeLogout($identity) { - $event = new UserEvent(array( + $event = new UserEvent([ 'identity' => $identity, - )); + ]); $this->trigger(self::EVENT_BEFORE_LOGOUT, $event); return $event->isValid; } @@ -374,9 +374,9 @@ class User extends Component */ protected function afterLogout($identity) { - $this->trigger(self::EVENT_AFTER_LOGOUT, new UserEvent(array( + $this->trigger(self::EVENT_AFTER_LOGOUT, new UserEvent([ 'identity' => $identity, - ))); + ])); } /** @@ -411,11 +411,11 @@ class User extends Component protected function sendIdentityCookie($identity, $duration) { $cookie = new Cookie($this->identityCookie); - $cookie->value = json_encode(array( + $cookie->value = json_encode([ $identity->getId(), $identity->getAuthKey(), $duration, - )); + ]); $cookie->expire = time() + $duration; Yii::$app->getResponse()->getCookies()->add($cookie); } @@ -487,10 +487,10 @@ class User extends Component * before, its result will be directly returned when calling this method to check the same * operation. If this parameter is false, this method will always call * [[AuthManager::checkAccess()]] to obtain the up-to-date access result. Note that this - * caching is effective only within the same request and only works when `$params = array()`. + * caching is effective only within the same request and only works when `$params = []`. * @return boolean whether the operations can be performed by this user. */ - public function checkAccess($operation, $params = array(), $allowCaching = true) + public function checkAccess($operation, $params = [], $allowCaching = true) { $auth = Yii::$app->getAuthManager(); if ($auth === null) { diff --git a/framework/yii/web/VerbFilter.php b/framework/yii/web/VerbFilter.php index 4f45190..c3235a6 100644 --- a/framework/yii/web/VerbFilter.php +++ b/framework/yii/web/VerbFilter.php @@ -24,18 +24,18 @@ use yii\base\Behavior; * ~~~ * public function behaviors() * { - * return array( - * 'verbs' => array( + * return [ + * 'verbs' => [ * 'class' => \yii\web\VerbFilter::className(), - * 'actions' => array( - * 'index' => array('get'), - * 'view' => array('get'), - * 'create' => array('get', 'post'), - * 'update' => array('get', 'put', 'post'), - * 'delete' => array('post', 'delete'), - * ), - * ), - * ); + * 'actions' => [ + * 'index' => ['get'], + * 'view' => ['get'], + * 'create' => ['get', 'post'], + * 'update' => ['get', 'put', 'post'], + * 'delete' => ['post', 'delete'], + * ], + * ], + * ]; * } * ~~~ * @@ -52,7 +52,7 @@ class VerbFilter extends Behavior * allowed methods (e.g. GET, HEAD, PUT) as the value. * If an action is not listed all request methods are considered allowed. */ - public $actions = array(); + public $actions = []; /** @@ -61,9 +61,7 @@ class VerbFilter extends Behavior */ public function events() { - return array( - Controller::EVENT_BEFORE_ACTION => 'beforeAction', - ); + return [Controller::EVENT_BEFORE_ACTION => 'beforeAction']; } /** diff --git a/framework/yii/web/XmlResponseFormatter.php b/framework/yii/web/XmlResponseFormatter.php index 737011d..05c2762 100644 --- a/framework/yii/web/XmlResponseFormatter.php +++ b/framework/yii/web/XmlResponseFormatter.php @@ -69,7 +69,7 @@ class XmlResponseFormatter extends Component implements ResponseFormatterInterfa if ($data instanceof Arrayable) { $this->buildXml($child, $data->toArray()); } else { - $array = array(); + $array = []; foreach ($data as $name => $value) { $array[$name] = $value; } diff --git a/framework/yii/web/YiiAsset.php b/framework/yii/web/YiiAsset.php index 2ad5384..29796e7 100644 --- a/framework/yii/web/YiiAsset.php +++ b/framework/yii/web/YiiAsset.php @@ -17,10 +17,10 @@ use yii\base\View; class YiiAsset extends AssetBundle { public $sourcePath = '@yii/assets'; - public $js = array( + public $js = [ 'yii.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\web\JqueryAsset', - ); + ]; } diff --git a/framework/yii/widgets/ActiveField.php b/framework/yii/widgets/ActiveField.php index d31c50b..b8924bd 100644 --- a/framework/yii/widgets/ActiveField.php +++ b/framework/yii/widgets/ActiveField.php @@ -40,9 +40,7 @@ class ActiveField extends Component * * - tag: the tag name of the container element. Defaults to "div". */ - public $options = array( - 'class' => 'form-group', - ); + public $options = ['class' => 'form-group']; /** * @var string the template that is used to arrange the label, the input field, the error message and the hint text. * The following tokens will be replaced when [[render()]] is called: `{label}`, `{input}`, `{error}` and `{hint}`. @@ -52,7 +50,7 @@ class ActiveField extends Component * @var array the default options for the input tags. The parameter passed to individual input methods * (e.g. [[textInput()]]) will be merged with this property when rendering the input tag. */ - public $inputOptions = array('class' => 'form-control'); + public $inputOptions = ['class' => 'form-control']; /** * @var array the default options for the error tags. The parameter passed to [[error()]] will be * merged with this property when rendering the error tag. @@ -60,12 +58,12 @@ class ActiveField extends Component * * - tag: the tag name of the container element. Defaults to "div". */ - public $errorOptions = array('class' => 'help-block'); + public $errorOptions = ['class' => 'help-block']; /** * @var array the default options for the label tags. The parameter passed to [[label()]] will be * merged with this property when rendering the label tag. */ - public $labelOptions = array('class' => 'control-label'); + public $labelOptions = ['class' => 'control-label']; /** * @var array the default options for the hint tags. The parameter passed to [[hint()]] will be * merged with this property when rendering the hint tag. @@ -73,7 +71,7 @@ class ActiveField extends Component * * - tag: the tag name of the container element. Defaults to "div". */ - public $hintOptions = array('class' => 'hint-block'); + public $hintOptions = ['class' => 'hint-block']; /** * @var boolean whether to enable client-side data validation. * If not set, it will take the value of [[ActiveForm::enableClientValidation]]. @@ -104,7 +102,7 @@ class ActiveField extends Component /** * @var array the jQuery selectors for selecting the container, input and error tags. * The array keys should be "container", "input", and/or "error", and the array values - * are the corresponding selectors. For example, `array('input' => '#my-input')`. + * are the corresponding selectors. For example, `['input' => '#my-input']`. * * The container selector is used under the context of the form, while the input and the error * selectors are used under the context of the container. @@ -119,7 +117,7 @@ class ActiveField extends Component * `{error}`, and `{error}`. Note that you normally don't need to access this property directly as * it is maintained by various methods of this class. */ - public $parts = array(); + public $parts = []; /** @@ -191,7 +189,7 @@ class ActiveField extends Component $inputID = Html::getInputId($this->model, $this->attribute); $attribute = Html::getAttributeName($this->attribute); $options = $this->options; - $class = isset($options['class']) ? array($options['class']) : array(); + $class = isset($options['class']) ? [$options['class']] : []; $class[] = "field-$inputID"; if ($this->model->isAttributeRequired($attribute)) { $class[] = $this->form->requiredCssClass; @@ -223,7 +221,7 @@ class ActiveField extends Component * using [[Html::encode()]]. If a value is null, the corresponding attribute will not be rendered. * @return static the field object itself */ - public function label($label = null, $options = array()) + public function label($label = null, $options = []) { $options = array_merge($this->labelOptions, $options); if ($label !== null) { @@ -246,7 +244,7 @@ class ActiveField extends Component * * @return static the field object itself */ - public function error($options = array()) + public function error($options = []) { $options = array_merge($this->errorOptions, $options); $this->parts['{error}'] = Html::error($this->model, $this->attribute, $options); @@ -265,7 +263,7 @@ class ActiveField extends Component * * @return static the field object itself */ - public function hint($content, $options = array()) + public function hint($content, $options = []) { $options = array_merge($this->hintOptions, $options); $tag = ArrayHelper::remove($options, 'tag', 'div'); @@ -280,7 +278,7 @@ class ActiveField extends Component * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]]. * @return static the field object itself */ - public function input($type, $options = array()) + public function input($type, $options = []) { $options = array_merge($this->inputOptions, $options); $this->parts['{input}'] = Html::activeInput($type, $this->model, $this->attribute, $options); @@ -295,7 +293,7 @@ class ActiveField extends Component * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]]. * @return static the field object itself */ - public function textInput($options = array()) + public function textInput($options = []) { $options = array_merge($this->inputOptions, $options); $this->parts['{input}'] = Html::activeTextInput($this->model, $this->attribute, $options); @@ -310,7 +308,7 @@ class ActiveField extends Component * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]]. * @return static the field object itself */ - public function passwordInput($options = array()) + public function passwordInput($options = []) { $options = array_merge($this->inputOptions, $options); $this->parts['{input}'] = Html::activePasswordInput($this->model, $this->attribute, $options); @@ -325,9 +323,9 @@ class ActiveField extends Component * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]]. * @return static the field object itself */ - public function fileInput($options = array()) + public function fileInput($options = []) { - if ($this->inputOptions !== array('class' => 'form-control')) { + if ($this->inputOptions !== ['class' => 'form-control']) { $options = array_merge($this->inputOptions, $options); } $this->parts['{input}'] = Html::activeFileInput($this->model, $this->attribute, $options); @@ -341,7 +339,7 @@ class ActiveField extends Component * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]]. * @return static the field object itself */ - public function textarea($options = array()) + public function textarea($options = []) { $options = array_merge($this->inputOptions, $options); $this->parts['{input}'] = Html::activeTextarea($this->model, $this->attribute, $options); @@ -369,7 +367,7 @@ class ActiveField extends Component * except that the radio is enclosed by the label tag. * @return static the field object itself */ - public function radio($options = array(), $enclosedByLabel = true) + public function radio($options = [], $enclosedByLabel = true) { if ($enclosedByLabel) { if (!isset($options['label'])) { @@ -404,7 +402,7 @@ class ActiveField extends Component * except that the checkbox is enclosed by the label tag. * @return static the field object itself */ - public function checkbox($options = array(), $enclosedByLabel = true) + public function checkbox($options = [], $enclosedByLabel = true) { if ($enclosedByLabel) { if (!isset($options['label'])) { @@ -436,10 +434,10 @@ class ActiveField extends Component * and the array values are the extra attributes for the corresponding option tags. For example, * * ~~~ - * array( - * 'value1' => array('disabled' => true), - * 'value2' => array('label' => 'value 2'), - * ); + * [ + * 'value1' => ['disabled' => true], + * 'value2' => ['label' => 'value 2'], + * ]; * ~~~ * * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options', @@ -450,7 +448,7 @@ class ActiveField extends Component * * @return static the field object itself */ - public function dropDownList($items, $options = array()) + public function dropDownList($items, $options = []) { $options = array_merge($this->inputOptions, $options); $this->parts['{input}'] = Html::activeDropDownList($this->model, $this->attribute, $items, $options); @@ -475,10 +473,10 @@ class ActiveField extends Component * and the array values are the extra attributes for the corresponding option tags. For example, * * ~~~ - * array( - * 'value1' => array('disabled' => true), - * 'value2' => array('label' => 'value 2'), - * ); + * [ + * 'value1' => ['disabled' => true], + * 'value2' => ['label' => 'value 2'], + * ]; * ~~~ * * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options', @@ -492,7 +490,7 @@ class ActiveField extends Component * * @return static the field object itself */ - public function listBox($items, $options = array()) + public function listBox($items, $options = []) { $options = array_merge($this->inputOptions, $options); $this->parts['{input}'] = Html::activeListBox($this->model, $this->attribute, $items, $options); @@ -524,7 +522,7 @@ class ActiveField extends Component * value and the checked status of the checkbox input. * @return static the field object itself */ - public function checkboxList($items, $options = array()) + public function checkboxList($items, $options = []) { $this->parts['{input}'] = Html::activeCheckboxList($this->model, $this->attribute, $items, $options); return $this; @@ -554,7 +552,7 @@ class ActiveField extends Component * value and the checked status of the radio button input. * @return static the field object itself */ - public function radioList($items, $options = array()) + public function radioList($items, $options = []) { $this->parts['{input}'] = Html::activeRadioList($this->model, $this->attribute, $items, $options); return $this; @@ -573,7 +571,7 @@ class ActiveField extends Component * @param array $config name-value pairs that will be used to initialize the widget * @return static the field object itself */ - public function widget($class, $config = array()) + public function widget($class, $config = []) { /** @var \yii\base\Widget $class */ $config['model'] = $this->model; @@ -591,12 +589,12 @@ class ActiveField extends Component { $attribute = Html::getAttributeName($this->attribute); if (!in_array($attribute, $this->model->activeAttributes(), true)) { - return array(); + return []; } $enableClientValidation = $this->enableClientValidation || $this->enableClientValidation === null && $this->form->enableClientValidation; if ($enableClientValidation) { - $validators = array(); + $validators = []; foreach ($this->model->getActiveValidators($attribute) as $validator) { /** @var \yii\validators\Validator $validator */ $js = $validator->clientValidateAttribute($this->model, $attribute, $this->form->getView()); @@ -617,7 +615,7 @@ class ActiveField extends Component if ($enableClientValidation && !empty($options['validate']) || $enableAjaxValidation) { $inputID = Html::getInputId($this->model, $this->attribute); $options['name'] = $inputID; - foreach (array('validateOnChange', 'validateOnType', 'validationDelay') as $name) { + foreach (['validateOnChange', 'validateOnType', 'validationDelay'] as $name) { $options[$name] = $this->$name === null ? $this->form->$name : $this->$name; } $options['container'] = isset($this->selectors['container']) ? $this->selectors['container'] : ".field-$inputID"; @@ -629,7 +627,7 @@ class ActiveField extends Component } return $options; } else { - return array(); + return []; } } } diff --git a/framework/yii/widgets/ActiveForm.php b/framework/yii/widgets/ActiveForm.php index b46ad46..3bd4a11 100644 --- a/framework/yii/widgets/ActiveForm.php +++ b/framework/yii/widgets/ActiveForm.php @@ -36,7 +36,7 @@ class ActiveForm extends Widget * The values will be HTML-encoded using [[Html::encode()]]. * If a value is null, the corresponding attribute will not be rendered. */ - public $options = array(); + public $options = []; /** * @var array the default configuration used by [[field()]] when creating a new field object. */ @@ -140,7 +140,7 @@ class ActiveForm extends Widget * represents the validation options for a particular attribute. * @internal */ - public $attributes = array(); + public $attributes = []; /** * Initializes the widget. @@ -180,18 +180,18 @@ class ActiveForm extends Widget */ protected function getClientOptions() { - $options = array( + $options = [ 'errorSummary' => '.' . $this->errorSummaryCssClass, 'validateOnSubmit' => $this->validateOnSubmit, 'errorCssClass' => $this->errorCssClass, 'successCssClass' => $this->successCssClass, 'validatingCssClass' => $this->validatingCssClass, 'ajaxVar' => $this->ajaxVar, - ); + ]; if ($this->validationUrl !== null) { $options['validationUrl'] = Html::url($this->validationUrl); } - foreach (array('beforeSubmit', 'beforeValidate', 'afterValidate') as $name) { + foreach (['beforeSubmit', 'beforeValidate', 'afterValidate'] as $name) { if (($value = $this->$name) !== null) { $options[$name] = $value instanceof JsExpression ? $value : new JsExpression($value); } @@ -212,13 +212,11 @@ class ActiveForm extends Widget * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. * @return string the generated error summary */ - public function errorSummary($models, $options = array()) + public function errorSummary($models, $options = []) { - if (!is_array($models)) { - $models = array($models); - } + $models = (array)$models; - $lines = array(); + $lines = []; foreach ($models as $model) { /** @var $model Model */ foreach ($model->getFirstErrors() as $error) { @@ -257,12 +255,12 @@ class ActiveForm extends Widget * @return ActiveField the created ActiveField object * @see fieldConfig */ - public function field($model, $attribute, $options = array()) + public function field($model, $attribute, $options = []) { - return Yii::createObject(array_merge($this->fieldConfig, $options, array( + return Yii::createObject(array_merge($this->fieldConfig, $options, [ 'model' => $model, 'attribute' => $attribute, 'form' => $this, - ))); + ])); } } diff --git a/framework/yii/widgets/ActiveFormAsset.php b/framework/yii/widgets/ActiveFormAsset.php index cbd3f9a..5acb5e1 100644 --- a/framework/yii/widgets/ActiveFormAsset.php +++ b/framework/yii/widgets/ActiveFormAsset.php @@ -15,10 +15,10 @@ use yii\web\AssetBundle; class ActiveFormAsset extends AssetBundle { public $sourcePath = '@yii/assets'; - public $js = array( + public $js = [ 'yii.activeForm.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\web\YiiAsset', - ); + ]; } diff --git a/framework/yii/widgets/BaseListView.php b/framework/yii/widgets/BaseListView.php index d59c197..bfa984f 100644 --- a/framework/yii/widgets/BaseListView.php +++ b/framework/yii/widgets/BaseListView.php @@ -23,7 +23,7 @@ abstract class BaseListView extends Widget * @var array the HTML attributes for the container tag of the list view. * The "tag" element specifies the tag name of the container element and defaults to "div". */ - public $options = array(); + public $options = []; /** * @var \yii\data\DataProviderInterface the data provider for the view. This property is required. */ @@ -32,12 +32,12 @@ abstract class BaseListView extends Widget * @var array the configuration for the pager widget. By default, [[LinkPager]] will be * used to render the pager. You can use a different widget class by configuring the "class" element. */ - public $pager = array(); + public $pager = []; /** * @var array the configuration for the sorter widget. By default, [[LinkSorter]] will be * used to render the sorter. You can use a different widget class by configuring the "class" element. */ - public $sorter = array(); + public $sorter = []; /** * @var string the HTML content to be displayed as the summary of the list view. * If you do not want to show the summary, you may set it with an empty string. @@ -147,14 +147,14 @@ abstract class BaseListView extends Widget $summaryContent = '
    ' . Yii::t('yii', 'Total {count} {0, plural, =1{item} other{items}}.', $count) . '
    '; } } - return strtr($summaryContent, array( + return strtr($summaryContent, [ '{begin}' => $begin, '{end}' => $end, '{count}' => $count, '{totalCount}' => $totalCount, '{page}' => $page, '{pageCount}' => $pageCount, - )); + ]); } /** diff --git a/framework/yii/widgets/Breadcrumbs.php b/framework/yii/widgets/Breadcrumbs.php index f1427aa..2353845 100644 --- a/framework/yii/widgets/Breadcrumbs.php +++ b/framework/yii/widgets/Breadcrumbs.php @@ -23,12 +23,12 @@ use yii\helpers\Html; * * ~~~ * // $this is the view object currently being used - * echo Breadcrumbs::widget(array( - * 'links' => array( - * array('label' => 'Sample Post', 'url' => array('post/edit', 'id' => 1)), + * echo Breadcrumbs::widget([ + * 'links' => [ + * ['label' => 'Sample Post', 'url' => ['post/edit', 'id' => 1]], * 'Edit', - * ), - * )); + * ], + * ]); * ~~~ * * Because breadcrumbs usually appears in nearly every page of a website, you may consider placing it in a layout view. @@ -37,9 +37,9 @@ use yii\helpers\Html; * * ~~~ * // $this is the view object currently being used - * echo Breadcrumbs::widget(array( - * 'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : array(), - * )); + * echo Breadcrumbs::widget([ + * 'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [], + * ]); * ~~~ * * @author Qiang Xue @@ -54,7 +54,7 @@ class Breadcrumbs extends Widget /** * @var array the HTML attributes for the breadcrumb container tag. */ - public $options = array('class' => 'breadcrumb'); + public $options = ['class' => 'breadcrumb']; /** * @var boolean whether to HTML-encode the link labels. */ @@ -71,16 +71,16 @@ class Breadcrumbs extends Widget * with the following structure: * * ~~~ - * array( + * [ * 'label' => 'label of the link', // required * 'url' => 'url of the link', // optional, will be processed by Html::url() - * ) + * ] * ~~~ * - * If a link is active, you only need to specify its "label", and instead of writing `array('label' => $label)`, + * If a link is active, you only need to specify its "label", and instead of writing `['label' => $label]`, * you should simply use `$label`. */ - public $links = array(); + public $links = []; /** * @var string the template used to render each inactive item in the breadcrumbs. The token `{link}` * will be replaced with the actual HTML link for each inactive item. @@ -100,18 +100,18 @@ class Breadcrumbs extends Widget if (empty($this->links)) { return; } - $links = array(); + $links = []; if ($this->homeLink === null) { - $links[] = $this->renderItem(array( + $links[] = $this->renderItem([ 'label' => Yii::t('yii', 'Home'), 'url' => Yii::$app->homeUrl, - ), $this->itemTemplate); + ], $this->itemTemplate); } elseif ($this->homeLink !== false) { $links[] = $this->renderItem($this->homeLink, $this->itemTemplate); } foreach ($this->links as $link) { if (!is_array($link)) { - $link = array('label' => $link); + $link = ['label' => $link]; } $links[] = $this->renderItem($link, isset($link['url']) ? $this->itemTemplate : $this->activeItemTemplate); } @@ -133,9 +133,9 @@ class Breadcrumbs extends Widget throw new InvalidConfigException('The "label" element is required for each link.'); } if (isset($link['url'])) { - return strtr($template, array('{link}' => Html::a($label, $link['url']))); + return strtr($template, ['{link}' => Html::a($label, $link['url'])]); } else { - return strtr($template, array('{link}' => $label)); + return strtr($template, ['{link}' => $label]); } } } diff --git a/framework/yii/widgets/ContentDecorator.php b/framework/yii/widgets/ContentDecorator.php index f91117a..9224f35 100644 --- a/framework/yii/widgets/ContentDecorator.php +++ b/framework/yii/widgets/ContentDecorator.php @@ -24,7 +24,7 @@ class ContentDecorator extends Widget /** * @var array the parameters (name => value) to be extracted and made available in the decorative view. */ - public $params = array(); + public $params = []; /** * Starts recording a clip. diff --git a/framework/yii/widgets/DetailView.php b/framework/yii/widgets/DetailView.php index c3bf864..bd30078 100644 --- a/framework/yii/widgets/DetailView.php +++ b/framework/yii/widgets/DetailView.php @@ -30,17 +30,17 @@ use yii\helpers\Inflector; * A typical usage of DetailView is as follows: * * ~~~ - * echo DetailView::widget(array( + * echo DetailView::widget([ * 'model' => $model, - * 'attributes' => array( + * 'attributes' => [ * 'title', // title attribute (in plain text) * 'description:html', // description attribute in HTML - * array( // the owner name of the model + * [ // the owner name of the model * 'label' => 'Owner', * 'value' => $model->owner->name, - * ), - * ), - * )); + * ], + * ], + * ]); * ~~~ * * @author Qiang Xue @@ -90,7 +90,7 @@ class DetailView extends Widget * @var array the HTML attributes for the container tag of this widget. The "tag" option specifies * what container tag should be used. It defaults to "table" if not set. */ - public $options = array('class' => 'table table-striped table-bordered'); + public $options = ['class' => 'table table-striped table-bordered']; /** * @var array|Formatter the formatter used to format model attribute values into displayable texts. * This can be either an instance of [[Formatter]] or an configuration array for creating the [[Formatter]] @@ -124,7 +124,7 @@ class DetailView extends Widget */ public function run() { - $rows = array(); + $rows = []; $i = 0; foreach ($this->attributes as $attribute) { $rows[] = $this->renderAttribute($attribute, $i++); @@ -143,10 +143,10 @@ class DetailView extends Widget protected function renderAttribute($attribute, $index) { if (is_string($this->template)) { - return strtr($this->template, array( + return strtr($this->template, [ '{label}' => $attribute['label'], '{value}' => $this->formatter->format($attribute['value'], $attribute['type']), - )); + ]); } else { return call_user_func($this->template, $attribute, $index, $this); } @@ -176,10 +176,10 @@ class DetailView extends Widget if (!preg_match('/^(\w+)(\s*:\s*(\w+))?$/', $attribute, $matches)) { throw new InvalidConfigException('The attribute must be specified in the format of "Name" or "Name:Type"'); } - $attribute = array( + $attribute = [ 'name' => $matches[1], 'type' => isset($matches[3]) ? $matches[3] : 'text', - ); + ]; } if (!is_array($attribute)) { diff --git a/framework/yii/widgets/FragmentCache.php b/framework/yii/widgets/FragmentCache.php index 3f4027b..3005df5 100644 --- a/framework/yii/widgets/FragmentCache.php +++ b/framework/yii/widgets/FragmentCache.php @@ -39,10 +39,10 @@ class FragmentCache extends Widget * For example, * * ~~~ - * array( + * [ * 'class' => 'yii\caching\DbDependency', * 'sql' => 'SELECT MAX(lastModified) FROM Post', - * ) + * ] * ~~~ * * would make the output cache depends on the last modified time of all posts. @@ -56,9 +56,9 @@ class FragmentCache extends Widget * according to the current application language: * * ~~~ - * array( + * [ * Yii::$app->language, - * ) + * ] */ public $variations; /** @@ -108,7 +108,7 @@ class FragmentCache extends Widget if (is_array($this->dependency)) { $this->dependency = Yii::createObject($this->dependency); } - $data = array($content, $this->dynamicPlaceholders); + $data = [$content, $this->dynamicPlaceholders]; $this->cache->set($this->calculateKey(), $data, $this->duration, $this->dependency); if (empty($this->getView()->cacheStack) && !empty($this->dynamicPlaceholders)) { @@ -167,7 +167,7 @@ class FragmentCache extends Widget */ protected function calculateKey() { - $factors = array(__CLASS__, $this->getId()); + $factors = [__CLASS__, $this->getId()]; if (is_array($this->variations)) { foreach ($this->variations as $factor) { $factors[] = $factor; diff --git a/framework/yii/widgets/LinkPager.php b/framework/yii/widgets/LinkPager.php index d375f46..952948f 100644 --- a/framework/yii/widgets/LinkPager.php +++ b/framework/yii/widgets/LinkPager.php @@ -36,7 +36,7 @@ class LinkPager extends Widget /** * @var array HTML attributes for the pager container tag. */ - public $options = array('class' => 'pagination'); + public $options = ['class' => 'pagination']; /** * @var string the CSS class for the "first" page button. */ @@ -112,7 +112,7 @@ class LinkPager extends Widget */ protected function renderPageButtons() { - $buttons = array(); + $buttons = []; $pageCount = $this->pagination->getPageCount(); $currentPage = $this->pagination->getPage(); @@ -171,8 +171,8 @@ class LinkPager extends Widget $class .= ' ' . $this->disabledPageCssClass; } $class = trim($class); - $options = array('class' => $class === '' ? null : $class); - return Html::tag('li', Html::a($label, $this->pagination->createUrl($page), array('data-page' => $page)), $options); + $options = ['class' => $class === '' ? null : $class]; + return Html::tag('li', Html::a($label, $this->pagination->createUrl($page), ['data-page' => $page]), $options); } /** @@ -188,6 +188,6 @@ class LinkPager extends Widget $endPage = $pageCount - 1; $beginPage = max(0, $endPage - $this->maxButtonCount + 1); } - return array($beginPage, $endPage); + return [$beginPage, $endPage]; } } diff --git a/framework/yii/widgets/LinkSorter.php b/framework/yii/widgets/LinkSorter.php index c8b30e5..4ed8cc0 100644 --- a/framework/yii/widgets/LinkSorter.php +++ b/framework/yii/widgets/LinkSorter.php @@ -35,7 +35,7 @@ class LinkSorter extends Widget /** * @var array HTML attributes for the sorter container tag. */ - public $options = array('class' => 'sorter'); + public $options = ['class' => 'sorter']; /** @@ -64,10 +64,10 @@ class LinkSorter extends Widget protected function renderSortLinks() { $attributes = empty($this->atttributes) ? array_keys($this->sort->attributes) : $this->attributes; - $links = array(); + $links = []; foreach ($attributes as $name) { $links[] = $this->sort->link($name); } - return Html::ul($links, array('encode' => false)); + return Html::ul($links, ['encode' => false]); } } diff --git a/framework/yii/widgets/ListView.php b/framework/yii/widgets/ListView.php index 1d8745d..ad13420 100644 --- a/framework/yii/widgets/ListView.php +++ b/framework/yii/widgets/ListView.php @@ -23,7 +23,7 @@ class ListView extends BaseListView * The "tag" element specifies the tag name of the container element and defaults to "div". * If "tag" is false, it means no container element will be rendered. */ - public $itemOptions = array(); + public $itemOptions = []; /** * @var string|callback the name of the view for rendering each data item, or a callback (e.g. an anonymous function) * for rendering each data item. If it specifies a view name, the following variables will @@ -57,7 +57,7 @@ class ListView extends BaseListView { $models = $this->dataProvider->getModels(); $keys = $this->dataProvider->getKeys(); - $rows = array(); + $rows = []; foreach (array_values($models) as $index => $model) { $rows[] = $this->renderItem($model, $keys[$index], $index); } @@ -76,12 +76,12 @@ class ListView extends BaseListView if ($this->itemView === null) { $content = $key; } elseif (is_string($this->itemView)) { - $content = $this->getView()->render($this->itemView, array( + $content = $this->getView()->render($this->itemView, [ 'model' => $model, 'key' => $key, 'index' => $index, 'widget' => $this, - )); + ]); } else { $content = call_user_func($this->itemView, $model, $key, $index, $this); } diff --git a/framework/yii/widgets/MaskedInput.php b/framework/yii/widgets/MaskedInput.php index 8b8cbc6..fc21cef 100644 --- a/framework/yii/widgets/MaskedInput.php +++ b/framework/yii/widgets/MaskedInput.php @@ -23,10 +23,10 @@ use yii\web\JsExpression; * shows how to use MaskedInput to collect phone numbers: * * ~~~ - * echo MaskedInput::widget(array( + * echo MaskedInput::widget([ * 'name' => 'phone', * 'mask' => '999-999-9999', - * )); + * ]); * ~~~ * * The masked text field is implemented based on the [jQuery masked input plugin](http://digitalbush.com/projects/masked-input-plugin). @@ -49,7 +49,7 @@ class MaskedInput extends InputWidget public $mask; /** * @var array the mapping between mask characters and the corresponding patterns. - * For example, `array('~' => '[+-]')` specifies that the '~' character expects '+' or '-' input. + * For example, `['~' => '[+-]']` specifies that the '~' character expects '+' or '-' input. * Defaults to null, meaning using the map as described in [[mask]]. */ public $charMap; @@ -64,7 +64,7 @@ class MaskedInput extends InputWidget /** * @var array the HTML attributes for the input tag. */ - public $options = array(); + public $options = []; /** @@ -119,7 +119,7 @@ class MaskedInput extends InputWidget */ protected function getClientOptions() { - $options = array(); + $options = []; if ($this->placeholder !== null) { $options['placeholder'] = $this->placeholder; } diff --git a/framework/yii/widgets/MaskedInputAsset.php b/framework/yii/widgets/MaskedInputAsset.php index d091505..52fa2da 100644 --- a/framework/yii/widgets/MaskedInputAsset.php +++ b/framework/yii/widgets/MaskedInputAsset.php @@ -15,10 +15,10 @@ use yii\web\AssetBundle; class MaskedInputAsset extends AssetBundle { public $sourcePath = '@yii/assets'; - public $js = array( + public $js = [ 'jquery.maskedinput.js', - ); - public $depends = array( + ]; + public $depends = [ 'yii\web\YiiAsset', - ); + ]; } diff --git a/framework/yii/widgets/Menu.php b/framework/yii/widgets/Menu.php index 8bf845e..db4a5d4 100644 --- a/framework/yii/widgets/Menu.php +++ b/framework/yii/widgets/Menu.php @@ -27,17 +27,17 @@ use yii\helpers\Html; * The following example shows how to use Menu: * * ~~~ - * echo Menu::widget(array( - * 'items' => array( + * echo Menu::widget([ + * 'items' => [ * // Important: you need to specify url as 'controller/action', * // not just as 'controller' even if default action is used. - * array('label' => 'Home', 'url' => array('site/index')), + * ['label' => 'Home', 'url' => ['site/index']], * // 'Products' menu item will be selected as long as the route is 'product/index' - * array('label' => 'Products', 'url' => array('product/index'), 'items' => array( - * array('label' => 'New Arrivals', 'url' => array('product/index', 'tag' => 'new')), - * array('label' => 'Most Popular', 'url' => array('product/index', 'tag' => 'popular')), - * )), - * array('label' => 'Login', 'url' => array('site/login'), 'visible' => Yii::$app->user->isGuest), + * ['label' => 'Products', 'url' => ['product/index'), 'items' => [ + * ['label' => 'New Arrivals', 'url' => ['product/index', 'tag' => 'new']], + * ['label' => 'Most Popular', 'url' => ['product/index', 'tag' => 'popular']], + * ]], + * ['label' => 'Login', 'url' => ['site/login'], 'visible' => Yii::$app->user->isGuest], * ), * )); * ~~~ @@ -67,14 +67,14 @@ class Menu extends Widget * If this option is not set, [[linkTemplate]] or [[labelTemplate]] will be used instead. * - options: array, optional, the HTML attributes for the menu container tag. */ - public $items = array(); + public $items = []; /** * @var array list of HTML attributes for the menu container tag. This will be overwritten * by the "options" set in individual [[items]]. The following special options are recognized: * * - tag: string, defaults to "li", the tag name of the item container tags. */ - public $itemOptions = array(); + public $itemOptions = []; /** * @var string the template used to render the body of a menu which is a link. * In this template, the token `{url}` will be replaced with the corresponding link URL; @@ -122,7 +122,7 @@ class Menu extends Widget * * - tag: string, defaults to "ul", the tag name of the item container tags. */ - public $options = array(); + public $options = []; /** * @var string the CSS class that will be assigned to the first item in the main menu or each submenu. * Defaults to null, meaning no such CSS class will be assigned. @@ -174,11 +174,11 @@ class Menu extends Widget protected function renderItems($items) { $n = count($items); - $lines = array(); + $lines = []; foreach ($items as $i => $item) { - $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', array())); + $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', [])); $tag = ArrayHelper::remove($options, 'tag', 'li'); - $class = array(); + $class = []; if ($item['active']) { $class[] = $this->activeCssClass; } @@ -198,9 +198,9 @@ class Menu extends Widget $menu = $this->renderItem($item); if (!empty($item['items'])) { - $menu .= strtr($this->submenuTemplate, array( + $menu .= strtr($this->submenuTemplate, [ '{items}' => $this->renderItems($item['items']), - )); + ]); } $lines[] = Html::tag($tag, $menu, $options); } @@ -217,15 +217,15 @@ class Menu extends Widget { if (isset($item['url'])) { $template = ArrayHelper::getValue($item, 'template', $this->linkTemplate); - return strtr($template, array( + return strtr($template, [ '{url}' => Html::url($item['url']), '{label}' => $item['label'], - )); + ]); } else { $template = ArrayHelper::getValue($item, 'template', $this->labelTemplate); - return strtr($template, array( + return strtr($template, [ '{label}' => $item['label'], - )); + ]); } } diff --git a/framework/yii/yii b/framework/yii/yii index ebba1a6..b34cfc8 100755 --- a/framework/yii/yii +++ b/framework/yii/yii @@ -15,10 +15,10 @@ defined('STDIN') or define('STDIN', fopen('php://stdin', 'r')); require(__DIR__ . '/Yii.php'); -$application = new yii\console\Application(array( +$application = new yii\console\Application([ 'id' => 'yii-console', 'basePath' => __DIR__ . '/console', 'controllerPath' => '@yii/console/controllers', -)); +]); $exitCode = $application->run(); exit($exitCode); diff --git a/tests/unit/TestCase.php b/tests/unit/TestCase.php index bd95465..d3ac557 100644 --- a/tests/unit/TestCase.php +++ b/tests/unit/TestCase.php @@ -39,12 +39,12 @@ abstract class TestCase extends \yii\test\TestCase * @param array $config The application configuration, if needed * @param string $appClass name of the application class to create */ - protected function mockApplication($config = array(), $appClass = '\yii\console\Application') + protected function mockApplication($config = [], $appClass = '\yii\console\Application') { - static $defaultConfig = array( + static $defaultConfig = [ 'id' => 'testapp', 'basePath' => __DIR__, - ); + ]; new $appClass(array_merge($defaultConfig, $config)); } diff --git a/tests/unit/data/ar/Customer.php b/tests/unit/data/ar/Customer.php index d4702b1..441b37c 100644 --- a/tests/unit/data/ar/Customer.php +++ b/tests/unit/data/ar/Customer.php @@ -24,7 +24,7 @@ class Customer extends ActiveRecord public function getOrders() { - return $this->hasMany('Order', array('customer_id' => 'id'))->orderBy('id'); + return $this->hasMany('Order', ['customer_id' => 'id'])->orderBy('id'); } public static function active($query) diff --git a/tests/unit/data/ar/Order.php b/tests/unit/data/ar/Order.php index 063bb67..b6392ed 100644 --- a/tests/unit/data/ar/Order.php +++ b/tests/unit/data/ar/Order.php @@ -19,17 +19,17 @@ class Order extends ActiveRecord public function getCustomer() { - return $this->hasOne('Customer', array('id' => 'customer_id')); + return $this->hasOne('Customer', ['id' => 'customer_id']); } public function getOrderItems() { - return $this->hasMany('OrderItem', array('order_id' => 'id')); + return $this->hasMany('OrderItem', ['order_id' => 'id']); } public function getItems() { - return $this->hasMany('Item', array('id' => 'item_id')) + return $this->hasMany('Item', ['id' => 'item_id']) ->via('orderItems', function ($q) { // additional query configuration })->orderBy('id'); @@ -37,9 +37,9 @@ class Order extends ActiveRecord public function getBooks() { - return $this->hasMany('Item', array('id' => 'item_id')) - ->viaTable('tbl_order_item', array('order_id' => 'id')) - ->where(array('category_id' => 1)); + return $this->hasMany('Item', ['id' => 'item_id']) + ->viaTable('tbl_order_item', ['order_id' => 'id']) + ->where(['category_id' => 1]); } public function beforeSave($insert) diff --git a/tests/unit/data/ar/OrderItem.php b/tests/unit/data/ar/OrderItem.php index 297432b..ad931a8 100644 --- a/tests/unit/data/ar/OrderItem.php +++ b/tests/unit/data/ar/OrderItem.php @@ -19,11 +19,11 @@ class OrderItem extends ActiveRecord public function getOrder() { - return $this->hasOne('Order', array('id' => 'order_id')); + return $this->hasOne('Order', ['id' => 'order_id']); } public function getItem() { - return $this->hasOne('Item', array('id' => 'item_id')); + return $this->hasOne('Item', ['id' => 'item_id']); } } diff --git a/tests/unit/data/base/InvalidRulesModel.php b/tests/unit/data/base/InvalidRulesModel.php index 13f428d..3c865e5 100644 --- a/tests/unit/data/base/InvalidRulesModel.php +++ b/tests/unit/data/base/InvalidRulesModel.php @@ -10,8 +10,8 @@ class InvalidRulesModel extends Model { public function rules() { - return array( - array('test'), - ); + return [ + ['test'], + ]; } } diff --git a/tests/unit/data/base/Singer.php b/tests/unit/data/base/Singer.php index 96c4850..5c0f0fe 100644 --- a/tests/unit/data/base/Singer.php +++ b/tests/unit/data/base/Singer.php @@ -13,10 +13,10 @@ class Singer extends Model public function rules() { - return array( - array('lastName', 'default', 'value' => 'Lennon'), - array('lastName', 'required'), - array('underscore_style', 'yii\captcha\CaptchaValidator'), - ); + return [ + ['lastName', 'default', 'value' => 'Lennon'], + ['lastName', 'required'], + ['underscore_style', 'yii\captcha\CaptchaValidator'], + ]; } } diff --git a/tests/unit/data/base/Speaker.php b/tests/unit/data/base/Speaker.php index b0acc6b..7585df3 100644 --- a/tests/unit/data/base/Speaker.php +++ b/tests/unit/data/base/Speaker.php @@ -26,22 +26,20 @@ class Speaker extends Model public function attributeLabels() { - return array( + return [ 'customLabel' => 'This is the custom label', - ); + ]; } public function rules() { - return array( - - ); + return []; } public function scenarios() { - return array( - 'test' => array('firstName', 'lastName', '!underscore_style'), - ); + return [ + 'test' => ['firstName', 'lastName', '!underscore_style'], + ]; } } diff --git a/tests/unit/data/config.php b/tests/unit/data/config.php index fda2be1..304c3fc 100644 --- a/tests/unit/data/config.php +++ b/tests/unit/data/config.php @@ -1,33 +1,33 @@ array( - 'cubrid' => array( +return [ + 'databases' => [ + 'cubrid' => [ 'dsn' => 'cubrid:dbname=demodb;host=localhost;port=33000', 'username' => 'dba', 'password' => '', 'fixture' => __DIR__ . '/cubrid.sql', - ), - 'mysql' => array( + ], + 'mysql' => [ 'dsn' => 'mysql:host=127.0.0.1;dbname=yiitest', 'username' => 'travis', 'password' => '', 'fixture' => __DIR__ . '/mysql.sql', - ), - 'sqlite' => array( + ], + 'sqlite' => [ 'dsn' => 'sqlite::memory:', 'fixture' => __DIR__ . '/sqlite.sql', - ), - 'sqlsrv' => array( + ], + 'sqlsrv' => [ 'dsn' => 'sqlsrv:Server=localhost;Database=test', 'username' => '', 'password' => '', 'fixture' => __DIR__ . '/mssql.sql', - ), - 'pgsql' => array( + ], + 'pgsql' => [ 'dsn' => 'pgsql:host=localhost;dbname=yiitest;port=5432;', 'username' => 'postgres', 'password' => 'postgres', 'fixture' => __DIR__ . '/postgres.sql', - ), - ), -); + ], + ], +]; diff --git a/tests/unit/data/i18n/messages/de_DE/test.php b/tests/unit/data/i18n/messages/de_DE/test.php index 9cb1369..d8c5290 100644 --- a/tests/unit/data/i18n/messages/de_DE/test.php +++ b/tests/unit/data/i18n/messages/de_DE/test.php @@ -2,8 +2,8 @@ /** * */ -return array( +return [ 'The dog runs fast.' => 'Der Hund rennt schnell.', 'His speed is about {n} km/h.' => 'Seine Geschwindigkeit beträgt {n} km/h.', 'His name is {name} and his speed is about {n, number} km/h.' => 'Er heißt {name} und ist {n, number} km/h schnell.', -); \ No newline at end of file +]; \ No newline at end of file diff --git a/tests/unit/data/i18n/messages/en_US/test.php b/tests/unit/data/i18n/messages/en_US/test.php index dcd3bc9..83342b0 100644 --- a/tests/unit/data/i18n/messages/en_US/test.php +++ b/tests/unit/data/i18n/messages/en_US/test.php @@ -2,6 +2,6 @@ /** * */ -return array( +return [ 'The dog runs fast.' => 'Der Hund rennt schell.', -); \ No newline at end of file +]; \ No newline at end of file diff --git a/tests/unit/data/validators/TestValidator.php b/tests/unit/data/validators/TestValidator.php index 13f12dc..de6fb07 100644 --- a/tests/unit/data/validators/TestValidator.php +++ b/tests/unit/data/validators/TestValidator.php @@ -7,7 +7,7 @@ use yii\validators\Validator; class TestValidator extends Validator { - private $_validatedAttributes = array(); + private $_validatedAttributes = []; private $_setErrorOnValidateAttribute = false; public function validateAttribute($object, $attribute) diff --git a/tests/unit/data/validators/models/FakedValidationModel.php b/tests/unit/data/validators/models/FakedValidationModel.php index 2951ca8..6e9c8b1 100644 --- a/tests/unit/data/validators/models/FakedValidationModel.php +++ b/tests/unit/data/validators/models/FakedValidationModel.php @@ -10,13 +10,13 @@ class FakedValidationModel extends Model public $val_attr_b; public $val_attr_c; public $val_attr_d; - private $attr = array(); + private $attr = []; /** * @param array $attributes * @return self */ - public static function createWithAttributes($attributes = array()) + public static function createWithAttributes($attributes = []) { $m = new static(); foreach ($attributes as $attribute => $value) { @@ -27,13 +27,13 @@ class FakedValidationModel extends Model public function rules() { - return array( - array('val_attr_a, val_attr_b', 'required', 'on' => 'reqTest'), - array('val_attr_c', 'integer'), - ); + return [ + ['val_attr_a, val_attr_b', 'required', 'on' => 'reqTest'], + ['val_attr_c', 'integer'], + ]; } - public function inlineVal($attribute, $params = array()) + public function inlineVal($attribute, $params = []) { return true; } diff --git a/tests/unit/data/validators/models/ValidatorTestMainModel.php b/tests/unit/data/validators/models/ValidatorTestMainModel.php index 00f977b..dd6696d 100644 --- a/tests/unit/data/validators/models/ValidatorTestMainModel.php +++ b/tests/unit/data/validators/models/ValidatorTestMainModel.php @@ -16,6 +16,6 @@ class ValidatorTestMainModel extends ActiveRecord public function getReferences() { - return $this->hasMany(ValidatorTestRefModel::className(), array('ref' => 'id')); + return $this->hasMany(ValidatorTestRefModel::className(), ['ref' => 'id']); } } \ No newline at end of file diff --git a/tests/unit/data/validators/models/ValidatorTestRefModel.php b/tests/unit/data/validators/models/ValidatorTestRefModel.php index fc4019d..ea86fc7 100644 --- a/tests/unit/data/validators/models/ValidatorTestRefModel.php +++ b/tests/unit/data/validators/models/ValidatorTestRefModel.php @@ -18,6 +18,6 @@ class ValidatorTestRefModel extends ActiveRecord public function getMain() { - return $this->hasOne(ValidatorTestMainModel::className(), array('id' => 'ref')); + return $this->hasOne(ValidatorTestMainModel::className(), ['id' => 'ref']); } } \ No newline at end of file diff --git a/tests/unit/framework/BaseYiiTest.php b/tests/unit/framework/BaseYiiTest.php index a04de99..6011f6b 100644 --- a/tests/unit/framework/BaseYiiTest.php +++ b/tests/unit/framework/BaseYiiTest.php @@ -28,7 +28,7 @@ class BaseYiiTest extends TestCase { $this->assertEquals(YII_PATH, Yii::getAlias('@yii')); - Yii::$aliases = array(); + Yii::$aliases = []; $this->assertFalse(Yii::getAlias('@yii', false)); Yii::setAlias('@yii', '/yii/framework'); diff --git a/tests/unit/framework/base/BehaviorTest.php b/tests/unit/framework/base/BehaviorTest.php index b6eda09..9e1d0a5 100644 --- a/tests/unit/framework/base/BehaviorTest.php +++ b/tests/unit/framework/base/BehaviorTest.php @@ -14,9 +14,9 @@ class FooClass extends Component { public function behaviors() { - return array( + return [ 'foo' => __NAMESPACE__ . '\BarBehavior', - ); + ]; } } @@ -67,7 +67,7 @@ class BehaviorTest extends TestCase $this->assertEquals('behavior property', $bar->getBehavior('bar')->behaviorProperty); $this->assertEquals('behavior method', $bar->getBehavior('bar')->behaviorMethod()); - $behavior = new BarBehavior(array('behaviorProperty' => 'reattached')); + $behavior = new BarBehavior(['behaviorProperty' => 'reattached']); $bar->attachBehavior('bar', $behavior); $this->assertEquals('reattached', $bar->behaviorProperty); } diff --git a/tests/unit/framework/base/ComponentTest.php b/tests/unit/framework/base/ComponentTest.php index 98786e2..d1698eb 100644 --- a/tests/unit/framework/base/ComponentTest.php +++ b/tests/unit/framework/base/ComponentTest.php @@ -187,7 +187,7 @@ class ComponentTest extends TestCase public function testTrigger() { - $this->component->on('click', array($this->component, 'myEventHandler')); + $this->component->on('click', [$this->component, 'myEventHandler']); $this->assertFalse($this->component->eventHandled); $this->assertNull($this->component->event); $this->component->raiseEvent(); @@ -223,7 +223,7 @@ class ComponentTest extends TestCase { $component = new NewComponent; $component->on('click', 'yiiunit\framework\base\globalEventHandler2'); - $component->on('click', array($this->component, 'myEventHandler')); + $component->on('click', [$this->component, 'myEventHandler']); $component->raiseEvent(); $this->assertTrue($component->eventHandled); $this->assertFalse($this->component->eventHandled); @@ -250,7 +250,7 @@ class ComponentTest extends TestCase $p = 'as b'; $component = new NewComponent; - $component->$p = array('class' => 'NewBehavior'); + $component->$p = ['class' => 'NewBehavior']; $this->assertSame($behavior, $component->getBehavior('a')); $this->assertTrue($component->hasProperty('p')); $component->test(); @@ -265,12 +265,12 @@ class ComponentTest extends TestCase $behavior = new NewBehavior; - $component->attachBehaviors(array( + $component->attachBehaviors([ 'a' => $behavior, 'b' => $behavior, - )); + ]); - $this->assertSame(array('a' => $behavior, 'b' => $behavior), $component->getBehaviors()); + $this->assertSame(['a' => $behavior, 'b' => $behavior], $component->getBehaviors()); } public function testDetachBehavior() @@ -310,7 +310,7 @@ class NewComponent extends Component { private $_object = null; private $_text = 'default'; - private $_items = array(); + private $_items = []; public $content; public function getText() diff --git a/tests/unit/framework/base/FormatterTest.php b/tests/unit/framework/base/FormatterTest.php index ae71a5c..322b751 100644 --- a/tests/unit/framework/base/FormatterTest.php +++ b/tests/unit/framework/base/FormatterTest.php @@ -193,7 +193,7 @@ class FormatterTest extends TestCase $value = time(); $this->assertSame(date('Y/m/d', $value), $this->formatter->format($value, 'date')); $this->assertSame(date('Y/m/d', $value), $this->formatter->format($value, 'DATE')); - $this->assertSame(date('Y-m-d', $value), $this->formatter->format($value, array('date', 'Y-m-d'))); + $this->assertSame(date('Y-m-d', $value), $this->formatter->format($value, ['date', 'Y-m-d'])); $this->setExpectedException('\yii\base\InvalidParamException'); $this->assertSame(date('Y-m-d', $value), $this->formatter->format($value, 'data')); } diff --git a/tests/unit/framework/base/ModelTest.php b/tests/unit/framework/base/ModelTest.php index d500933..da8495b 100644 --- a/tests/unit/framework/base/ModelTest.php +++ b/tests/unit/framework/base/ModelTest.php @@ -33,44 +33,44 @@ class ModelTest extends TestCase $speaker->firstName = 'Qiang'; $speaker->lastName = 'Xue'; - $this->assertEquals(array( + $this->assertEquals([ 'firstName' => 'Qiang', 'lastName' => 'Xue', 'customLabel' => null, 'underscore_style' => null, - ), $speaker->getAttributes()); + ], $speaker->getAttributes()); - $this->assertEquals(array( + $this->assertEquals([ 'firstName' => 'Qiang', 'lastName' => 'Xue', - ), $speaker->getAttributes(array('firstName', 'lastName'))); + ], $speaker->getAttributes(['firstName', 'lastName'])); - $this->assertEquals(array( + $this->assertEquals([ 'firstName' => 'Qiang', 'lastName' => 'Xue', - ), $speaker->getAttributes(null, array('customLabel', 'underscore_style'))); + ], $speaker->getAttributes(null, ['customLabel', 'underscore_style'])); - $this->assertEquals(array( + $this->assertEquals([ 'firstName' => 'Qiang', - ), $speaker->getAttributes(array('firstName', 'lastName'), array('lastName', 'customLabel', 'underscore_style'))); + ], $speaker->getAttributes(['firstName', 'lastName'], ['lastName', 'customLabel', 'underscore_style'])); } public function testSetAttributes() { // by default mass assignment doesn't work at all $speaker = new Speaker(); - $speaker->setAttributes(array('firstName' => 'Qiang', 'underscore_style' => 'test')); + $speaker->setAttributes(['firstName' => 'Qiang', 'underscore_style' => 'test']); $this->assertNull($speaker->firstName); $this->assertNull($speaker->underscore_style); // in the test scenario $speaker = new Speaker(); $speaker->setScenario('test'); - $speaker->setAttributes(array('firstName' => 'Qiang', 'underscore_style' => 'test')); + $speaker->setAttributes(['firstName' => 'Qiang', 'underscore_style' => 'test']); $this->assertNull($speaker->underscore_style); $this->assertEquals('Qiang', $speaker->firstName); - $speaker->setAttributes(array('firstName' => 'Qiang', 'underscore_style' => 'test'), false); + $speaker->setAttributes(['firstName' => 'Qiang', 'underscore_style' => 'test'], false); $this->assertEquals('test', $speaker->underscore_style); $this->assertEquals('Qiang', $speaker->firstName); } @@ -80,7 +80,7 @@ class ModelTest extends TestCase $singer = new Singer(); $this->assertEquals('Singer', $singer->formName()); - $post = array('firstName' => 'Qiang'); + $post = ['firstName' => 'Qiang']; Speaker::$formName = ''; $model = new Speaker(); @@ -91,13 +91,13 @@ class ModelTest extends TestCase Speaker::$formName = 'Speaker'; $model = new Speaker(); $model->setScenario('test'); - $this->assertTrue($model->load(array('Speaker' => $post))); + $this->assertTrue($model->load(['Speaker' => $post])); $this->assertEquals('Qiang', $model->firstName); Speaker::$formName = 'Speaker'; $model = new Speaker(); $model->setScenario('test'); - $this->assertFalse($model->load(array('Example' => array()))); + $this->assertFalse($model->load(['Example' => []])); $this->assertEquals('', $model->firstName); } @@ -109,7 +109,7 @@ class ModelTest extends TestCase $speaker = new Speaker(); $speaker->setScenario('test'); - $this->assertEquals(array('firstName', 'lastName', 'underscore_style'), $speaker->activeAttributes()); + $this->assertEquals(['firstName', 'lastName', 'underscore_style'], $speaker->activeAttributes()); } public function testIsAttributeSafe() @@ -136,34 +136,34 @@ class ModelTest extends TestCase $this->assertFalse($speaker->hasErrors('firstName')); $speaker->addError('firstName', 'Something is wrong!'); - $this->assertEquals(array('firstName' => array('Something is wrong!')), $speaker->getErrors()); - $this->assertEquals(array('Something is wrong!'), $speaker->getErrors('firstName')); + $this->assertEquals(['firstName' => ['Something is wrong!']], $speaker->getErrors()); + $this->assertEquals(['Something is wrong!'], $speaker->getErrors('firstName')); $speaker->addError('firstName', 'Totally wrong!'); - $this->assertEquals(array('firstName' => array('Something is wrong!', 'Totally wrong!')), $speaker->getErrors()); - $this->assertEquals(array('Something is wrong!', 'Totally wrong!'), $speaker->getErrors('firstName')); + $this->assertEquals(['firstName' => ['Something is wrong!', 'Totally wrong!']], $speaker->getErrors()); + $this->assertEquals(['Something is wrong!', 'Totally wrong!'], $speaker->getErrors('firstName')); $this->assertTrue($speaker->hasErrors()); $this->assertTrue($speaker->hasErrors('firstName')); $this->assertFalse($speaker->hasErrors('lastName')); - $this->assertEquals(array('Something is wrong!'), $speaker->getFirstErrors()); + $this->assertEquals(['Something is wrong!'], $speaker->getFirstErrors()); $this->assertEquals('Something is wrong!', $speaker->getFirstError('firstName')); $this->assertNull($speaker->getFirstError('lastName')); $speaker->addError('lastName', 'Another one!'); - $this->assertEquals(array( - 'firstName' => array( + $this->assertEquals([ + 'firstName' => [ 'Something is wrong!', 'Totally wrong!', - ), - 'lastName' => array('Another one!'), - ), $speaker->getErrors()); + ], + 'lastName' => ['Another one!'], + ], $speaker->getErrors()); $speaker->clearErrors('firstName'); - $this->assertEquals(array( - 'lastName' => array('Another one!'), - ), $speaker->getErrors()); + $this->assertEquals([ + 'lastName' => ['Another one!'], + ], $speaker->getErrors()); $speaker->clearErrors(); $this->assertEmpty($speaker->getErrors()); @@ -187,16 +187,16 @@ class ModelTest extends TestCase $this->assertTrue(isset($speaker['firstName'])); // iteration - $attributes = array(); + $attributes = []; foreach ($speaker as $key => $attribute) { $attributes[$key] = $attribute; } - $this->assertEquals(array( + $this->assertEquals([ 'firstName' => 'Qiang', 'lastName' => null, 'customLabel' => null, 'underscore_style' => null, - ), $attributes); + ], $attributes); // unset unset($speaker['firstName']); @@ -209,14 +209,14 @@ class ModelTest extends TestCase public function testDefaults() { $singer = new Model(); - $this->assertEquals(array(), $singer->rules()); - $this->assertEquals(array(), $singer->attributeLabels()); + $this->assertEquals([], $singer->rules()); + $this->assertEquals([], $singer->attributeLabels()); } public function testDefaultScenarios() { $singer = new Singer(); - $this->assertEquals(array('default' => array('lastName', 'underscore_style')), $singer->scenarios()); + $this->assertEquals(['default' => ['lastName', 'underscore_style']], $singer->scenarios()); } public function testIsAttributeRequired() diff --git a/tests/unit/framework/base/ObjectTest.php b/tests/unit/framework/base/ObjectTest.php index 0bd9b1d..a889f42 100644 --- a/tests/unit/framework/base/ObjectTest.php +++ b/tests/unit/framework/base/ObjectTest.php @@ -118,11 +118,11 @@ class ObjectTest extends TestCase public function testArrayProperty() { - $this->assertEquals(array(), $this->object->items); + $this->assertEquals([], $this->object->items); // the following won't work /* $this->object->items[] = 1; - $this->assertEquals(array(1), $this->object->items); + $this->assertEquals([1], $this->object->items); */ } @@ -136,7 +136,7 @@ class ObjectTest extends TestCase public function testConstruct() { - $object = new NewObject(array('text' => 'test text')); + $object = new NewObject(['text' => 'test text']); $this->assertEquals('test text', $object->getText()); } } @@ -146,7 +146,7 @@ class NewObject extends Object { private $_object = null; private $_text = 'default'; - private $_items = array(); + private $_items = []; public $content; public function getText() diff --git a/tests/unit/framework/behaviors/AutoTimestampTest.php b/tests/unit/framework/behaviors/AutoTimestampTest.php index c26d912..ca1217b 100644 --- a/tests/unit/framework/behaviors/AutoTimestampTest.php +++ b/tests/unit/framework/behaviors/AutoTimestampTest.php @@ -30,22 +30,20 @@ class AutoTimestampTest extends TestCase public function setUp() { - $this->mockApplication( - array( - 'components' => array( - 'db' => array( - 'class' => '\yii\db\Connection', - 'dsn' => 'sqlite::memory:', - ) - ) - ) - ); - - $columns = array( + $this->mockApplication([ + 'components' => [ + 'db' => [ + 'class' => '\yii\db\Connection', + 'dsn' => 'sqlite::memory:', + ] + ] + ]); + + $columns = [ 'id' => 'pk', 'create_time' => 'integer', 'update_time' => 'integer', - ); + ]; Yii::$app->getDb()->createCommand()->createTable('test_auto_timestamp', $columns)->execute(); } @@ -100,15 +98,15 @@ class ActiveRecordAutoTimestamp extends ActiveRecord { public function behaviors() { - return array( - 'timestamp' => array( + return [ + 'timestamp' => [ 'class' => AutoTimestamp::className(), - 'attributes' => array( - static::EVENT_BEFORE_INSERT => array('create_time', 'update_time'), + 'attributes' => [ + static::EVENT_BEFORE_INSERT => ['create_time', 'update_time'], static::EVENT_BEFORE_UPDATE => 'update_time', - ), - ), - ); + ], + ], + ]; } public static function tableName() diff --git a/tests/unit/framework/caching/CacheTestCase.php b/tests/unit/framework/caching/CacheTestCase.php index 542999a..9ff6409 100644 --- a/tests/unit/framework/caching/CacheTestCase.php +++ b/tests/unit/framework/caching/CacheTestCase.php @@ -54,7 +54,7 @@ abstract class CacheTestCase extends TestCase $cache->flush(); $cache->set('string_test', 'string_test'); $cache->set('number_test', 42); - $cache->set('array_test', array('array_test' => 'array_test')); + $cache->set('array_test', ['array_test' => 'array_test']); $cache['arrayaccess_test'] = new \stdClass(); return $cache; @@ -76,7 +76,7 @@ abstract class CacheTestCase extends TestCase $this->assertTrue($cache->set('string_test', 'string_test')); $this->assertTrue($cache->set('number_test', 42)); - $this->assertTrue($cache->set('array_test', array('array_test' => 'array_test'))); + $this->assertTrue($cache->set('array_test', ['array_test' => 'array_test'])); } public function testGet() @@ -134,10 +134,10 @@ abstract class CacheTestCase extends TestCase { $cache = $this->prepare(); - $this->assertEquals(array('string_test' => 'string_test', 'number_test' => 42), $cache->mget(array('string_test', 'number_test'))); + $this->assertEquals(['string_test' => 'string_test', 'number_test' => 42], $cache->mget(['string_test', 'number_test'])); // ensure that order does not matter - $this->assertEquals(array('number_test' => 42, 'string_test' => 'string_test'), $cache->mget(array('number_test', 'string_test'))); - $this->assertEquals(array('number_test' => 42, 'non_existent_key' => null), $cache->mget(array('number_test', 'non_existent_key'))); + $this->assertEquals(['number_test' => 42, 'string_test' => 'string_test'], $cache->mget(['number_test', 'string_test'])); + $this->assertEquals(['number_test' => 42, 'non_existent_key' => null], $cache->mget(['number_test', 'non_existent_key'])); } public function testExpire() diff --git a/tests/unit/framework/caching/DbCacheTest.php b/tests/unit/framework/caching/DbCacheTest.php index 1e94d58..c3c0233 100644 --- a/tests/unit/framework/caching/DbCacheTest.php +++ b/tests/unit/framework/caching/DbCacheTest.php @@ -67,9 +67,7 @@ class DbCacheTest extends CacheTestCase protected function getCacheInstance() { if ($this->_cacheInstance === null) { - $this->_cacheInstance = new DbCache(array( - 'db' => $this->getConnection(), - )); + $this->_cacheInstance = new DbCache(['db' => $this->getConnection()]); } return $this->_cacheInstance; } diff --git a/tests/unit/framework/caching/FileCacheTest.php b/tests/unit/framework/caching/FileCacheTest.php index 263ecb4..70271c9 100644 --- a/tests/unit/framework/caching/FileCacheTest.php +++ b/tests/unit/framework/caching/FileCacheTest.php @@ -17,9 +17,7 @@ class FileCacheTest extends CacheTestCase protected function getCacheInstance() { if ($this->_cacheInstance === null) { - $this->_cacheInstance = new FileCache(array( - 'cachePath' => '@yiiunit/runtime/cache', - )); + $this->_cacheInstance = new FileCache(['cachePath' => '@yiiunit/runtime/cache']); } return $this->_cacheInstance; } diff --git a/tests/unit/framework/caching/MemCachedTest.php b/tests/unit/framework/caching/MemCachedTest.php index f39ed17..807cef1 100644 --- a/tests/unit/framework/caching/MemCachedTest.php +++ b/tests/unit/framework/caching/MemCachedTest.php @@ -22,9 +22,7 @@ class MemCachedTest extends CacheTestCase } if ($this->_cacheInstance === null) { - $this->_cacheInstance = new MemCache(array( - 'useMemcached' => true, - )); + $this->_cacheInstance = new MemCache(['useMemcached' => true]); } return $this->_cacheInstance; } diff --git a/tests/unit/framework/caching/RedisCacheTest.php b/tests/unit/framework/caching/RedisCacheTest.php index d02773d..d4e414e 100644 --- a/tests/unit/framework/caching/RedisCacheTest.php +++ b/tests/unit/framework/caching/RedisCacheTest.php @@ -18,12 +18,12 @@ class RedisCacheTest extends CacheTestCase */ protected function getCacheInstance() { - $config = array( + $config = [ 'hostname' => 'localhost', 'port' => 6379, 'database' => 0, 'dataTimeout' => 0.1, - ); + ]; $dsn = $config['hostname'] . ':' .$config['port']; if(!@stream_socket_client($dsn, $errorNumber, $errorDescription, 0.5)) { $this->markTestSkipped('No redis server running at ' . $dsn .' : ' . $errorNumber . ' - ' . $errorDescription); @@ -74,7 +74,7 @@ class RedisCacheTest extends CacheTestCase { $cache = $this->getCacheInstance(); - $data=array('abc'=>'ежик',2=>'def'); + $data=['abc'=>'ежик',2=>'def']; $key='data1'; $this->assertFalse($cache->get($key)); diff --git a/tests/unit/framework/console/controllers/AssetControllerTest.php b/tests/unit/framework/console/controllers/AssetControllerTest.php index 67dbdaa..0858d32 100644 --- a/tests/unit/framework/console/controllers/AssetControllerTest.php +++ b/tests/unit/framework/console/controllers/AssetControllerTest.php @@ -62,7 +62,7 @@ class AssetControllerTest extends TestCase */ protected function createAssetController() { - $module = $this->getMock('yii\\base\\Module', array('fake'), array('console')); + $module = $this->getMock('yii\\base\\Module', ['fake'], ['console']); $assetController = new AssetController('asset', $module); $assetController->interactive = false; $assetController->jsCompressor = 'cp {from} {to}'; @@ -76,7 +76,7 @@ class AssetControllerTest extends TestCase * @param array $args action arguments. * @return string command output. */ - protected function runAssetControllerAction($actionId, array $args = array()) + protected function runAssetControllerAction($actionId, array $args = []) { $controller = $this->createAssetController(); ob_start(); @@ -93,21 +93,21 @@ class AssetControllerTest extends TestCase protected function createCompressConfig(array $bundles) { $baseUrl = '/test'; - $config = array( + $config = [ 'bundles' => $this->createBundleConfig($bundles), - 'targets' => array( - 'all' => array( + 'targets' => [ + 'all' => [ 'basePath' => $this->testAssetsBasePath, 'baseUrl' => $baseUrl, 'js' => 'all.js', 'css' => 'all.css', - ), - ), - 'assetManager' => array( + ], + ], + 'assetManager' => [ 'basePath' => $this->testAssetsBasePath, 'baseUrl' => '', - ), - ); + ], + ]; return $config; } @@ -175,7 +175,7 @@ class AssetControllerTest extends TestCase * @param array $args method arguments. * @return mixed method invoke result. */ - protected function invokeAssetControllerMethod($methodName, array $args = array()) + protected function invokeAssetControllerMethod($methodName, array $args = []) { $controller = $this->createAssetController(); $controllerClassReflection = new ReflectionClass(get_class($controller)); @@ -191,14 +191,14 @@ class AssetControllerTest extends TestCase public function testActionTemplate() { $configFileName = $this->testFilePath . DIRECTORY_SEPARATOR . 'config.php'; - $this->runAssetControllerAction('template', array($configFileName)); + $this->runAssetControllerAction('template', [$configFileName]); $this->assertTrue(file_exists($configFileName), 'Unable to create config file template!'); } public function atestActionCompress() { // Given : - $cssFiles = array( + $cssFiles = [ 'css/test_body.css' => 'body { padding-top: 20px; padding-bottom: 60px; @@ -207,35 +207,35 @@ class AssetControllerTest extends TestCase margin: 20px; display: block; }', - ); + ]; $this->createAssetSourceFiles($cssFiles); - $jsFiles = array( + $jsFiles = [ 'js/test_alert.js' => "function test() { alert('Test message'); }", 'js/test_sum_ab.js' => "function sumAB(a, b) { return a + b; }", - ); + ]; $this->createAssetSourceFiles($jsFiles); - $bundles = array( - 'app' => array( + $bundles = [ + 'app' => [ 'css' => array_keys($cssFiles), 'js' => array_keys($jsFiles), - 'depends' => array( + 'depends' => [ 'yii', - ), - ), - ); + ], + ], + ]; $bundleFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'bundle.php'; $configFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'config.php'; $this->createCompressConfigFile($configFile, $bundles); // When : - $this->runAssetControllerAction('compress', array($configFile, $bundleFile)); + $this->runAssetControllerAction('compress', [$configFile, $bundleFile]); // Then : $this->assertTrue(file_exists($bundleFile), 'Unable to create output bundle file!'); @@ -262,44 +262,44 @@ class AssetControllerTest extends TestCase */ public function adjustCssUrlDataProvider() { - return array( - array( - '.published-same-dir-class {background-image: url(published_same_dir.png);}', + return [ + [ + '.published-same-dir-class {background-image: url(published_same_dir.png];}', '/test/base/path/assets/input', '/test/base/path/assets/output', - '.published-same-dir-class {background-image: url(../input/published_same_dir.png);}', - ), - array( - '.published-relative-dir-class {background-image: url(../img/published_relative_dir.png);}', + '.published-same-dir-class {background-image: url(../input/published_same_dir.png];}', + ], + [ + '.published-relative-dir-class {background-image: url(../img/published_relative_dir.png];}', '/test/base/path/assets/input', '/test/base/path/assets/output', - '.published-relative-dir-class {background-image: url(../img/published_relative_dir.png);}', - ), - array( - '.static-same-dir-class {background-image: url(\'static_same_dir.png\');}', + '.published-relative-dir-class {background-image: url(../img/published_relative_dir.png];}', + ], + [ + '.static-same-dir-class {background-image: url(\'static_same_dir.png\'];}', '/test/base/path/css', '/test/base/path/assets/output', - '.static-same-dir-class {background-image: url(\'../../css/static_same_dir.png\');}', - ), - array( - '.static-relative-dir-class {background-image: url("../img/static_relative_dir.png");}', + '.static-same-dir-class {background-image: url(\'../../css/static_same_dir.png\'];}', + ], + [ + '.static-relative-dir-class {background-image: url("../img/static_relative_dir.png"];}', '/test/base/path/css', '/test/base/path/assets/output', - '.static-relative-dir-class {background-image: url("../../img/static_relative_dir.png");}', - ), - array( - '.absolute-url-class {background-image: url(http://domain.com/img/image.gif);}', + '.static-relative-dir-class {background-image: url("../../img/static_relative_dir.png"];}', + ], + [ + '.absolute-url-class {background-image: url(http://domain.com/img/image.gif];}', '/test/base/path/assets/input', '/test/base/path/assets/output', - '.absolute-url-class {background-image: url(http://domain.com/img/image.gif);}', - ), - array( - '.absolute-url-secure-class {background-image: url(https://secure.domain.com/img/image.gif);}', + '.absolute-url-class {background-image: url(http://domain.com/img/image.gif];}', + ], + [ + '.absolute-url-secure-class {background-image: url(https://secure.domain.com/img/image.gif];}', '/test/base/path/assets/input', '/test/base/path/assets/output', - '.absolute-url-secure-class {background-image: url(https://secure.domain.com/img/image.gif);}', - ), - ); + '.absolute-url-secure-class {background-image: url(https://secure.domain.com/img/image.gif];}', + ], + ]; } /** @@ -312,7 +312,7 @@ class AssetControllerTest extends TestCase */ public function testAdjustCssUrl($cssContent, $inputFilePath, $outputFilePath, $expectedCssContent) { - $adjustedCssContent = $this->invokeAssetControllerMethod('adjustCssUrl', array($cssContent, $inputFilePath, $outputFilePath)); + $adjustedCssContent = $this->invokeAssetControllerMethod('adjustCssUrl', [$cssContent, $inputFilePath, $outputFilePath]); $this->assertEquals($expectedCssContent, $adjustedCssContent, 'Unable to adjust CSS correctly!'); } diff --git a/tests/unit/framework/console/controllers/MessageControllerTest.php b/tests/unit/framework/console/controllers/MessageControllerTest.php index b0c697c..8bd2b12 100644 --- a/tests/unit/framework/console/controllers/MessageControllerTest.php +++ b/tests/unit/framework/console/controllers/MessageControllerTest.php @@ -86,7 +86,7 @@ class MessageControllerTest extends TestCase */ protected function createMessageController() { - $module = $this->getMock('yii\\base\\Module', array('fake'), array('console')); + $module = $this->getMock('yii\\base\\Module', ['fake'], ['console']); $messageController = new MessageController('message', $module); $messageController->interactive = false; return $messageController; @@ -98,7 +98,7 @@ class MessageControllerTest extends TestCase * @param array $args action arguments. * @return string command output. */ - protected function runMessageControllerAction($actionId, array $args = array()) + protected function runMessageControllerAction($actionId, array $args = []) { $controller = $this->createMessageController(); ob_start(); @@ -138,7 +138,7 @@ class MessageControllerTest extends TestCase * @param string $name file name * @param array $messages messages. */ - protected function createMessageFile($name, array $messages = array()) + protected function createMessageFile($name, array $messages = []) { $fileName = $this->messagePath . DIRECTORY_SEPARATOR . $name; if (file_exists($fileName)) { @@ -158,14 +158,14 @@ class MessageControllerTest extends TestCase public function testActionConfig() { $configFileName = $this->configFileName; - $this->runMessageControllerAction('config', array($configFileName)); + $this->runMessageControllerAction('config', [$configFileName]); $this->assertTrue(file_exists($configFileName), 'Unable to create config file template!'); } public function testConfigFileNotExist() { $this->setExpectedException('yii\\console\\Exception'); - $this->runMessageControllerAction('extract', array('not_existing_file.php')); + $this->runMessageControllerAction('extract', ['not_existing_file.php']); } public function testCreateTranslation() @@ -177,12 +177,12 @@ class MessageControllerTest extends TestCase $sourceFileContent = "Yii::t('{$category}', '{$message}')"; $this->createSourceFile($sourceFileContent); - $this->composeConfigFile(array( - 'languages' => array($language), + $this->composeConfigFile([ + 'languages' => [$language], 'sourcePath' => $this->sourcePath, 'messagePath' => $this->messagePath, - )); - $this->runMessageControllerAction('extract', array($this->configFileName)); + ]); + $this->runMessageControllerAction('extract', [$this->configFileName]); $this->assertTrue(file_exists($this->messagePath . DIRECTORY_SEPARATOR . $language), 'No language dir created!'); $messageFileName = $this->messagePath . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . $category . '.php'; @@ -204,12 +204,12 @@ class MessageControllerTest extends TestCase $sourceFileContent = "Yii::t('{$category}', '{$message}')"; $this->createSourceFile($sourceFileContent); - $this->composeConfigFile(array( - 'languages' => array($language), + $this->composeConfigFile([ + 'languages' => [$language], 'sourcePath' => $this->sourcePath, 'messagePath' => $this->messagePath, - )); - $this->runMessageControllerAction('extract', array($this->configFileName)); + ]); + $this->runMessageControllerAction('extract', [$this->configFileName]); $messageFileName = $this->messagePath . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . $category . '.php'; @@ -218,7 +218,7 @@ class MessageControllerTest extends TestCase $messageFileContent .= '// some not generated by command content'; file_put_contents($messageFileName, $messageFileContent); - $this->runMessageControllerAction('extract', array($this->configFileName)); + $this->runMessageControllerAction('extract', [$this->configFileName]); $this->assertEquals($messageFileContent, file_get_contents($messageFileName)); } @@ -234,22 +234,22 @@ class MessageControllerTest extends TestCase $existingMessage = 'test existing message'; $existingMessageContent = 'test existing message content'; - $this->createMessageFile($messageFileName, array( + $this->createMessageFile($messageFileName, [ $existingMessage => $existingMessageContent - )); + ]); $newMessage = 'test new message'; $sourceFileContent = "Yii::t('{$category}', '{$existingMessage}')"; $sourceFileContent .= "Yii::t('{$category}', '{$newMessage}')"; $this->createSourceFile($sourceFileContent); - $this->composeConfigFile(array( - 'languages' => array($language), + $this->composeConfigFile([ + 'languages' => [$language], 'sourcePath' => $this->sourcePath, 'messagePath' => $this->messagePath, 'overwrite' => true, - )); - $this->runMessageControllerAction('extract', array($this->configFileName)); + ]); + $this->runMessageControllerAction('extract', [$this->configFileName]); $messages = require($this->messagePath . DIRECTORY_SEPARATOR . $messageFileName); $this->assertTrue(array_key_exists($newMessage, $messages), 'Unable to add new message!'); @@ -269,21 +269,21 @@ class MessageControllerTest extends TestCase $oldMessage = 'test old message'; $oldMessageContent = 'test old message content'; - $this->createMessageFile($messageFileName, array( + $this->createMessageFile($messageFileName, [ $oldMessage => $oldMessageContent - )); + ]); $sourceFileContent = "Yii::t('{$category}', 'some new message')"; $this->createSourceFile($sourceFileContent); - $this->composeConfigFile(array( - 'languages' => array($language), + $this->composeConfigFile([ + 'languages' => [$language], 'sourcePath' => $this->sourcePath, 'messagePath' => $this->messagePath, 'overwrite' => true, 'removeUnused' => false, - )); - $this->runMessageControllerAction('extract', array($this->configFileName)); + ]); + $this->runMessageControllerAction('extract', [$this->configFileName]); $messages = require($this->messagePath . DIRECTORY_SEPARATOR . $messageFileName); @@ -304,10 +304,10 @@ class MessageControllerTest extends TestCase $zeroMessageContent = '0'; $falseMessage = 'test false message'; $falseMessageContent = 'false'; - $this->createMessageFile($messageFileName, array( + $this->createMessageFile($messageFileName, [ $zeroMessage => $zeroMessageContent, $falseMessage => $falseMessageContent, - )); + ]); $newMessage = 'test new message'; $sourceFileContent = "Yii::t('{$category}', '{$zeroMessage}')"; @@ -315,13 +315,13 @@ class MessageControllerTest extends TestCase $sourceFileContent .= "Yii::t('{$category}', '{$newMessage}')"; $this->createSourceFile($sourceFileContent); - $this->composeConfigFile(array( - 'languages' => array($language), + $this->composeConfigFile([ + 'languages' => [$language], 'sourcePath' => $this->sourcePath, 'messagePath' => $this->messagePath, 'overwrite' => true, - )); - $this->runMessageControllerAction('extract', array($this->configFileName)); + ]); + $this->runMessageControllerAction('extract', [$this->configFileName]); $messages = require($this->messagePath . DIRECTORY_SEPARATOR . $messageFileName); $this->assertTrue($zeroMessageContent === $messages[$zeroMessage], 'Message content "0" is lost!'); @@ -336,28 +336,28 @@ class MessageControllerTest extends TestCase $language = 'en'; $category = 'test_category'; - $translators = array( + $translators = [ 'Yii::t', 'Custom::translate', - ); + ]; - $sourceMessages = array( + $sourceMessages = [ 'first message', 'second message', - ); + ]; $sourceFileContent = ''; foreach ($sourceMessages as $key => $message) { $sourceFileContent .= $translators[$key] . "('{$category}', '{$message}');\n"; } $this->createSourceFile($sourceFileContent); - $this->composeConfigFile(array( - 'languages' => array($language), + $this->composeConfigFile([ + 'languages' => [$language], 'sourcePath' => $this->sourcePath, 'messagePath' => $this->messagePath, 'translator' => $translators, - )); - $this->runMessageControllerAction('extract', array($this->configFileName)); + ]); + $this->runMessageControllerAction('extract', [$this->configFileName]); $messageFileName = $this->messagePath . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . $category . '.php'; $messages = require($messageFileName); diff --git a/tests/unit/framework/data/ActiveDataProviderTest.php b/tests/unit/framework/data/ActiveDataProviderTest.php index 276c525..3b445e0 100644 --- a/tests/unit/framework/data/ActiveDataProviderTest.php +++ b/tests/unit/framework/data/ActiveDataProviderTest.php @@ -29,20 +29,20 @@ class ActiveDataProviderTest extends DatabaseTestCase public function testActiveQuery() { - $provider = new ActiveDataProvider(array( + $provider = new ActiveDataProvider([ 'query' => Order::find()->orderBy('id'), - )); + ]); $orders = $provider->getModels(); $this->assertEquals(3, count($orders)); $this->assertTrue($orders[0] instanceof Order); - $this->assertEquals(array(1, 2, 3), $provider->getKeys()); + $this->assertEquals([1, 2, 3], $provider->getKeys()); - $provider = new ActiveDataProvider(array( + $provider = new ActiveDataProvider([ 'query' => Order::find(), - 'pagination' => array( + 'pagination' => [ 'pageSize' => 2, - ) - )); + ] + ]); $orders = $provider->getModels(); $this->assertEquals(2, count($orders)); } @@ -50,23 +50,23 @@ class ActiveDataProviderTest extends DatabaseTestCase public function testQuery() { $query = new Query; - $provider = new ActiveDataProvider(array( + $provider = new ActiveDataProvider([ 'db' => $this->getConnection(), 'query' => $query->from('tbl_order')->orderBy('id'), - )); + ]); $orders = $provider->getModels(); $this->assertEquals(3, count($orders)); $this->assertTrue(is_array($orders[0])); - $this->assertEquals(array(0, 1, 2), $provider->getKeys()); + $this->assertEquals([0, 1, 2], $provider->getKeys()); $query = new Query; - $provider = new ActiveDataProvider(array( + $provider = new ActiveDataProvider([ 'db' => $this->getConnection(), 'query' => $query->from('tbl_order'), - 'pagination' => array( + 'pagination' => [ 'pageSize' => 2, - ) - )); + ] + ]); $orders = $provider->getModels(); $this->assertEquals(2, count($orders)); } @@ -74,10 +74,10 @@ class ActiveDataProviderTest extends DatabaseTestCase public function testRefresh() { $query = new Query; - $provider = new ActiveDataProvider(array( + $provider = new ActiveDataProvider([ 'db' => $this->getConnection(), 'query' => $query->from('tbl_order')->orderBy('id'), - )); + ]); $this->assertEquals(3, count($provider->getModels())); $provider->getPagination()->pageSize = 2; @@ -89,10 +89,10 @@ class ActiveDataProviderTest extends DatabaseTestCase public function testPaginationBeforeModels() { $query = new Query; - $provider = new ActiveDataProvider(array( + $provider = new ActiveDataProvider([ 'db' => $this->getConnection(), 'query' => $query->from('tbl_order')->orderBy('id'), - )); + ]); $pagination = $provider->getPagination(); $this->assertEquals(0, $pagination->getPageCount()); $this->assertCount(3, $provider->getModels()); diff --git a/tests/unit/framework/data/SortTest.php b/tests/unit/framework/data/SortTest.php index c4cc6aa..abe0031 100644 --- a/tests/unit/framework/data/SortTest.php +++ b/tests/unit/framework/data/SortTest.php @@ -21,19 +21,19 @@ class SortTest extends TestCase { public function testGetOrders() { - $sort = new Sort(array( - 'attributes' => array( + $sort = new Sort([ + 'attributes' => [ 'age', - 'name' => array( - 'asc' => array('first_name' => Sort::ASC, 'last_name' => Sort::ASC), - 'desc' => array('first_name' => Sort::DESC, 'last_name' => Sort::DESC), - ), - ), - 'params' => array( + 'name' => [ + 'asc' => ['first_name' => Sort::ASC, 'last_name' => Sort::ASC], + 'desc' => ['first_name' => Sort::DESC, 'last_name' => Sort::DESC], + ], + ], + 'params' => [ 'sort' => 'age.name-desc' - ), + ], 'enableMultiSort' => true, - )); + ]); $orders = $sort->getOrders(); $this->assertEquals(3, count($orders)); @@ -49,19 +49,19 @@ class SortTest extends TestCase public function testGetAttributeOrders() { - $sort = new Sort(array( - 'attributes' => array( + $sort = new Sort([ + 'attributes' => [ 'age', - 'name' => array( - 'asc' => array('first_name' => Sort::ASC, 'last_name' => Sort::ASC), - 'desc' => array('first_name' => Sort::DESC, 'last_name' => Sort::DESC), - ), - ), - 'params' => array( + 'name' => [ + 'asc' => ['first_name' => Sort::ASC, 'last_name' => Sort::ASC], + 'desc' => ['first_name' => Sort::DESC, 'last_name' => Sort::DESC], + ], + ], + 'params' => [ 'sort' => 'age.name-desc' - ), + ], 'enableMultiSort' => true, - )); + ]); $orders = $sort->getAttributeOrders(); $this->assertEquals(2, count($orders)); @@ -76,19 +76,19 @@ class SortTest extends TestCase public function testGetAttributeOrder() { - $sort = new Sort(array( - 'attributes' => array( + $sort = new Sort([ + 'attributes' => [ 'age', - 'name' => array( - 'asc' => array('first_name' => Sort::ASC, 'last_name' => Sort::ASC), - 'desc' => array('first_name' => Sort::DESC, 'last_name' => Sort::DESC), - ), - ), - 'params' => array( + 'name' => [ + 'asc' => ['first_name' => Sort::ASC, 'last_name' => Sort::ASC], + 'desc' => ['first_name' => Sort::DESC, 'last_name' => Sort::DESC], + ], + ], + 'params' => [ 'sort' => 'age.name-desc' - ), + ], 'enableMultiSort' => true, - )); + ]); $this->assertEquals(Sort::ASC, $sort->getAttributeOrder('age')); $this->assertEquals(Sort::DESC, $sort->getAttributeOrder('name')); @@ -97,20 +97,20 @@ class SortTest extends TestCase public function testCreateSortVar() { - $sort = new Sort(array( - 'attributes' => array( + $sort = new Sort([ + 'attributes' => [ 'age', - 'name' => array( - 'asc' => array('first_name' => Sort::ASC, 'last_name' => Sort::ASC), - 'desc' => array('first_name' => Sort::DESC, 'last_name' => Sort::DESC), - ), - ), - 'params' => array( + 'name' => [ + 'asc' => ['first_name' => Sort::ASC, 'last_name' => Sort::ASC], + 'desc' => ['first_name' => Sort::DESC, 'last_name' => Sort::DESC], + ], + ], + 'params' => [ 'sort' => 'age.name-desc' - ), + ], 'enableMultiSort' => true, 'route' => 'site/index', - )); + ]); $this->assertEquals('age-desc.name-desc', $sort->createSortVar('age')); $this->assertEquals('name.age', $sort->createSortVar('name')); @@ -118,26 +118,26 @@ class SortTest extends TestCase public function testCreateUrl() { - $manager = new UrlManager(array( + $manager = new UrlManager([ 'baseUrl' => '/index.php', 'cache' => null, - )); + ]); - $sort = new Sort(array( - 'attributes' => array( + $sort = new Sort([ + 'attributes' => [ 'age', - 'name' => array( - 'asc' => array('first_name' => Sort::ASC, 'last_name' => Sort::ASC), - 'desc' => array('first_name' => Sort::DESC, 'last_name' => Sort::DESC), - ), - ), - 'params' => array( + 'name' => [ + 'asc' => ['first_name' => Sort::ASC, 'last_name' => Sort::ASC], + 'desc' => ['first_name' => Sort::DESC, 'last_name' => Sort::DESC], + ], + ], + 'params' => [ 'sort' => 'age.name-desc' - ), + ], 'enableMultiSort' => true, 'urlManager' => $manager, 'route' => 'site/index', - )); + ]); $this->assertEquals('/index.php?r=site/index&sort=age-desc.name-desc', $sort->createUrl('age')); $this->assertEquals('/index.php?r=site/index&sort=name.age', $sort->createUrl('name')); @@ -146,26 +146,26 @@ class SortTest extends TestCase public function testLink() { $this->mockApplication(); - $manager = new UrlManager(array( + $manager = new UrlManager([ 'baseUrl' => '/index.php', 'cache' => null, - )); + ]); - $sort = new Sort(array( - 'attributes' => array( + $sort = new Sort([ + 'attributes' => [ 'age', - 'name' => array( - 'asc' => array('first_name' => Sort::ASC, 'last_name' => Sort::ASC), - 'desc' => array('first_name' => Sort::DESC, 'last_name' => Sort::DESC), - ), - ), - 'params' => array( + 'name' => [ + 'asc' => ['first_name' => Sort::ASC, 'last_name' => Sort::ASC], + 'desc' => ['first_name' => Sort::DESC, 'last_name' => Sort::DESC], + ], + ], + 'params' => [ 'sort' => 'age.name-desc' - ), + ], 'enableMultiSort' => true, 'urlManager' => $manager, 'route' => 'site/index', - )); + ]); $this->assertEquals('Age', $sort->link('age')); } diff --git a/tests/unit/framework/db/ActiveRecordTest.php b/tests/unit/framework/db/ActiveRecordTest.php index 2f9b345..5e20edb 100644 --- a/tests/unit/framework/db/ActiveRecordTest.php +++ b/tests/unit/framework/db/ActiveRecordTest.php @@ -42,20 +42,20 @@ class ActiveRecordTest extends DatabaseTestCase $this->assertEquals('user2', $customer->name); // find by column values - $customer = Customer::find(array('id' => 2, 'name' => 'user2')); + $customer = Customer::find(['id' => 2, 'name' => 'user2']); $this->assertTrue($customer instanceof Customer); $this->assertEquals('user2', $customer->name); - $customer = Customer::find(array('id' => 2, 'name' => 'user1')); + $customer = Customer::find(['id' => 2, 'name' => 'user1']); $this->assertNull($customer); // find by attributes - $customer = Customer::find()->where(array('name' => 'user2'))->one(); + $customer = Customer::find()->where(['name' => 'user2'])->one(); $this->assertTrue($customer instanceof Customer); $this->assertEquals(2, $customer->id); // find custom column - $customer = Customer::find()->select(array('*', '(status*2) AS status2')) - ->where(array('name' => 'user3'))->one(); + $customer = Customer::find()->select(['*', '(status*2) AS status2']) + ->where(['name' => 'user3'])->one(); $this->assertEquals(3, $customer->id); $this->assertEquals(4, $customer->status2); @@ -73,13 +73,13 @@ class ActiveRecordTest extends DatabaseTestCase // asArray $customer = Customer::find()->where('id=2')->asArray()->one(); - $this->assertEquals(array( + $this->assertEquals([ 'id' => '2', 'email' => 'user2@example.com', 'name' => 'user2', 'address' => 'address2', 'status' => '1', - ), $customer); + ], $customer); // indexBy $customers = Customer::find()->indexBy('name')->orderBy('id')->all(); @@ -110,7 +110,7 @@ class ActiveRecordTest extends DatabaseTestCase $this->assertEquals(3, count($customers)); // find with parameter binding - $customer = Customer::findBySql('SELECT * FROM tbl_customer WHERE id=:id', array(':id' => 2))->one(); + $customer = Customer::findBySql('SELECT * FROM tbl_customer WHERE id=:id', [':id' => 2])->one(); $this->assertTrue($customer instanceof Customer); $this->assertEquals('user2', $customer->name); } @@ -146,7 +146,7 @@ class ActiveRecordTest extends DatabaseTestCase $order = Order::find(1); $order->id = 100; - $this->assertEquals(array(), $order->items); + $this->assertEquals([], $order->items); } public function testFindEagerViaRelation() @@ -236,12 +236,12 @@ class ActiveRecordTest extends DatabaseTestCase // via table $order = Order::find(2); $this->assertEquals(0, count($order->books)); - $orderItem = OrderItem::find(array('order_id' => 2, 'item_id' => 1)); + $orderItem = OrderItem::find(['order_id' => 2, 'item_id' => 1]); $this->assertNull($orderItem); $item = Item::find(1); - $order->link('books', $item, array('quantity' => 10, 'subtotal' => 100)); + $order->link('books', $item, ['quantity' => 10, 'subtotal' => 100]); $this->assertEquals(1, count($order->books)); - $orderItem = OrderItem::find(array('order_id' => 2, 'item_id' => 1)); + $orderItem = OrderItem::find(['order_id' => 2, 'item_id' => 1]); $this->assertTrue($orderItem instanceof OrderItem); $this->assertEquals(10, $orderItem->quantity); $this->assertEquals(100, $orderItem->subtotal); @@ -250,13 +250,13 @@ class ActiveRecordTest extends DatabaseTestCase $order = Order::find(1); $this->assertEquals(2, count($order->items)); $this->assertEquals(2, count($order->orderItems)); - $orderItem = OrderItem::find(array('order_id' => 1, 'item_id' => 3)); + $orderItem = OrderItem::find(['order_id' => 1, 'item_id' => 3]); $this->assertNull($orderItem); $item = Item::find(3); - $order->link('items', $item, array('quantity' => 10, 'subtotal' => 100)); + $order->link('items', $item, ['quantity' => 10, 'subtotal' => 100]); $this->assertEquals(3, count($order->items)); $this->assertEquals(3, count($order->orderItems)); - $orderItem = OrderItem::find(array('order_id' => 1, 'item_id' => 3)); + $orderItem = OrderItem::find(['order_id' => 1, 'item_id' => 3]); $this->assertTrue($orderItem instanceof OrderItem); $this->assertEquals(10, $orderItem->quantity); $this->assertEquals(100, $orderItem->subtotal); @@ -318,10 +318,10 @@ class ActiveRecordTest extends DatabaseTestCase $this->assertEquals('user2x', $customer2->name); // updateCounters - $pk = array('order_id' => 2, 'item_id' => 4); + $pk = ['order_id' => 2, 'item_id' => 4]; $orderItem = OrderItem::find($pk); $this->assertEquals(1, $orderItem->quantity); - $ret = $orderItem->updateCounters(array('quantity' => -1)); + $ret = $orderItem->updateCounters(['quantity' => -1]); $this->assertTrue($ret); $this->assertEquals(0, $orderItem->quantity); $orderItem = OrderItem::find($pk); @@ -330,21 +330,19 @@ class ActiveRecordTest extends DatabaseTestCase // updateAll $customer = Customer::find(3); $this->assertEquals('user3', $customer->name); - $ret = Customer::updateAll(array( - 'name' => 'temp', - ), array('id' => 3)); + $ret = Customer::updateAll(['name' => 'temp'], ['id' => 3]); $this->assertEquals(1, $ret); $customer = Customer::find(3); $this->assertEquals('temp', $customer->name); // updateCounters - $pk = array('order_id' => 1, 'item_id' => 2); + $pk = ['order_id' => 1, 'item_id' => 2]; $orderItem = OrderItem::find($pk); $this->assertEquals(2, $orderItem->quantity); - $ret = OrderItem::updateAllCounters(array( + $ret = OrderItem::updateAllCounters([ 'quantity' => 3, 'subtotal' => -10, - ), $pk); + ], $pk); $this->assertEquals(1, $ret); $orderItem = OrderItem::find($pk); $this->assertEquals(5, $orderItem->quantity); diff --git a/tests/unit/framework/db/CommandTest.php b/tests/unit/framework/db/CommandTest.php index 7b16c76..da3d557 100644 --- a/tests/unit/framework/db/CommandTest.php +++ b/tests/unit/framework/db/CommandTest.php @@ -95,7 +95,7 @@ class CommandTest extends DatabaseTestCase $this->assertEquals('user3', $row['name']); $rows = $db->createCommand('SELECT * FROM tbl_customer WHERE id=10')->queryAll(); - $this->assertEquals(array(), $rows); + $this->assertEquals([], $rows); // queryOne $sql = 'SELECT * FROM tbl_customer ORDER BY id'; @@ -120,7 +120,7 @@ class CommandTest extends DatabaseTestCase $this->assertEquals(range(1, 3), $column); $command = $db->createCommand('SELECT id FROM tbl_customer WHERE id=10'); - $this->assertEquals(array(), $command->queryColumn()); + $this->assertEquals([], $command->queryColumn()); // queryScalar $sql = 'SELECT * FROM tbl_customer ORDER BY id'; @@ -215,7 +215,7 @@ class CommandTest extends DatabaseTestCase // FETCH_NUM, customized in query method $sql = 'SELECT * FROM tbl_customer'; $command = $db->createCommand($sql); - $result = $command->queryOne(array(), \PDO::FETCH_NUM); + $result = $command->queryOne([], \PDO::FETCH_NUM); $this->assertTrue(is_array($result) && isset($result[0])); } diff --git a/tests/unit/framework/db/QueryBuilderTest.php b/tests/unit/framework/db/QueryBuilderTest.php index d43c901..b8eefe0 100644 --- a/tests/unit/framework/db/QueryBuilderTest.php +++ b/tests/unit/framework/db/QueryBuilderTest.php @@ -43,65 +43,65 @@ class QueryBuilderTest extends DatabaseTestCase */ public function columnTypes() { - return array( - array(Schema::TYPE_PK, 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY'), - array(Schema::TYPE_PK . '(8)', 'int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY'), - array(Schema::TYPE_PK . ' CHECK (value > 5)', 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY CHECK (value > 5)'), - array(Schema::TYPE_PK . '(8) CHECK (value > 5)', 'int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY CHECK (value > 5)'), - array(Schema::TYPE_STRING, 'varchar(255)'), - array(Schema::TYPE_STRING . '(32)', 'varchar(32)'), - array(Schema::TYPE_STRING . ' CHECK (value LIKE "test%")', 'varchar(255) CHECK (value LIKE "test%")'), - array(Schema::TYPE_STRING . '(32) CHECK (value LIKE "test%")', 'varchar(32) CHECK (value LIKE "test%")'), - array(Schema::TYPE_STRING . ' NOT NULL', 'varchar(255) NOT NULL'), - array(Schema::TYPE_TEXT, 'text'), - array(Schema::TYPE_TEXT . '(255)', 'text'), - array(Schema::TYPE_TEXT . ' CHECK (value LIKE "test%")', 'text CHECK (value LIKE "test%")'), - array(Schema::TYPE_TEXT . '(255) CHECK (value LIKE "test%")', 'text CHECK (value LIKE "test%")'), - array(Schema::TYPE_TEXT . ' NOT NULL', 'text NOT NULL'), - array(Schema::TYPE_TEXT . '(255) NOT NULL', 'text NOT NULL'), - array(Schema::TYPE_SMALLINT, 'smallint(6)'), - array(Schema::TYPE_SMALLINT . '(8)', 'smallint(8)'), - array(Schema::TYPE_INTEGER, 'int(11)'), - array(Schema::TYPE_INTEGER . '(8)', 'int(8)'), - array(Schema::TYPE_INTEGER . ' CHECK (value > 5)', 'int(11) CHECK (value > 5)'), - array(Schema::TYPE_INTEGER . '(8) CHECK (value > 5)', 'int(8) CHECK (value > 5)'), - array(Schema::TYPE_INTEGER . ' NOT NULL', 'int(11) NOT NULL'), - array(Schema::TYPE_BIGINT, 'bigint(20)'), - array(Schema::TYPE_BIGINT . '(8)', 'bigint(8)'), - array(Schema::TYPE_BIGINT . ' CHECK (value > 5)', 'bigint(20) CHECK (value > 5)'), - array(Schema::TYPE_BIGINT . '(8) CHECK (value > 5)', 'bigint(8) CHECK (value > 5)'), - array(Schema::TYPE_BIGINT . ' NOT NULL', 'bigint(20) NOT NULL'), - array(Schema::TYPE_FLOAT, 'float'), - array(Schema::TYPE_FLOAT . '(16,5)', 'float'), - array(Schema::TYPE_FLOAT . ' CHECK (value > 5.6)', 'float CHECK (value > 5.6)'), - array(Schema::TYPE_FLOAT . '(16,5) CHECK (value > 5.6)', 'float CHECK (value > 5.6)'), - array(Schema::TYPE_FLOAT . ' NOT NULL', 'float NOT NULL'), - array(Schema::TYPE_DECIMAL, 'decimal(10,0)'), - array(Schema::TYPE_DECIMAL . '(12,4)', 'decimal(12,4)'), - array(Schema::TYPE_DECIMAL . ' CHECK (value > 5.6)', 'decimal(10,0) CHECK (value > 5.6)'), - array(Schema::TYPE_DECIMAL . '(12,4) CHECK (value > 5.6)', 'decimal(12,4) CHECK (value > 5.6)'), - array(Schema::TYPE_DECIMAL . ' NOT NULL', 'decimal(10,0) NOT NULL'), - array(Schema::TYPE_DATETIME, 'datetime'), - array(Schema::TYPE_DATETIME . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "datetime CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"), - array(Schema::TYPE_DATETIME . ' NOT NULL', 'datetime NOT NULL'), - array(Schema::TYPE_TIMESTAMP, 'timestamp'), - array(Schema::TYPE_TIMESTAMP . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "timestamp CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"), - array(Schema::TYPE_TIMESTAMP . ' NOT NULL', 'timestamp NOT NULL'), - array(Schema::TYPE_TIME, 'time'), - array(Schema::TYPE_TIME . " CHECK(value BETWEEN '12:00:00' AND '13:01:01')", "time CHECK(value BETWEEN '12:00:00' AND '13:01:01')"), - array(Schema::TYPE_TIME . ' NOT NULL', 'time NOT NULL'), - array(Schema::TYPE_DATE, 'date'), - array(Schema::TYPE_DATE . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "date CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"), - array(Schema::TYPE_DATE . ' NOT NULL', 'date NOT NULL'), - array(Schema::TYPE_BINARY, 'blob'), - array(Schema::TYPE_BOOLEAN, 'tinyint(1)'), - array(Schema::TYPE_BOOLEAN . ' NOT NULL DEFAULT 1', 'tinyint(1) NOT NULL DEFAULT 1'), - array(Schema::TYPE_MONEY, 'decimal(19,4)'), - array(Schema::TYPE_MONEY . '(16,2)', 'decimal(16,2)'), - array(Schema::TYPE_MONEY . ' CHECK (value > 0.0)', 'decimal(19,4) CHECK (value > 0.0)'), - array(Schema::TYPE_MONEY . '(16,2) CHECK (value > 0.0)', 'decimal(16,2) CHECK (value > 0.0)'), - array(Schema::TYPE_MONEY . ' NOT NULL', 'decimal(19,4) NOT NULL'), - ); + return [ + [Schema::TYPE_PK, 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY'], + [Schema::TYPE_PK . '(8)', 'int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY'], + [Schema::TYPE_PK . ' CHECK (value > 5)', 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY CHECK (value > 5)'], + [Schema::TYPE_PK . '(8) CHECK (value > 5)', 'int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY CHECK (value > 5)'], + [Schema::TYPE_STRING, 'varchar(255)'], + [Schema::TYPE_STRING . '(32)', 'varchar(32)'], + [Schema::TYPE_STRING . ' CHECK (value LIKE "test%")', 'varchar(255) CHECK (value LIKE "test%")'], + [Schema::TYPE_STRING . '(32) CHECK (value LIKE "test%")', 'varchar(32) CHECK (value LIKE "test%")'], + [Schema::TYPE_STRING . ' NOT NULL', 'varchar(255) NOT NULL'], + [Schema::TYPE_TEXT, 'text'], + [Schema::TYPE_TEXT . '(255)', 'text'], + [Schema::TYPE_TEXT . ' CHECK (value LIKE "test%")', 'text CHECK (value LIKE "test%")'], + [Schema::TYPE_TEXT . '(255) CHECK (value LIKE "test%")', 'text CHECK (value LIKE "test%")'], + [Schema::TYPE_TEXT . ' NOT NULL', 'text NOT NULL'], + [Schema::TYPE_TEXT . '(255) NOT NULL', 'text NOT NULL'], + [Schema::TYPE_SMALLINT, 'smallint(6)'], + [Schema::TYPE_SMALLINT . '(8)', 'smallint(8)'], + [Schema::TYPE_INTEGER, 'int(11)'], + [Schema::TYPE_INTEGER . '(8)', 'int(8)'], + [Schema::TYPE_INTEGER . ' CHECK (value > 5)', 'int(11) CHECK (value > 5)'], + [Schema::TYPE_INTEGER . '(8) CHECK (value > 5)', 'int(8) CHECK (value > 5)'], + [Schema::TYPE_INTEGER . ' NOT NULL', 'int(11) NOT NULL'], + [Schema::TYPE_BIGINT, 'bigint(20)'], + [Schema::TYPE_BIGINT . '(8)', 'bigint(8)'], + [Schema::TYPE_BIGINT . ' CHECK (value > 5)', 'bigint(20) CHECK (value > 5)'], + [Schema::TYPE_BIGINT . '(8) CHECK (value > 5)', 'bigint(8) CHECK (value > 5)'], + [Schema::TYPE_BIGINT . ' NOT NULL', 'bigint(20) NOT NULL'], + [Schema::TYPE_FLOAT, 'float'], + [Schema::TYPE_FLOAT . '(16,5)', 'float'], + [Schema::TYPE_FLOAT . ' CHECK (value > 5.6)', 'float CHECK (value > 5.6)'], + [Schema::TYPE_FLOAT . '(16,5) CHECK (value > 5.6)', 'float CHECK (value > 5.6)'], + [Schema::TYPE_FLOAT . ' NOT NULL', 'float NOT NULL'], + [Schema::TYPE_DECIMAL, 'decimal(10,0)'], + [Schema::TYPE_DECIMAL . '(12,4)', 'decimal(12,4)'], + [Schema::TYPE_DECIMAL . ' CHECK (value > 5.6)', 'decimal(10,0) CHECK (value > 5.6)'], + [Schema::TYPE_DECIMAL . '(12,4) CHECK (value > 5.6)', 'decimal(12,4) CHECK (value > 5.6)'], + [Schema::TYPE_DECIMAL . ' NOT NULL', 'decimal(10,0) NOT NULL'], + [Schema::TYPE_DATETIME, 'datetime'], + [Schema::TYPE_DATETIME . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "datetime CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"], + [Schema::TYPE_DATETIME . ' NOT NULL', 'datetime NOT NULL'], + [Schema::TYPE_TIMESTAMP, 'timestamp'], + [Schema::TYPE_TIMESTAMP . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "timestamp CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"], + [Schema::TYPE_TIMESTAMP . ' NOT NULL', 'timestamp NOT NULL'], + [Schema::TYPE_TIME, 'time'], + [Schema::TYPE_TIME . " CHECK(value BETWEEN '12:00:00' AND '13:01:01')", "time CHECK(value BETWEEN '12:00:00' AND '13:01:01')"], + [Schema::TYPE_TIME . ' NOT NULL', 'time NOT NULL'], + [Schema::TYPE_DATE, 'date'], + [Schema::TYPE_DATE . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "date CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"], + [Schema::TYPE_DATE . ' NOT NULL', 'date NOT NULL'], + [Schema::TYPE_BINARY, 'blob'], + [Schema::TYPE_BOOLEAN, 'tinyint(1)'], + [Schema::TYPE_BOOLEAN . ' NOT NULL DEFAULT 1', 'tinyint(1) NOT NULL DEFAULT 1'], + [Schema::TYPE_MONEY, 'decimal(19,4)'], + [Schema::TYPE_MONEY . '(16,2)', 'decimal(16,2)'], + [Schema::TYPE_MONEY . ' CHECK (value > 0.0)', 'decimal(19,4) CHECK (value > 0.0)'], + [Schema::TYPE_MONEY . '(16,2) CHECK (value > 0.0)', 'decimal(16,2) CHECK (value > 0.0)'], + [Schema::TYPE_MONEY . ' NOT NULL', 'decimal(19,4) NOT NULL'], + ]; } public function testGetColumnType() @@ -120,7 +120,7 @@ class QueryBuilderTest extends DatabaseTestCase // ADD $qb = $this->getQueryBuilder(); - $qb->db->createCommand()->addPrimaryKey($pkeyName, $tableName, array('id'))->execute(); + $qb->db->createCommand()->addPrimaryKey($pkeyName, $tableName, ['id'])->execute(); $tableSchema = $qb->db->getSchema()->getTableSchema($tableName); $this->assertEquals(1, count($tableSchema->primaryKey)); diff --git a/tests/unit/framework/db/QueryTest.php b/tests/unit/framework/db/QueryTest.php index a275afd..5cb019e 100644 --- a/tests/unit/framework/db/QueryTest.php +++ b/tests/unit/framework/db/QueryTest.php @@ -18,13 +18,13 @@ class QueryTest extends DatabaseTestCase // default $query = new Query; $query->select('*'); - $this->assertEquals(array('*'), $query->select); + $this->assertEquals(['*'], $query->select); $this->assertNull($query->distinct); $this->assertEquals(null, $query->selectOption); $query = new Query; $query->select('id, name', 'something')->distinct(true); - $this->assertEquals(array('id', 'name'), $query->select); + $this->assertEquals(['id', 'name'], $query->select); $this->assertTrue($query->distinct); $this->assertEquals('something', $query->selectOption); } @@ -33,23 +33,23 @@ class QueryTest extends DatabaseTestCase { $query = new Query; $query->from('tbl_user'); - $this->assertEquals(array('tbl_user'), $query->from); + $this->assertEquals(['tbl_user'], $query->from); } public function testWhere() { $query = new Query; - $query->where('id = :id', array(':id' => 1)); + $query->where('id = :id', [':id' => 1]); $this->assertEquals('id = :id', $query->where); - $this->assertEquals(array(':id' => 1), $query->params); + $this->assertEquals([':id' => 1], $query->params); - $query->andWhere('name = :name', array(':name' => 'something')); - $this->assertEquals(array('and', 'id = :id', 'name = :name'), $query->where); - $this->assertEquals(array(':id' => 1, ':name' => 'something'), $query->params); + $query->andWhere('name = :name', [':name' => 'something']); + $this->assertEquals(['and', 'id = :id', 'name = :name'], $query->where); + $this->assertEquals([':id' => 1, ':name' => 'something'], $query->params); - $query->orWhere('age = :age', array(':age' => '30')); - $this->assertEquals(array('or', array('and', 'id = :id', 'name = :name'), 'age = :age'), $query->where); - $this->assertEquals(array(':id' => 1, ':name' => 'something', ':age' => '30'), $query->params); + $query->orWhere('age = :age', [':age' => '30']); + $this->assertEquals(['or', ['and', 'id = :id', 'name = :name'], 'age = :age'], $query->where); + $this->assertEquals([':id' => 1, ':name' => 'something', ':age' => '30'], $query->params); } public function testJoin() @@ -60,48 +60,48 @@ class QueryTest extends DatabaseTestCase { $query = new Query; $query->groupBy('team'); - $this->assertEquals(array('team'), $query->groupBy); + $this->assertEquals(['team'], $query->groupBy); $query->addGroupBy('company'); - $this->assertEquals(array('team', 'company'), $query->groupBy); + $this->assertEquals(['team', 'company'], $query->groupBy); $query->addGroupBy('age'); - $this->assertEquals(array('team', 'company', 'age'), $query->groupBy); + $this->assertEquals(['team', 'company', 'age'], $query->groupBy); } public function testHaving() { $query = new Query; - $query->having('id = :id', array(':id' => 1)); + $query->having('id = :id', [':id' => 1]); $this->assertEquals('id = :id', $query->having); - $this->assertEquals(array(':id' => 1), $query->params); + $this->assertEquals([':id' => 1], $query->params); - $query->andHaving('name = :name', array(':name' => 'something')); - $this->assertEquals(array('and', 'id = :id', 'name = :name'), $query->having); - $this->assertEquals(array(':id' => 1, ':name' => 'something'), $query->params); + $query->andHaving('name = :name', [':name' => 'something']); + $this->assertEquals(['and', 'id = :id', 'name = :name'], $query->having); + $this->assertEquals([':id' => 1, ':name' => 'something'], $query->params); - $query->orHaving('age = :age', array(':age' => '30')); - $this->assertEquals(array('or', array('and', 'id = :id', 'name = :name'), 'age = :age'), $query->having); - $this->assertEquals(array(':id' => 1, ':name' => 'something', ':age' => '30'), $query->params); + $query->orHaving('age = :age', [':age' => '30']); + $this->assertEquals(['or', ['and', 'id = :id', 'name = :name'], 'age = :age'], $query->having); + $this->assertEquals([':id' => 1, ':name' => 'something', ':age' => '30'], $query->params); } public function testOrder() { $query = new Query; $query->orderBy('team'); - $this->assertEquals(array('team' => false), $query->orderBy); + $this->assertEquals(['team' => false], $query->orderBy); $query->addOrderBy('company'); - $this->assertEquals(array('team' => false, 'company' => false), $query->orderBy); + $this->assertEquals(['team' => false, 'company' => false], $query->orderBy); $query->addOrderBy('age'); - $this->assertEquals(array('team' => false, 'company' => false, 'age' => false), $query->orderBy); + $this->assertEquals(['team' => false, 'company' => false, 'age' => false], $query->orderBy); - $query->addOrderBy(array('age' => true)); - $this->assertEquals(array('team' => false, 'company' => false, 'age' => true), $query->orderBy); + $query->addOrderBy(['age' => true]); + $this->assertEquals(['team' => false, 'company' => false, 'age' => true], $query->orderBy); $query->addOrderBy('age ASC, company DESC'); - $this->assertEquals(array('team' => false, 'company' => true, 'age' => false), $query->orderBy); + $this->assertEquals(['team' => false, 'company' => true, 'age' => false], $query->orderBy); } public function testLimitOffset() diff --git a/tests/unit/framework/db/SchemaTest.php b/tests/unit/framework/db/SchemaTest.php index d3cb2fd..3727737 100644 --- a/tests/unit/framework/db/SchemaTest.php +++ b/tests/unit/framework/db/SchemaTest.php @@ -70,17 +70,17 @@ class SchemaTest extends DatabaseTestCase public function testGetPDOType() { - $values = array( - array(null, \PDO::PARAM_NULL), - array('', \PDO::PARAM_STR), - array('hello', \PDO::PARAM_STR), - array(0, \PDO::PARAM_INT), - array(1, \PDO::PARAM_INT), - array(1337, \PDO::PARAM_INT), - array(true, \PDO::PARAM_BOOL), - array(false, \PDO::PARAM_BOOL), - array($fp=fopen(__FILE__, 'rb'), \PDO::PARAM_LOB), - ); + $values = [ + [null, \PDO::PARAM_NULL], + ['', \PDO::PARAM_STR], + ['hello', \PDO::PARAM_STR], + [0, \PDO::PARAM_INT], + [1, \PDO::PARAM_INT], + [1337, \PDO::PARAM_INT], + [true, \PDO::PARAM_BOOL], + [false, \PDO::PARAM_BOOL], + [$fp=fopen(__FILE__, 'rb'), \PDO::PARAM_LOB], + ]; /** @var Schema $schema */ $schema = $this->getConnection()->schema; diff --git a/tests/unit/framework/db/cubrid/CubridActiveRecordTest.php b/tests/unit/framework/db/cubrid/CubridActiveRecordTest.php index 49f9bc0..9fb9915 100644 --- a/tests/unit/framework/db/cubrid/CubridActiveRecordTest.php +++ b/tests/unit/framework/db/cubrid/CubridActiveRecordTest.php @@ -33,10 +33,10 @@ class CubridActiveRecordTest extends ActiveRecordTest $customer->refresh(); $this->assertEquals(0, $customer->status); - $customers = Customer::find()->where(array('status' => true))->all(); + $customers = Customer::find()->where(['status' => true])->all(); $this->assertEquals(2, count($customers)); - $customers = Customer::find()->where(array('status' => false))->all(); + $customers = Customer::find()->where(['status' => false])->all(); $this->assertEquals(1, count($customers)); } } diff --git a/tests/unit/framework/db/cubrid/CubridQueryBuilderTest.php b/tests/unit/framework/db/cubrid/CubridQueryBuilderTest.php index 107b73b..a2e1135 100644 --- a/tests/unit/framework/db/cubrid/CubridQueryBuilderTest.php +++ b/tests/unit/framework/db/cubrid/CubridQueryBuilderTest.php @@ -20,65 +20,65 @@ class CubridQueryBuilderTest extends QueryBuilderTest */ public function columnTypes() { - return array( - array(Schema::TYPE_PK, 'int NOT NULL AUTO_INCREMENT PRIMARY KEY'), - array(Schema::TYPE_PK . '(8)', 'int NOT NULL AUTO_INCREMENT PRIMARY KEY'), - array(Schema::TYPE_PK . ' CHECK (value > 5)', 'int NOT NULL AUTO_INCREMENT PRIMARY KEY CHECK (value > 5)'), - array(Schema::TYPE_PK . '(8) CHECK (value > 5)', 'int NOT NULL AUTO_INCREMENT PRIMARY KEY CHECK (value > 5)'), - array(Schema::TYPE_STRING, 'varchar(255)'), - array(Schema::TYPE_STRING . '(32)', 'varchar(32)'), - array(Schema::TYPE_STRING . ' CHECK (value LIKE "test%")', 'varchar(255) CHECK (value LIKE "test%")'), - array(Schema::TYPE_STRING . '(32) CHECK (value LIKE "test%")', 'varchar(32) CHECK (value LIKE "test%")'), - array(Schema::TYPE_STRING . ' NOT NULL', 'varchar(255) NOT NULL'), - array(Schema::TYPE_TEXT, 'varchar'), - array(Schema::TYPE_TEXT . '(255)', 'varchar'), - array(Schema::TYPE_TEXT . ' CHECK (value LIKE "test%")', 'varchar CHECK (value LIKE "test%")'), - array(Schema::TYPE_TEXT . '(255) CHECK (value LIKE "test%")', 'varchar CHECK (value LIKE "test%")'), - array(Schema::TYPE_TEXT . ' NOT NULL', 'varchar NOT NULL'), - array(Schema::TYPE_TEXT . '(255) NOT NULL', 'varchar NOT NULL'), - array(Schema::TYPE_SMALLINT, 'smallint'), - array(Schema::TYPE_SMALLINT . '(8)', 'smallint'), - array(Schema::TYPE_INTEGER, 'int'), - array(Schema::TYPE_INTEGER . '(8)', 'int'), - array(Schema::TYPE_INTEGER . ' CHECK (value > 5)', 'int CHECK (value > 5)'), - array(Schema::TYPE_INTEGER . '(8) CHECK (value > 5)', 'int CHECK (value > 5)'), - array(Schema::TYPE_INTEGER . ' NOT NULL', 'int NOT NULL'), - array(Schema::TYPE_BIGINT, 'bigint'), - array(Schema::TYPE_BIGINT . '(8)', 'bigint'), - array(Schema::TYPE_BIGINT . ' CHECK (value > 5)', 'bigint CHECK (value > 5)'), - array(Schema::TYPE_BIGINT . '(8) CHECK (value > 5)', 'bigint CHECK (value > 5)'), - array(Schema::TYPE_BIGINT . ' NOT NULL', 'bigint NOT NULL'), - array(Schema::TYPE_FLOAT, 'float(7)'), - array(Schema::TYPE_FLOAT . '(16)', 'float(16)'), - array(Schema::TYPE_FLOAT . ' CHECK (value > 5.6)', 'float(7) CHECK (value > 5.6)'), - array(Schema::TYPE_FLOAT . '(16) CHECK (value > 5.6)', 'float(16) CHECK (value > 5.6)'), - array(Schema::TYPE_FLOAT . ' NOT NULL', 'float(7) NOT NULL'), - array(Schema::TYPE_DECIMAL, 'decimal(10,0)'), - array(Schema::TYPE_DECIMAL . '(12,4)', 'decimal(12,4)'), - array(Schema::TYPE_DECIMAL . ' CHECK (value > 5.6)', 'decimal(10,0) CHECK (value > 5.6)'), - array(Schema::TYPE_DECIMAL . '(12,4) CHECK (value > 5.6)', 'decimal(12,4) CHECK (value > 5.6)'), - array(Schema::TYPE_DECIMAL . ' NOT NULL', 'decimal(10,0) NOT NULL'), - array(Schema::TYPE_DATETIME, 'datetime'), - array(Schema::TYPE_DATETIME . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "datetime CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"), - array(Schema::TYPE_DATETIME . ' NOT NULL', 'datetime NOT NULL'), - array(Schema::TYPE_TIMESTAMP, 'timestamp'), - array(Schema::TYPE_TIMESTAMP . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "timestamp CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"), - array(Schema::TYPE_TIMESTAMP . ' NOT NULL', 'timestamp NOT NULL'), - array(Schema::TYPE_TIME, 'time'), - array(Schema::TYPE_TIME . " CHECK(value BETWEEN '12:00:00' AND '13:01:01')", "time CHECK(value BETWEEN '12:00:00' AND '13:01:01')"), - array(Schema::TYPE_TIME . ' NOT NULL', 'time NOT NULL'), - array(Schema::TYPE_DATE, 'date'), - array(Schema::TYPE_DATE . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "date CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"), - array(Schema::TYPE_DATE . ' NOT NULL', 'date NOT NULL'), - array(Schema::TYPE_BINARY, 'blob'), - array(Schema::TYPE_BOOLEAN, 'smallint'), - array(Schema::TYPE_BOOLEAN . ' NOT NULL DEFAULT 1', 'smallint NOT NULL DEFAULT 1'), - array(Schema::TYPE_MONEY, 'decimal(19,4)'), - array(Schema::TYPE_MONEY . '(16,2)', 'decimal(16,2)'), - array(Schema::TYPE_MONEY . ' CHECK (value > 0.0)', 'decimal(19,4) CHECK (value > 0.0)'), - array(Schema::TYPE_MONEY . '(16,2) CHECK (value > 0.0)', 'decimal(16,2) CHECK (value > 0.0)'), - array(Schema::TYPE_MONEY . ' NOT NULL', 'decimal(19,4) NOT NULL'), - ); + return [ + [Schema::TYPE_PK, 'int NOT NULL AUTO_INCREMENT PRIMARY KEY'], + [Schema::TYPE_PK . '(8)', 'int NOT NULL AUTO_INCREMENT PRIMARY KEY'], + [Schema::TYPE_PK . ' CHECK (value > 5)', 'int NOT NULL AUTO_INCREMENT PRIMARY KEY CHECK (value > 5)'], + [Schema::TYPE_PK . '(8) CHECK (value > 5)', 'int NOT NULL AUTO_INCREMENT PRIMARY KEY CHECK (value > 5)'], + [Schema::TYPE_STRING, 'varchar(255)'], + [Schema::TYPE_STRING . '(32)', 'varchar(32)'], + [Schema::TYPE_STRING . ' CHECK (value LIKE "test%")', 'varchar(255) CHECK (value LIKE "test%")'], + [Schema::TYPE_STRING . '(32) CHECK (value LIKE "test%")', 'varchar(32) CHECK (value LIKE "test%")'], + [Schema::TYPE_STRING . ' NOT NULL', 'varchar(255) NOT NULL'], + [Schema::TYPE_TEXT, 'varchar'], + [Schema::TYPE_TEXT . '(255)', 'varchar'], + [Schema::TYPE_TEXT . ' CHECK (value LIKE "test%")', 'varchar CHECK (value LIKE "test%")'], + [Schema::TYPE_TEXT . '(255) CHECK (value LIKE "test%")', 'varchar CHECK (value LIKE "test%")'], + [Schema::TYPE_TEXT . ' NOT NULL', 'varchar NOT NULL'], + [Schema::TYPE_TEXT . '(255) NOT NULL', 'varchar NOT NULL'], + [Schema::TYPE_SMALLINT, 'smallint'], + [Schema::TYPE_SMALLINT . '(8)', 'smallint'], + [Schema::TYPE_INTEGER, 'int'], + [Schema::TYPE_INTEGER . '(8)', 'int'], + [Schema::TYPE_INTEGER . ' CHECK (value > 5)', 'int CHECK (value > 5)'], + [Schema::TYPE_INTEGER . '(8) CHECK (value > 5)', 'int CHECK (value > 5)'], + [Schema::TYPE_INTEGER . ' NOT NULL', 'int NOT NULL'], + [Schema::TYPE_BIGINT, 'bigint'], + [Schema::TYPE_BIGINT . '(8)', 'bigint'], + [Schema::TYPE_BIGINT . ' CHECK (value > 5)', 'bigint CHECK (value > 5)'], + [Schema::TYPE_BIGINT . '(8) CHECK (value > 5)', 'bigint CHECK (value > 5)'], + [Schema::TYPE_BIGINT . ' NOT NULL', 'bigint NOT NULL'], + [Schema::TYPE_FLOAT, 'float(7)'], + [Schema::TYPE_FLOAT . '(16)', 'float(16)'], + [Schema::TYPE_FLOAT . ' CHECK (value > 5.6)', 'float(7) CHECK (value > 5.6)'], + [Schema::TYPE_FLOAT . '(16) CHECK (value > 5.6)', 'float(16) CHECK (value > 5.6)'], + [Schema::TYPE_FLOAT . ' NOT NULL', 'float(7) NOT NULL'], + [Schema::TYPE_DECIMAL, 'decimal(10,0)'], + [Schema::TYPE_DECIMAL . '(12,4)', 'decimal(12,4)'], + [Schema::TYPE_DECIMAL . ' CHECK (value > 5.6)', 'decimal(10,0) CHECK (value > 5.6)'], + [Schema::TYPE_DECIMAL . '(12,4) CHECK (value > 5.6)', 'decimal(12,4) CHECK (value > 5.6)'], + [Schema::TYPE_DECIMAL . ' NOT NULL', 'decimal(10,0) NOT NULL'], + [Schema::TYPE_DATETIME, 'datetime'], + [Schema::TYPE_DATETIME . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "datetime CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"], + [Schema::TYPE_DATETIME . ' NOT NULL', 'datetime NOT NULL'], + [Schema::TYPE_TIMESTAMP, 'timestamp'], + [Schema::TYPE_TIMESTAMP . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "timestamp CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"], + [Schema::TYPE_TIMESTAMP . ' NOT NULL', 'timestamp NOT NULL'], + [Schema::TYPE_TIME, 'time'], + [Schema::TYPE_TIME . " CHECK(value BETWEEN '12:00:00' AND '13:01:01')", "time CHECK(value BETWEEN '12:00:00' AND '13:01:01')"], + [Schema::TYPE_TIME . ' NOT NULL', 'time NOT NULL'], + [Schema::TYPE_DATE, 'date'], + [Schema::TYPE_DATE . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "date CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"], + [Schema::TYPE_DATE . ' NOT NULL', 'date NOT NULL'], + [Schema::TYPE_BINARY, 'blob'], + [Schema::TYPE_BOOLEAN, 'smallint'], + [Schema::TYPE_BOOLEAN . ' NOT NULL DEFAULT 1', 'smallint NOT NULL DEFAULT 1'], + [Schema::TYPE_MONEY, 'decimal(19,4)'], + [Schema::TYPE_MONEY . '(16,2)', 'decimal(16,2)'], + [Schema::TYPE_MONEY . ' CHECK (value > 0.0)', 'decimal(19,4) CHECK (value > 0.0)'], + [Schema::TYPE_MONEY . '(16,2) CHECK (value > 0.0)', 'decimal(16,2) CHECK (value > 0.0)'], + [Schema::TYPE_MONEY . ' NOT NULL', 'decimal(19,4) NOT NULL'], + ]; } } diff --git a/tests/unit/framework/db/cubrid/CubridSchemaTest.php b/tests/unit/framework/db/cubrid/CubridSchemaTest.php index cdfe3c8..41f4110 100644 --- a/tests/unit/framework/db/cubrid/CubridSchemaTest.php +++ b/tests/unit/framework/db/cubrid/CubridSchemaTest.php @@ -13,17 +13,17 @@ class CubridSchemaTest extends SchemaTest public function testGetPDOType() { - $values = array( - array(null, \PDO::PARAM_NULL), - array('', \PDO::PARAM_STR), - array('hello', \PDO::PARAM_STR), - array(0, \PDO::PARAM_INT), - array(1, \PDO::PARAM_INT), - array(1337, \PDO::PARAM_INT), - array(true, \PDO::PARAM_INT), - array(false, \PDO::PARAM_INT), - array($fp=fopen(__FILE__, 'rb'), \PDO::PARAM_LOB), - ); + $values = [ + [null, \PDO::PARAM_NULL], + ['', \PDO::PARAM_STR], + ['hello', \PDO::PARAM_STR], + [0, \PDO::PARAM_INT], + [1, \PDO::PARAM_INT], + [1337, \PDO::PARAM_INT], + [true, \PDO::PARAM_INT], + [false, \PDO::PARAM_INT], + [$fp=fopen(__FILE__, 'rb'), \PDO::PARAM_LOB], + ]; /** @var Schema $schema */ $schema = $this->getConnection()->schema; diff --git a/tests/unit/framework/db/pgsql/PostgreSQLQueryBuilderTest.php b/tests/unit/framework/db/pgsql/PostgreSQLQueryBuilderTest.php index 3ef329e..e2a62d0 100644 --- a/tests/unit/framework/db/pgsql/PostgreSQLQueryBuilderTest.php +++ b/tests/unit/framework/db/pgsql/PostgreSQLQueryBuilderTest.php @@ -15,63 +15,63 @@ class PostgreSQLQueryBuilderTest extends QueryBuilderTest public function columnTypes() { - return array( - array(Schema::TYPE_PK, 'serial NOT NULL PRIMARY KEY'), - array(Schema::TYPE_PK . '(8)', 'serial NOT NULL PRIMARY KEY'), - array(Schema::TYPE_PK . ' CHECK (value > 5)', 'serial NOT NULL PRIMARY KEY CHECK (value > 5)'), - array(Schema::TYPE_PK . '(8) CHECK (value > 5)', 'serial NOT NULL PRIMARY KEY CHECK (value > 5)'), - array(Schema::TYPE_STRING, 'varchar(255)'), - array(Schema::TYPE_STRING . '(32)', 'varchar(32)'), - array(Schema::TYPE_STRING . ' CHECK (value LIKE "test%")', 'varchar(255) CHECK (value LIKE "test%")'), - array(Schema::TYPE_STRING . '(32) CHECK (value LIKE "test%")', 'varchar(32) CHECK (value LIKE "test%")'), - array(Schema::TYPE_STRING . ' NOT NULL', 'varchar(255) NOT NULL'), - array(Schema::TYPE_TEXT, 'text'), - array(Schema::TYPE_TEXT . '(255)', 'text'), - array(Schema::TYPE_TEXT . ' CHECK (value LIKE "test%")', 'text CHECK (value LIKE "test%")'), - array(Schema::TYPE_TEXT . '(255) CHECK (value LIKE "test%")', 'text CHECK (value LIKE "test%")'), - array(Schema::TYPE_TEXT . ' NOT NULL', 'text NOT NULL'), - array(Schema::TYPE_TEXT . '(255) NOT NULL', 'text NOT NULL'), - array(Schema::TYPE_SMALLINT, 'smallint'), - array(Schema::TYPE_SMALLINT . '(8)', 'smallint'), - array(Schema::TYPE_INTEGER, 'integer'), - array(Schema::TYPE_INTEGER . '(8)', 'integer'), - array(Schema::TYPE_INTEGER . ' CHECK (value > 5)', 'integer CHECK (value > 5)'), - array(Schema::TYPE_INTEGER . '(8) CHECK (value > 5)', 'integer CHECK (value > 5)'), - array(Schema::TYPE_INTEGER . ' NOT NULL', 'integer NOT NULL'), - array(Schema::TYPE_BIGINT, 'bigint'), - array(Schema::TYPE_BIGINT . '(8)', 'bigint'), - array(Schema::TYPE_BIGINT . ' CHECK (value > 5)', 'bigint CHECK (value > 5)'), - array(Schema::TYPE_BIGINT . '(8) CHECK (value > 5)', 'bigint CHECK (value > 5)'), - array(Schema::TYPE_BIGINT . ' NOT NULL', 'bigint NOT NULL'), - array(Schema::TYPE_FLOAT, 'double precision'), - array(Schema::TYPE_FLOAT . ' CHECK (value > 5.6)', 'double precision CHECK (value > 5.6)'), - array(Schema::TYPE_FLOAT . '(16,5) CHECK (value > 5.6)', 'double precision CHECK (value > 5.6)'), - array(Schema::TYPE_FLOAT . ' NOT NULL', 'double precision NOT NULL'), - array(Schema::TYPE_DECIMAL, 'numeric(10,0)'), - array(Schema::TYPE_DECIMAL . '(12,4)', 'numeric(12,4)'), - array(Schema::TYPE_DECIMAL . ' CHECK (value > 5.6)', 'numeric(10,0) CHECK (value > 5.6)'), - array(Schema::TYPE_DECIMAL . '(12,4) CHECK (value > 5.6)', 'numeric(12,4) CHECK (value > 5.6)'), - array(Schema::TYPE_DECIMAL . ' NOT NULL', 'numeric(10,0) NOT NULL'), - array(Schema::TYPE_DATETIME, 'timestamp'), - array(Schema::TYPE_DATETIME . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "timestamp CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"), - array(Schema::TYPE_DATETIME . ' NOT NULL', 'timestamp NOT NULL'), - array(Schema::TYPE_TIMESTAMP, 'timestamp'), - array(Schema::TYPE_TIMESTAMP . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "timestamp CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"), - array(Schema::TYPE_TIMESTAMP . ' NOT NULL', 'timestamp NOT NULL'), - array(Schema::TYPE_TIME, 'time'), - array(Schema::TYPE_TIME . " CHECK(value BETWEEN '12:00:00' AND '13:01:01')", "time CHECK(value BETWEEN '12:00:00' AND '13:01:01')"), - array(Schema::TYPE_TIME . ' NOT NULL', 'time NOT NULL'), - array(Schema::TYPE_DATE, 'date'), - array(Schema::TYPE_DATE . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "date CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"), - array(Schema::TYPE_DATE . ' NOT NULL', 'date NOT NULL'), - array(Schema::TYPE_BINARY, 'bytea'), - array(Schema::TYPE_BOOLEAN, 'boolean'), - array(Schema::TYPE_BOOLEAN . ' NOT NULL DEFAULT 1', 'boolean NOT NULL DEFAULT 1'), - array(Schema::TYPE_MONEY, 'numeric(19,4)'), - array(Schema::TYPE_MONEY . '(16,2)', 'numeric(16,2)'), - array(Schema::TYPE_MONEY . ' CHECK (value > 0.0)', 'numeric(19,4) CHECK (value > 0.0)'), - array(Schema::TYPE_MONEY . '(16,2) CHECK (value > 0.0)', 'numeric(16,2) CHECK (value > 0.0)'), - array(Schema::TYPE_MONEY . ' NOT NULL', 'numeric(19,4) NOT NULL'), - ); + return [ + [Schema::TYPE_PK, 'serial NOT NULL PRIMARY KEY'], + [Schema::TYPE_PK . '(8)', 'serial NOT NULL PRIMARY KEY'], + [Schema::TYPE_PK . ' CHECK (value > 5)', 'serial NOT NULL PRIMARY KEY CHECK (value > 5)'], + [Schema::TYPE_PK . '(8) CHECK (value > 5)', 'serial NOT NULL PRIMARY KEY CHECK (value > 5)'], + [Schema::TYPE_STRING, 'varchar(255)'], + [Schema::TYPE_STRING . '(32)', 'varchar(32)'], + [Schema::TYPE_STRING . ' CHECK (value LIKE "test%")', 'varchar(255) CHECK (value LIKE "test%")'], + [Schema::TYPE_STRING . '(32) CHECK (value LIKE "test%")', 'varchar(32) CHECK (value LIKE "test%")'], + [Schema::TYPE_STRING . ' NOT NULL', 'varchar(255) NOT NULL'], + [Schema::TYPE_TEXT, 'text'], + [Schema::TYPE_TEXT . '(255)', 'text'], + [Schema::TYPE_TEXT . ' CHECK (value LIKE "test%")', 'text CHECK (value LIKE "test%")'], + [Schema::TYPE_TEXT . '(255) CHECK (value LIKE "test%")', 'text CHECK (value LIKE "test%")'], + [Schema::TYPE_TEXT . ' NOT NULL', 'text NOT NULL'], + [Schema::TYPE_TEXT . '(255) NOT NULL', 'text NOT NULL'], + [Schema::TYPE_SMALLINT, 'smallint'], + [Schema::TYPE_SMALLINT . '(8)', 'smallint'], + [Schema::TYPE_INTEGER, 'integer'], + [Schema::TYPE_INTEGER . '(8)', 'integer'], + [Schema::TYPE_INTEGER . ' CHECK (value > 5)', 'integer CHECK (value > 5)'], + [Schema::TYPE_INTEGER . '(8) CHECK (value > 5)', 'integer CHECK (value > 5)'], + [Schema::TYPE_INTEGER . ' NOT NULL', 'integer NOT NULL'], + [Schema::TYPE_BIGINT, 'bigint'], + [Schema::TYPE_BIGINT . '(8)', 'bigint'], + [Schema::TYPE_BIGINT . ' CHECK (value > 5)', 'bigint CHECK (value > 5)'], + [Schema::TYPE_BIGINT . '(8) CHECK (value > 5)', 'bigint CHECK (value > 5)'], + [Schema::TYPE_BIGINT . ' NOT NULL', 'bigint NOT NULL'], + [Schema::TYPE_FLOAT, 'double precision'], + [Schema::TYPE_FLOAT . ' CHECK (value > 5.6)', 'double precision CHECK (value > 5.6)'], + [Schema::TYPE_FLOAT . '(16,5) CHECK (value > 5.6)', 'double precision CHECK (value > 5.6)'], + [Schema::TYPE_FLOAT . ' NOT NULL', 'double precision NOT NULL'], + [Schema::TYPE_DECIMAL, 'numeric(10,0)'], + [Schema::TYPE_DECIMAL . '(12,4)', 'numeric(12,4)'], + [Schema::TYPE_DECIMAL . ' CHECK (value > 5.6)', 'numeric(10,0) CHECK (value > 5.6)'], + [Schema::TYPE_DECIMAL . '(12,4) CHECK (value > 5.6)', 'numeric(12,4) CHECK (value > 5.6)'], + [Schema::TYPE_DECIMAL . ' NOT NULL', 'numeric(10,0) NOT NULL'], + [Schema::TYPE_DATETIME, 'timestamp'], + [Schema::TYPE_DATETIME . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "timestamp CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"], + [Schema::TYPE_DATETIME . ' NOT NULL', 'timestamp NOT NULL'], + [Schema::TYPE_TIMESTAMP, 'timestamp'], + [Schema::TYPE_TIMESTAMP . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "timestamp CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"], + [Schema::TYPE_TIMESTAMP . ' NOT NULL', 'timestamp NOT NULL'], + [Schema::TYPE_TIME, 'time'], + [Schema::TYPE_TIME . " CHECK(value BETWEEN '12:00:00' AND '13:01:01')", "time CHECK(value BETWEEN '12:00:00' AND '13:01:01')"], + [Schema::TYPE_TIME . ' NOT NULL', 'time NOT NULL'], + [Schema::TYPE_DATE, 'date'], + [Schema::TYPE_DATE . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "date CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"], + [Schema::TYPE_DATE . ' NOT NULL', 'date NOT NULL'], + [Schema::TYPE_BINARY, 'bytea'], + [Schema::TYPE_BOOLEAN, 'boolean'], + [Schema::TYPE_BOOLEAN . ' NOT NULL DEFAULT 1', 'boolean NOT NULL DEFAULT 1'], + [Schema::TYPE_MONEY, 'numeric(19,4)'], + [Schema::TYPE_MONEY . '(16,2)', 'numeric(16,2)'], + [Schema::TYPE_MONEY . ' CHECK (value > 0.0)', 'numeric(19,4) CHECK (value > 0.0)'], + [Schema::TYPE_MONEY . '(16,2) CHECK (value > 0.0)', 'numeric(16,2) CHECK (value > 0.0)'], + [Schema::TYPE_MONEY . ' NOT NULL', 'numeric(19,4) NOT NULL'], + ]; } } diff --git a/tests/unit/framework/db/sqlite/SqliteQueryBuilderTest.php b/tests/unit/framework/db/sqlite/SqliteQueryBuilderTest.php index b20acad..d7904d0 100644 --- a/tests/unit/framework/db/sqlite/SqliteQueryBuilderTest.php +++ b/tests/unit/framework/db/sqlite/SqliteQueryBuilderTest.php @@ -15,65 +15,65 @@ class SqliteQueryBuilderTest extends QueryBuilderTest public function columnTypes() { - return array( - array(Schema::TYPE_PK, 'integer PRIMARY KEY AUTOINCREMENT NOT NULL'), - array(Schema::TYPE_PK . '(8)', 'integer PRIMARY KEY AUTOINCREMENT NOT NULL'), - array(Schema::TYPE_PK . ' CHECK (value > 5)', 'integer PRIMARY KEY AUTOINCREMENT NOT NULL CHECK (value > 5)'), - array(Schema::TYPE_PK . '(8) CHECK (value > 5)', 'integer PRIMARY KEY AUTOINCREMENT NOT NULL CHECK (value > 5)'), - array(Schema::TYPE_STRING, 'varchar(255)'), - array(Schema::TYPE_STRING . '(32)', 'varchar(32)'), - array(Schema::TYPE_STRING . ' CHECK (value LIKE "test%")', 'varchar(255) CHECK (value LIKE "test%")'), - array(Schema::TYPE_STRING . '(32) CHECK (value LIKE "test%")', 'varchar(32) CHECK (value LIKE "test%")'), - array(Schema::TYPE_STRING . ' NOT NULL', 'varchar(255) NOT NULL'), - array(Schema::TYPE_TEXT, 'text'), - array(Schema::TYPE_TEXT . '(255)', 'text'), - array(Schema::TYPE_TEXT . ' CHECK (value LIKE "test%")', 'text CHECK (value LIKE "test%")'), - array(Schema::TYPE_TEXT . '(255) CHECK (value LIKE "test%")', 'text CHECK (value LIKE "test%")'), - array(Schema::TYPE_TEXT . ' NOT NULL', 'text NOT NULL'), - array(Schema::TYPE_TEXT . '(255) NOT NULL', 'text NOT NULL'), - array(Schema::TYPE_SMALLINT, 'smallint'), - array(Schema::TYPE_SMALLINT . '(8)', 'smallint'), - array(Schema::TYPE_INTEGER, 'integer'), - array(Schema::TYPE_INTEGER . '(8)', 'integer'), - array(Schema::TYPE_INTEGER . ' CHECK (value > 5)', 'integer CHECK (value > 5)'), - array(Schema::TYPE_INTEGER . '(8) CHECK (value > 5)', 'integer CHECK (value > 5)'), - array(Schema::TYPE_INTEGER . ' NOT NULL', 'integer NOT NULL'), - array(Schema::TYPE_BIGINT, 'bigint'), - array(Schema::TYPE_BIGINT . '(8)', 'bigint'), - array(Schema::TYPE_BIGINT . ' CHECK (value > 5)', 'bigint CHECK (value > 5)'), - array(Schema::TYPE_BIGINT . '(8) CHECK (value > 5)', 'bigint CHECK (value > 5)'), - array(Schema::TYPE_BIGINT . ' NOT NULL', 'bigint NOT NULL'), - array(Schema::TYPE_FLOAT, 'float'), - array(Schema::TYPE_FLOAT . '(16,5)', 'float'), - array(Schema::TYPE_FLOAT . ' CHECK (value > 5.6)', 'float CHECK (value > 5.6)'), - array(Schema::TYPE_FLOAT . '(16,5) CHECK (value > 5.6)', 'float CHECK (value > 5.6)'), - array(Schema::TYPE_FLOAT . ' NOT NULL', 'float NOT NULL'), - array(Schema::TYPE_DECIMAL, 'decimal(10,0)'), - array(Schema::TYPE_DECIMAL . '(12,4)', 'decimal(12,4)'), - array(Schema::TYPE_DECIMAL . ' CHECK (value > 5.6)', 'decimal(10,0) CHECK (value > 5.6)'), - array(Schema::TYPE_DECIMAL . '(12,4) CHECK (value > 5.6)', 'decimal(12,4) CHECK (value > 5.6)'), - array(Schema::TYPE_DECIMAL . ' NOT NULL', 'decimal(10,0) NOT NULL'), - array(Schema::TYPE_DATETIME, 'datetime'), - array(Schema::TYPE_DATETIME . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "datetime CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"), - array(Schema::TYPE_DATETIME . ' NOT NULL', 'datetime NOT NULL'), - array(Schema::TYPE_TIMESTAMP, 'timestamp'), - array(Schema::TYPE_TIMESTAMP . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "timestamp CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"), - array(Schema::TYPE_TIMESTAMP . ' NOT NULL', 'timestamp NOT NULL'), - array(Schema::TYPE_TIME, 'time'), - array(Schema::TYPE_TIME . " CHECK(value BETWEEN '12:00:00' AND '13:01:01')", "time CHECK(value BETWEEN '12:00:00' AND '13:01:01')"), - array(Schema::TYPE_TIME . ' NOT NULL', 'time NOT NULL'), - array(Schema::TYPE_DATE, 'date'), - array(Schema::TYPE_DATE . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "date CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"), - array(Schema::TYPE_DATE . ' NOT NULL', 'date NOT NULL'), - array(Schema::TYPE_BINARY, 'blob'), - array(Schema::TYPE_BOOLEAN, 'boolean'), - array(Schema::TYPE_BOOLEAN . ' NOT NULL DEFAULT 1', 'boolean NOT NULL DEFAULT 1'), - array(Schema::TYPE_MONEY, 'decimal(19,4)'), - array(Schema::TYPE_MONEY . '(16,2)', 'decimal(16,2)'), - array(Schema::TYPE_MONEY . ' CHECK (value > 0.0)', 'decimal(19,4) CHECK (value > 0.0)'), - array(Schema::TYPE_MONEY . '(16,2) CHECK (value > 0.0)', 'decimal(16,2) CHECK (value > 0.0)'), - array(Schema::TYPE_MONEY . ' NOT NULL', 'decimal(19,4) NOT NULL'), - ); + return [ + [Schema::TYPE_PK, 'integer PRIMARY KEY AUTOINCREMENT NOT NULL'], + [Schema::TYPE_PK . '(8)', 'integer PRIMARY KEY AUTOINCREMENT NOT NULL'], + [Schema::TYPE_PK . ' CHECK (value > 5)', 'integer PRIMARY KEY AUTOINCREMENT NOT NULL CHECK (value > 5)'], + [Schema::TYPE_PK . '(8) CHECK (value > 5)', 'integer PRIMARY KEY AUTOINCREMENT NOT NULL CHECK (value > 5)'], + [Schema::TYPE_STRING, 'varchar(255)'], + [Schema::TYPE_STRING . '(32)', 'varchar(32)'], + [Schema::TYPE_STRING . ' CHECK (value LIKE "test%")', 'varchar(255) CHECK (value LIKE "test%")'], + [Schema::TYPE_STRING . '(32) CHECK (value LIKE "test%")', 'varchar(32) CHECK (value LIKE "test%")'], + [Schema::TYPE_STRING . ' NOT NULL', 'varchar(255) NOT NULL'], + [Schema::TYPE_TEXT, 'text'], + [Schema::TYPE_TEXT . '(255)', 'text'], + [Schema::TYPE_TEXT . ' CHECK (value LIKE "test%")', 'text CHECK (value LIKE "test%")'], + [Schema::TYPE_TEXT . '(255) CHECK (value LIKE "test%")', 'text CHECK (value LIKE "test%")'], + [Schema::TYPE_TEXT . ' NOT NULL', 'text NOT NULL'], + [Schema::TYPE_TEXT . '(255) NOT NULL', 'text NOT NULL'], + [Schema::TYPE_SMALLINT, 'smallint'], + [Schema::TYPE_SMALLINT . '(8)', 'smallint'], + [Schema::TYPE_INTEGER, 'integer'], + [Schema::TYPE_INTEGER . '(8)', 'integer'], + [Schema::TYPE_INTEGER . ' CHECK (value > 5)', 'integer CHECK (value > 5)'], + [Schema::TYPE_INTEGER . '(8) CHECK (value > 5)', 'integer CHECK (value > 5)'], + [Schema::TYPE_INTEGER . ' NOT NULL', 'integer NOT NULL'], + [Schema::TYPE_BIGINT, 'bigint'], + [Schema::TYPE_BIGINT . '(8)', 'bigint'], + [Schema::TYPE_BIGINT . ' CHECK (value > 5)', 'bigint CHECK (value > 5)'], + [Schema::TYPE_BIGINT . '(8) CHECK (value > 5)', 'bigint CHECK (value > 5)'], + [Schema::TYPE_BIGINT . ' NOT NULL', 'bigint NOT NULL'], + [Schema::TYPE_FLOAT, 'float'], + [Schema::TYPE_FLOAT . '(16,5)', 'float'], + [Schema::TYPE_FLOAT . ' CHECK (value > 5.6)', 'float CHECK (value > 5.6)'], + [Schema::TYPE_FLOAT . '(16,5) CHECK (value > 5.6)', 'float CHECK (value > 5.6)'], + [Schema::TYPE_FLOAT . ' NOT NULL', 'float NOT NULL'], + [Schema::TYPE_DECIMAL, 'decimal(10,0)'], + [Schema::TYPE_DECIMAL . '(12,4)', 'decimal(12,4)'], + [Schema::TYPE_DECIMAL . ' CHECK (value > 5.6)', 'decimal(10,0) CHECK (value > 5.6)'], + [Schema::TYPE_DECIMAL . '(12,4) CHECK (value > 5.6)', 'decimal(12,4) CHECK (value > 5.6)'], + [Schema::TYPE_DECIMAL . ' NOT NULL', 'decimal(10,0) NOT NULL'], + [Schema::TYPE_DATETIME, 'datetime'], + [Schema::TYPE_DATETIME . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "datetime CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"], + [Schema::TYPE_DATETIME . ' NOT NULL', 'datetime NOT NULL'], + [Schema::TYPE_TIMESTAMP, 'timestamp'], + [Schema::TYPE_TIMESTAMP . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "timestamp CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"], + [Schema::TYPE_TIMESTAMP . ' NOT NULL', 'timestamp NOT NULL'], + [Schema::TYPE_TIME, 'time'], + [Schema::TYPE_TIME . " CHECK(value BETWEEN '12:00:00' AND '13:01:01')", "time CHECK(value BETWEEN '12:00:00' AND '13:01:01')"], + [Schema::TYPE_TIME . ' NOT NULL', 'time NOT NULL'], + [Schema::TYPE_DATE, 'date'], + [Schema::TYPE_DATE . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "date CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"], + [Schema::TYPE_DATE . ' NOT NULL', 'date NOT NULL'], + [Schema::TYPE_BINARY, 'blob'], + [Schema::TYPE_BOOLEAN, 'boolean'], + [Schema::TYPE_BOOLEAN . ' NOT NULL DEFAULT 1', 'boolean NOT NULL DEFAULT 1'], + [Schema::TYPE_MONEY, 'decimal(19,4)'], + [Schema::TYPE_MONEY . '(16,2)', 'decimal(16,2)'], + [Schema::TYPE_MONEY . ' CHECK (value > 0.0)', 'decimal(19,4) CHECK (value > 0.0)'], + [Schema::TYPE_MONEY . '(16,2) CHECK (value > 0.0)', 'decimal(16,2) CHECK (value > 0.0)'], + [Schema::TYPE_MONEY . ' NOT NULL', 'decimal(19,4) NOT NULL'], + ]; } public function testAddDropPrimaryKey() diff --git a/tests/unit/framework/helpers/ArrayHelperTest.php b/tests/unit/framework/helpers/ArrayHelperTest.php index ca8c95a..159e41c 100644 --- a/tests/unit/framework/helpers/ArrayHelperTest.php +++ b/tests/unit/framework/helpers/ArrayHelperTest.php @@ -49,47 +49,48 @@ class ArrayHelperTest extends TestCase $object1 = new Post1; $object2 = new Post2; - $this->assertEquals(array( + $this->assertEquals([ get_object_vars($object1), get_object_vars($object2), - ), ArrayHelper::toArray(array( + ], ArrayHelper::toArray([ $object1, $object2, - ))); + ])); $object = new Post2; - $this->assertEquals(array( + $this->assertEquals([ 'id' => 123, 'secret' => 's', '_content' => 'test', 'length' => 4, - ), ArrayHelper::toArray($object, array( - $object->className() => array( + ], ArrayHelper::toArray($object, [ + $object->className() => [ 'id', 'secret', '_content' => 'content', 'length' => function ($post) { return strlen($post->content); } - )))); + ] + ])); $object = new Post3(); - $this->assertEquals(get_object_vars($object), ArrayHelper::toArray($object, array(), false)); - $this->assertEquals(array( + $this->assertEquals(get_object_vars($object), ArrayHelper::toArray($object, [], false)); + $this->assertEquals([ 'id' => 33, - 'subObject' => array( + 'subObject' => [ 'id' => 123, 'content' => 'test', - ), - ), ArrayHelper::toArray($object)); + ], + ], ArrayHelper::toArray($object)); } public function testRemove() { - $array = array('name' => 'b', 'age' => 3); + $array = ['name' => 'b', 'age' => 3]; $name = ArrayHelper::remove($array, 'name'); $this->assertEquals($name, 'b'); - $this->assertEquals($array, array('age' => 3)); + $this->assertEquals($array, ['age' => 3]); $default = ArrayHelper::remove($array, 'nonExisting', 'defaultValue'); $this->assertEquals('defaultValue', $default); @@ -99,201 +100,201 @@ class ArrayHelperTest extends TestCase public function testMultisort() { // single key - $array = array( - array('name' => 'b', 'age' => 3), - array('name' => 'a', 'age' => 1), - array('name' => 'c', 'age' => 2), - ); + $array = [ + ['name' => 'b', 'age' => 3], + ['name' => 'a', 'age' => 1], + ['name' => 'c', 'age' => 2], + ]; ArrayHelper::multisort($array, 'name'); - $this->assertEquals(array('name' => 'a', 'age' => 1), $array[0]); - $this->assertEquals(array('name' => 'b', 'age' => 3), $array[1]); - $this->assertEquals(array('name' => 'c', 'age' => 2), $array[2]); + $this->assertEquals(['name' => 'a', 'age' => 1], $array[0]); + $this->assertEquals(['name' => 'b', 'age' => 3], $array[1]); + $this->assertEquals(['name' => 'c', 'age' => 2], $array[2]); // multiple keys - $array = array( - array('name' => 'b', 'age' => 3), - array('name' => 'a', 'age' => 2), - array('name' => 'a', 'age' => 1), - ); - ArrayHelper::multisort($array, array('name', 'age')); - $this->assertEquals(array('name' => 'a', 'age' => 1), $array[0]); - $this->assertEquals(array('name' => 'a', 'age' => 2), $array[1]); - $this->assertEquals(array('name' => 'b', 'age' => 3), $array[2]); + $array = [ + ['name' => 'b', 'age' => 3], + ['name' => 'a', 'age' => 2], + ['name' => 'a', 'age' => 1], + ]; + ArrayHelper::multisort($array, ['name', 'age']); + $this->assertEquals(['name' => 'a', 'age' => 1], $array[0]); + $this->assertEquals(['name' => 'a', 'age' => 2], $array[1]); + $this->assertEquals(['name' => 'b', 'age' => 3], $array[2]); // case-insensitive - $array = array( - array('name' => 'a', 'age' => 3), - array('name' => 'b', 'age' => 2), - array('name' => 'B', 'age' => 4), - array('name' => 'A', 'age' => 1), - ); - - ArrayHelper::multisort($array, array('name', 'age'), false, array(SORT_STRING, SORT_REGULAR)); - $this->assertEquals(array('name' => 'A', 'age' => 1), $array[0]); - $this->assertEquals(array('name' => 'B', 'age' => 4), $array[1]); - $this->assertEquals(array('name' => 'a', 'age' => 3), $array[2]); - $this->assertEquals(array('name' => 'b', 'age' => 2), $array[3]); - - ArrayHelper::multisort($array, array('name', 'age'), false, array(SORT_STRING, SORT_REGULAR), false); - $this->assertEquals(array('name' => 'A', 'age' => 1), $array[0]); - $this->assertEquals(array('name' => 'a', 'age' => 3), $array[1]); - $this->assertEquals(array('name' => 'b', 'age' => 2), $array[2]); - $this->assertEquals(array('name' => 'B', 'age' => 4), $array[3]); + $array = [ + ['name' => 'a', 'age' => 3], + ['name' => 'b', 'age' => 2], + ['name' => 'B', 'age' => 4], + ['name' => 'A', 'age' => 1], + ]; + + ArrayHelper::multisort($array, ['name', 'age'], false, [SORT_STRING, SORT_REGULAR]); + $this->assertEquals(['name' => 'A', 'age' => 1], $array[0]); + $this->assertEquals(['name' => 'B', 'age' => 4], $array[1]); + $this->assertEquals(['name' => 'a', 'age' => 3], $array[2]); + $this->assertEquals(['name' => 'b', 'age' => 2], $array[3]); + + ArrayHelper::multisort($array, ['name', 'age'], false, [SORT_STRING, SORT_REGULAR], false); + $this->assertEquals(['name' => 'A', 'age' => 1], $array[0]); + $this->assertEquals(['name' => 'a', 'age' => 3], $array[1]); + $this->assertEquals(['name' => 'b', 'age' => 2], $array[2]); + $this->assertEquals(['name' => 'B', 'age' => 4], $array[3]); } public function testMultisortUseSort() { // single key - $sort = new Sort(array( - 'attributes' => array('name', 'age'), - 'defaultOrder' => array('name' => Sort::ASC), - )); + $sort = new Sort([ + 'attributes' => ['name', 'age'], + 'defaultOrder' => ['name' => Sort::ASC], + ]); $orders = $sort->getOrders(); - $array = array( - array('name' => 'b', 'age' => 3), - array('name' => 'a', 'age' => 1), - array('name' => 'c', 'age' => 2), - ); + $array = [ + ['name' => 'b', 'age' => 3], + ['name' => 'a', 'age' => 1], + ['name' => 'c', 'age' => 2], + ]; ArrayHelper::multisort($array, array_keys($orders), array_values($orders)); - $this->assertEquals(array('name' => 'a', 'age' => 1), $array[0]); - $this->assertEquals(array('name' => 'b', 'age' => 3), $array[1]); - $this->assertEquals(array('name' => 'c', 'age' => 2), $array[2]); + $this->assertEquals(['name' => 'a', 'age' => 1], $array[0]); + $this->assertEquals(['name' => 'b', 'age' => 3], $array[1]); + $this->assertEquals(['name' => 'c', 'age' => 2], $array[2]); // multiple keys - $sort = new Sort(array( - 'attributes' => array('name', 'age'), - 'defaultOrder' => array('name' => Sort::ASC, 'age' => Sort::DESC), - )); + $sort = new Sort([ + 'attributes' => ['name', 'age'], + 'defaultOrder' => ['name' => Sort::ASC, 'age' => Sort::DESC], + ]); $orders = $sort->getOrders(); - $array = array( - array('name' => 'b', 'age' => 3), - array('name' => 'a', 'age' => 2), - array('name' => 'a', 'age' => 1), - ); + $array = [ + ['name' => 'b', 'age' => 3], + ['name' => 'a', 'age' => 2], + ['name' => 'a', 'age' => 1], + ]; ArrayHelper::multisort($array, array_keys($orders), array_values($orders)); - $this->assertEquals(array('name' => 'a', 'age' => 2), $array[0]); - $this->assertEquals(array('name' => 'a', 'age' => 1), $array[1]); - $this->assertEquals(array('name' => 'b', 'age' => 3), $array[2]); + $this->assertEquals(['name' => 'a', 'age' => 2], $array[0]); + $this->assertEquals(['name' => 'a', 'age' => 1], $array[1]); + $this->assertEquals(['name' => 'b', 'age' => 3], $array[2]); } public function testMerge() { - $a = array( + $a = [ 'name' => 'Yii', 'version' => '1.0', - 'options' => array( + 'options' => [ 'namespace' => false, 'unittest' => false, - ), - 'features' => array( + ], + 'features' => [ 'mvc', - ), - ); - $b = array( + ], + ]; + $b = [ 'version' => '1.1', - 'options' => array( + 'options' => [ 'unittest' => true, - ), - 'features' => array( + ], + 'features' => [ 'gii', - ), - ); - $c = array( + ], + ]; + $c = [ 'version' => '2.0', - 'options' => array( + 'options' => [ 'namespace' => true, - ), - 'features' => array( + ], + 'features' => [ 'debug', - ), - ); + ], + ]; $result = ArrayHelper::merge($a, $b, $c); - $expected = array( + $expected = [ 'name' => 'Yii', 'version' => '2.0', - 'options' => array( + 'options' => [ 'namespace' => true, 'unittest' => true, - ), - 'features' => array( + ], + 'features' => [ 'mvc', 'gii', 'debug', - ), - ); + ], + ]; $this->assertEquals($expected, $result); } public function testIndex() { - $array = array( - array('id' => '123', 'data' => 'abc'), - array('id' => '345', 'data' => 'def'), - ); + $array = [ + ['id' => '123', 'data' => 'abc'], + ['id' => '345', 'data' => 'def'], + ]; $result = ArrayHelper::index($array, 'id'); - $this->assertEquals(array( - '123' => array('id' => '123', 'data' => 'abc'), - '345' => array('id' => '345', 'data' => 'def'), - ), $result); + $this->assertEquals([ + '123' => ['id' => '123', 'data' => 'abc'], + '345' => ['id' => '345', 'data' => 'def'], + ], $result); $result = ArrayHelper::index($array, function ($element) { return $element['data']; }); - $this->assertEquals(array( - 'abc' => array('id' => '123', 'data' => 'abc'), - 'def' => array('id' => '345', 'data' => 'def'), - ), $result); + $this->assertEquals([ + 'abc' => ['id' => '123', 'data' => 'abc'], + 'def' => ['id' => '345', 'data' => 'def'], + ], $result); } public function testGetColumn() { - $array = array( - 'a' => array('id' => '123', 'data' => 'abc'), - 'b' => array('id' => '345', 'data' => 'def'), - ); + $array = [ + 'a' => ['id' => '123', 'data' => 'abc'], + 'b' => ['id' => '345', 'data' => 'def'], + ]; $result = ArrayHelper::getColumn($array, 'id'); - $this->assertEquals(array('a' => '123', 'b' => '345'), $result); + $this->assertEquals(['a' => '123', 'b' => '345'], $result); $result = ArrayHelper::getColumn($array, 'id', false); - $this->assertEquals(array('123', '345'), $result); + $this->assertEquals(['123', '345'], $result); $result = ArrayHelper::getColumn($array, function ($element) { return $element['data']; }); - $this->assertEquals(array('a' => 'abc', 'b' => 'def'), $result); + $this->assertEquals(['a' => 'abc', 'b' => 'def'], $result); $result = ArrayHelper::getColumn($array, function ($element) { return $element['data']; }, false); - $this->assertEquals(array('abc', 'def'), $result); + $this->assertEquals(['abc', 'def'], $result); } public function testMap() { - $array = array( - array('id' => '123', 'name' => 'aaa', 'class' => 'x'), - array('id' => '124', 'name' => 'bbb', 'class' => 'x'), - array('id' => '345', 'name' => 'ccc', 'class' => 'y'), - ); + $array = [ + ['id' => '123', 'name' => 'aaa', 'class' => 'x'], + ['id' => '124', 'name' => 'bbb', 'class' => 'x'], + ['id' => '345', 'name' => 'ccc', 'class' => 'y'], + ]; $result = ArrayHelper::map($array, 'id', 'name'); - $this->assertEquals(array( + $this->assertEquals([ '123' => 'aaa', '124' => 'bbb', '345' => 'ccc', - ), $result); + ], $result); $result = ArrayHelper::map($array, 'id', 'name', 'class'); - $this->assertEquals(array( - 'x' => array( + $this->assertEquals([ + 'x' => [ '123' => 'aaa', '124' => 'bbb', - ), - 'y' => array( + ], + 'y' => [ '345' => 'ccc', - ), - ), $result); + ], + ], $result); } } diff --git a/tests/unit/framework/helpers/ConsoleTest.php b/tests/unit/framework/helpers/ConsoleTest.php index 4b983f8..6775b5a 100644 --- a/tests/unit/framework/helpers/ConsoleTest.php +++ b/tests/unit/framework/helpers/ConsoleTest.php @@ -57,11 +57,11 @@ class ConsoleTest extends TestCase echo 'a'; Console::restoreCursorPosition(); echo 'a'; - Console::beginAnsiFormat(array(Console::FG_GREEN, Console::BG_BLUE, Console::UNDERLINE)); + Console::beginAnsiFormat([Console::FG_GREEN, Console::BG_BLUE, Console::UNDERLINE]); echo 'a'; Console::endAnsiFormat(); echo 'a'; - Console::beginAnsiFormat(array(Console::xtermBgColor(128), Console::xtermFgColor(55))); + Console::beginAnsiFormat([Console::xtermBgColor(128), Console::xtermFgColor(55)]); echo 'a'; Console::endAnsiFormat(); echo 'a'; diff --git a/tests/unit/framework/helpers/FileHelperTest.php b/tests/unit/framework/helpers/FileHelperTest.php index 05bd7af..3fde06e 100644 --- a/tests/unit/framework/helpers/FileHelperTest.php +++ b/tests/unit/framework/helpers/FileHelperTest.php @@ -112,13 +112,13 @@ class FileHelperTest extends TestCase public function testCopyDirectory() { $srcDirName = 'test_src_dir'; - $files = array( + $files = [ 'file1.txt' => 'file 1 content', 'file2.txt' => 'file 2 content', - ); - $this->createFileStructure(array( + ]; + $this->createFileStructure([ $srcDirName => $files - )); + ]); $basePath = $this->testFilePath; $srcDirName = $basePath . DIRECTORY_SEPARATOR . $srcDirName; @@ -146,12 +146,12 @@ class FileHelperTest extends TestCase $srcDirName = 'test_src_dir'; $subDirName = 'test_sub_dir'; $fileName = 'test_file.txt'; - $this->createFileStructure(array( - $srcDirName => array( - $subDirName => array(), + $this->createFileStructure([ + $srcDirName => [ + $subDirName => [], $fileName => 'test file content', - ), - )); + ], + ]); $basePath = $this->testFilePath; $srcDirName = $basePath . DIRECTORY_SEPARATOR . $srcDirName; @@ -159,10 +159,10 @@ class FileHelperTest extends TestCase $dirMode = 0755; $fileMode = 0755; - $options = array( + $options = [ 'dirMode' => $dirMode, 'fileMode' => $fileMode, - ); + ]; FileHelper::copyDirectory($srcDirName, $dstDirName, $options); $this->assertFileMode($dirMode, $dstDirName, 'Destination directory has wrong mode!'); @@ -173,16 +173,16 @@ class FileHelperTest extends TestCase public function testRemoveDirectory() { $dirName = 'test_dir_for_remove'; - $this->createFileStructure(array( - $dirName => array( + $this->createFileStructure([ + $dirName => [ 'file1.txt' => 'file 1 content', 'file2.txt' => 'file 2 content', - 'test_sub_dir' => array( + 'test_sub_dir' => [ 'sub_dir_file_1.txt' => 'sub dir file 1 content', 'sub_dir_file_2.txt' => 'sub dir file 2 content', - ), - ), - )); + ], + ], + ]); $basePath = $this->testFilePath; $dirName = $basePath . DIRECTORY_SEPARATOR . $dirName; @@ -198,24 +198,24 @@ class FileHelperTest extends TestCase public function testFindFiles() { $dirName = 'test_dir'; - $this->createFileStructure(array( - $dirName => array( + $this->createFileStructure([ + $dirName => [ 'file_1.txt' => 'file 1 content', 'file_2.txt' => 'file 2 content', - 'test_sub_dir' => array( + 'test_sub_dir' => [ 'file_1_1.txt' => 'sub dir file 1 content', 'file_1_2.txt' => 'sub dir file 2 content', - ), - ), - )); + ], + ], + ]); $basePath = $this->testFilePath; $dirName = $basePath . DIRECTORY_SEPARATOR . $dirName; - $expectedFiles = array( + $expectedFiles = [ $dirName . DIRECTORY_SEPARATOR . 'file_1.txt', $dirName . DIRECTORY_SEPARATOR . 'file_2.txt', $dirName . DIRECTORY_SEPARATOR . 'test_sub_dir' . DIRECTORY_SEPARATOR . 'file_1_1.txt', $dirName . DIRECTORY_SEPARATOR . 'test_sub_dir' . DIRECTORY_SEPARATOR . 'file_1_2.txt', - ); + ]; $foundFiles = FileHelper::findFiles($dirName); sort($expectedFiles); @@ -230,22 +230,22 @@ class FileHelperTest extends TestCase { $dirName = 'test_dir'; $passedFileName = 'passed.txt'; - $this->createFileStructure(array( - $dirName => array( + $this->createFileStructure([ + $dirName => [ $passedFileName => 'passed file content', 'declined.txt' => 'declined file content', - ), - )); + ], + ]); $basePath = $this->testFilePath; $dirName = $basePath . DIRECTORY_SEPARATOR . $dirName; - $options = array( + $options = [ 'filter' => function ($path) use ($passedFileName) { return $passedFileName == basename($path); } - ); + ]; $foundFiles = FileHelper::findFiles($dirName, $options); - $this->assertEquals(array($dirName . DIRECTORY_SEPARATOR . $passedFileName), $foundFiles); + $this->assertEquals([$dirName . DIRECTORY_SEPARATOR . $passedFileName], $foundFiles); } /** @@ -256,20 +256,20 @@ class FileHelperTest extends TestCase $dirName = 'test_dir'; $fileName = 'test_file.txt'; $excludeFileName = 'exclude_file.txt'; - $this->createFileStructure(array( - $dirName => array( + $this->createFileStructure([ + $dirName => [ $fileName => 'file content', $excludeFileName => 'exclude file content', - ), - )); + ], + ]); $basePath = $this->testFilePath; $dirName = $basePath . DIRECTORY_SEPARATOR . $dirName; - $options = array( - 'except' => array($excludeFileName), - ); + $options = [ + 'except' => [$excludeFileName], + ]; $foundFiles = FileHelper::findFiles($dirName, $options); - $this->assertEquals(array($dirName . DIRECTORY_SEPARATOR . $fileName), $foundFiles); + $this->assertEquals([$dirName . DIRECTORY_SEPARATOR . $fileName], $foundFiles); } public function testCreateDirectory() @@ -284,10 +284,10 @@ class FileHelperTest extends TestCase public function testGetMimeTypeByExtension() { $magicFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'mime_type.php'; - $mimeTypeMap = array( + $mimeTypeMap = [ 'txa' => 'application/json', 'txb' => 'another/mime', - ); + ]; $magicFileContent = 'mockApplication(array( - 'components' => array( - 'request' => array( + $this->mockApplication([ + 'components' => [ + 'request' => [ 'class' => 'yii\web\Request', 'url' => '/test', 'enableCsrfValidation' => false, - ), - 'response' => array( + ], + 'response' => [ 'class' => 'yii\web\Response', - ), - ), - )); + ], + ], + ]); } public function assertEqualsWithoutLE($expected, $actual) @@ -51,14 +51,14 @@ class HtmlTest extends TestCase $this->assertEquals('
    ', Html::tag('br')); $this->assertEquals('', Html::tag('span')); $this->assertEquals('
    content
    ', Html::tag('div', 'content')); - $this->assertEquals('', Html::tag('input', '', array('type' => 'text', 'name' => 'test', 'value' => '<>'))); - $this->assertEquals('', Html::tag('span', '', array('disabled' => true))); + $this->assertEquals('', Html::tag('input', '', ['type' => 'text', 'name' => 'test', 'value' => '<>'])); + $this->assertEquals('', Html::tag('span', '', ['disabled' => true])); } public function testBeginTag() { $this->assertEquals('
    ', Html::beginTag('br')); - $this->assertEquals('', Html::beginTag('span', array('id' => 'test', 'class' => 'title'))); + $this->assertEquals('', Html::beginTag('span', ['id' => 'test', 'class' => 'title'])); } public function testEndTag() @@ -71,14 +71,14 @@ class HtmlTest extends TestCase { $content = 'a <>'; $this->assertEquals("", Html::style($content)); - $this->assertEquals("", Html::style($content, array('type' => 'text/less'))); + $this->assertEquals("", Html::style($content, ['type' => 'text/less'])); } public function testScript() { $content = 'a <>'; $this->assertEquals("", Html::script($content)); - $this->assertEquals("", Html::script($content, array('type' => 'text/js'))); + $this->assertEquals("", Html::script($content, ['type' => 'text/js'])); } public function testCssFile() @@ -97,10 +97,10 @@ class HtmlTest extends TestCase { $this->assertEquals('
    ', Html::beginForm()); $this->assertEquals('', Html::beginForm('/example', 'get')); - $hiddens = array( + $hiddens = [ '', '', - ); + ]; $this->assertEquals('' . "\n" . implode("\n", $hiddens), Html::beginForm('/example?id=1&title=%3C', 'get')); } @@ -126,127 +126,127 @@ class HtmlTest extends TestCase { $this->assertEquals('', Html::img('/example')); $this->assertEquals('', Html::img('')); - $this->assertEquals('something', Html::img('/example', array('alt' => 'something', 'width' => 10))); + $this->assertEquals('something', Html::img('/example', ['alt' => 'something', 'width' => 10])); } public function testLabel() { $this->assertEquals('', Html::label('something<>')); $this->assertEquals('', Html::label('something<>', 'a')); - $this->assertEquals('', Html::label('something<>', 'a', array('class' => 'test'))); + $this->assertEquals('', Html::label('something<>', 'a', ['class' => 'test'])); } public function testButton() { $this->assertEquals('', Html::button()); - $this->assertEquals('', Html::button('content<>', array('name' => 'test', 'value' => 'value'))); - $this->assertEquals('', Html::button('content<>', array('type' => 'submit', 'name' => 'test', 'value' => 'value', 'class' => "t"))); + $this->assertEquals('', Html::button('content<>', ['name' => 'test', 'value' => 'value'])); + $this->assertEquals('', Html::button('content<>', ['type' => 'submit', 'name' => 'test', 'value' => 'value', 'class' => "t"])); } public function testSubmitButton() { $this->assertEquals('', Html::submitButton()); - $this->assertEquals('', Html::submitButton('content<>', array('name' => 'test', 'value' => 'value', 'class' => 't'))); + $this->assertEquals('', Html::submitButton('content<>', ['name' => 'test', 'value' => 'value', 'class' => 't'])); } public function testResetButton() { $this->assertEquals('', Html::resetButton()); - $this->assertEquals('', Html::resetButton('content<>', array('name' => 'test', 'value' => 'value', 'class' => 't'))); + $this->assertEquals('', Html::resetButton('content<>', ['name' => 'test', 'value' => 'value', 'class' => 't'])); } public function testInput() { $this->assertEquals('', Html::input('text')); - $this->assertEquals('', Html::input('text', 'test', 'value', array('class' => 't'))); + $this->assertEquals('', Html::input('text', 'test', 'value', ['class' => 't'])); } public function testButtonInput() { $this->assertEquals('', Html::buttonInput()); - $this->assertEquals('', Html::buttonInput('text', array('name' => 'test', 'class' => 'a'))); + $this->assertEquals('', Html::buttonInput('text', ['name' => 'test', 'class' => 'a'])); } public function testSubmitInput() { $this->assertEquals('', Html::submitInput()); - $this->assertEquals('', Html::submitInput('text', array('name' => 'test', 'class' => 'a'))); + $this->assertEquals('', Html::submitInput('text', ['name' => 'test', 'class' => 'a'])); } public function testResetInput() { $this->assertEquals('', Html::resetInput()); - $this->assertEquals('', Html::resetInput('text', array('name' => 'test', 'class' => 'a'))); + $this->assertEquals('', Html::resetInput('text', ['name' => 'test', 'class' => 'a'])); } public function testTextInput() { $this->assertEquals('', Html::textInput('test')); - $this->assertEquals('', Html::textInput('test', 'value', array('class' => 't'))); + $this->assertEquals('', Html::textInput('test', 'value', ['class' => 't'])); } public function testHiddenInput() { $this->assertEquals('', Html::hiddenInput('test')); - $this->assertEquals('', Html::hiddenInput('test', 'value', array('class' => 't'))); + $this->assertEquals('', Html::hiddenInput('test', 'value', ['class' => 't'])); } public function testPasswordInput() { $this->assertEquals('', Html::passwordInput('test')); - $this->assertEquals('', Html::passwordInput('test', 'value', array('class' => 't'))); + $this->assertEquals('', Html::passwordInput('test', 'value', ['class' => 't'])); } public function testFileInput() { $this->assertEquals('', Html::fileInput('test')); - $this->assertEquals('', Html::fileInput('test', 'value', array('class' => 't'))); + $this->assertEquals('', Html::fileInput('test', 'value', ['class' => 't'])); } public function testTextarea() { $this->assertEquals('', Html::textarea('test')); - $this->assertEquals('', Html::textarea('test', 'value<>', array('class' => 't'))); + $this->assertEquals('', Html::textarea('test', 'value<>', ['class' => 't'])); } public function testRadio() { $this->assertEquals('', Html::radio('test')); - $this->assertEquals('', Html::radio('test', true, array('class' => 'a', 'value' => null))); - $this->assertEquals('', Html::radio('test', true, array('class' => 'a' , 'uncheck' => '0', 'value' => 2))); + $this->assertEquals('', Html::radio('test', true, ['class' => 'a', 'value' => null])); + $this->assertEquals('', Html::radio('test', true, ['class' => 'a' , 'uncheck' => '0', 'value' => 2])); - $this->assertEquals('
    ', Html::radio('test', true, array( + $this->assertEquals('
    ', Html::radio('test', true, [ 'class' => 'a', 'value' => null, 'label' => 'ccc', - 'labelOptions' => array('class' =>'bbb'), - ))); - $this->assertEquals('
    ', Html::radio('test', true, array( + 'labelOptions' => ['class' =>'bbb'], + ])); + $this->assertEquals('
    ', Html::radio('test', true, [ 'class' => 'a', 'uncheck' => '0', 'label' => 'ccc', 'value' => 2, - ))); + ])); } public function testCheckbox() { $this->assertEquals('', Html::checkbox('test')); - $this->assertEquals('', Html::checkbox('test', true, array('class' => 'a', 'value' => null))); - $this->assertEquals('', Html::checkbox('test', true, array('class' => 'a', 'uncheck' => '0', 'value' => 2))); + $this->assertEquals('', Html::checkbox('test', true, ['class' => 'a', 'value' => null])); + $this->assertEquals('', Html::checkbox('test', true, ['class' => 'a', 'uncheck' => '0', 'value' => 2])); - $this->assertEquals('
    ', Html::checkbox('test', true, array( + $this->assertEquals('
    ', Html::checkbox('test', true, [ 'class' => 'a', 'value' => null, 'label' => 'ccc', - 'labelOptions' => array('class' =>'bbb'), - ))); - $this->assertEquals('
    ', Html::checkbox('test', true, array( + 'labelOptions' => ['class' =>'bbb'], + ])); + $this->assertEquals('
    ', Html::checkbox('test', true, [ 'class' => 'a', 'uncheck' => '0', 'label' => 'ccc', 'value' => 2, - ))); + ])); } public function testDropDownList() @@ -287,7 +287,7 @@ EOD; EOD; - $this->assertEqualsWithoutLE($expected, Html::listBox('test', null, $this->getDataItems(), array('size' => 5))); + $this->assertEqualsWithoutLE($expected, Html::listBox('test', null, $this->getDataItems(), ['size' => 5])); $expected = << @@ -308,20 +308,20 @@ EOD; EOD; - $this->assertEqualsWithoutLE($expected, Html::listBox('test', array('value1', 'value2'), $this->getDataItems())); + $this->assertEqualsWithoutLE($expected, Html::listBox('test', ['value1', 'value2'], $this->getDataItems())); $expected = << EOD; - $this->assertEqualsWithoutLE($expected, Html::listBox('test', null, array(), array('multiple' => true))); + $this->assertEqualsWithoutLE($expected, Html::listBox('test', null, [], ['multiple' => true])); $expected = << EOD; - $this->assertEqualsWithoutLE($expected, Html::listBox('test', '', array(), array('unselect' => '0'))); + $this->assertEqualsWithoutLE($expected, Html::listBox('test', '', [], ['unselect' => '0'])); } public function testCheckboxList() @@ -332,32 +332,32 @@ EOD;
    EOD; - $this->assertEqualsWithoutLE($expected, Html::checkboxList('test', array('value2'), $this->getDataItems())); + $this->assertEqualsWithoutLE($expected, Html::checkboxList('test', ['value2'], $this->getDataItems())); $expected = <<
    EOD; - $this->assertEqualsWithoutLE($expected, Html::checkboxList('test', array('value2'), $this->getDataItems2())); + $this->assertEqualsWithoutLE($expected, Html::checkboxList('test', ['value2'], $this->getDataItems2())); $expected = <<

    EOD; - $this->assertEqualsWithoutLE($expected, Html::checkboxList('test', array('value2'), $this->getDataItems(), array( + $this->assertEqualsWithoutLE($expected, Html::checkboxList('test', ['value2'], $this->getDataItems(), [ 'separator' => "
    \n", 'unselect' => '0', - ))); + ])); $expected = <<0 1 EOD; - $this->assertEqualsWithoutLE($expected, Html::checkboxList('test', array('value2'), $this->getDataItems(), array( + $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, array('value' => $value))); + return $index . Html::label($label . ' ' . Html::checkbox($name, $checked, ['value' => $value])); } - ))); + ])); } public function testRadioList() @@ -368,39 +368,39 @@ EOD;
    EOD; - $this->assertEqualsWithoutLE($expected, Html::radioList('test', array('value2'), $this->getDataItems())); + $this->assertEqualsWithoutLE($expected, Html::radioList('test', ['value2'], $this->getDataItems())); $expected = <<
    EOD; - $this->assertEqualsWithoutLE($expected, Html::radioList('test', array('value2'), $this->getDataItems2())); + $this->assertEqualsWithoutLE($expected, Html::radioList('test', ['value2'], $this->getDataItems2())); $expected = <<

    EOD; - $this->assertEqualsWithoutLE($expected, Html::radioList('test', array('value2'), $this->getDataItems(), array( + $this->assertEqualsWithoutLE($expected, Html::radioList('test', ['value2'], $this->getDataItems(), [ 'separator' => "
    \n", 'unselect' => '0', - ))); + ])); $expected = <<0 1 EOD; - $this->assertEqualsWithoutLE($expected, Html::radioList('test', array('value2'), $this->getDataItems(), array( + $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, array('value' => $value))); + return $index . Html::label($label . ' ' . Html::radio($name, $checked, ['value' => $value])); } - ))); + ])); } public function testUl() { - $data = array( + $data = [ 1, 'abc', '<>', - ); + ]; $expected = <<
  • 1
  • @@ -416,19 +416,19 @@ EOD;
  • <>
  • EOD; - $this->assertEqualsWithoutLE($expected, Html::ul($data, array( + $this->assertEqualsWithoutLE($expected, Html::ul($data, [ 'class' => 'test', 'item' => function ($item, $index) { return "
  • $item
  • "; } - ))); + ])); } public function testOl() { - $data = array( + $data = [ 1, 'abc', '<>', - ); + ]; $expected = <<
  • 1
  • @@ -436,9 +436,9 @@ EOD;
  • <>
  • EOD; - $this->assertEqualsWithoutLE($expected, Html::ol($data, array( - 'itemOptions' => array('class' => 'ti'), - ))); + $this->assertEqualsWithoutLE($expected, Html::ol($data, [ + 'itemOptions' => ['class' => 'ti'], + ])); $expected = <<
  • 1
  • @@ -446,28 +446,28 @@ EOD;
  • <>
  • EOD; - $this->assertEqualsWithoutLE($expected, Html::ol($data, array( + $this->assertEqualsWithoutLE($expected, Html::ol($data, [ 'class' => 'test', 'item' => function ($item, $index) { return "
  • $item
  • "; } - ))); + ])); } public function testRenderOptions() { - $data = array( + $data = [ 'value1' => 'label1', - 'group1' => array( + 'group1' => [ 'value11' => 'label11', - 'group11' => array( + 'group11' => [ 'value111' => 'label111', - ), - 'group12' => array(), - ), + ], + 'group12' => [], + ], 'value2' => 'label2', - 'group2' => array(), - ); + 'group2' => [], + ]; $expected = <<please select<> @@ -485,70 +485,70 @@ EOD; EOD; - $attributes = array( + $attributes = [ 'prompt' => 'please select<>', - 'options' => array( - 'value111' => array('class' => 'option'), - ), - 'groups' => array( - 'group12' => array('class' => 'group'), - ), - ); - $this->assertEqualsWithoutLE($expected, Html::renderSelectOptions(array('value111', 'value1'), $data, $attributes)); + 'options' => [ + 'value111' => ['class' => 'option'], + ], + 'groups' => [ + 'group12' => ['class' => 'group'], + ], + ]; + $this->assertEqualsWithoutLE($expected, Html::renderSelectOptions(['value111', 'value1'], $data, $attributes)); } public function testRenderAttributes() { - $this->assertEquals('', Html::renderTagAttributes(array())); - $this->assertEquals(' name="test" value="1<>"', Html::renderTagAttributes(array('name' => 'test', 'empty' => null, 'value' => '1<>'))); - $this->assertEquals(' checked disabled', Html::renderTagAttributes(array('checked' => true, 'disabled' => true, 'hidden' => false))); + $this->assertEquals('', Html::renderTagAttributes([])); + $this->assertEquals(' name="test" value="1<>"', Html::renderTagAttributes(['name' => 'test', 'empty' => null, 'value' => '1<>'])); + $this->assertEquals(' checked disabled', Html::renderTagAttributes(['checked' => true, 'disabled' => true, 'hidden' => false])); } public function testAddCssClass() { - $options = array(); + $options = []; Html::addCssClass($options, 'test'); - $this->assertEquals(array('class' => 'test'), $options); + $this->assertEquals(['class' => 'test'], $options); Html::addCssClass($options, 'test'); - $this->assertEquals(array('class' => 'test'), $options); + $this->assertEquals(['class' => 'test'], $options); Html::addCssClass($options, 'test2'); - $this->assertEquals(array('class' => 'test test2'), $options); + $this->assertEquals(['class' => 'test test2'], $options); Html::addCssClass($options, 'test'); - $this->assertEquals(array('class' => 'test test2'), $options); + $this->assertEquals(['class' => 'test test2'], $options); Html::addCssClass($options, 'test2'); - $this->assertEquals(array('class' => 'test test2'), $options); + $this->assertEquals(['class' => 'test test2'], $options); Html::addCssClass($options, 'test3'); - $this->assertEquals(array('class' => 'test test2 test3'), $options); + $this->assertEquals(['class' => 'test test2 test3'], $options); Html::addCssClass($options, 'test2'); - $this->assertEquals(array('class' => 'test test2 test3'), $options); + $this->assertEquals(['class' => 'test test2 test3'], $options); } public function testRemoveCssClass() { - $options = array('class' => 'test test2 test3'); + $options = ['class' => 'test test2 test3']; Html::removeCssClass($options, 'test2'); - $this->assertEquals(array('class' => 'test test3'), $options); + $this->assertEquals(['class' => 'test test3'], $options); Html::removeCssClass($options, 'test2'); - $this->assertEquals(array('class' => 'test test3'), $options); + $this->assertEquals(['class' => 'test test3'], $options); Html::removeCssClass($options, 'test'); - $this->assertEquals(array('class' => 'test3'), $options); + $this->assertEquals(['class' => 'test3'], $options); Html::removeCssClass($options, 'test3'); - $this->assertEquals(array(), $options); + $this->assertEquals([], $options); } protected function getDataItems() { - return array( + return [ 'value1' => 'text1', 'value2' => 'text2', - ); + ]; } protected function getDataItems2() { - return array( + return [ 'value1<>' => 'text1<>', 'value 2' => 'text 2', - ); + ]; } } diff --git a/tests/unit/framework/helpers/InflectorTest.php b/tests/unit/framework/helpers/InflectorTest.php index de7fe01..2cd3c9f 100644 --- a/tests/unit/framework/helpers/InflectorTest.php +++ b/tests/unit/framework/helpers/InflectorTest.php @@ -13,7 +13,7 @@ class InflectorTest extends TestCase { public function testPluralize() { - $testData = array( + $testData = [ 'move' => 'moves', 'foot' => 'feet', 'child' => 'children', @@ -30,7 +30,7 @@ class InflectorTest extends TestCase 'bus' => 'buses', 'test' => 'tests', 'car' => 'cars', - ); + ]; foreach ($testData as $testIn => $testOut) { $this->assertEquals($testOut, Inflector::pluralize($testIn)); @@ -40,7 +40,7 @@ class InflectorTest extends TestCase public function testSingularize() { - $testData = array( + $testData = [ 'moves' => 'move', 'feet' => 'foot', 'children' => 'child', @@ -57,7 +57,7 @@ class InflectorTest extends TestCase 'buses' => 'bus', 'tests' => 'test', 'cars' => 'car', - ); + ]; foreach ($testData as $testIn => $testOut) { $this->assertEquals($testOut, Inflector::singularize($testIn)); $this->assertEquals(ucfirst($testOut), ucfirst(Inflector::singularize($testIn))); diff --git a/tests/unit/framework/helpers/JsonTest.php b/tests/unit/framework/helpers/JsonTest.php index 069fdc3..d08ebb8 100644 --- a/tests/unit/framework/helpers/JsonTest.php +++ b/tests/unit/framework/helpers/JsonTest.php @@ -19,9 +19,9 @@ class JsonTest extends TestCase $this->assertSame('"1"', Json::encode($data)); // simple array encoding - $data = array(1, 2); + $data = [1, 2]; $this->assertSame('[1,2]', Json::encode($data)); - $data = array('a' => 1, 'b' => 2); + $data = ['a' => 1, 'b' => 2]; $this->assertSame('{"a":1,"b":2}', Json::encode($data)); // simple object encoding @@ -38,12 +38,12 @@ class JsonTest extends TestCase // complex data $expression1 = 'function (a) {}'; $expression2 = 'function (b) {}'; - $data = array( - 'a' => array( + $data = [ + 'a' => [ 1, new JsExpression($expression1) - ), + ], 'b' => new JsExpression($expression2), - ); + ]; $this->assertSame("{\"a\":[1,$expression1],\"b\":$expression2}", Json::encode($data)); // https://github.com/yiisoft/yii2/issues/957 @@ -59,7 +59,7 @@ class JsonTest extends TestCase // array decoding $json = '{"a":1,"b":2}'; - $this->assertSame(array('a' => 1, 'b' => 2), Json::decode($json)); + $this->assertSame(['a' => 1, 'b' => 2], Json::decode($json)); // exception $json = '{"a":1,"b":2'; diff --git a/tests/unit/framework/i18n/FormatterTest.php b/tests/unit/framework/i18n/FormatterTest.php index 6966853..622c308 100644 --- a/tests/unit/framework/i18n/FormatterTest.php +++ b/tests/unit/framework/i18n/FormatterTest.php @@ -29,9 +29,7 @@ class FormatterTest extends TestCase $this->markTestSkipped('intl extension is required.'); } $this->mockApplication(); - $this->formatter = new Formatter(array( - 'locale' => 'en_US', - )); + $this->formatter = new Formatter(['locale' => 'en_US']); } protected function tearDown() diff --git a/tests/unit/framework/i18n/GettextMoFileTest.php b/tests/unit/framework/i18n/GettextMoFileTest.php index 9b61145..373fa20 100644 --- a/tests/unit/framework/i18n/GettextMoFileTest.php +++ b/tests/unit/framework/i18n/GettextMoFileTest.php @@ -44,7 +44,7 @@ class GettextMoFileTest extends TestCase { // initial data $s = chr(4); - $messages = array( + $messages = [ 'Hello!' => 'Привет!', "context1{$s}Hello?" => 'Привет?', 'Hello!?' => '', @@ -53,7 +53,7 @@ class GettextMoFileTest extends TestCase "context2{$s}\nNew lines\n" => "\nПереносы строк\n", "context2{$s}\tTabs\t" => "\tТабы\t", "context2{$s}\rCarriage returns\r" => "\rВозвраты кареток\r", - ); + ]; // create temporary directory and dump messages $poFileDirectory = __DIR__ . '/../../runtime/i18n'; diff --git a/tests/unit/framework/i18n/GettextPoFileTest.php b/tests/unit/framework/i18n/GettextPoFileTest.php index 4165b81..29db141 100644 --- a/tests/unit/framework/i18n/GettextPoFileTest.php +++ b/tests/unit/framework/i18n/GettextPoFileTest.php @@ -44,7 +44,7 @@ class GettextPoFileTest extends TestCase { // initial data $s = chr(4); - $messages = array( + $messages = [ 'Hello!' => 'Привет!', "context1{$s}Hello?" => 'Привет?', 'Hello!?' => '', @@ -53,7 +53,7 @@ class GettextPoFileTest extends TestCase "context2{$s}\nNew lines\n" => "\nПереносы строк\n", "context2{$s}\tTabs\t" => "\tТабы\t", "context2{$s}\rCarriage returns\r" => "\rВозвраты кареток\r", - ); + ]; // create temporary directory and dump messages $poFileDirectory = __DIR__ . '/../../runtime/i18n'; diff --git a/tests/unit/framework/i18n/I18NTest.php b/tests/unit/framework/i18n/I18NTest.php index ac19c02..a6d8d9f 100644 --- a/tests/unit/framework/i18n/I18NTest.php +++ b/tests/unit/framework/i18n/I18NTest.php @@ -29,36 +29,34 @@ class I18NTest extends TestCase { parent::setUp(); $this->mockApplication(); - $this->i18n = new I18N(array( - 'translations' => array( - 'test' => new PhpMessageSource(array( + $this->i18n = new I18N([ + 'translations' => [ + 'test' => new PhpMessageSource([ 'basePath' => '@yiiunit/data/i18n/messages', - )) - ) - )); + ]) + ] + ]); } public function testTranslate() { $msg = 'The dog runs fast.'; - $this->assertEquals('The dog runs fast.', $this->i18n->translate('test', $msg, array(), 'en_US')); - $this->assertEquals('Der Hund rennt schnell.', $this->i18n->translate('test', $msg, array(), 'de_DE')); + $this->assertEquals('The dog runs fast.', $this->i18n->translate('test', $msg, [], 'en_US')); + $this->assertEquals('Der Hund rennt schnell.', $this->i18n->translate('test', $msg, [], 'de_DE')); } public function testTranslateParams() { $msg = 'His speed is about {n} km/h.'; - $params = array( - 'n' => 42, - ); + $params = ['n' => 42]; $this->assertEquals('His speed is about 42 km/h.', $this->i18n->translate('test', $msg, $params, 'en_US')); $this->assertEquals('Seine Geschwindigkeit beträgt 42 km/h.', $this->i18n->translate('test', $msg, $params, 'de_DE')); $msg = 'His name is {name} and his speed is about {n, number} km/h.'; - $params = array( + $params = [ 'n' => 42, 'name' => 'DA VINCI', // http://petrix.com/dognames/d.html - ); + ]; $this->assertEquals('His name is DA VINCI and his speed is about 42 km/h.', $this->i18n->translate('test', $msg, $params, 'en_US')); $this->assertEquals('Er heißt DA VINCI und ist 42 km/h schnell.', $this->i18n->translate('test', $msg, $params, 'de_DE')); } @@ -70,7 +68,7 @@ class I18NTest extends TestCase $this->assertEquals('His speed is about 0 km/h.', $this->i18n->translate('test', $msg, 0, 'en_US')); $this->assertEquals('His speed is about 42 km/h.', $this->i18n->translate('test', $msg, 42, 'en_US')); $this->assertEquals('His speed is about {0} km/h.', $this->i18n->translate('test', $msg, null, 'en_US')); - $this->assertEquals('His speed is about {0} km/h.', $this->i18n->translate('test', $msg, array(), 'en_US')); + $this->assertEquals('His speed is about {0} km/h.', $this->i18n->translate('test', $msg, [], 'en_US')); $msg = 'His name is {name} and he is {age} years old.'; $model = new ParamModel(); diff --git a/tests/unit/framework/i18n/MessageFormatterTest.php b/tests/unit/framework/i18n/MessageFormatterTest.php index 2465409..c392ce0 100644 --- a/tests/unit/framework/i18n/MessageFormatterTest.php +++ b/tests/unit/framework/i18n/MessageFormatterTest.php @@ -31,18 +31,18 @@ class MessageFormatterTest extends TestCase public function patterns() { - return array( - array( + return [ + [ '{'.self::SUBJECT.'} is {'.self::N.', number}', // pattern self::SUBJECT_VALUE.' is '.self::N_VALUE, // expected - array( // params + [ // params self::N => self::N_VALUE, self::SUBJECT => self::SUBJECT_VALUE, - ) - ), + ] + ], // This one was provided by Aura.Intl. Thanks! - array(<<<_MSG_ + [<<<_MSG_ {gender_of_host, select, female {{num_guests, plural, offset:1 =0 {{host} does not give a party.} @@ -62,61 +62,61 @@ class MessageFormatterTest extends TestCase _MSG_ , 'ralph invites beep and 3 other people to his party.', - array( + [ 'gender_of_host' => 'male', 'num_guests' => 4, 'host' => 'ralph', 'guest' => 'beep' - ) - ), + ] + ], - array( + [ '{name} is {gender} and {gender, select, female{she} male{he} other{it}} loves Yii!', 'Alexander is male and he loves Yii!', - array( + [ 'name' => 'Alexander', 'gender' => 'male', - ), - ), + ], + ], // verify pattern in select does not get replaced - array( + [ '{name} is {gender} and {gender, select, female{she} male{he} other{it}} loves Yii!', 'Alexander is male and he loves Yii!', - array( + [ 'name' => 'Alexander', 'gender' => 'male', // following should not be replaced 'he' => 'wtf', 'she' => 'wtf', 'it' => 'wtf', - ) - ), + ] + ], // verify pattern in select message gets replaced - array( + [ '{name} is {gender} and {gender, select, female{she} male{{he}} other{it}} loves Yii!', 'Alexander is male and wtf loves Yii!', - array( + [ 'name' => 'Alexander', 'gender' => 'male', 'he' => 'wtf', 'she' => 'wtf', - ), - ), + ], + ], // some parser specific verifications - array( + [ '{gender} and {gender, select, female{she} male{{he}} other{it}} loves {nr, number} is {gender}!', 'male and wtf loves 42 is male!', - array( + [ 'nr' => 42, 'gender' => 'male', 'he' => 'wtf', 'she' => 'wtf', - ), - ), - ); + ], + ], + ]; } /** @@ -142,9 +142,9 @@ _MSG_ { $expected = '{'.self::SUBJECT.'} is '.self::N_VALUE; - $result = MessageFormatter::formatMessage('en_US', '{'.self::SUBJECT.'} is {'.self::N.', number}', array( + $result = MessageFormatter::formatMessage('en_US', '{'.self::SUBJECT.'} is {'.self::N.', number}', [ self::N => self::N_VALUE, - )); + ]); $this->assertEquals($expected, $result, intl_get_error_message()); } @@ -167,11 +167,11 @@ _MSG_ public function testNoParams() { $pattern = '{'.self::SUBJECT.'} is '.self::N; - $result = MessageFormatter::formatMessage('en_US', $pattern, array()); + $result = MessageFormatter::formatMessage('en_US', $pattern, []); $this->assertEquals($pattern, $result, intl_get_error_message()); $formatter = new MessageFormatter('en_US', $pattern); - $result = $formatter->format(array()); + $result = $formatter->format([]); $this->assertEquals($pattern, $result, $formatter->getErrorMessage()); } } \ No newline at end of file diff --git a/tests/unit/framework/rbac/ManagerTestCase.php b/tests/unit/framework/rbac/ManagerTestCase.php index 7cb4941..3bf80ad 100644 --- a/tests/unit/framework/rbac/ManagerTestCase.php +++ b/tests/unit/framework/rbac/ManagerTestCase.php @@ -17,7 +17,7 @@ abstract class ManagerTestCase extends TestCase $name = 'editUser'; $description = 'edit a user'; $bizRule = 'checkUserIdentity()'; - $data = array(1, 2, 3); + $data = [1, 2, 3]; $item = $this->auth->createItem($name, $type, $description, $bizRule, $data); $this->assertTrue($item instanceof Item); $this->assertEquals($item->type, $type); @@ -90,7 +90,7 @@ abstract class ManagerTestCase extends TestCase public function testGetItemChildren() { - $this->assertEquals(array(), $this->auth->getItemChildren('readPost')); + $this->assertEquals([], $this->auth->getItemChildren('readPost')); $children = $this->auth->getItemChildren('author'); $this->assertEquals(3, count($children)); $this->assertTrue(reset($children) instanceof Item); @@ -164,50 +164,50 @@ abstract class ManagerTestCase extends TestCase public function testExecuteBizRule() { - $this->assertTrue($this->auth->executeBizRule(null, array(), null)); - $this->assertTrue($this->auth->executeBizRule('return 1 == true;', array(), null)); - $this->assertTrue($this->auth->executeBizRule('return $params[0] == $params[1];', array(1, '1'), null)); - $this->assertFalse($this->auth->executeBizRule('invalid;', array(), null)); + $this->assertTrue($this->auth->executeBizRule(null, [], null)); + $this->assertTrue($this->auth->executeBizRule('return 1 == true;', [], null)); + $this->assertTrue($this->auth->executeBizRule('return $params[0] == $params[1];', [1, '1'], null)); + $this->assertFalse($this->auth->executeBizRule('invalid;', [], null)); } public function testCheckAccess() { - $results = array( - 'reader A' => array( + $results = [ + 'reader A' => [ 'createPost' => false, 'readPost' => true, 'updatePost' => false, 'updateOwnPost' => false, 'deletePost' => false, - ), - 'author B' => array( + ], + 'author B' => [ 'createPost' => true, 'readPost' => true, 'updatePost' => true, 'updateOwnPost' => true, 'deletePost' => false, - ), - 'editor C' => array( + ], + 'editor C' => [ 'createPost' => false, 'readPost' => true, 'updatePost' => true, 'updateOwnPost' => false, 'deletePost' => false, - ), - 'admin D' => array( + ], + 'admin D' => [ 'createPost' => true, 'readPost' => true, 'updatePost' => true, 'updateOwnPost' => false, 'deletePost' => true, - ), - ); + ], + ]; - $params = array('authorID' => 'author B'); + $params = ['authorID' => 'author B']; - foreach (array('reader A', 'author B', 'editor C', 'admin D') as $user) { + foreach (['reader A', 'author B', 'editor C', 'admin D'] as $user) { $params['userID'] = $user; - foreach (array('createPost', 'readPost', 'updatePost', 'updateOwnPost', 'deletePost') as $operation) { + foreach (['createPost', 'readPost', 'updatePost', 'updateOwnPost', 'deletePost'] as $operation) { $result = $this->auth->checkAccess($user, $operation, $params); $this->assertEquals($results[$user][$operation], $result); } diff --git a/tests/unit/framework/requirements/YiiRequirementCheckerTest.php b/tests/unit/framework/requirements/YiiRequirementCheckerTest.php index 652d003..4339dcf 100644 --- a/tests/unit/framework/requirements/YiiRequirementCheckerTest.php +++ b/tests/unit/framework/requirements/YiiRequirementCheckerTest.php @@ -15,29 +15,29 @@ class YiiRequirementCheckerTest extends TestCase { $requirementsChecker = new YiiRequirementChecker(); - $requirements = array( - 'requirementPass' => array( + $requirements = [ + 'requirementPass' => [ 'name' => 'Requirement 1', 'mandatory' => true, 'condition' => true, 'by' => 'Requirement 1', 'memo' => 'Requirement 1', - ), - 'requirementError' => array( + ], + 'requirementError' => [ 'name' => 'Requirement 2', 'mandatory' => true, 'condition' => false, 'by' => 'Requirement 2', 'memo' => 'Requirement 2', - ), - 'requirementWarning' => array( + ], + 'requirementWarning' => [ 'name' => 'Requirement 3', 'mandatory' => false, 'condition' => false, 'by' => 'Requirement 3', 'memo' => 'Requirement 3', - ), - ); + ], + ]; $checkResult = $requirementsChecker->check($requirements)->getResult(); $summary = $checkResult['summary']; @@ -65,22 +65,22 @@ class YiiRequirementCheckerTest extends TestCase { $requirementsChecker = new YiiRequirementChecker(); - $requirements = array( - 'requirementPass' => array( + $requirements = [ + 'requirementPass' => [ 'name' => 'Requirement 1', 'mandatory' => true, 'condition' => 'eval:2>1', 'by' => 'Requirement 1', 'memo' => 'Requirement 1', - ), - 'requirementError' => array( + ], + 'requirementError' => [ 'name' => 'Requirement 2', 'mandatory' => true, 'condition' => 'eval:2<1', 'by' => 'Requirement 2', 'memo' => 'Requirement 2', - ), - ); + ], + ]; $checkResult = $requirementsChecker->check($requirements)->getResult(); $checkedRequirements = $checkResult['requirements']; @@ -99,24 +99,24 @@ class YiiRequirementCheckerTest extends TestCase { $requirementsChecker = new YiiRequirementChecker(); - $requirements1 = array( - array( + $requirements1 = [ + [ 'name' => 'Requirement 1', 'mandatory' => true, 'condition' => true, 'by' => 'Requirement 1', 'memo' => 'Requirement 1', - ), - ); - $requirements2 = array( - array( + ], + ]; + $requirements2 = [ + [ 'name' => 'Requirement 2', 'mandatory' => true, 'condition' => true, 'by' => 'Requirement 2', 'memo' => 'Requirement 2', - ), - ); + ], + ]; $checkResult = $requirementsChecker->check($requirements1)->check($requirements2)->getResult(); $mergedRequirements = array_merge($requirements1, $requirements2); @@ -141,15 +141,15 @@ class YiiRequirementCheckerTest extends TestCase */ public function dataProviderGetByteSize() { - return array( - array('456', 456), - array('5K', 5*1024), - array('16KB', 16*1024), - array('4M', 4*1024*1024), - array('14MB', 14*1024*1024), - array('7G', 7*1024*1024*1024), - array('12GB', 12*1024*1024*1024), - ); + return [ + ['456', 456], + ['5K', 5*1024], + ['16KB', 16*1024], + ['4M', 4*1024*1024], + ['14MB', 14*1024*1024], + ['7G', 7*1024*1024*1024], + ['12GB', 12*1024*1024*1024], + ]; } /** @@ -171,13 +171,13 @@ class YiiRequirementCheckerTest extends TestCase */ public function dataProviderCompareByteSize() { - return array( - array('2M', '2K', '>', true), - array('2M', '2K', '>=', true), - array('1K', '1024', '==', true), - array('10M', '11M', '<', true), - array('10M', '11M', '<=', true), - ); + return [ + ['2M', '2K', '>', true], + ['2M', '2K', '>=', true], + ['1K', '1024', '==', true], + ['10M', '11M', '<', true], + ['10M', '11M', '<=', true], + ]; } /** diff --git a/tests/unit/framework/validators/BooleanValidatorTest.php b/tests/unit/framework/validators/BooleanValidatorTest.php index f37b39a..f30aa3d 100644 --- a/tests/unit/framework/validators/BooleanValidatorTest.php +++ b/tests/unit/framework/validators/BooleanValidatorTest.php @@ -18,7 +18,7 @@ class BooleanValidatorTest extends TestCase $this->assertTrue($val->validateValue('0')); $this->assertTrue($val->validateValue('1')); $this->assertFalse($val->validateValue(null)); - $this->assertFalse($val->validateValue(array())); + $this->assertFalse($val->validateValue([])); $val->strict = true; $this->assertTrue($val->validateValue('0')); $this->assertTrue($val->validateValue('1')); @@ -27,7 +27,7 @@ class BooleanValidatorTest extends TestCase $val->trueValue = true; $val->falseValue = false; $this->assertFalse($val->validateValue('0')); - $this->assertFalse($val->validateValue(array())); + $this->assertFalse($val->validateValue([])); $this->assertTrue($val->validateValue(true)); $this->assertTrue($val->validateValue(false)); } @@ -38,7 +38,7 @@ class BooleanValidatorTest extends TestCase $obj->attrA = true; $obj->attrB = '1'; $obj->attrC = '0'; - $obj->attrD = array(); + $obj->attrD = []; $val = new BooleanValidator; $val->validateAttribute($obj, 'attrA'); $this->assertFalse($obj->hasErrors('attrA')); diff --git a/tests/unit/framework/validators/CompareValidatorTest.php b/tests/unit/framework/validators/CompareValidatorTest.php index 5a16a30..b3fd6b4 100644 --- a/tests/unit/framework/validators/CompareValidatorTest.php +++ b/tests/unit/framework/validators/CompareValidatorTest.php @@ -22,12 +22,12 @@ class CompareValidatorTest extends TestCase { $value = 18449; // default config - $val = new CompareValidator(array('compareValue' => $value)); + $val = new CompareValidator(['compareValue' => $value]); $this->assertTrue($val->validateValue($value)); $this->assertTrue($val->validateValue((string)$value)); $this->assertFalse($val->validateValue($value + 1)); foreach ($this->getOperationTestData($value) as $op => $tests) { - $val = new CompareValidator(array('compareValue' => $value)); + $val = new CompareValidator(['compareValue' => $value]); $val->operator = $op; foreach ($tests as $test) { $this->assertEquals($test[1], $val->validateValue($test[0])); @@ -37,53 +37,52 @@ class CompareValidatorTest extends TestCase protected function getOperationTestData($value) { - return array( - '===' => array( - array($value, true), - array((string)$value, false), - array((float)$value, false), - array($value + 1, false), - ), - '!=' => array( - array($value, false), - array((string)$value, false), - array((float)$value, false), - array($value + 0.00001, true), - array(false, true), - ), - '!==' => array( - array($value, false), - array((string)$value, true), - array((float)$value, true), - array(false, true), - ), - '>' => array( - array($value, false), - array($value + 1, true), - array($value - 1, false), - ), - '>=' => array( - array($value, true), - array($value + 1, true), - array($value - 1, false), - ), - '<' => array( - array($value, false), - array($value + 1, false), - array($value - 1, true), - ), - '<=' => array( - array($value, true), - array($value + 1, false), - array($value - 1, true), - ), - //'non-op' => array( - // array($value, false), - // array($value + 1, false), - // array($value - 1, false), - //), - - ); + return [ + '===' => [ + [$value, true], + [(string)$value, false], + [(float)$value, false], + [$value + 1, false], + ], + '!=' => [ + [$value, false], + [(string)$value, false], + [(float)$value, false], + [$value + 0.00001, true], + [false, true], + ], + '!==' => [ + [$value, false], + [(string)$value, true], + [(float)$value, true], + [false, true], + ], + '>' => [ + [$value, false], + [$value + 1, true], + [$value - 1, false], + ], + '>=' => [ + [$value, true], + [$value + 1, true], + [$value - 1, false], + ], + '<' => [ + [$value, false], + [$value + 1, false], + [$value - 1, true], + ], + '<=' => [ + [$value, true], + [$value + 1, false], + [$value - 1, true], + ], + //'non-op' => [ + // [$value, false], + // [$value + 1, false], + // [$value - 1, false], + //], + ]; } public function testValidateAttribute() @@ -91,22 +90,22 @@ class CompareValidatorTest extends TestCase // invalid-array $val = new CompareValidator; $model = new FakedValidationModel; - $model->attr = array('test_val'); + $model->attr = ['test_val']; $val->validateAttribute($model, 'attr'); $this->assertTrue($model->hasErrors('attr')); - $val = new CompareValidator(array('compareValue' => 'test-string')); + $val = new CompareValidator(['compareValue' => 'test-string']); $model = new FakedValidationModel; $model->attr_test = 'test-string'; $val->validateAttribute($model, 'attr_test'); $this->assertFalse($model->hasErrors('attr_test')); - $val = new CompareValidator(array('compareAttribute' => 'attr_test_val')); + $val = new CompareValidator(['compareAttribute' => 'attr_test_val']); $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(array('compareAttribute' => 'attr_test_val')); + $val = new CompareValidator(['compareAttribute' => 'attr_test_val']); $model = new FakedValidationModel; $model->attr_test = 'test-string'; $model->attr_test_val = 'test-string-false'; @@ -131,7 +130,7 @@ class CompareValidatorTest extends TestCase // not existing op $val = new CompareValidator(); $val->operator = '<>'; - $model = FakedValidationModel::createWithAttributes(array('attr_o' => 5, 'attr_o_repeat' => 5 )); + $model = FakedValidationModel::createWithAttributes(['attr_o' => 5, 'attr_o_repeat' => 5]); $val->validateAttribute($model, 'attr_o'); $this->assertTrue($model->hasErrors('attr_o')); } @@ -140,7 +139,7 @@ class CompareValidatorTest extends TestCase { $value = 55; foreach ($this->getOperationTestData($value) as $operator => $tests) { - $val = new CompareValidator(array('operator' => $operator, 'compareValue' => $value)); + $val = new CompareValidator(['operator' => $operator, 'compareValue' => $value]); foreach ($tests as $test) { $model = new FakedValidationModel; $model->attr_test = $test[0]; @@ -154,11 +153,11 @@ class CompareValidatorTest extends TestCase public function testEnsureMessageSetOnInit() { foreach ($this->getOperationTestData(1337) as $operator => $tests) { - $val = new CompareValidator(array('operator' => $operator)); + $val = new CompareValidator(['operator' => $operator]); $this->assertTrue(strlen($val->message) > 1); } try { - $val = new CompareValidator(array('operator' => '<>')); + $val = new CompareValidator(['operator' => '<>']); } catch (InvalidConfigException $e) { return; } diff --git a/tests/unit/framework/validators/DateValidatorTest.php b/tests/unit/framework/validators/DateValidatorTest.php index a551889..28a6a4a 100644 --- a/tests/unit/framework/validators/DateValidatorTest.php +++ b/tests/unit/framework/validators/DateValidatorTest.php @@ -44,7 +44,7 @@ class DateValidatorTest extends TestCase $val->validateAttribute($model, 'attr_date'); $this->assertTrue($model->hasErrors('attr_date')); //// timestamp attribute - $val = new DateValidator(array('timestampAttribute' => 'attr_timestamp')); + $val = new DateValidator(['timestampAttribute' => 'attr_timestamp']); $model = new FakedValidationModel; $model->attr_date = '2013-09-13'; $model->attr_timestamp = true; @@ -56,7 +56,7 @@ class DateValidatorTest extends TestCase $model->attr_timestamp ); $val = new DateValidator(); - $model = FakedValidationModel::createWithAttributes(array('attr_date' => array())); + $model = FakedValidationModel::createWithAttributes(['attr_date' => []]); $val->validateAttribute($model, 'attr_date'); $this->assertTrue($model->hasErrors('attr_date')); diff --git a/tests/unit/framework/validators/EmailValidatorTest.php b/tests/unit/framework/validators/EmailValidatorTest.php index f423663..950ac97 100644 --- a/tests/unit/framework/validators/EmailValidatorTest.php +++ b/tests/unit/framework/validators/EmailValidatorTest.php @@ -44,7 +44,7 @@ class EmailValidatorTest extends TestCase $this->markTestSkipped('Intl extension required'); return; } - $val = new EmailValidator(array('enableIDN' => true)); + $val = new EmailValidator(['enableIDN' => true]); $this->assertTrue($val->validateValue('5011@example.com')); $this->assertTrue($val->validateValue('example@äüößìà.de')); $this->assertTrue($val->validateValue('example@xn--zcack7ayc9a.de')); @@ -52,7 +52,7 @@ class EmailValidatorTest extends TestCase public function testValidateValueWithName() { - $val = new EmailValidator(array('allowName' => true)); + $val = new EmailValidator(['allowName' => true]); $this->assertTrue($val->validateValue('test@example.com')); $this->assertTrue($val->validateValue('John Smith ')); $this->assertFalse($val->validateValue('John Smith ')); diff --git a/tests/unit/framework/validators/ExistValidatorTest.php b/tests/unit/framework/validators/ExistValidatorTest.php index 0df42e3..5a3a175 100644 --- a/tests/unit/framework/validators/ExistValidatorTest.php +++ b/tests/unit/framework/validators/ExistValidatorTest.php @@ -33,7 +33,7 @@ class ExistValidatorTest extends DatabaseTestCase } // combine to save the time creating a new db-fixture set (likely ~5 sec) try { - $val = new ExistValidator(array('className' => ValidatorTestMainModel::className())); + $val = new ExistValidator(['className' => ValidatorTestMainModel::className()]); $val->validateValue('ref'); $this->fail('Exception should have been thrown at this time'); } catch (Exception $e) { @@ -44,50 +44,50 @@ class ExistValidatorTest extends DatabaseTestCase public function testValidateValue() { - $val = new ExistValidator(array('className' => ValidatorTestRefModel::className(), 'attributeName' => 'id')); + $val = new ExistValidator(['className' => ValidatorTestRefModel::className(), 'attributeName' => 'id']); $this->assertTrue($val->validateValue(2)); $this->assertTrue($val->validateValue(5)); $this->assertFalse($val->validateValue(99)); - $this->assertFalse($val->validateValue(array('1'))); + $this->assertFalse($val->validateValue(['1'])); } public function testValidateAttribute() { // existing value on different table - $val = new ExistValidator(array('className' => ValidatorTestMainModel::className(), 'attributeName' => 'id')); - $m = ValidatorTestRefModel::find(array('id' => 1)); + $val = new ExistValidator(['className' => ValidatorTestMainModel::className(), 'attributeName' => 'id']); + $m = ValidatorTestRefModel::find(['id' => 1]); $val->validateAttribute($m, 'ref'); $this->assertFalse($m->hasErrors()); // non-existing value on different table - $val = new ExistValidator(array('className' => ValidatorTestMainModel::className(), 'attributeName' => 'id')); - $m = ValidatorTestRefModel::find(array('id' => 6)); + $val = new ExistValidator(['className' => ValidatorTestMainModel::className(), 'attributeName' => 'id']); + $m = ValidatorTestRefModel::find(['id' => 6]); $val->validateAttribute($m, 'ref'); $this->assertTrue($m->hasErrors('ref')); // existing value on same table - $val = new ExistValidator(array('attributeName' => 'ref')); - $m = ValidatorTestRefModel::find(array('id' => 2)); + $val = new ExistValidator(['attributeName' => 'ref']); + $m = ValidatorTestRefModel::find(['id' => 2]); $val->validateAttribute($m, 'test_val'); $this->assertFalse($m->hasErrors()); // non-existing value on same table - $val = new ExistValidator(array('attributeName' => 'ref')); - $m = ValidatorTestRefModel::find(array('id' => 5)); + $val = new ExistValidator(['attributeName' => 'ref']); + $m = ValidatorTestRefModel::find(['id' => 5]); $val->validateAttribute($m, 'test_val_fail'); $this->assertTrue($m->hasErrors('test_val_fail')); // check for given value (true) $val = new ExistValidator(); - $m = ValidatorTestRefModel::find(array('id' => 3)); + $m = ValidatorTestRefModel::find(['id' => 3]); $val->validateAttribute($m, 'ref'); $this->assertFalse($m->hasErrors()); // check for given defaults (false) $val = new ExistValidator(); - $m = ValidatorTestRefModel::find(array('id' => 4)); + $m = ValidatorTestRefModel::find(['id' => 4]); $m->a_field = 'some new value'; $val->validateAttribute($m, 'a_field'); $this->assertTrue($m->hasErrors('a_field')); // check array - $val = new ExistValidator(array('attributeName' => 'ref')); - $m = ValidatorTestRefModel::find(array('id' => 2)); - $m->test_val = array(1,2,3); + $val = new ExistValidator(['attributeName' => 'ref']); + $m = ValidatorTestRefModel::find(['id' => 2]); + $m->test_val = [1,2,3]; $val->validateAttribute($m, 'test_val'); $this->assertTrue($m->hasErrors('test_val')); } diff --git a/tests/unit/framework/validators/FileValidatorTest.php b/tests/unit/framework/validators/FileValidatorTest.php index b6674bb..f68fbe7 100644 --- a/tests/unit/framework/validators/FileValidatorTest.php +++ b/tests/unit/framework/validators/FileValidatorTest.php @@ -19,25 +19,25 @@ class FileValidatorTest extends TestCase public function testAssureMessagesSetOnInit() { $val = new FileValidator(); - foreach (array('message', 'uploadRequired', 'tooMany', 'wrongType', 'tooBig', 'tooSmall') as $attr) { + foreach (['message', 'uploadRequired', 'tooMany', 'wrongType', 'tooBig', 'tooSmall'] as $attr) { $this->assertTrue(is_string($val->$attr)); } } public function testTypeSplitOnInit() { - $val = new FileValidator(array('types' => 'jpeg, jpg, gif')); - $this->assertEquals(array('jpeg', 'jpg', 'gif'), $val->types); - $val = new FileValidator(array('types' => 'jpeg')); - $this->assertEquals(array('jpeg'), $val->types); - $val = new FileValidator(array('types' => '')); - $this->assertEquals(array(), $val->types); - $val = new FileValidator(array('types' => array())); - $this->assertEquals(array(), $val->types); + $val = new FileValidator(['types' => 'jpeg, jpg, gif']); + $this->assertEquals(['jpeg', 'jpg', 'gif'], $val->types); + $val = new FileValidator(['types' => 'jpeg']); + $this->assertEquals(['jpeg'], $val->types); + $val = new FileValidator(['types' => '']); + $this->assertEquals([], $val->types); + $val = new FileValidator(['types' => []]); + $this->assertEquals([], $val->types); $val = new FileValidator(); - $this->assertEquals(array(), $val->types); - $val = new FileValidator(array('types' => array('jpeg', 'exe'))); - $this->assertEquals(array('jpeg', 'exe'), $val->types); + $this->assertEquals([], $val->types); + $val = new FileValidator(['types' => ['jpeg', 'exe']]); + $this->assertEquals(['jpeg', 'exe'], $val->types); } public function testGetSizeLimit() @@ -74,34 +74,36 @@ class FileValidatorTest extends TestCase public function testValidateAttributeMultiple() { - $val = new FileValidator(array('maxFiles' => 2)); - $m = FakedValidationModel::createWithAttributes(array('attr_files' => 'path')); + $val = new FileValidator(['maxFiles' => 2]); + $m = FakedValidationModel::createWithAttributes(['attr_files' => 'path']); $val->validateAttribute($m, 'attr_files'); $this->assertTrue($m->hasErrors('attr_files')); - $m = FakedValidationModel::createWithAttributes(array('attr_files' => array())); + $m = FakedValidationModel::createWithAttributes(['attr_files' => []]); $val->validateAttribute($m, 'attr_files'); $this->assertTrue($m->hasErrors('attr_files')); $this->assertSame($val->uploadRequired, current($m->getErrors('attr_files'))); $m = FakedValidationModel::createWithAttributes( - array( + [ 'attr_files' => $this->createTestFiles( - array( - array( + [ + [ 'name' => 'test_up_1.txt', 'size' => 1024, - ), - array( + ], + [ 'error' => UPLOAD_ERR_NO_FILE, - ), - ) + ], + ] ) - ) + ] ); $val->validateAttribute($m, 'attr_files'); $this->assertFalse($m->hasErrors('attr_files')); - $m = FakedValidationModel::createWithAttributes( - array('attr_files' => $this->createTestFiles(array(array(''), array(''), array(''),))) - ); + $m = FakedValidationModel::createWithAttributes([ + 'attr_files' => $this->createTestFiles([ + [''], [''], [''] + ]) + ]); $val->validateAttribute($m, 'attr_files'); $this->assertTrue($m->hasErrors()); $this->assertTrue(stripos(current($m->getErrors('attr_files')), 'you can upload at most') !== false); @@ -111,7 +113,7 @@ class FileValidatorTest extends TestCase * @param array $params * @return UploadedFile[] */ - protected function createTestFiles($params = array()) + protected function createTestFiles($params = []) { $rndString = function ($len = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; @@ -121,10 +123,10 @@ class FileValidatorTest extends TestCase } return $randomString; }; - $files = array(); + $files = []; foreach ($params as $param) { if (empty($param) && count($params) != 1) { - $files[] = array('no instance of UploadedFile'); + $files[] = ['no instance of UploadedFile']; continue; } $name = isset($param['name']) ? $param['name'] : $rndString(); @@ -141,21 +143,21 @@ class FileValidatorTest extends TestCase $error = isset($param['error']) ? $param['error'] : UPLOAD_ERR_OK; if (count($params) == 1) { $error = empty($param) ? UPLOAD_ERR_NO_FILE : $error; - return new UploadedFile(array( + return new UploadedFile([ 'name' => $name, 'tempName' => $tempName, 'type' => $type, 'size' => $size, 'error' => $error - )); + ]); } - $files[] = new UploadedFile(array( + $files[] = new UploadedFile([ 'name' => $name, 'tempName' => $tempName, 'type' => $type, 'size' => $size, 'error' => $error - )); + ]); } return $files; } @@ -172,24 +174,24 @@ class FileValidatorTest extends TestCase $this->assertSame($val->uploadRequired, current($m->getErrors('attr_files_empty'))); $m = $this->createModelForAttributeTest(); // too big - $val = new FileValidator(array('maxSize' => 128)); + $val = new FileValidator(['maxSize' => 128]); $val->validateAttribute($m, 'attr_files'); $this->assertTrue($m->hasErrors('attr_files')); $this->assertTrue( stripos( current($m->getErrors('attr_files')), - str_ireplace(array('{file}', '{limit}'), array($m->attr_files->name, 128), $val->tooBig) + str_ireplace(['{file}', '{limit}'], [$m->attr_files->name, 128], $val->tooBig) ) !== false ); // to Small $m = $this->createModelForAttributeTest(); - $val = new FileValidator(array('minSize' => 2048)); + $val = new FileValidator(['minSize' => 2048]); $val->validateAttribute($m, 'attr_files'); $this->assertTrue($m->hasErrors('attr_files')); $this->assertTrue( stripos( current($m->getErrors('attr_files')), - str_ireplace(array('{file}', '{limit}'), array($m->attr_files->name, 2048), $val->tooSmall) + str_ireplace(['{file}', '{limit}'], [$m->attr_files->name, 2048], $val->tooSmall) ) !== false ); // UPLOAD_ERR_INI_SIZE/UPLOAD_ERR_FORM_SIZE @@ -201,8 +203,8 @@ class FileValidatorTest extends TestCase stripos( current($m->getErrors('attr_err_ini')), str_ireplace( - array('{file}', '{limit}'), - array($m->attr_err_ini->name, $val->getSizeLimit()), + ['{file}', '{limit}'], + [$m->attr_err_ini->name, $val->getSizeLimit()], $val->tooBig ) ) !== false @@ -219,12 +221,12 @@ class FileValidatorTest extends TestCase public function testValidateAttributeType() { - $val = new FileValidator(array('types' => 'jpeg, jpg')); + $val = new FileValidator(['types' => 'jpeg, jpg']); $m = FakedValidationModel::createWithAttributes( - array( - 'attr_jpg' => $this->createTestFiles(array(array('name' => 'one.jpeg'))), - 'attr_exe' => $this->createTestFiles(array(array('name' => 'bad.exe'))), - ) + [ + 'attr_jpg' => $this->createTestFiles([['name' => 'one.jpeg']]), + 'attr_exe' => $this->createTestFiles([['name' => 'bad.exe']]), + ] ); $val->validateAttribute($m, 'attr_jpg'); $this->assertFalse($m->hasErrors('attr_jpg')); @@ -237,20 +239,17 @@ class FileValidatorTest extends TestCase protected function createModelForAttributeTest() { return FakedValidationModel::createWithAttributes( - array( - 'attr_files' => $this->createTestFiles( - array( - array('name' => 'abc.jpg', 'size' => 1024, 'type' => 'image/jpeg'), - ) - ), - 'attr_files_empty' => $this->createTestFiles(array(array())), - 'attr_err_ini' => $this->createTestFiles(array(array('error' => UPLOAD_ERR_INI_SIZE))), - 'attr_err_part' => $this->createTestFiles(array(array('error' => UPLOAD_ERR_PARTIAL))), - 'attr_err_tmp' => $this->createTestFiles(array(array('error' => UPLOAD_ERR_NO_TMP_DIR))), - 'attr_err_write' => $this->createTestFiles(array(array('error' => UPLOAD_ERR_CANT_WRITE))), - 'attr_err_ext' => $this->createTestFiles(array(array('error' => UPLOAD_ERR_EXTENSION))), - - ) + [ + 'attr_files' => $this->createTestFiles([ + ['name' => 'abc.jpg', 'size' => 1024, 'type' => 'image/jpeg'], + ]), + 'attr_files_empty' => $this->createTestFiles([[]]), + 'attr_err_ini' => $this->createTestFiles([['error' => UPLOAD_ERR_INI_SIZE]]), + 'attr_err_part' => $this->createTestFiles([['error' => UPLOAD_ERR_PARTIAL]]), + 'attr_err_tmp' => $this->createTestFiles([['error' => UPLOAD_ERR_NO_TMP_DIR]]), + 'attr_err_write' => $this->createTestFiles([['error' => UPLOAD_ERR_CANT_WRITE]]), + 'attr_err_ext' => $this->createTestFiles([['error' => UPLOAD_ERR_EXTENSION]]), + ] ); } diff --git a/tests/unit/framework/validators/FilterValidatorTest.php b/tests/unit/framework/validators/FilterValidatorTest.php index 322f921..139d51d 100644 --- a/tests/unit/framework/validators/FilterValidatorTest.php +++ b/tests/unit/framework/validators/FilterValidatorTest.php @@ -17,13 +17,13 @@ class FilterValidatorTest extends TestCase public function testValidateAttribute() { - $m = FakedValidationModel::createWithAttributes(array( + $m = FakedValidationModel::createWithAttributes([ 'attr_one' => ' to be trimmed ', 'attr_two' => 'set this to null', 'attr_empty1' => '', 'attr_empty2' => null - )); - $val = new FilterValidator(array('filter' => 'trim')); + ]); + $val = new FilterValidator(['filter' => 'trim']); $val->validateAttribute($m, 'attr_one'); $this->assertSame('to be trimmed', $m->attr_one); $val->filter = function ($value) { @@ -31,7 +31,7 @@ class FilterValidatorTest extends TestCase }; $val->validateAttribute($m, 'attr_two'); $this->assertNull($m->attr_two); - $val->filter = array($this, 'notToBeNull'); + $val->filter = [$this, 'notToBeNull']; $val->validateAttribute($m, 'attr_empty1'); $this->assertSame($this->notToBeNull(''), $m->attr_empty1); $val->skipOnEmpty = true; diff --git a/tests/unit/framework/validators/NumberValidatorTest.php b/tests/unit/framework/validators/NumberValidatorTest.php index fa158d3..c2352ec 100644 --- a/tests/unit/framework/validators/NumberValidatorTest.php +++ b/tests/unit/framework/validators/NumberValidatorTest.php @@ -14,7 +14,7 @@ class NumberValidatorTest extends TestCase $val = new NumberValidator; $this->assertTrue(is_string($val->message)); $this->assertTrue(is_null($val->max)); - $val = new NumberValidator(array('min' => -1, 'max' => 20, 'integerOnly' => true)); + $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)); @@ -30,7 +30,7 @@ class NumberValidatorTest extends TestCase $this->assertTrue($val->validateValue(25.45)); $this->assertFalse($val->validateValue('25,45')); $this->assertFalse($val->validateValue('12:45')); - $val = new NumberValidator(array('integerOnly' => true)); + $val = new NumberValidator(['integerOnly' => true]); $this->assertTrue($val->validateValue(20)); $this->assertTrue($val->validateValue(0)); $this->assertFalse($val->validateValue(25.45)); @@ -51,7 +51,7 @@ class NumberValidatorTest extends TestCase $this->assertFalse($val->validateValue('-e3')); $this->assertFalse($val->validateValue('-4.534-e-12')); // 'signed' exponent $this->assertFalse($val->validateValue('12.23^4')); // expression instead of value - $val = new NumberValidator(array('integerOnly' => true)); + $val = new NumberValidator(['integerOnly' => true]); $this->assertFalse($val->validateValue('-1.23')); $this->assertFalse($val->validateValue('-4.423e-12')); $this->assertFalse($val->validateValue('12E3')); @@ -63,12 +63,12 @@ class NumberValidatorTest extends TestCase public function testValidateValueMin() { - $val = new NumberValidator(array('min' => 1)); + $val = new NumberValidator(['min' => 1]); $this->assertTrue($val->validateValue(1)); $this->assertFalse($val->validateValue(-1)); $this->assertFalse($val->validateValue('22e-12')); $this->assertTrue($val->validateValue(PHP_INT_MAX + 1)); - $val = new NumberValidator(array('min' => 1), array('integerOnly' => true)); + $val = new NumberValidator(['min' => 1], ['integerOnly' => true]); $this->assertTrue($val->validateValue(1)); $this->assertFalse($val->validateValue(-1)); $this->assertFalse($val->validateValue('22e-12')); @@ -77,12 +77,12 @@ class NumberValidatorTest extends TestCase public function testValidateValueMax() { - $val = new NumberValidator(array('max' => 1.25)); + $val = new NumberValidator(['max' => 1.25]); $this->assertTrue($val->validateValue(1)); $this->assertFalse($val->validateValue(1.5)); $this->assertTrue($val->validateValue('22e-12')); $this->assertTrue($val->validateValue('125e-2')); - $val = new NumberValidator(array('max' => 1.25, 'integerOnly' => true)); + $val = new NumberValidator(['max' => 1.25, 'integerOnly' => true]); $this->assertTrue($val->validateValue(1)); $this->assertFalse($val->validateValue(1.5)); $this->assertFalse($val->validateValue('22e-12')); @@ -91,12 +91,12 @@ class NumberValidatorTest extends TestCase public function testValidateValueRange() { - $val = new NumberValidator(array('min' => -10, 'max' => 20)); + $val = new NumberValidator(['min' => -10, 'max' => 20]); $this->assertTrue($val->validateValue(0)); $this->assertTrue($val->validateValue(-10)); $this->assertFalse($val->validateValue(-11)); $this->assertFalse($val->validateValue(21)); - $val = new NumberValidator(array('min' => -10, 'max' => 20, 'integerOnly' => true)); + $val = new NumberValidator(['min' => -10, 'max' => 20, 'integerOnly' => true]); $this->assertTrue($val->validateValue(0)); $this->assertFalse($val->validateValue(-11)); $this->assertFalse($val->validateValue(22)); @@ -113,7 +113,7 @@ class NumberValidatorTest extends TestCase $model->attr_number = '43^32'; //expression $val->validateAttribute($model, 'attr_number'); $this->assertTrue($model->hasErrors('attr_number')); - $val = new NumberValidator(array('min' => 10)); + $val = new NumberValidator(['min' => 10]); $model = new FakedValidationModel(); $model->attr_number = 10; $val->validateAttribute($model, 'attr_number'); @@ -121,7 +121,7 @@ class NumberValidatorTest extends TestCase $model->attr_number = 5; $val->validateAttribute($model, 'attr_number'); $this->assertTrue($model->hasErrors('attr_number')); - $val = new NumberValidator(array('max' => 10)); + $val = new NumberValidator(['max' => 10]); $model = new FakedValidationModel(); $model->attr_number = 10; $val->validateAttribute($model, 'attr_number'); @@ -129,7 +129,7 @@ class NumberValidatorTest extends TestCase $model->attr_number = 15; $val->validateAttribute($model, 'attr_number'); $this->assertTrue($model->hasErrors('attr_number')); - $val = new NumberValidator(array('max' => 10, 'integerOnly' => true)); + $val = new NumberValidator(['max' => 10, 'integerOnly' => true]); $model = new FakedValidationModel(); $model->attr_number = 10; $val->validateAttribute($model, 'attr_number'); @@ -137,18 +137,18 @@ class NumberValidatorTest extends TestCase $model->attr_number = 3.43; $val->validateAttribute($model, 'attr_number'); $this->assertTrue($model->hasErrors('attr_number')); - $val = new NumberValidator(array('min' => 1)); - $model = FakedValidationModel::createWithAttributes(array('attr_num' => array(1,2,3))); + $val = new NumberValidator(['min' => 1]); + $model = FakedValidationModel::createWithAttributes(['attr_num' => [1,2,3]]); $val->validateAttribute($model, 'attr_num'); $this->assertTrue($model->hasErrors('attr_num')); } public function testEnsureCustomMessageIsSetOnValidateAttribute() { - $val = new NumberValidator(array( + $val = new NumberValidator([ 'tooSmall' => '{attribute} is to small.', 'min' => 5 - )); + ]); $model = new FakedValidationModel(); $model->attr_number = 0; $val->validateAttribute($model, 'attr_number'); diff --git a/tests/unit/framework/validators/RangeValidatorTest.php b/tests/unit/framework/validators/RangeValidatorTest.php index a22d190..bfa7cae 100644 --- a/tests/unit/framework/validators/RangeValidatorTest.php +++ b/tests/unit/framework/validators/RangeValidatorTest.php @@ -12,18 +12,18 @@ class RangeValidatorTest extends TestCase public function testInitException() { $this->setExpectedException('yii\base\InvalidConfigException', 'The "range" property must be set.'); - $val = new RangeValidator(array('range' => 'not an array')); + $val = new RangeValidator(['range' => 'not an array']); } public function testAssureMessageSetOnInit() { - $val = new RangeValidator(array('range' => array())); + $val = new RangeValidator(['range' => []]); $this->assertTrue(is_string($val->message)); } public function testValidateValue() { - $val = new RangeValidator(array('range' => range(1, 10, 1))); + $val = new RangeValidator(['range' => range(1, 10, 1)]); $this->assertTrue($val->validateValue(1)); $this->assertFalse($val->validateValue(0)); $this->assertFalse($val->validateValue(11)); @@ -35,7 +35,7 @@ class RangeValidatorTest extends TestCase public function testValidateValueStrict() { - $val = new RangeValidator(array('range' => range(1, 10, 1), 'strict' => true)); + $val = new RangeValidator(['range' => range(1, 10, 1), 'strict' => true]); $this->assertTrue($val->validateValue(1)); $this->assertTrue($val->validateValue(5)); $this->assertTrue($val->validateValue(10)); @@ -46,7 +46,7 @@ class RangeValidatorTest extends TestCase public function testValidateValueNot() { - $val = new RangeValidator(array('range' => range(1, 10, 1), 'not' => true)); + $val = new RangeValidator(['range' => range(1, 10, 1), 'not' => true]); $this->assertFalse($val->validateValue(1)); $this->assertTrue($val->validateValue(0)); $this->assertTrue($val->validateValue(11)); @@ -58,8 +58,8 @@ class RangeValidatorTest extends TestCase public function testValidateAttribute() { - $val = new RangeValidator(array('range' => range(1, 10, 1))); - $m = FakedValidationModel::createWithAttributes(array('attr_r1' => 5, 'attr_r2' => 999)); + $val = new RangeValidator(['range' => range(1, 10, 1)]); + $m = FakedValidationModel::createWithAttributes(['attr_r1' => 5, 'attr_r2' => 999]); $val->validateAttribute($m, 'attr_r1'); $this->assertFalse($m->hasErrors()); $val->validateAttribute($m, 'attr_r2'); diff --git a/tests/unit/framework/validators/RegularExpressionValidatorTest.php b/tests/unit/framework/validators/RegularExpressionValidatorTest.php index fc89139..3262025 100644 --- a/tests/unit/framework/validators/RegularExpressionValidatorTest.php +++ b/tests/unit/framework/validators/RegularExpressionValidatorTest.php @@ -11,20 +11,20 @@ class RegularExpressionValidatorTest extends TestCase { public function testValidateValue() { - $val = new RegularExpressionValidator(array('pattern' => '/^[a-zA-Z0-9](\.)?([^\/]*)$/m')); + $val = new RegularExpressionValidator(['pattern' => '/^[a-zA-Z0-9](\.)?([^\/]*)$/m']); $this->assertTrue($val->validateValue('b.4')); $this->assertFalse($val->validateValue('b./')); - $this->assertFalse($val->validateValue(array('a', 'b'))); + $this->assertFalse($val->validateValue(['a', 'b'])); $val->not = true; $this->assertFalse($val->validateValue('b.4')); $this->assertTrue($val->validateValue('b./')); - $this->assertFalse($val->validateValue(array('a', 'b'))); + $this->assertFalse($val->validateValue(['a', 'b'])); } public function testValidateAttribute() { - $val = new RegularExpressionValidator(array('pattern' => '/^[a-zA-Z0-9](\.)?([^\/]*)$/m')); - $m = FakedValidationModel::createWithAttributes(array('attr_reg1' => 'b.4')); + $val = new RegularExpressionValidator(['pattern' => '/^[a-zA-Z0-9](\.)?([^\/]*)$/m']); + $m = FakedValidationModel::createWithAttributes(['attr_reg1' => 'b.4']); $val->validateAttribute($m, 'attr_reg1'); $this->assertFalse($m->hasErrors('attr_reg1')); $m->attr_reg1 = 'b./'; @@ -34,7 +34,7 @@ class RegularExpressionValidatorTest extends TestCase public function testMessageSetOnInit() { - $val = new RegularExpressionValidator(array('pattern' => '/^[a-zA-Z0-9](\.)?([^\/]*)$/m')); + $val = new RegularExpressionValidator(['pattern' => '/^[a-zA-Z0-9](\.)?([^\/]*)$/m']); $this->assertTrue(is_string($val->message)); } diff --git a/tests/unit/framework/validators/RequiredValidatorTest.php b/tests/unit/framework/validators/RequiredValidatorTest.php index 22c9d0b..f60e69e 100644 --- a/tests/unit/framework/validators/RequiredValidatorTest.php +++ b/tests/unit/framework/validators/RequiredValidatorTest.php @@ -12,14 +12,14 @@ class RequiredValidatorTest extends TestCase { $val = new RequiredValidator(); $this->assertFalse($val->validateValue(null)); - $this->assertFalse($val->validateValue(array())); + $this->assertFalse($val->validateValue([])); $this->assertTrue($val->validateValue('not empty')); - $this->assertTrue($val->validateValue(array('with', 'elements'))); + $this->assertTrue($val->validateValue(['with', 'elements'])); } public function testValidateValueWithValue() { - $val = new RequiredValidator(array('requiredValue' => 55)); + $val = new RequiredValidator(['requiredValue' => 55]); $this->assertTrue($val->validateValue(55)); $this->assertTrue($val->validateValue("55")); $this->assertTrue($val->validateValue("0x37")); @@ -37,17 +37,17 @@ class RequiredValidatorTest extends TestCase { // empty req-value $val = new RequiredValidator(); - $m = FakedValidationModel::createWithAttributes(array('attr_val' => null)); + $m = FakedValidationModel::createWithAttributes(['attr_val' => null]); $val->validateAttribute($m, 'attr_val'); $this->assertTrue($m->hasErrors('attr_val')); $this->assertTrue(stripos(current($m->getErrors('attr_val')), 'blank') !== false); - $val = new RequiredValidator(array('requiredValue' => 55)); - $m = FakedValidationModel::createWithAttributes(array('attr_val' => 56)); + $val = new RequiredValidator(['requiredValue' => 55]); + $m = FakedValidationModel::createWithAttributes(['attr_val' => 56]); $val->validateAttribute($m, 'attr_val'); $this->assertTrue($m->hasErrors('attr_val')); $this->assertTrue(stripos(current($m->getErrors('attr_val')), 'must be') !== false); - $val = new RequiredValidator(array('requiredValue' => 55)); - $m = FakedValidationModel::createWithAttributes(array('attr_val' => 55)); + $val = new RequiredValidator(['requiredValue' => 55]); + $m = FakedValidationModel::createWithAttributes(['attr_val' => 55]); $val->validateAttribute($m, 'attr_val'); $this->assertFalse($m->hasErrors('attr_val')); } diff --git a/tests/unit/framework/validators/StringValidatorTest.php b/tests/unit/framework/validators/StringValidatorTest.php index 8beaf16..a99567b 100644 --- a/tests/unit/framework/validators/StringValidatorTest.php +++ b/tests/unit/framework/validators/StringValidatorTest.php @@ -18,23 +18,23 @@ class StringValidatorTest extends TestCase public function testValidateValue() { $val = new StringValidator(); - $this->assertFalse($val->validateValue(array('not a string'))); + $this->assertFalse($val->validateValue(['not a string'])); $this->assertTrue($val->validateValue('Just some string')); } public function testValidateValueLength() { - $val = new StringValidator(array('length' => 25)); + $val = new StringValidator(['length' => 25]); $this->assertTrue($val->validateValue(str_repeat('x', 25))); $this->assertTrue($val->validateValue(str_repeat('€', 25))); $this->assertFalse($val->validateValue(str_repeat('x', 125))); $this->assertFalse($val->validateValue('')); - $val = new StringValidator(array('length' => array(25))); + $val = new StringValidator(['length' => [25]]); $this->assertTrue($val->validateValue(str_repeat('x', 25))); $this->assertTrue($val->validateValue(str_repeat('x', 1250))); $this->assertFalse($val->validateValue(str_repeat('Ä', 24))); $this->assertFalse($val->validateValue('')); - $val = new StringValidator(array('length' => array(10, 20))); + $val = new StringValidator(['length' => [10, 20]]); $this->assertTrue($val->validateValue(str_repeat('x', 15))); $this->assertTrue($val->validateValue(str_repeat('x', 10))); $this->assertTrue($val->validateValue(str_repeat('x', 20))); @@ -42,20 +42,20 @@ class StringValidatorTest extends TestCase $this->assertFalse($val->validateValue(str_repeat('x', 25))); $this->assertFalse($val->validateValue('')); // make sure min/max are overridden - $val = new StringValidator(array('length' => array(10, 20), 'min' => 25, 'max' => 35)); + $val = new StringValidator(['length' => [10, 20], 'min' => 25, 'max' => 35]); $this->assertTrue($val->validateValue(str_repeat('x', 15))); $this->assertFalse($val->validateValue(str_repeat('x', 30))); } public function testValidateValueMinMax() { - $val = new StringValidator(array('min' => 10)); + $val = new StringValidator(['min' => 10]); $this->assertTrue($val->validateValue(str_repeat('x', 10))); $this->assertFalse($val->validateValue('xxxx')); - $val = new StringValidator(array('max' => 10)); + $val = new StringValidator(['max' => 10]); $this->assertTrue($val->validateValue('xxxx')); $this->assertFalse($val->validateValue(str_repeat('y', 20))); - $val = new StringValidator(array('min' => 10, 'max' => 20)); + $val = new StringValidator(['min' => 10, 'max' => 20]); $this->assertTrue($val->validateValue(str_repeat('y', 15))); $this->assertFalse($val->validateValue('abc')); $this->assertFalse($val->validateValue(str_repeat('b', 25))); @@ -68,7 +68,7 @@ class StringValidatorTest extends TestCase $model->attr_string = 'a tet string'; $val->validateAttribute($model, 'attr_string'); $this->assertFalse($model->hasErrors()); - $val = new StringValidator(array('length' => 20)); + $val = new StringValidator(['length' => 20]); $model = new FakedValidationModel(); $model->attr_string = str_repeat('x', 20); $val->validateAttribute($model, 'attr_string'); @@ -77,7 +77,7 @@ class StringValidatorTest extends TestCase $model->attr_string = 'abc'; $val->validateAttribute($model, 'attr_string'); $this->assertTrue($model->hasErrors('attr_string')); - $val = new StringValidator(array('max' => 2)); + $val = new StringValidator(['max' => 2]); $model = new FakedValidationModel(); $model->attr_string = 'a'; $val->validateAttribute($model, 'attr_string'); @@ -86,15 +86,15 @@ class StringValidatorTest extends TestCase $model->attr_string = 'abc'; $val->validateAttribute($model, 'attr_string'); $this->assertTrue($model->hasErrors('attr_string')); - $val = new StringValidator(array('max' => 1)); - $model = FakedValidationModel::createWithAttributes(array('attr_str' => array('abc'))); + $val = new StringValidator(['max' => 1]); + $model = FakedValidationModel::createWithAttributes(['attr_str' => ['abc']]); $val->validateAttribute($model, 'attr_str'); $this->assertTrue($model->hasErrors('attr_str')); } public function testEnsureMessagesOnInit() { - $val = new StringValidator(array('min' => 1, 'max' => 2)); + $val = new StringValidator(['min' => 1, 'max' => 2]); $this->assertTrue(is_string($val->message)); $this->assertTrue(is_string($val->tooLong)); $this->assertTrue(is_string($val->tooShort)); @@ -102,10 +102,10 @@ class StringValidatorTest extends TestCase public function testCustomErrorMessageInValidateAttribute() { - $val = new StringValidator(array( + $val = new StringValidator([ 'min' => 5, 'tooShort' => '{attribute} to short. Min is {min}', - )); + ]); $model = new FakedValidationModel(); $model->attr_string = 'abc'; $val->validateAttribute($model, 'attr_string'); diff --git a/tests/unit/framework/validators/UniqueValidatorTest.php b/tests/unit/framework/validators/UniqueValidatorTest.php index a39ee41..37d666f 100644 --- a/tests/unit/framework/validators/UniqueValidatorTest.php +++ b/tests/unit/framework/validators/UniqueValidatorTest.php @@ -51,15 +51,15 @@ class UniqueValidatorTest extends DatabaseTestCase $val->validateAttribute($m, 'ref'); $this->assertFalse($m->hasErrors('ref')); // array error - $m = FakedValidationModel::createWithAttributes(array('attr_arr' => array('a', 'b'))); + $m = FakedValidationModel::createWithAttributes(['attr_arr' => ['a', 'b']]); $val->validateAttribute($m, 'attr_arr'); $this->assertTrue($m->hasErrors('attr_arr')); } public function testValidateAttributeOfNonARModel() { - $val = new UniqueValidator(array('className' => ValidatorTestRefModel::className(), 'attributeName' => 'ref')); - $m = FakedValidationModel::createWithAttributes(array('attr_1' => 5, 'attr_2' => 1313)); + $val = new UniqueValidator(['className' => ValidatorTestRefModel::className(), 'attributeName' => 'ref']); + $m = FakedValidationModel::createWithAttributes(['attr_1' => 5, 'attr_2' => 1313]); $val->validateAttribute($m, 'attr_1'); $this->assertTrue($m->hasErrors('attr_1')); $val->validateAttribute($m, 'attr_2'); @@ -68,7 +68,7 @@ class UniqueValidatorTest extends DatabaseTestCase public function testValidateNonDatabaseAttribute() { - $val = new UniqueValidator(array('className' => ValidatorTestRefModel::className(), 'attributeName' => 'ref')); + $val = new UniqueValidator(['className' => ValidatorTestRefModel::className(), 'attributeName' => 'ref']); $m = ValidatorTestMainModel::find(1); $val->validateAttribute($m, 'testMainVal'); $this->assertFalse($m->hasErrors('testMainVal')); diff --git a/tests/unit/framework/validators/UrlValidatorTest.php b/tests/unit/framework/validators/UrlValidatorTest.php index 239c92b..4d5fae2 100644 --- a/tests/unit/framework/validators/UrlValidatorTest.php +++ b/tests/unit/framework/validators/UrlValidatorTest.php @@ -25,23 +25,23 @@ class UrlValidatorTest extends TestCase public function testValidateValueWithDefaultScheme() { - $val = new UrlValidator(array('defaultScheme' => 'https')); + $val = new UrlValidator(['defaultScheme' => 'https']); $this->assertTrue($val->validateValue('yiiframework.com')); $this->assertTrue($val->validateValue('http://yiiframework.com')); } public function testValidateValueWithoutScheme() { - $val = new UrlValidator(array('pattern' => '/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)/i')); + $val = new UrlValidator(['pattern' => '/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)/i']); $this->assertTrue($val->validateValue('yiiframework.com')); } public function testValidateWithCustomScheme() { - $val = new UrlValidator(array( - 'validSchemes' => array('http', 'https', 'ftp', 'ftps'), + $val = new UrlValidator([ + 'validSchemes' => ['http', 'https', 'ftp', 'ftps'], 'defaultScheme' => 'http', - )); + ]); $this->assertTrue($val->validateValue('ftp://ftp.ruhr-uni-bochum.de/')); $this->assertTrue($val->validateValue('google.de')); $this->assertTrue($val->validateValue('http://google.de')); @@ -57,9 +57,9 @@ class UrlValidatorTest extends TestCase $this->markTestSkipped('intl package required'); return; } - $val = new UrlValidator(array( + $val = new UrlValidator([ 'enableIDN' => true, - )); + ]); $this->assertTrue($val->validateValue('http://äüößìà.de')); // converted via http://mct.verisign-grs.com/convertServlet $this->assertTrue($val->validateValue('http://xn--zcack7ayc9a.de')); diff --git a/tests/unit/framework/validators/ValidatorTest.php b/tests/unit/framework/validators/ValidatorTest.php index f0a114b..8582b8c 100644 --- a/tests/unit/framework/validators/ValidatorTest.php +++ b/tests/unit/framework/validators/ValidatorTest.php @@ -13,10 +13,10 @@ use yiiunit\TestCase; class ValidatorTest extends TestCase { - protected function getTestModel($additionalAttributes = array()) + protected function getTestModel($additionalAttributes = []) { $attributes = array_merge( - array('attr_runMe1' => true, 'attr_runMe2' => true, 'attr_skip' => true), + ['attr_runMe1' => true, 'attr_runMe2' => true, 'attr_skip' => true], $additionalAttributes ); return FakedValidationModel::createWithAttributes($attributes); @@ -24,31 +24,31 @@ class ValidatorTest extends TestCase public function testCreateValidator() { - $model = FakedValidationModel::createWithAttributes(array('attr_test1' => 'abc', 'attr_test2' => '2013')); + $model = FakedValidationModel::createWithAttributes(['attr_test1' => 'abc', 'attr_test2' => '2013']); /** @var $numberVal NumberValidator */ - $numberVal = TestValidator::createValidator('number', $model, array('attr_test1')); + $numberVal = TestValidator::createValidator('number', $model, ['attr_test1']); $this->assertInstanceOf(NumberValidator::className(), $numberVal); - $numberVal = TestValidator::createValidator('integer', $model, array('attr_test2')); + $numberVal = TestValidator::createValidator('integer', $model, ['attr_test2']); $this->assertInstanceOf(NumberValidator::className(), $numberVal); $this->assertTrue($numberVal->integerOnly); $val = TestValidator::createValidator( 'boolean', $model, 'attr_test1, attr_test2', - array('on' => array('a', 'b')) + ['on' => ['a', 'b']] ); $this->assertInstanceOf(BooleanValidator::className(), $val); - $this->assertSame(array('a', 'b'), $val->on); - $this->assertSame(array('attr_test1', 'attr_test2'), $val->attributes); + $this->assertSame(['a', 'b'], $val->on); + $this->assertSame(['attr_test1', 'attr_test2'], $val->attributes); $val = TestValidator::createValidator( 'boolean', $model, 'attr_test1, attr_test2', - array('on' => 'a, b', 'except' => 'c,d,e') + ['on' => 'a, b', 'except' => 'c,d,e'] ); $this->assertInstanceOf(BooleanValidator::className(), $val); - $this->assertSame(array('a', 'b'), $val->on); - $this->assertSame(array('c', 'd', 'e'), $val->except); + $this->assertSame(['a', 'b'], $val->on); + $this->assertSame(['c', 'd', 'e'], $val->except); $val = TestValidator::createValidator('inlineVal', $model, 'val_attr_a'); $this->assertInstanceOf(InlineValidator::className(), $val); $this->assertSame('inlineVal', $val->method); @@ -56,7 +56,7 @@ class ValidatorTest extends TestCase public function testValidate() { - $val = new TestValidator(array('attributes' => array('attr_runMe1', 'attr_runMe2'))); + $val = new TestValidator(['attributes' => ['attr_runMe1', 'attr_runMe2']]); $model = $this->getTestModel(); $val->validate($model); $this->assertTrue($val->isAttributeValidated('attr_runMe1')); @@ -66,9 +66,9 @@ class ValidatorTest extends TestCase public function testValidateWithAttributeIntersect() { - $val = new TestValidator(array('attributes' => array('attr_runMe1', 'attr_runMe2'))); + $val = new TestValidator(['attributes' => ['attr_runMe1', 'attr_runMe2']]); $model = $this->getTestModel(); - $val->validate($model, array('attr_runMe1')); + $val->validate($model, ['attr_runMe1']); $this->assertTrue($val->isAttributeValidated('attr_runMe1')); $this->assertFalse($val->isAttributeValidated('attr_runMe2')); $this->assertFalse($val->isAttributeValidated('attr_skip')); @@ -78,7 +78,7 @@ class ValidatorTest extends TestCase { $val = new TestValidator(); $model = $this->getTestModel(); - $val->validate($model, array('attr_runMe1')); + $val->validate($model, ['attr_runMe1']); $this->assertFalse($val->isAttributeValidated('attr_runMe1')); $this->assertFalse($val->isAttributeValidated('attr_runMe2')); $this->assertFalse($val->isAttributeValidated('attr_skip')); @@ -90,7 +90,7 @@ class ValidatorTest extends TestCase public function testValidateWithError() { - $val = new TestValidator(array('attributes' => array('attr_runMe1', 'attr_runMe2'), 'skipOnError' => false)); + $val = new TestValidator(['attributes' => ['attr_runMe1', 'attr_runMe2'], 'skipOnError' => false]); $model = $this->getTestModel(); $val->validate($model); $this->assertTrue($val->isAttributeValidated('attr_runMe1')); @@ -98,11 +98,11 @@ class ValidatorTest extends TestCase $this->assertFalse($val->isAttributeValidated('attr_skip')); $this->assertEquals(1, $val->countAttributeValidations('attr_runMe2')); $this->assertEquals(1, $val->countAttributeValidations('attr_runMe1')); - $val->validate($model, array('attr_runMe2')); + $val->validate($model, ['attr_runMe2']); $this->assertEquals(2, $val->countAttributeValidations('attr_runMe2')); $this->assertEquals(1, $val->countAttributeValidations('attr_runMe1')); $this->assertEquals(0, $val->countAttributeValidations('attr_skip')); - $val = new TestValidator(array('attributes' => array('attr_runMe1', 'attr_runMe2'), 'skipOnError' => true)); + $val = new TestValidator(['attributes' => ['attr_runMe1', 'attr_runMe2'], 'skipOnError' => true]); $model = $this->getTestModel(); $val->enableErrorOnValidateAttribute(); $val->validate($model); @@ -112,7 +112,7 @@ class ValidatorTest extends TestCase $this->assertEquals(1, $val->countAttributeValidations('attr_runMe1')); $this->assertEquals(1, $val->countAttributeValidations('attr_runMe1')); $this->assertEquals(0, $val->countAttributeValidations('attr_skip')); - $val->validate($model, array('attr_runMe2')); + $val->validate($model, ['attr_runMe2']); $this->assertEquals(1, $val->countAttributeValidations('attr_runMe2')); $this->assertEquals(1, $val->countAttributeValidations('attr_runMe1')); $this->assertEquals(0, $val->countAttributeValidations('attr_skip')); @@ -120,16 +120,16 @@ class ValidatorTest extends TestCase public function testValidateWithEmpty() { - $val = new TestValidator(array( - 'attributes' => array( + $val = new TestValidator([ + 'attributes' => [ 'attr_runMe1', 'attr_runMe2', 'attr_empty1', 'attr_empty2' - ), + ], 'skipOnEmpty' => true, - )); - $model = $this->getTestModel(array('attr_empty1' => '', 'attr_emtpy2' => ' ')); + ]); + $model = $this->getTestModel(['attr_empty1' => '', 'attr_emtpy2' => ' ']); $val->validate($model); $this->assertTrue($val->isAttributeValidated('attr_runMe1')); $this->assertTrue($val->isAttributeValidated('attr_runMe2')); @@ -139,16 +139,16 @@ class ValidatorTest extends TestCase $val->validate($model); $this->assertTrue($val->isAttributeValidated('attr_empty1')); $this->assertFalse($val->isAttributeValidated('attr_empty2')); - $val = new TestValidator(array( - 'attributes' => array( + $val = new TestValidator([ + 'attributes' => [ 'attr_runMe1', 'attr_runMe2', 'attr_empty1', 'attr_empty2' - ), + ], 'skipOnEmpty' => false, - )); - $model = $this->getTestModel(array('attr_empty1' => '', 'attr_emtpy2' => ' ')); + ]); + $model = $this->getTestModel(['attr_empty1' => '', 'attr_emtpy2' => ' ']); $val->validate($model); $this->assertTrue($val->isAttributeValidated('attr_runMe1')); $this->assertTrue($val->isAttributeValidated('attr_runMe2')); @@ -160,7 +160,7 @@ class ValidatorTest extends TestCase { $val = new TestValidator(); $this->assertTrue($val->isEmpty(null)); - $this->assertTrue($val->isEmpty(array())); + $this->assertTrue($val->isEmpty([])); $this->assertTrue($val->isEmpty('')); $this->assertFalse($val->isEmpty(5)); $this->assertFalse($val->isEmpty(0)); @@ -190,7 +190,7 @@ class ValidatorTest extends TestCase { $val = new TestValidator(); $this->assertNull( - $val->clientValidateAttribute($this->getTestModel(), 'attr_runMe1', array()) + $val->clientValidateAttribute($this->getTestModel(), 'attr_runMe1', []) ); //todo pass a view instead of array } @@ -199,10 +199,10 @@ class ValidatorTest extends TestCase $val = new TestValidator(); $this->assertTrue($val->isActive('scenA')); $this->assertTrue($val->isActive('scenB')); - $val->except = array('scenB'); + $val->except = ['scenB']; $this->assertTrue($val->isActive('scenA')); $this->assertFalse($val->isActive('scenB')); - $val->on = array('scenC'); + $val->on = ['scenC']; $this->assertFalse($val->isActive('scenA')); $this->assertFalse($val->isActive('scenB')); $this->assertTrue($val->isActive('scenC')); @@ -211,16 +211,16 @@ class ValidatorTest extends TestCase public function testAddError() { $val = new TestValidator(); - $m = $this->getTestModel(array('attr_msg_val' => 'abc')); + $m = $this->getTestModel(['attr_msg_val' => 'abc']); $val->addError($m, 'attr_msg_val', '{attribute}::{value}'); $errors = $m->getErrors('attr_msg_val'); $this->assertEquals('attr_msg_val::abc', $errors[0]); - $m = $this->getTestModel(array('attr_msg_val' => array('bcc'))); + $m = $this->getTestModel(['attr_msg_val' => ['bcc']]); $val->addError($m, 'attr_msg_val', '{attribute}::{value}'); $errors = $m->getErrors('attr_msg_val'); - $this->assertEquals('attr_msg_val::array()', $errors[0]); - $m = $this->getTestModel(array('attr_msg_val' => 'abc')); - $val->addError($m, 'attr_msg_val', '{attribute}::{value}::{param}', array('{param}' => 'param_value')); + $this->assertEquals('attr_msg_val::[)', $errors[0]); + $m = $this->getTestModel(['attr_msg_val' => 'abc']); + $val->addError($m, 'attr_msg_val', '{attribute}::{value}::{param}', ['{param}' => 'param_value']); $errors = $m->getErrors('attr_msg_val'); $this->assertEquals('attr_msg_val::abc::param_value', $errors[0]); } diff --git a/tests/unit/framework/web/AssetBundleTest.php b/tests/unit/framework/web/AssetBundleTest.php index 6fa6238..9cc3894 100644 --- a/tests/unit/framework/web/AssetBundleTest.php +++ b/tests/unit/framework/web/AssetBundleTest.php @@ -29,10 +29,10 @@ class AssetBundleTest extends \yiiunit\TestCase protected function getView() { $view = new View(); - $view->setAssetManager(new AssetManager(array( + $view->setAssetManager(new AssetManager([ 'basePath' => '@testWebRoot/assets', 'baseUrl' => '@testWeb/assets', - ))); + ])); return $view; } @@ -76,14 +76,14 @@ EOF; public function positionProvider() { - return array( - array(View::POS_HEAD, true), - array(View::POS_HEAD, false), - array(View::POS_BEGIN, true), - array(View::POS_BEGIN, false), - array(View::POS_END, true), - array(View::POS_END, false), - ); + return [ + [View::POS_HEAD, true], + [View::POS_HEAD, false], + [View::POS_BEGIN, true], + [View::POS_BEGIN, false], + [View::POS_END, true], + [View::POS_END, false], + ]; } /** @@ -93,11 +93,11 @@ EOF; { $view = $this->getView(); - $view->getAssetManager()->bundles['yiiunit\\framework\\web\\TestAssetBundle'] = array( - 'jsOptions' => array( + $view->getAssetManager()->bundles['yiiunit\\framework\\web\\TestAssetBundle'] = [ + 'jsOptions' => [ 'position' => $pos, - ), - ); + ], + ]; $this->assertEmpty($view->assetBundles); if ($jqAlreadyRegistered) { @@ -148,12 +148,12 @@ EOF; public function positionProvider2() { - return array( - array(View::POS_BEGIN, true), - array(View::POS_BEGIN, false), - array(View::POS_END, true), - array(View::POS_END, false), - ); + return [ + [View::POS_BEGIN, true], + [View::POS_BEGIN, false], + [View::POS_END, true], + [View::POS_END, false], + ]; } /** @@ -163,16 +163,16 @@ EOF; { $view = $this->getView(); - $view->getAssetManager()->bundles['yiiunit\\framework\\web\\TestAssetBundle'] = array( - 'jsOptions' => array( + $view->getAssetManager()->bundles['yiiunit\\framework\\web\\TestAssetBundle'] = [ + 'jsOptions' => [ 'position' => $pos - 1, - ), - ); - $view->getAssetManager()->bundles['yiiunit\\framework\\web\\TestJqueryAsset'] = array( - 'jsOptions' => array( + ], + ]; + $view->getAssetManager()->bundles['yiiunit\\framework\\web\\TestJqueryAsset'] = [ + 'jsOptions' => [ 'position' => $pos, - ), - ); + ], + ]; $this->assertEmpty($view->assetBundles); if ($jqAlreadyRegistered) { @@ -193,36 +193,36 @@ class TestSimpleAsset extends AssetBundle { public $basePath = '@testWebRoot/js'; public $baseUrl = '@testWeb/js'; - public $js = array( + public $js = [ 'jquery.js', - ); + ]; } class TestAssetBundle extends AssetBundle { public $basePath = '@testWebRoot/files'; public $baseUrl = '@testWeb/files'; - public $css = array( + public $css = [ 'cssFile.css', - ); - public $js = array( + ]; + public $js = [ 'jsFile.js', - ); - public $depends = array( + ]; + public $depends = [ 'yiiunit\\framework\\web\\TestJqueryAsset' - ); + ]; } class TestJqueryAsset extends AssetBundle { public $basePath = '@testWebRoot/js'; public $baseUrl = '@testWeb/js'; - public $js = array( + public $js = [ 'jquery.js', - ); - public $depends = array( + ]; + public $depends = [ 'yiiunit\\framework\\web\\TestAssetLevel3' - ); + ]; } class TestAssetLevel3 extends AssetBundle @@ -235,22 +235,22 @@ class TestAssetCircleA extends AssetBundle { public $basePath = '@testWebRoot/js'; public $baseUrl = '@testWeb/js'; - public $js = array( + public $js = [ 'jquery.js', - ); - public $depends = array( + ]; + public $depends = [ 'yiiunit\\framework\\web\\TestAssetCircleB' - ); + ]; } class TestAssetCircleB extends AssetBundle { public $basePath = '@testWebRoot/js'; public $baseUrl = '@testWeb/js'; - public $js = array( + public $js = [ 'jquery.js', - ); - public $depends = array( + ]; + public $depends = [ 'yiiunit\\framework\\web\\TestAssetCircleA' - ); + ]; } \ No newline at end of file diff --git a/tests/unit/framework/web/CacheSessionTest.php b/tests/unit/framework/web/CacheSessionTest.php index e740596..ae73868 100644 --- a/tests/unit/framework/web/CacheSessionTest.php +++ b/tests/unit/framework/web/CacheSessionTest.php @@ -31,9 +31,6 @@ class CacheSessionTest extends \yiiunit\TestCase public function testInvalidCache() { $this->setExpectedException('yii\base\InvalidConfigException'); - - $session = new CacheSession(array( - 'cache' => 'invalid', - )); + $session = new CacheSession(['cache' => 'invalid']); } } diff --git a/tests/unit/framework/web/ResponseTest.php b/tests/unit/framework/web/ResponseTest.php index 2a9b4bf..6077945 100644 --- a/tests/unit/framework/web/ResponseTest.php +++ b/tests/unit/framework/web/ResponseTest.php @@ -34,11 +34,11 @@ 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 array( - array('0-5', '0-5', 6, '12ёж'), - array('2-', '2-66', 65, 'ёжик3456798áèabcdefghijklmnopqrstuvwxyz!"§$%&/(ёжик)=?'), - array('-12', '55-66', 12, '(ёжик)=?'), - ); + return [ + ['0-5', '0-5', 6, '12ёж'], + ['2-', '2-66', 65, 'ёжик3456798áèabcdefghijklmnopqrstuvwxyz!"§$%&/(ёжик)=?'], + ['-12', '55-66', 12, '(ёжик)=?'], + ]; } /** @@ -66,12 +66,12 @@ 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 array( - array('1-2,3-5,6-10'), // multiple range request not supported - array('5-1'), // last-byte-pos value is less than its first-byte-pos value - array('-100000'), // last-byte-pos bigger then content length - array('10000-'), // first-byte-pos bigger then content length - ); + 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 + ]; } /** diff --git a/tests/unit/framework/web/UrlManagerTest.php b/tests/unit/framework/web/UrlManagerTest.php index a77a66d..2c3d458 100644 --- a/tests/unit/framework/web/UrlManagerTest.php +++ b/tests/unit/framework/web/UrlManagerTest.php @@ -19,205 +19,203 @@ class UrlManagerTest extends TestCase public function testCreateUrl() { // default setting with '/' as base url - $manager = new UrlManager(array( + $manager = new UrlManager([ 'baseUrl' => '/', 'cache' => null, - )); + ]); $url = $manager->createUrl('post/view'); $this->assertEquals('?r=post/view', $url); - $url = $manager->createUrl('post/view', array('id' => 1, 'title' => 'sample post')); + $url = $manager->createUrl('post/view', ['id' => 1, 'title' => 'sample post']); $this->assertEquals('?r=post/view&id=1&title=sample+post', $url); // default setting with '/test/' as base url - $manager = new UrlManager(array( + $manager = new UrlManager([ 'baseUrl' => '/test/', 'cache' => null, - )); - $url = $manager->createUrl('post/view', array('id' => 1, 'title' => 'sample post')); + ]); + $url = $manager->createUrl('post/view', ['id' => 1, 'title' => 'sample post']); $this->assertEquals('/test?r=post/view&id=1&title=sample+post', $url); // pretty URL without rules - $manager = new UrlManager(array( + $manager = new UrlManager([ 'enablePrettyUrl' => true, 'baseUrl' => '/', 'cache' => null, - )); - $url = $manager->createUrl('post/view', array('id' => 1, 'title' => 'sample post')); + ]); + $url = $manager->createUrl('post/view', ['id' => 1, 'title' => 'sample post']); $this->assertEquals('/post/view?id=1&title=sample+post', $url); - $manager = new UrlManager(array( + $manager = new UrlManager([ 'enablePrettyUrl' => true, 'baseUrl' => '/test/', 'cache' => null, - )); - $url = $manager->createUrl('post/view', array('id' => 1, 'title' => 'sample post')); + ]); + $url = $manager->createUrl('post/view', ['id' => 1, 'title' => 'sample post']); $this->assertEquals('/test/post/view?id=1&title=sample+post', $url); - $manager = new UrlManager(array( + $manager = new UrlManager([ 'enablePrettyUrl' => true, 'baseUrl' => '/test/index.php', 'cache' => null, - )); - $url = $manager->createUrl('post/view', array('id' => 1, 'title' => 'sample post')); + ]); + $url = $manager->createUrl('post/view', ['id' => 1, 'title' => 'sample post']); $this->assertEquals('/test/index.php/post/view?id=1&title=sample+post', $url); // todo: test showScriptName // pretty URL with rules - $manager = new UrlManager(array( + $manager = new UrlManager([ 'enablePrettyUrl' => true, 'cache' => null, - 'rules' => array( - array( + 'rules' => [ + [ 'pattern' => 'post//', 'route' => 'post/view', - ), - ), + ], + ], 'baseUrl' => '/', - )); - $url = $manager->createUrl('post/view', array('id' => 1, 'title' => 'sample post')); + ]); + $url = $manager->createUrl('post/view', ['id' => 1, 'title' => 'sample post']); $this->assertEquals('/post/1/sample+post', $url); - $url = $manager->createUrl('post/index', array('page' => 1)); + $url = $manager->createUrl('post/index', ['page' => 1]); $this->assertEquals('/post/index?page=1', $url); // pretty URL with rules and suffix - $manager = new UrlManager(array( + $manager = new UrlManager([ 'enablePrettyUrl' => true, 'cache' => null, - 'rules' => array( - array( + 'rules' => [ + [ 'pattern' => 'post/<id>/<title>', 'route' => 'post/view', - ), - ), + ], + ], 'baseUrl' => '/', 'suffix' => '.html', - )); - $url = $manager->createUrl('post/view', array('id' => 1, 'title' => 'sample post')); + ]); + $url = $manager->createUrl('post/view', ['id' => 1, 'title' => 'sample post']); $this->assertEquals('/post/1/sample+post.html', $url); - $url = $manager->createUrl('post/index', array('page' => 1)); + $url = $manager->createUrl('post/index', ['page' => 1]); $this->assertEquals('/post/index.html?page=1', $url); // pretty URL with rules that have host info - $manager = new UrlManager(array( + $manager = new UrlManager([ 'enablePrettyUrl' => true, 'cache' => null, - 'rules' => array( - array( + 'rules' => [ + [ 'pattern' => 'post/<id>/<title>', 'route' => 'post/view', 'host' => 'http://<lang:en|fr>.example.com', - ), - ), + ], + ], 'baseUrl' => '/test', - )); - $url = $manager->createUrl('post/view', array('id' => 1, 'title' => 'sample post', 'lang' => 'en')); + ]); + $url = $manager->createUrl('post/view', ['id' => 1, 'title' => 'sample post', 'lang' => 'en']); $this->assertEquals('http://en.example.com/test/post/1/sample+post', $url); - $url = $manager->createUrl('post/index', array('page' => 1)); + $url = $manager->createUrl('post/index', ['page' => 1]); $this->assertEquals('/test/post/index?page=1', $url); } public function testCreateAbsoluteUrl() { - $manager = new UrlManager(array( + $manager = new UrlManager([ 'baseUrl' => '/', 'hostInfo' => 'http://www.example.com', 'cache' => null, - )); - $url = $manager->createAbsoluteUrl('post/view', array('id' => 1, 'title' => 'sample post')); + ]); + $url = $manager->createAbsoluteUrl('post/view', ['id' => 1, 'title' => 'sample post']); $this->assertEquals('http://www.example.com?r=post/view&id=1&title=sample+post', $url); } public function testParseRequest() { - $manager = new UrlManager(array( - 'cache' => null, - )); + $manager = new UrlManager(['cache' => null]); $request = new Request; // default setting without 'r' param unset($_GET['r']); $result = $manager->parseRequest($request); - $this->assertEquals(array('', array()), $result); + $this->assertEquals(['', []], $result); // default setting with 'r' param $_GET['r'] = 'site/index'; $result = $manager->parseRequest($request); - $this->assertEquals(array('site/index', array()), $result); + $this->assertEquals(['site/index', []], $result); // default setting with 'r' param as an array - $_GET['r'] = array('site/index'); + $_GET['r'] = ['site/index']; $result = $manager->parseRequest($request); - $this->assertEquals(array('', array()), $result); + $this->assertEquals(['', []], $result); // pretty URL without rules - $manager = new UrlManager(array( + $manager = new UrlManager([ 'enablePrettyUrl' => true, 'cache' => null, - )); + ]); // empty pathinfo $request->pathInfo = ''; $result = $manager->parseRequest($request); - $this->assertEquals(array('', array()), $result); + $this->assertEquals(['', []], $result); // normal pathinfo $request->pathInfo = 'site/index'; $result = $manager->parseRequest($request); - $this->assertEquals(array('site/index', array()), $result); + $this->assertEquals(['site/index', []], $result); // pathinfo with module $request->pathInfo = 'module/site/index'; $result = $manager->parseRequest($request); - $this->assertEquals(array('module/site/index', array()), $result); + $this->assertEquals(['module/site/index', []], $result); // pathinfo with trailing slashes $request->pathInfo = '/module/site/index/'; $result = $manager->parseRequest($request); - $this->assertEquals(array('module/site/index/', array()), $result); + $this->assertEquals(['module/site/index/', []], $result); // pretty URL rules - $manager = new UrlManager(array( + $manager = new UrlManager([ 'enablePrettyUrl' => true, 'cache' => null, - 'rules' => array( - array( + 'rules' => [ + [ 'pattern' => 'post/<id>/<title>', 'route' => 'post/view', - ), - ), - )); + ], + ], + ]); // matching pathinfo $request->pathInfo = 'post/123/this+is+sample'; $result = $manager->parseRequest($request); - $this->assertEquals(array('post/view', array('id' => '123', 'title' => 'this+is+sample')), $result); + $this->assertEquals(['post/view', ['id' => '123', 'title' => 'this+is+sample']], $result); // trailing slash is significant $request->pathInfo = 'post/123/this+is+sample/'; $result = $manager->parseRequest($request); - $this->assertEquals(array('post/123/this+is+sample/', array()), $result); + $this->assertEquals(['post/123/this+is+sample/', []], $result); // empty pathinfo $request->pathInfo = ''; $result = $manager->parseRequest($request); - $this->assertEquals(array('', array()), $result); + $this->assertEquals(['', []], $result); // normal pathinfo $request->pathInfo = 'site/index'; $result = $manager->parseRequest($request); - $this->assertEquals(array('site/index', array()), $result); + $this->assertEquals(['site/index', []], $result); // pathinfo with module $request->pathInfo = 'module/site/index'; $result = $manager->parseRequest($request); - $this->assertEquals(array('module/site/index', array()), $result); + $this->assertEquals(['module/site/index', []], $result); // pretty URL rules - $manager = new UrlManager(array( + $manager = new UrlManager([ 'enablePrettyUrl' => true, 'suffix' => '.html', 'cache' => null, - 'rules' => array( - array( + 'rules' => [ + [ 'pattern' => 'post/<id>/<title>', 'route' => 'post/view', - ), - ), - )); + ], + ], + ]); // matching pathinfo $request->pathInfo = 'post/123/this+is+sample.html'; $result = $manager->parseRequest($request); - $this->assertEquals(array('post/view', array('id' => '123', 'title' => 'this+is+sample')), $result); + $this->assertEquals(['post/view', ['id' => '123', 'title' => 'this+is+sample']], $result); // matching pathinfo without suffix $request->pathInfo = 'post/123/this+is+sample'; $result = $manager->parseRequest($request); @@ -225,33 +223,33 @@ class UrlManagerTest extends TestCase // empty pathinfo $request->pathInfo = ''; $result = $manager->parseRequest($request); - $this->assertEquals(array('', array()), $result); + $this->assertEquals(['', []], $result); // normal pathinfo $request->pathInfo = 'site/index.html'; $result = $manager->parseRequest($request); - $this->assertEquals(array('site/index', array()), $result); + $this->assertEquals(['site/index', []], $result); // pathinfo without suffix $request->pathInfo = 'site/index'; $result = $manager->parseRequest($request); $this->assertFalse($result); // strict parsing - $manager = new UrlManager(array( + $manager = new UrlManager([ 'enablePrettyUrl' => true, 'enableStrictParsing' => true, 'suffix' => '.html', 'cache' => null, - 'rules' => array( - array( + 'rules' => [ + [ 'pattern' => 'post/<id>/<title>', 'route' => 'post/view', - ), - ), - )); + ], + ], + ]); // matching pathinfo $request->pathInfo = 'post/123/this+is+sample.html'; $result = $manager->parseRequest($request); - $this->assertEquals(array('post/view', array('id' => '123', 'title' => 'this+is+sample')), $result); + $this->assertEquals(['post/view', ['id' => '123', 'title' => 'this+is+sample']], $result); // unmatching pathinfo $request->pathInfo = 'site/index.html'; $result = $manager->parseRequest($request); @@ -263,48 +261,48 @@ class UrlManagerTest extends TestCase $request = new Request; // pretty URL rules - $manager = new UrlManager(array( + $manager = new UrlManager([ 'enablePrettyUrl' => true, 'showScriptName' => false, 'cache' => null, - 'rules' => array( + 'rules' => [ 'PUT,POST post/<id>/<title>' => 'post/create', 'DELETE post/<id>' => 'post/delete', 'post/<id>/<title>' => 'post/view', 'POST/GET' => 'post/get', - ), - )); + ], + ]); // matching pathinfo GET request $_SERVER['REQUEST_METHOD'] = 'GET'; $request->pathInfo = 'post/123/this+is+sample'; $result = $manager->parseRequest($request); - $this->assertEquals(array('post/view', array('id' => '123', 'title' => 'this+is+sample')), $result); + $this->assertEquals(['post/view', ['id' => '123', 'title' => 'this+is+sample']], $result); // matching pathinfo PUT/POST request $_SERVER['REQUEST_METHOD'] = 'PUT'; $request->pathInfo = 'post/123/this+is+sample'; $result = $manager->parseRequest($request); - $this->assertEquals(array('post/create', array('id' => '123', 'title' => 'this+is+sample')), $result); + $this->assertEquals(['post/create', ['id' => '123', 'title' => 'this+is+sample']], $result); $_SERVER['REQUEST_METHOD'] = 'POST'; $request->pathInfo = 'post/123/this+is+sample'; $result = $manager->parseRequest($request); - $this->assertEquals(array('post/create', array('id' => '123', 'title' => 'this+is+sample')), $result); + $this->assertEquals(['post/create', ['id' => '123', 'title' => 'this+is+sample']], $result); // no wrong matching $_SERVER['REQUEST_METHOD'] = 'POST'; $request->pathInfo = 'POST/GET'; $result = $manager->parseRequest($request); - $this->assertEquals(array('post/get', array()), $result); + $this->assertEquals(['post/get', []], $result); // createUrl should ignore REST rules - $this->mockApplication(array( - 'components' => array( - 'request' => array( + $this->mockApplication([ + 'components' => [ + 'request' => [ 'hostInfo' => 'http://localhost/', 'baseUrl' => '/app' - ) - ) - ), \yii\web\Application::className()); - $this->assertEquals('/app/post/delete?id=123', $manager->createUrl('post/delete', array('id' => 123))); + ] + ] + ], \yii\web\Application::className()); + $this->assertEquals('/app/post/delete?id=123', $manager->createUrl('post/delete', ['id' => 123])); $this->destroyApplication(); unset($_SERVER['REQUEST_METHOD']); diff --git a/tests/unit/framework/web/UrlRuleTest.php b/tests/unit/framework/web/UrlRuleTest.php index 5e57cb6..39fa9bd 100644 --- a/tests/unit/framework/web/UrlRuleTest.php +++ b/tests/unit/framework/web/UrlRuleTest.php @@ -14,7 +14,7 @@ class UrlRuleTest extends TestCase { public function testCreateUrl() { - $manager = new UrlManager(array('cache' => null)); + $manager = new UrlManager(['cache' => null]); $suites = $this->getTestsForCreateUrl(); foreach ($suites as $i => $suite) { list ($name, $config, $tests) = $suite; @@ -29,8 +29,8 @@ class UrlRuleTest extends TestCase public function testParseRequest() { - $manager = new UrlManager(array('cache' => null)); - $request = new Request(array('hostInfo' => 'http://en.example.com')); + $manager = new UrlManager(['cache' => null]); + $request = new Request(['hostInfo' => 'http://en.example.com']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { list ($name, $config, $tests) = $suite; @@ -38,12 +38,12 @@ class UrlRuleTest extends TestCase foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; $route = $test[1]; - $params = isset($test[2]) ? $test[2] : array(); + $params = isset($test[2]) ? $test[2] : []; $result = $rule->parseRequest($manager, $request); if ($route === false) { $this->assertFalse($result, "Test#$i-$j: $name"); } else { - $this->assertEquals(array($route, $params), $result, "Test#$i-$j: $name"); + $this->assertEquals([$route, $params], $result, "Test#$i-$j: $name"); } } } @@ -58,293 +58,293 @@ class UrlRuleTest extends TestCase // route // params // expected output - return array( - array( + return [ + [ 'empty pattern', - array( + [ 'pattern' => '', 'route' => 'post/index', - ), - array( - array('post/index', array(), ''), - array('comment/index', array(), false), - array('post/index', array('page' => 1), '?page=1'), - ), - ), - array( + ], + [ + ['post/index', [], ''], + ['comment/index', [], false], + ['post/index', ['page' => 1], '?page=1'], + ], + ], + [ 'without param', - array( + [ 'pattern' => 'posts', 'route' => 'post/index', - ), - array( - array('post/index', array(), 'posts'), - array('comment/index', array(), false), - array('post/index', array('page' => 1), 'posts?page=1'), - ), - ), - array( + ], + [ + ['post/index', [], 'posts'], + ['comment/index', [], false], + ['post/index', ['page' => 1], 'posts?page=1'], + ], + ], + [ 'parsing only', - array( + [ 'pattern' => 'posts', 'route' => 'post/index', 'mode' => UrlRule::PARSING_ONLY, - ), - array( - array('post/index', array(), false), - ), - ), - array( + ], + [ + ['post/index', [], false], + ], + ], + [ 'with param', - array( + [ 'pattern' => 'post/<page>', 'route' => 'post/index', - ), - array( - array('post/index', array(), false), - array('comment/index', array(), false), - array('post/index', array('page' => 1), 'post/1'), - array('post/index', array('page' => 1, 'tag' => 'a'), 'post/1?tag=a'), - ), - ), - array( + ], + [ + ['post/index', [], false], + ['comment/index', [], false], + ['post/index', ['page' => 1], 'post/1'], + ['post/index', ['page' => 1, 'tag' => 'a'], 'post/1?tag=a'], + ], + ], + [ 'with param requirement', - array( + [ 'pattern' => 'post/<page:\d+>', 'route' => 'post/index', - ), - array( - array('post/index', array('page' => 'abc'), false), - array('post/index', array('page' => 1), 'post/1'), - array('post/index', array('page' => 1, 'tag' => 'a'), 'post/1?tag=a'), - ), - ), - array( + ], + [ + ['post/index', ['page' => 'abc'], false], + ['post/index', ['page' => 1], 'post/1'], + ['post/index', ['page' => 1, 'tag' => 'a'], 'post/1?tag=a'], + ], + ], + [ 'with multiple params', - array( + [ 'pattern' => 'post/<page:\d+>-<tag>', 'route' => 'post/index', - ), - array( - array('post/index', array('page' => '1abc'), false), - array('post/index', array('page' => 1), false), - array('post/index', array('page' => 1, 'tag' => 'a'), 'post/1-a'), - ), - ), - array( + ], + [ + ['post/index', ['page' => '1abc'], false], + ['post/index', ['page' => 1], false], + ['post/index', ['page' => 1, 'tag' => 'a'], 'post/1-a'], + ], + ], + [ 'with optional param', - array( + [ 'pattern' => 'post/<page:\d+>/<tag>', 'route' => 'post/index', - 'defaults' => array('page' => 1), - ), - array( - array('post/index', array('page' => 1), false), - array('post/index', array('page' => '1abc', 'tag' => 'a'), false), - array('post/index', array('page' => 1, 'tag' => 'a'), 'post/a'), - array('post/index', array('page' => 2, 'tag' => 'a'), 'post/2/a'), - ), - ), - array( + 'defaults' => ['page' => 1], + ], + [ + ['post/index', ['page' => 1], false], + ['post/index', ['page' => '1abc', 'tag' => 'a'], false], + ['post/index', ['page' => 1, 'tag' => 'a'], 'post/a'], + ['post/index', ['page' => 2, 'tag' => 'a'], 'post/2/a'], + ], + ], + [ 'with optional param not in pattern', - array( + [ 'pattern' => 'post/<tag>', 'route' => 'post/index', - 'defaults' => array('page' => 1), - ), - array( - array('post/index', array('page' => 1), false), - array('post/index', array('page' => '1abc', 'tag' => 'a'), false), - array('post/index', array('page' => 2, 'tag' => 'a'), false), - array('post/index', array('page' => 1, 'tag' => 'a'), 'post/a'), - ), - ), - array( + 'defaults' => ['page' => 1], + ], + [ + ['post/index', ['page' => 1], false], + ['post/index', ['page' => '1abc', 'tag' => 'a'], false], + ['post/index', ['page' => 2, 'tag' => 'a'], false], + ['post/index', ['page' => 1, 'tag' => 'a'], 'post/a'], + ], + ], + [ 'multiple optional params', - array( + [ 'pattern' => 'post/<page:\d+>/<tag>/<sort:yes|no>', 'route' => 'post/index', - 'defaults' => array('page' => 1, 'sort' => 'yes'), - ), - array( - array('post/index', array('page' => 1), false), - array('post/index', array('page' => '1abc', 'tag' => 'a'), false), - array('post/index', array('page' => 1, 'tag' => 'a', 'sort' => 'YES'), false), - array('post/index', array('page' => 1, 'tag' => 'a', 'sort' => 'yes'), 'post/a'), - array('post/index', array('page' => 2, 'tag' => 'a', 'sort' => 'yes'), 'post/2/a'), - array('post/index', array('page' => 2, 'tag' => 'a', 'sort' => 'no'), 'post/2/a/no'), - array('post/index', array('page' => 1, 'tag' => 'a', 'sort' => 'no'), 'post/a/no'), - ), - ), - array( + 'defaults' => ['page' => 1, 'sort' => 'yes'], + ], + [ + ['post/index', ['page' => 1], false], + ['post/index', ['page' => '1abc', 'tag' => 'a'], false], + ['post/index', ['page' => 1, 'tag' => 'a', 'sort' => 'YES'], false], + ['post/index', ['page' => 1, 'tag' => 'a', 'sort' => 'yes'], 'post/a'], + ['post/index', ['page' => 2, 'tag' => 'a', 'sort' => 'yes'], 'post/2/a'], + ['post/index', ['page' => 2, 'tag' => 'a', 'sort' => 'no'], 'post/2/a/no'], + ['post/index', ['page' => 1, 'tag' => 'a', 'sort' => 'no'], 'post/a/no'], + ], + ], + [ 'optional param and required param separated by dashes', - array( + [ 'pattern' => 'post/<page:\d+>-<tag>', 'route' => 'post/index', - 'defaults' => array('page' => 1), - ), - array( - array('post/index', array('page' => 1), false), - array('post/index', array('page' => '1abc', 'tag' => 'a'), false), - array('post/index', array('page' => 1, 'tag' => 'a'), 'post/-a'), - array('post/index', array('page' => 2, 'tag' => 'a'), 'post/2-a'), - ), - ), - array( + 'defaults' => ['page' => 1], + ], + [ + ['post/index', ['page' => 1], false], + ['post/index', ['page' => '1abc', 'tag' => 'a'], false], + ['post/index', ['page' => 1, 'tag' => 'a'], 'post/-a'], + ['post/index', ['page' => 2, 'tag' => 'a'], 'post/2-a'], + ], + ], + [ 'optional param at the end', - array( + [ 'pattern' => 'post/<tag>/<page:\d+>', 'route' => 'post/index', - 'defaults' => array('page' => 1), - ), - array( - array('post/index', array('page' => 1), false), - array('post/index', array('page' => '1abc', 'tag' => 'a'), false), - array('post/index', array('page' => 1, 'tag' => 'a'), 'post/a'), - array('post/index', array('page' => 2, 'tag' => 'a'), 'post/a/2'), - ), - ), - array( + 'defaults' => ['page' => 1], + ], + [ + ['post/index', ['page' => 1], false], + ['post/index', ['page' => '1abc', 'tag' => 'a'], false], + ['post/index', ['page' => 1, 'tag' => 'a'], 'post/a'], + ['post/index', ['page' => 2, 'tag' => 'a'], 'post/a/2'], + ], + ], + [ 'consecutive optional params', - array( + [ 'pattern' => 'post/<page:\d+>/<tag>', 'route' => 'post/index', - 'defaults' => array('page' => 1, 'tag' => 'a'), - ), - array( - array('post/index', array('page' => 1), false), - array('post/index', array('page' => '1abc', 'tag' => 'a'), false), - array('post/index', array('page' => 1, 'tag' => 'a'), 'post'), - array('post/index', array('page' => 2, 'tag' => 'a'), 'post/2'), - array('post/index', array('page' => 1, 'tag' => 'b'), 'post/b'), - array('post/index', array('page' => 2, 'tag' => 'b'), 'post/2/b'), - ), - ), - array( + 'defaults' => ['page' => 1, 'tag' => 'a'], + ], + [ + ['post/index', ['page' => 1], false], + ['post/index', ['page' => '1abc', 'tag' => 'a'], false], + ['post/index', ['page' => 1, 'tag' => 'a'], 'post'], + ['post/index', ['page' => 2, 'tag' => 'a'], 'post/2'], + ['post/index', ['page' => 1, 'tag' => 'b'], 'post/b'], + ['post/index', ['page' => 2, 'tag' => 'b'], 'post/2/b'], + ], + ], + [ 'consecutive optional params separated by dash', - array( + [ 'pattern' => 'post/<page:\d+>-<tag>', 'route' => 'post/index', - 'defaults' => array('page' => 1, 'tag' => 'a'), - ), - array( - array('post/index', array('page' => 1), false), - array('post/index', array('page' => '1abc', 'tag' => 'a'), false), - array('post/index', array('page' => 1, 'tag' => 'a'), 'post/-'), - array('post/index', array('page' => 1, 'tag' => 'b'), 'post/-b'), - array('post/index', array('page' => 2, 'tag' => 'a'), 'post/2-'), - array('post/index', array('page' => 2, 'tag' => 'b'), 'post/2-b'), - ), - ), - array( + 'defaults' => ['page' => 1, 'tag' => 'a'], + ], + [ + ['post/index', ['page' => 1], false], + ['post/index', ['page' => '1abc', 'tag' => 'a'], false], + ['post/index', ['page' => 1, 'tag' => 'a'], 'post/-'], + ['post/index', ['page' => 1, 'tag' => 'b'], 'post/-b'], + ['post/index', ['page' => 2, 'tag' => 'a'], 'post/2-'], + ['post/index', ['page' => 2, 'tag' => 'b'], 'post/2-b'], + ], + ], + [ 'route has parameters', - array( + [ 'pattern' => '<controller>/<action>', 'route' => '<controller>/<action>', - 'defaults' => array(), - ), - array( - array('post/index', array('page' => 1), 'post/index?page=1'), - array('module/post/index', array(), false), - ), - ), - array( + 'defaults' => [], + ], + [ + ['post/index', ['page' => 1], 'post/index?page=1'], + ['module/post/index', [], false], + ], + ], + [ 'route has parameters with regex', - array( + [ 'pattern' => '<controller:post|comment>/<action>', 'route' => '<controller>/<action>', - 'defaults' => array(), - ), - array( - array('post/index', array('page' => 1), 'post/index?page=1'), - array('comment/index', array('page' => 1), 'comment/index?page=1'), - array('test/index', array('page' => 1), false), - array('post', array(), false), - array('module/post/index', array(), false), - array('post/index', array('controller' => 'comment'), 'post/index?controller=comment'), - ), - ), - array( + 'defaults' => [], + ], + [ + ['post/index', ['page' => 1], 'post/index?page=1'], + ['comment/index', ['page' => 1], 'comment/index?page=1'], + ['test/index', ['page' => 1], false], + ['post', [], false], + ['module/post/index', [], false], + ['post/index', ['controller' => 'comment'], 'post/index?controller=comment'], + ], + ], + [ 'route has default parameter', - array( + [ 'pattern' => '<controller:post|comment>/<action>', 'route' => '<controller>/<action>', - 'defaults' => array('action' => 'index'), - ), - array( - array('post/view', array('page' => 1), 'post/view?page=1'), - array('comment/view', array('page' => 1), 'comment/view?page=1'), - array('test/view', array('page' => 1), false), - array('test/index', array('page' => 1), false), - array('post/index', array('page' => 1), 'post?page=1'), - ), - ), - array( + 'defaults' => ['action' => 'index'], + ], + [ + ['post/view', ['page' => 1], 'post/view?page=1'], + ['comment/view', ['page' => 1], 'comment/view?page=1'], + ['test/view', ['page' => 1], false], + ['test/index', ['page' => 1], false], + ['post/index', ['page' => 1], 'post?page=1'], + ], + ], + [ 'empty pattern with suffix', - array( + [ 'pattern' => '', 'route' => 'post/index', 'suffix' => '.html', - ), - array( - array('post/index', array(), ''), - array('comment/index', array(), false), - array('post/index', array('page' => 1), '?page=1'), - ), - ), - array( + ], + [ + ['post/index', [], ''], + ['comment/index', [], false], + ['post/index', ['page' => 1], '?page=1'], + ], + ], + [ 'regular pattern with suffix', - array( + [ 'pattern' => 'posts', 'route' => 'post/index', 'suffix' => '.html', - ), - array( - array('post/index', array(), 'posts.html'), - array('comment/index', array(), false), - array('post/index', array('page' => 1), 'posts.html?page=1'), - ), - ), - array( + ], + [ + ['post/index', [], 'posts.html'], + ['comment/index', [], false], + ['post/index', ['page' => 1], 'posts.html?page=1'], + ], + ], + [ 'empty pattern with slash suffix', - array( + [ 'pattern' => '', 'route' => 'post/index', 'suffix' => '/', - ), - array( - array('post/index', array(), ''), - array('comment/index', array(), false), - array('post/index', array('page' => 1), '?page=1'), - ), - ), - array( + ], + [ + ['post/index', [], ''], + ['comment/index', [], false], + ['post/index', ['page' => 1], '?page=1'], + ], + ], + [ 'regular pattern with slash suffix', - array( + [ 'pattern' => 'posts', 'route' => 'post/index', 'suffix' => '/', - ), - array( - array('post/index', array(), 'posts/'), - array('comment/index', array(), false), - array('post/index', array('page' => 1), 'posts/?page=1'), - ), - ), - array( + ], + [ + ['post/index', [], 'posts/'], + ['comment/index', [], false], + ['post/index', ['page' => 1], 'posts/?page=1'], + ], + ], + [ 'with host info', - array( + [ 'pattern' => 'post/<page:\d+>/<tag>', 'route' => 'post/index', - 'defaults' => array('page' => 1), + 'defaults' => ['page' => 1], 'host' => 'http://<lang:en|fr>.example.com', - ), - array( - array('post/index', array('page' => 1, 'tag' => 'a'), false), - array('post/index', array('page' => 1, 'tag' => 'a', 'lang' => 'en'), 'http://en.example.com/post/a'), - ), - ), - ); + ], + [ + ['post/index', ['page' => 1, 'tag' => 'a'], false], + ['post/index', ['page' => 1, 'tag' => 'a', 'lang' => 'en'], 'http://en.example.com/post/a'], + ], + ], + ]; } protected function getTestsForParseRequest() @@ -356,303 +356,303 @@ class UrlRuleTest extends TestCase // pathInfo // expected route, or false if the rule doesn't apply // expected params, or not set if empty - return array( - array( + return [ + [ 'empty pattern', - array( + [ 'pattern' => '', 'route' => 'post/index', - ), - array( - array('', 'post/index'), - array('a', false), - ), - ), - array( + ], + [ + ['', 'post/index'], + ['a', false], + ], + ], + [ 'without param', - array( + [ 'pattern' => 'posts', 'route' => 'post/index', - ), - array( - array('posts', 'post/index'), - array('a', false), - ), - ), - array( + ], + [ + ['posts', 'post/index'], + ['a', false], + ], + ], + [ 'with dot', // https://github.com/yiisoft/yii/issues/2945 - array( + [ 'pattern' => 'posts.html', 'route' => 'post/index', - ), - array( - array('posts.html', 'post/index'), - array('postsahtml', false), - ), - ), - array( + ], + [ + ['posts.html', 'post/index'], + ['postsahtml', false], + ], + ], + [ 'creation only', - array( + [ 'pattern' => 'posts', 'route' => 'post/index', 'mode' => UrlRule::CREATION_ONLY, - ), - array( - array('posts', false), - ), - ), - array( + ], + [ + ['posts', false], + ], + ], + [ 'with param', - array( + [ 'pattern' => 'post/<page>', 'route' => 'post/index', - ), - array( - array('post/1', 'post/index', array('page' => '1')), - array('post/a', 'post/index', array('page' => 'a')), - array('post', false), - array('posts', false), - ), - ), - array( + ], + [ + ['post/1', 'post/index', ['page' => '1']], + ['post/a', 'post/index', ['page' => 'a']], + ['post', false], + ['posts', false], + ], + ], + [ 'with param requirement', - array( + [ 'pattern' => 'post/<page:\d+>', 'route' => 'post/index', - ), - array( - array('post/1', 'post/index', array('page' => '1')), - array('post/a', false), - array('post/1/a', false), - ), - ), - array( + ], + [ + ['post/1', 'post/index', ['page' => '1']], + ['post/a', false], + ['post/1/a', false], + ], + ], + [ 'with multiple params', - array( + [ 'pattern' => 'post/<page:\d+>-<tag>', 'route' => 'post/index', - ), - array( - array('post/1-a', 'post/index', array('page' => '1', 'tag' => 'a')), - array('post/a', false), - array('post/1', false), - array('post/1/a', false), - ), - ), - array( + ], + [ + ['post/1-a', 'post/index', ['page' => '1', 'tag' => 'a']], + ['post/a', false], + ['post/1', false], + ['post/1/a', false], + ], + ], + [ 'with optional param', - array( + [ 'pattern' => 'post/<page:\d+>/<tag>', 'route' => 'post/index', - 'defaults' => array('page' => 1), - ), - array( - array('post/1/a', 'post/index', array('page' => '1', 'tag' => 'a')), - array('post/2/a', 'post/index', array('page' => '2', 'tag' => 'a')), - array('post/a', 'post/index', array('page' => '1', 'tag' => 'a')), - array('post/1', 'post/index', array('page' => '1', 'tag' => '1')), - ), - ), - array( + 'defaults' => ['page' => 1], + ], + [ + ['post/1/a', 'post/index', ['page' => '1', 'tag' => 'a']], + ['post/2/a', 'post/index', ['page' => '2', 'tag' => 'a']], + ['post/a', 'post/index', ['page' => '1', 'tag' => 'a']], + ['post/1', 'post/index', ['page' => '1', 'tag' => '1']], + ], + ], + [ 'with optional param not in pattern', - array( + [ 'pattern' => 'post/<tag>', 'route' => 'post/index', - 'defaults' => array('page' => 1), - ), - array( - array('post/a', 'post/index', array('page' => '1', 'tag' => 'a')), - array('post/1', 'post/index', array('page' => '1', 'tag' => '1')), - array('post', false), - ), - ), - array( + 'defaults' => ['page' => 1], + ], + [ + ['post/a', 'post/index', ['page' => '1', 'tag' => 'a']], + ['post/1', 'post/index', ['page' => '1', 'tag' => '1']], + ['post', false], + ], + ], + [ 'multiple optional params', - array( + [ 'pattern' => 'post/<page:\d+>/<tag>/<sort:yes|no>', 'route' => 'post/index', - 'defaults' => array('page' => 1, 'sort' => 'yes'), - ), - array( - array('post/1/a/yes', 'post/index', array('page' => '1', 'tag' => 'a', 'sort' => 'yes')), - array('post/1/a/no', 'post/index', array('page' => '1', 'tag' => 'a', 'sort' => 'no')), - array('post/2/a/no', 'post/index', array('page' => '2', 'tag' => 'a', 'sort' => 'no')), - array('post/2/a', 'post/index', array('page' => '2', 'tag' => 'a', 'sort' => 'yes')), - array('post/a/no', 'post/index', array('page' => '1', 'tag' => 'a', 'sort' => 'no')), - array('post/a', 'post/index', array('page' => '1', 'tag' => 'a', 'sort' => 'yes')), - array('post', false), - ), - ), - array( + 'defaults' => ['page' => 1, 'sort' => 'yes'], + ], + [ + ['post/1/a/yes', 'post/index', ['page' => '1', 'tag' => 'a', 'sort' => 'yes']], + ['post/1/a/no', 'post/index', ['page' => '1', 'tag' => 'a', 'sort' => 'no']], + ['post/2/a/no', 'post/index', ['page' => '2', 'tag' => 'a', 'sort' => 'no']], + ['post/2/a', 'post/index', ['page' => '2', 'tag' => 'a', 'sort' => 'yes']], + ['post/a/no', 'post/index', ['page' => '1', 'tag' => 'a', 'sort' => 'no']], + ['post/a', 'post/index', ['page' => '1', 'tag' => 'a', 'sort' => 'yes']], + ['post', false], + ], + ], + [ 'optional param and required param separated by dashes', - array( + [ 'pattern' => 'post/<page:\d+>-<tag>', 'route' => 'post/index', - 'defaults' => array('page' => 1), - ), - array( - array('post/1-a', 'post/index', array('page' => '1', 'tag' => 'a')), - array('post/2-a', 'post/index', array('page' => '2', 'tag' => 'a')), - array('post/-a', 'post/index', array('page' => '1', 'tag' => 'a')), - array('post/a', false), - array('post-a', false), - ), - ), - array( + 'defaults' => ['page' => 1], + ], + [ + ['post/1-a', 'post/index', ['page' => '1', 'tag' => 'a']], + ['post/2-a', 'post/index', ['page' => '2', 'tag' => 'a']], + ['post/-a', 'post/index', ['page' => '1', 'tag' => 'a']], + ['post/a', false], + ['post-a', false], + ], + ], + [ 'optional param at the end', - array( + [ 'pattern' => 'post/<tag>/<page:\d+>', 'route' => 'post/index', - 'defaults' => array('page' => 1), - ), - array( - array('post/a/1', 'post/index', array('page' => '1', 'tag' => 'a')), - array('post/a/2', 'post/index', array('page' => '2', 'tag' => 'a')), - array('post/a', 'post/index', array('page' => '1', 'tag' => 'a')), - array('post/2', 'post/index', array('page' => '1', 'tag' => '2')), - array('post', false), - ), - ), - array( + 'defaults' => ['page' => 1], + ], + [ + ['post/a/1', 'post/index', ['page' => '1', 'tag' => 'a']], + ['post/a/2', 'post/index', ['page' => '2', 'tag' => 'a']], + ['post/a', 'post/index', ['page' => '1', 'tag' => 'a']], + ['post/2', 'post/index', ['page' => '1', 'tag' => '2']], + ['post', false], + ], + ], + [ 'consecutive optional params', - array( + [ 'pattern' => 'post/<page:\d+>/<tag>', 'route' => 'post/index', - 'defaults' => array('page' => 1, 'tag' => 'a'), - ), - array( - array('post/2/b', 'post/index', array('page' => '2', 'tag' => 'b')), - array('post/2', 'post/index', array('page' => '2', 'tag' => 'a')), - array('post', 'post/index', array('page' => '1', 'tag' => 'a')), - array('post/b', 'post/index', array('page' => '1', 'tag' => 'b')), - array('post//b', false), - ), - ), - array( + 'defaults' => ['page' => 1, 'tag' => 'a'], + ], + [ + ['post/2/b', 'post/index', ['page' => '2', 'tag' => 'b']], + ['post/2', 'post/index', ['page' => '2', 'tag' => 'a']], + ['post', 'post/index', ['page' => '1', 'tag' => 'a']], + ['post/b', 'post/index', ['page' => '1', 'tag' => 'b']], + ['post//b', false], + ], + ], + [ 'consecutive optional params separated by dash', - array( + [ 'pattern' => 'post/<page:\d+>-<tag>', 'route' => 'post/index', - 'defaults' => array('page' => 1, 'tag' => 'a'), - ), - array( - array('post/2-b', 'post/index', array('page' => '2', 'tag' => 'b')), - array('post/2-', 'post/index', array('page' => '2', 'tag' => 'a')), - array('post/-b', 'post/index', array('page' => '1', 'tag' => 'b')), - array('post/-', 'post/index', array('page' => '1', 'tag' => 'a')), - array('post', false), - ), - ), - array( + 'defaults' => ['page' => 1, 'tag' => 'a'], + ], + [ + ['post/2-b', 'post/index', ['page' => '2', 'tag' => 'b']], + ['post/2-', 'post/index', ['page' => '2', 'tag' => 'a']], + ['post/-b', 'post/index', ['page' => '1', 'tag' => 'b']], + ['post/-', 'post/index', ['page' => '1', 'tag' => 'a']], + ['post', false], + ], + ], + [ 'route has parameters', - array( + [ 'pattern' => '<controller>/<action>', 'route' => '<controller>/<action>', - 'defaults' => array(), - ), - array( - array('post/index', 'post/index'), - array('module/post/index', false), - ), - ), - array( + 'defaults' => [], + ], + [ + ['post/index', 'post/index'], + ['module/post/index', false], + ], + ], + [ 'route has parameters with regex', - array( + [ 'pattern' => '<controller:post|comment>/<action>', 'route' => '<controller>/<action>', - 'defaults' => array(), - ), - array( - array('post/index', 'post/index'), - array('comment/index', 'comment/index'), - array('test/index', false), - array('post', false), - array('module/post/index', false), - ), - ), - array( + 'defaults' => [], + ], + [ + ['post/index', 'post/index'], + ['comment/index', 'comment/index'], + ['test/index', false], + ['post', false], + ['module/post/index', false], + ], + ], + [ 'route has default parameter', - array( + [ 'pattern' => '<controller:post|comment>/<action>', 'route' => '<controller>/<action>', - 'defaults' => array('action' => 'index'), - ), - array( - array('post/view', 'post/view'), - array('comment/view', 'comment/view'), - array('test/view', false), - array('post', 'post/index'), - array('posts', false), - array('test', false), - array('index', false), - ), - ), - array( + 'defaults' => ['action' => 'index'], + ], + [ + ['post/view', 'post/view'], + ['comment/view', 'comment/view'], + ['test/view', false], + ['post', 'post/index'], + ['posts', false], + ['test', false], + ['index', false], + ], + ], + [ 'empty pattern with suffix', - array( + [ 'pattern' => '', 'route' => 'post/index', 'suffix' => '.html', - ), - array( - array('', 'post/index'), - array('.html', false), - array('a.html', false), - ), - ), - array( + ], + [ + ['', 'post/index'], + ['.html', false], + ['a.html', false], + ], + ], + [ 'regular pattern with suffix', - array( + [ 'pattern' => 'posts', 'route' => 'post/index', 'suffix' => '.html', - ), - array( - array('posts.html', 'post/index'), - array('posts', false), - array('posts.HTML', false), - array('a.html', false), - array('a', false), - ), - ), - array( + ], + [ + ['posts.html', 'post/index'], + ['posts', false], + ['posts.HTML', false], + ['a.html', false], + ['a', false], + ], + ], + [ 'empty pattern with slash suffix', - array( + [ 'pattern' => '', 'route' => 'post/index', 'suffix' => '/', - ), - array( - array('', 'post/index'), - array('a', false), - ), - ), - array( + ], + [ + ['', 'post/index'], + ['a', false], + ], + ], + [ 'regular pattern with slash suffix', - array( + [ 'pattern' => 'posts', 'route' => 'post/index', 'suffix' => '/', - ), - array( - array('posts/', 'post/index'), - array('posts', false), - array('a', false), - ), - ), - array( + ], + [ + ['posts/', 'post/index'], + ['posts', false], + ['a', false], + ], + ], + [ 'with host info', - array( + [ 'pattern' => 'post/<page:\d+>', 'route' => 'post/index', 'host' => 'http://<lang:en|fr>.example.com', - ), - array( - array('post/1', 'post/index', array('page' => '1', 'lang' => 'en')), - array('post/a', false), - array('post/1/a', false), - ), - ), - ); + ], + [ + ['post/1', 'post/index', ['page' => '1', 'lang' => 'en']], + ['post/a', false], + ['post/1/a', false], + ], + ], + ]; } } diff --git a/tests/unit/framework/web/XmlResponseFormatterTest.php b/tests/unit/framework/web/XmlResponseFormatterTest.php index e97962a..800de66 100644 --- a/tests/unit/framework/web/XmlResponseFormatterTest.php +++ b/tests/unit/framework/web/XmlResponseFormatterTest.php @@ -62,13 +62,13 @@ class XmlResponseFormatterTest extends \yiiunit\TestCase public function formatScalarDataProvider() { - return array( - array(null, "<response></response>\n"), - array(1, "<response>1</response>\n"), - array('abc', "<response>abc</response>\n"), - array(true, "<response>1</response>\n"), - array("<>", "<response><></response>\n"), - ); + return [ + [null, "<response></response>\n"], + [1, "<response>1</response>\n"], + ['abc', "<response>abc</response>\n"], + [true, "<response>1</response>\n"], + ["<>", "<response><></response>\n"], + ]; } /** @@ -86,26 +86,26 @@ class XmlResponseFormatterTest extends \yiiunit\TestCase public function formatArrayDataProvider() { - return array( - array(array(), "<response/>\n"), - array(array(1, 'abc'), "<response><item>1</item><item>abc</item></response>\n"), - array(array( + return [ + [[], "<response/>\n"], + [[1, 'abc'], "<response><item>1</item><item>abc</item></response>\n"], + [[ 'a' => 1, 'b' => 'abc', - ), "<response><a>1</a><b>abc</b></response>\n"), - array(array( + ], "<response><a>1</a><b>abc</b></response>\n"], + [[ 1, 'abc', - array(2, 'def'), + [2, 'def'], true, - ), "<response><item>1</item><item>abc</item><item><item>2</item><item>def</item></item><item>1</item></response>\n"), - array(array( + ], "<response><item>1</item><item>abc</item><item><item>2</item><item>def</item></item><item>1</item></response>\n"], + [[ 'a' => 1, 'b' => 'abc', - 'c' => array(2, '<>'), + 'c' => [2, '<>'], true, - ), "<response><a>1</a><b>abc</b><c><item>2</item><item><></item></c><item>1</item></response>\n"), - ); + ], "<response><a>1</a><b>abc</b><c><item>2</item><item><></item></c><item>1</item></response>\n"], + ]; } /** @@ -123,16 +123,16 @@ class XmlResponseFormatterTest extends \yiiunit\TestCase public function formatObjectDataProvider() { - return array( - array(new Post(123, 'abc'), "<response><Post><id>123</id><title>abc\n"), - array(array( + return [ + [new Post(123, 'abc'), "123abc\n"], + [[ new Post(123, 'abc'), new Post(456, 'def'), - ), "123abc456def\n"), - array(array( + ], "123abc456def\n"], + [[ new Post(123, '<>'), 'a' => new Post(456, 'def'), - ), "123<>456def\n"), - ); + ], "123<>456def\n"], + ]; } } diff --git a/tests/web/app/protected/config/main.php b/tests/web/app/protected/config/main.php index d5be5de..0b67a5f 100644 --- a/tests/web/app/protected/config/main.php +++ b/tests/web/app/protected/config/main.php @@ -1,3 +1,3 @@ 'item 1', 'value 2' => 'item 2', 'value 3' => 'item 3', - ), isset($_POST['test']) ? $_POST['test'] : null, + ], isset($_POST['test']) ? $_POST['test'] : null, function ($index, $label, $name, $value, $checked) { return Html::label( $label . ' ' . Html::checkbox($name, $value, $checked), - null, array('class' => 'inline checkbox') + null, ['class' => 'inline checkbox'] ); }); echo Html::submitButton();