Commit e79e33ff authored by Qiang Xue's avatar Qiang Xue

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

parents 40cb5b81 6bcacec9
......@@ -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',
);
];
}
......@@ -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,
);
];
<?php
return array(
return [
'adminEmail' => 'admin@example.com',
);
];
......@@ -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()
......
......@@ -4,8 +4,8 @@ return [
//'debug',
],
'modules' => [
// 'debug' => array(
// 'debug' => [
// 'class' => 'yii\debug\Module',
// ),
// ],
],
];
......@@ -4,8 +4,8 @@ return [
//'debug',
],
'modules' => [
// 'debug' => array(
// 'debug' => [
// 'class' => 'yii\debug\Module',
// ),
// ],
],
];
......@@ -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 [
......
......@@ -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();
......@@ -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();
......@@ -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) {
......
......@@ -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(?<name>\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)
......
......@@ -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()]]
......
......@@ -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.
......@@ -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
......@@ -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]);
}
}
......
......@@ -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()
......
......@@ -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
......
......@@ -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.
......
......@@ -29,12 +29,12 @@ stored in a PHP file in `/config` directory of the application and looks like th
```php
<?php
return array(
return [
'id' => '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
<?php
return array(
return [
'id' => '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
......
......@@ -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',
],
];
}
}
```
......
......@@ -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]].
......@@ -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!".
......
......@@ -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)
......
......@@ -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'],
];
}
```
......
......@@ -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]);
}
}
```
......
......@@ -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
......
......@@ -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
......
......@@ -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/<page:\d+>/<tag>',
'route' => 'post/index',
'defaults' => array('page' => 1),
)
'defaults' => ['page' => 1],
]
```
......
......@@ -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)_
......
......@@ -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 `<meta>` tag option names and values. The code above will produce:
......@@ -144,8 +142,8 @@ The first argument is an map of `<meta>` 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:
<div class="user-index">
<?php
foreach($users as $user) {
echo $this->render('_profile', array(
echo $this->render('_profile', [
'username' => $user->name,
'tagline' => $user->tagline,
));
]);
}
?>
</div>
......@@ -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',
),
],
// ...
),
);
],
];
```
......@@ -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],
],
];
}
```
......
......@@ -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.');
......
......@@ -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.');
......
......@@ -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.
......
......@@ -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);
}
......
......@@ -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',
);
];
}
......@@ -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/
......
......@@ -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',
);
];
}
......@@ -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',
);
];
}
......@@ -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',
);
];
}
......@@ -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()) {
......
......@@ -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',
);
];
}
......@@ -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',
);
];
}
......@@ -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...';
*
......
......@@ -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',
);
];
}
......@@ -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...';
*
......
......@@ -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',
);
];
}
......@@ -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...';
*
......
......@@ -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',
);
];
}
......@@ -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',
);
];
}
......@@ -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);";
}
......
......@@ -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',
);
];
}
......@@ -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 '<div class="progress-label">Loading...</div>';
*
......
......@@ -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',
);
];
}
......@@ -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...';
*
......
......@@ -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',
);
];
}
......@@ -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 {
......
......@@ -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',
);
];
}
......@@ -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/
......
......@@ -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',
);
];
}
......@@ -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 {
......
......@@ -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',
);
];
}
......@@ -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/
......
......@@ -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',
);
];
}
......@@ -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);
}
......
......@@ -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',
);
];
}
......@@ -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',
);
];
}
......@@ -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',
);
];
}
......@@ -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);";
}
......
<?php
return array(
return [
yii\jui\CoreAsset::className(),
yii\jui\EffectAsset::className(),
yii\jui\AccordionAsset::className(),
......@@ -20,4 +20,4 @@ return array(
yii\jui\DraggableAsset::className(),
yii\jui\DroppableAsset::className(),
yii\jui\MenuAsset::className(),
);
];
......@@ -38,7 +38,7 @@ class FileMutex extends Mutex
/**
* @var resource[] stores all opened lock files. Keys are lock names and values are file handles.
*/
private $_files = array();
private $_files = [];
/**
......
......@@ -25,7 +25,7 @@ abstract class Mutex extends Component
/**
* @var string[] names of the locks acquired in the current PHP process.
*/
private $_locks = array();
private $_locks = [];
/**
......
......@@ -38,7 +38,7 @@ class MysqlMutex extends Mutex
protected function acquireLock($name, $timeout = 0)
{
return (boolean)$this->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();
}
}
......@@ -45,20 +45,20 @@ Example:
```php
<?php
// config.php
return array(
return [
//....
'components' => 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.
......@@ -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']);
}
/**
......
......@@ -44,21 +44,21 @@ Example:
```php
<?php
// config.php
return array(
return [
//....
'components' => 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.
......@@ -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);
......
......@@ -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);
......
......@@ -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');
<?php
return array(
return [
yii\web\YiiAsset::className(),
yii\web\JqueryAsset::className(),
yii\validators\PunycodeAsset::className(),
......@@ -8,4 +8,4 @@ return array(
yii\widgets\ActiveFormAsset::className(),
yii\captcha\CaptchaAsset::className(),
yii\widgets\MaskedInputAsset::className(),
);
];
......@@ -25,7 +25,7 @@ use Yii;
* public function run($id, $type = 'book') { ... }
* ~~~
*
* And the parameters provided for the action are: `array('id' => 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);
}
}
......@@ -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);
......
......@@ -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',
);
];
}
/**
......
......@@ -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'],
]);
}
/**
......
......@@ -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;
}
......
......@@ -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);
}
......
......@@ -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);
}
......
......@@ -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');
}
}
......@@ -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) {
......
......@@ -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);
}
......
......@@ -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");
}
......
......@@ -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);
}
}
......@@ -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) {
......
......@@ -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;
}
/**
......
......@@ -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);
......
......@@ -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));
......
......@@ -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);
}
......
......@@ -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);
......
......@@ -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);
}
......
......@@ -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) {
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment