Browse Source

Short array syntax

tags/2.0.0-beta
Alexander Makarov 11 years ago
parent
commit
1f6a823073
  1. 11
      apps/advanced/backend/config/AppAsset.php
  2. 39
      apps/advanced/backend/config/main.php
  3. 4
      apps/advanced/backend/config/params.php
  4. 4
      apps/advanced/console/migrations/m130524_201442_init.php
  5. 4
      apps/advanced/environments/dev/backend/config/main-local.php
  6. 4
      apps/advanced/environments/dev/frontend/config/main-local.php
  7. 12
      apps/advanced/environments/index.php
  8. 12
      apps/benchmark/index.php
  9. 4
      build/build
  10. 16
      build/controllers/ClassmapController.php
  11. 25
      build/controllers/PhpDocController.php
  12. 16
      docs/api/base/Component.md
  13. 4
      docs/api/base/Object.md
  14. 8
      docs/api/db/ActiveRecord-find.md
  15. 42
      docs/api/db/ActiveRecord.md
  16. 74
      docs/guide/active-record.md
  17. 4
      docs/guide/bootstrap-widgets.md
  18. 20
      docs/guide/caching.md
  19. 40
      docs/guide/configuration.md
  20. 21
      docs/guide/controller.md
  21. 38
      docs/guide/database-basics.md
  22. 46
      docs/guide/i18n.md
  23. 8
      docs/guide/migration.md
  24. 46
      docs/guide/model.md
  25. 32
      docs/guide/performance.md
  26. 44
      docs/guide/query-builder.md
  27. 28
      docs/guide/template.md
  28. 48
      docs/guide/upgrade-from-v1.md
  29. 10
      docs/guide/validation.md
  30. 46
      docs/guide/view.md
  31. 14
      docs/internals/ar.md
  32. 14
      extensions/composer/yii/composer/InstallHandler.php
  33. 18
      extensions/composer/yii/composer/Installer.php
  34. 8
      extensions/jui/README.md
  35. 62
      extensions/jui/yii/jui/Accordion.php
  36. 8
      extensions/jui/yii/jui/AccordionAsset.php
  37. 22
      extensions/jui/yii/jui/AutoComplete.php
  38. 8
      extensions/jui/yii/jui/AutoCompleteAsset.php
  39. 8
      extensions/jui/yii/jui/ButtonAsset.php
  40. 8
      extensions/jui/yii/jui/CoreAsset.php
  41. 18
      extensions/jui/yii/jui/DatePicker.php
  42. 8
      extensions/jui/yii/jui/DatePickerAsset.php
  43. 8
      extensions/jui/yii/jui/DatePickerRegionalAsset.php
  44. 8
      extensions/jui/yii/jui/Dialog.php
  45. 8
      extensions/jui/yii/jui/DialogAsset.php
  46. 8
      extensions/jui/yii/jui/Draggable.php
  47. 8
      extensions/jui/yii/jui/DraggableAsset.php
  48. 8
      extensions/jui/yii/jui/Droppable.php
  49. 8
      extensions/jui/yii/jui/DroppableAsset.php
  50. 8
      extensions/jui/yii/jui/EffectAsset.php
  51. 6
      extensions/jui/yii/jui/Menu.php
  52. 8
      extensions/jui/yii/jui/MenuAsset.php
  53. 16
      extensions/jui/yii/jui/ProgressBar.php
  54. 8
      extensions/jui/yii/jui/ProgressBarAsset.php
  55. 10
      extensions/jui/yii/jui/Resizable.php
  56. 8
      extensions/jui/yii/jui/ResizableAsset.php
  57. 46
      extensions/jui/yii/jui/Selectable.php
  58. 8
      extensions/jui/yii/jui/SelectableAsset.php
  59. 16
      extensions/jui/yii/jui/Slider.php
  60. 8
      extensions/jui/yii/jui/SliderAsset.php
  61. 46
      extensions/jui/yii/jui/Sortable.php
  62. 8
      extensions/jui/yii/jui/SortableAsset.php
  63. 16
      extensions/jui/yii/jui/Spinner.php
  64. 8
      extensions/jui/yii/jui/SpinnerAsset.php
  65. 72
      extensions/jui/yii/jui/Tabs.php
  66. 8
      extensions/jui/yii/jui/TabsAsset.php
  67. 4
      extensions/jui/yii/jui/ThemeAsset.php
  68. 8
      extensions/jui/yii/jui/TooltipAsset.php
  69. 8
      extensions/jui/yii/jui/Widget.php
  70. 4
      extensions/jui/yii/jui/assets.php
  71. 2
      extensions/mutex/yii/mutex/FileMutex.php
  72. 2
      extensions/mutex/yii/mutex/Mutex.php
  73. 4
      extensions/mutex/yii/mutex/MysqlMutex.php
  74. 20
      extensions/smarty/README.md
  75. 2
      extensions/smarty/yii/smarty/ViewRenderer.php
  76. 22
      extensions/twig/README.md
  77. 10
      extensions/twig/yii/twig/ViewRenderer.php
  78. 38
      framework/yii/BaseYii.php
  79. 2
      framework/yii/Yii.php
  80. 4
      framework/yii/assets.php
  81. 6
      framework/yii/base/Action.php
  82. 2
      framework/yii/base/ActionEvent.php
  83. 6
      framework/yii/base/ActionFilter.php
  84. 38
      framework/yii/base/Application.php
  85. 16
      framework/yii/base/Behavior.php
  86. 22
      framework/yii/base/Component.php
  87. 28
      framework/yii/base/Controller.php
  88. 8
      framework/yii/base/ErrorException.php
  89. 36
      framework/yii/base/ErrorHandler.php
  90. 4
      framework/yii/base/Exception.php
  91. 10
      framework/yii/base/Formatter.php
  92. 4
      framework/yii/base/InlineAction.php
  93. 70
      framework/yii/base/Model.php
  94. 56
      framework/yii/base/Module.php
  95. 2
      framework/yii/base/Object.php
  96. 14
      framework/yii/base/Theme.php
  97. 66
      framework/yii/base/View.php
  98. 2
      framework/yii/base/ViewEvent.php
  99. 10
      framework/yii/base/Widget.php
  100. 14
      framework/yii/behaviors/AutoTimestamp.php
  101. Some files were not shown because too many files have changed in this diff Show More

11
apps/advanced/backend/config/AppAsset.php

@ -17,13 +17,10 @@ class AppAsset extends AssetBundle
{ {
public $basePath = '@webroot'; public $basePath = '@webroot';
public $baseUrl = '@web'; public $baseUrl = '@web';
public $css = array( public $css = ['css/site.css'];
'css/site.css', public $js = [];
); public $depends = [
public $js = array(
);
public $depends = array(
'yii\web\YiiAsset', 'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset', 'yii\bootstrap\BootstrapAsset',
); ];
} }

39
apps/advanced/backend/config/main.php

@ -8,35 +8,34 @@ $params = array_merge(
require(__DIR__ . '/params-local.php') require(__DIR__ . '/params-local.php')
); );
return array( return [
'id' => 'app-backend', 'id' => 'app-backend',
'basePath' => dirname(__DIR__), 'basePath' => dirname(__DIR__),
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor', 'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'preload' => array('log'), 'preload' => ['log'],
'controllerNamespace' => 'backend\controllers', 'controllerNamespace' => 'backend\controllers',
'modules' => array( 'modules' => [],
), 'components' => [
'components' => array( 'request' => [
'request' => array(
'enableCsrfValidation' => true, 'enableCsrfValidation' => true,
), ],
'db' => $params['components.db'], 'db' => $params['components.db'],
'cache' => $params['components.cache'], 'cache' => $params['components.cache'],
'user' => array( 'user' => [
'identityClass' => 'common\models\User', 'identityClass' => 'common\models\User',
), ],
'log' => array( 'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0, 'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => array( 'targets' => [
array( [
'class' => 'yii\log\FileTarget', 'class' => 'yii\log\FileTarget',
'levels' => array('error', 'warning'), 'levels' => ['error', 'warning'],
), ],
), ],
), ],
'errorHandler' => array( 'errorHandler' => [
'errorAction' => 'site/error', 'errorAction' => 'site/error',
), ],
), ],
'params' => $params, 'params' => $params,
); ];

4
apps/advanced/backend/config/params.php

@ -1,4 +1,4 @@
<?php <?php
return array( return [
'adminEmail' => 'admin@example.com', 'adminEmail' => 'admin@example.com',
); ];

4
apps/advanced/console/migrations/m130524_201442_init.php

@ -9,7 +9,7 @@ class m130524_201442_init extends \yii\db\Migration
// MySQL-specific table options. Adjust if you plan working with another DBMS // MySQL-specific table options. Adjust if you plan working with another DBMS
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB'; $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
$this->createTable('tbl_user', array( $this->createTable('tbl_user', [
'id' => Schema::TYPE_PK, 'id' => Schema::TYPE_PK,
'username' => Schema::TYPE_STRING.' NOT NULL', 'username' => Schema::TYPE_STRING.' NOT NULL',
'auth_key' => Schema::TYPE_STRING.'(32) 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', 'status' => 'tinyint NOT NULL DEFAULT 10',
'create_time' => Schema::TYPE_INTEGER.' NOT NULL', 'create_time' => Schema::TYPE_INTEGER.' NOT NULL',
'update_time' => Schema::TYPE_INTEGER.' NOT NULL', 'update_time' => Schema::TYPE_INTEGER.' NOT NULL',
), $tableOptions); ], $tableOptions);
} }
public function down() public function down()

4
apps/advanced/environments/dev/backend/config/main-local.php

@ -4,8 +4,8 @@ return [
//'debug', //'debug',
], ],
'modules' => [ 'modules' => [
// 'debug' => array( // 'debug' => [
// 'class' => 'yii\debug\Module', // 'class' => 'yii\debug\Module',
// ), // ],
], ],
]; ];

4
apps/advanced/environments/dev/frontend/config/main-local.php

@ -4,8 +4,8 @@ return [
//'debug', //'debug',
], ],
'modules' => [ 'modules' => [
// 'debug' => array( // 'debug' => [
// 'class' => 'yii\debug\Module', // 'class' => 'yii\debug\Module',
// ), // ],
], ],
]; ];

12
apps/advanced/environments/index.php

@ -6,14 +6,14 @@
* format: * format:
* *
* ```php * ```php
* return array( * return [
* 'environment name' => array( * 'environment name' => [
* 'path' => 'directory storing the local files', * 'path' => 'directory storing the local files',
* 'writable' => array( * 'writable' => [
* // list of directories that should be set writable * // list of directories that should be set writable
* ), * ],
* ), * ],
* ); * ];
* ``` * ```
*/ */
return [ return [

12
apps/benchmark/index.php

@ -4,15 +4,15 @@ defined('YII_DEBUG') or define('YII_DEBUG', false);
require(__DIR__ . '/protected/vendor/yiisoft/yii2/yii/Yii.php'); require(__DIR__ . '/protected/vendor/yiisoft/yii2/yii/Yii.php');
$config = array( $config = [
'id' => 'benchmark', 'id' => 'benchmark',
'basePath' => __DIR__ . '/protected', 'basePath' => __DIR__ . '/protected',
'components' => array( 'components' => [
'urlManager' => array( 'urlManager' => [
'enablePrettyUrl' => true, 'enablePrettyUrl' => true,
), ],
) ],
); ];
$application = new yii\web\Application($config); $application = new yii\web\Application($config);
$application->run(); $application->run();

4
build/build

@ -13,9 +13,9 @@ defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
require(__DIR__ . '/../framework/yii/Yii.php'); require(__DIR__ . '/../framework/yii/Yii.php');
$application = new yii\console\Application(array( $application = new yii\console\Application([
'id' => 'yii-build', 'id' => 'yii-build',
'basePath' => __DIR__, 'basePath' => __DIR__,
'controllerNamespace' => 'yii\build\controllers', 'controllerNamespace' => 'yii\build\controllers',
)); ]);
$application->run(); $application->run();

16
build/controllers/ClassmapController.php

@ -32,7 +32,7 @@ class ClassmapController extends Controller
if ($mapFile === null) { if ($mapFile === null) {
$mapFile = YII_PATH . '/classes.php'; $mapFile = YII_PATH . '/classes.php';
} }
$options = array( $options = [
'filter' => function ($path) { 'filter' => function ($path) {
if (is_file($path)) { if (is_file($path)) {
$file = basename($path); $file = basename($path);
@ -42,18 +42,18 @@ class ClassmapController extends Controller
} }
return null; return null;
}, },
'only' => array('.php'), 'only' => ['.php'],
'except' => array( 'except' => [
'Yii.php', 'Yii.php',
'BaseYii.php', 'BaseYii.php',
'/debug/', '/debug/',
'/console/', '/console/',
'/test/', '/test/',
'/gii/', '/gii/',
), ],
); ];
$files = FileHelper::findFiles($root, $options); $files = FileHelper::findFiles($root, $options);
$map = array(); $map = [];
foreach ($files as $file) { foreach ($files as $file) {
if (($pos = strpos($file, $root)) !== 0) { if (($pos = strpos($file, $root)) !== 0) {
die("Something wrong: $file\n"); die("Something wrong: $file\n");
@ -76,9 +76,9 @@ class ClassmapController extends Controller
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
return array( return [
$map $map
); ];
EOD; EOD;
if (is_file($mapFile) && file_get_contents($mapFile) === $output) { if (is_file($mapFile) && file_get_contents($mapFile) === $output) {

25
build/controllers/PhpDocController.php

@ -44,7 +44,7 @@ class PhpDocController extends Controller
$root = YII_PATH; $root = YII_PATH;
} }
$root = FileHelper::normalizePath($root); $root = FileHelper::normalizePath($root);
$options = array( $options = [
'filter' => function ($path) { 'filter' => function ($path) {
if (is_file($path)) { if (is_file($path)) {
$file = basename($path); $file = basename($path);
@ -54,16 +54,16 @@ class PhpDocController extends Controller
} }
return null; return null;
}, },
'only' => array('.php'), 'only' => ['.php'],
'except' => array( 'except' => [
'BaseYii.php', 'BaseYii.php',
'Yii.php', 'Yii.php',
'/debug/views/', '/debug/views/',
'/requirements/', '/requirements/',
'/gii/views/', '/gii/views/',
'/gii/generators/', '/gii/generators/',
), ],
); ];
$files = FileHelper::findFiles($root, $options); $files = FileHelper::findFiles($root, $options);
$nFilesTotal = 0; $nFilesTotal = 0;
$nFilesUpdated = 0; $nFilesUpdated = 0;
@ -89,7 +89,7 @@ class PhpDocController extends Controller
public function globalOptions() public function globalOptions()
{ {
return array_merge(parent::globalOptions(), array('updateFiles')); return array_merge(parent::globalOptions(), ['updateFiles']);
} }
protected function updateClassPropertyDocs($file, $className, $propertyDoc) protected function updateClassPropertyDocs($file, $className, $propertyDoc)
@ -136,7 +136,7 @@ class PhpDocController extends Controller
$start = $ref->getStartLine() - 2; $start = $ref->getStartLine() - 2;
$docStart = $start - count(explode("\n", $oldDoc)) + 1; $docStart = $start - count(explode("\n", $oldDoc)) + 1;
$newFileContent = array(); $newFileContent = [];
$n = count($fileContent); $n = count($fileContent);
for($i = 0; $i < $n; $i++) { for($i = 0; $i < $n; $i++) {
if ($i > $start || $i < $docStart) { 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+ ?= ?[^,]+)*)\)#', '[\s\n]{2,}public function [g|s]et(?<name>\w+)\(((?:,? ?\$\w+ ?= ?[^,]+)*|\$\w+(?:, ?\$\w+ ?= ?[^,]+)*)\)#',
$class['content']); $class['content']);
$acrs = array_merge($properties, $gets, $sets); $acrs = array_merge($properties, $gets, $sets);
//print_r($acrs); continue;
$props = array(); $props = [];
foreach ($acrs as &$acr) { foreach ($acrs as &$acr) {
$acr['name'] = lcfirst($acr['name']); $acr['name'] = lcfirst($acr['name']);
$acr['comment'] = trim(preg_replace('#(^|\n)\s+\*\s?#', '$1 * ', $acr['comment'])); $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'], 'type' => $acr['type'],
'comment' => $this->fixSentence($acr['comment']), 'comment' => $this->fixSentence($acr['comment']),
); ];
} }
ksort($props); ksort($props);
@ -299,12 +298,12 @@ class PhpDocController extends Controller
$phpdoc .= " *\n"; $phpdoc .= " *\n";
} }
} }
return array($className, $phpdoc); return [$className, $phpdoc];
} }
protected function match($pattern, $subject) protected function match($pattern, $subject)
{ {
$sets = array(); $sets = [];
preg_match_all($pattern . 'suU', $subject, $sets, PREG_SET_ORDER); preg_match_all($pattern . 'suU', $subject, $sets, PREG_SET_ORDER);
foreach ($sets as &$set) foreach ($sets as &$set)
foreach ($set as $i => $match) foreach ($set as $i => $match)

16
docs/api/base/Component.md

@ -25,8 +25,8 @@ In the above, an anonymous function is attached to the "update" event of the pos
the following types of event handlers: the following types of event handlers:
- anonymous function: `function($event) { ... }` - anonymous function: `function($event) { ... }`
- object method: `array($object, 'handleAdd')` - object method: `[$object, 'handleAdd']`
- static class method: `array('Page', 'handleAdd')` - static class method: `['Page', 'handleAdd']`
- global function: `'handleAdd'` - global function: `'handleAdd'`
The signature of an event handler should be like the following: 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: The syntax is like the following:
~~~ ~~~
array( [
'on add' => function($event) { ... } 'on add' => function($event) { ... }
) ]
~~~ ~~~
where `on add` stands for attaching an event to the `add` 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: following:
~~~ ~~~
array( [
'as tree' => array( 'as tree' => [
'class' => 'Tree', 'class' => 'Tree',
), ],
) ]
~~~ ~~~
where `as tree` stands for attaching a behavior named `tree`, and the array will be passed to [[\Yii::createObject()]] where `as tree` stands for attaching a behavior named `tree`, and the array will be passed to [[\Yii::createObject()]]

4
docs/api/base/Object.md

@ -50,12 +50,12 @@ In order to ensure the above life cycles, if a child class of Object needs to ov
it should be done like the following: it should be done like the following:
~~~ ~~~
public function __construct($param1, $param2, ..., $config = array()) public function __construct($param1, $param2, ..., $config = [])
{ {
... ...
parent::__construct($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. of the constructor, and the parent implementation should be called at the end of the constructor.

8
docs/api/db/ActiveRecord-find.md

@ -8,7 +8,7 @@ $customers = Customer::find()->all();
// find all active customers and order them by their age: // find all active customers and order them by their age:
$customers = Customer::find() $customers = Customer::find()
->where(array('status' => 1)) ->where(['status' => 1])
->orderBy('age') ->orderBy('age')
->all(); ->all();
@ -16,11 +16,11 @@ $customers = Customer::find()
$customer = Customer::find(10); $customer = Customer::find(10);
// the above is equivalent to: // 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 // 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: // the above is equivalent to:
$customer = Customer::find()->where(array('age' => 30, 'status' => 1))->one(); $customer = Customer::find()->where(['age' => 30, 'status' => 1])->one();
~~~ ~~~

42
docs/api/db/ActiveRecord.md

@ -40,18 +40,18 @@ instance which serves as the DB connection. Usually this component is configured
via application configuration like the following: via application configuration like the following:
~~~ ~~~
return array( return [
'components' => array( 'components' => [
'db' => array( 'db' => [
'class' => 'yii\db\Connection', 'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=testdb', 'dsn' => 'mysql:host=localhost;dbname=testdb',
'username' => 'demo', 'username' => 'demo',
'password' => 'demo', 'password' => 'demo',
// turn on schema caching to improve performance // turn on schema caching to improve performance
// 'schemaCacheDuration' => 3600, // 'schemaCacheDuration' => 3600,
), ],
), ],
); ];
~~~ ~~~
@ -70,13 +70,13 @@ The followings are some examples,
~~~ ~~~
// to retrieve all *active* customers and order them by their ID: // to retrieve all *active* customers and order them by their ID:
$customers = Customer::find() $customers = Customer::find()
->where(array('status' => $active)) ->where(['status' => $active])
->orderBy('id') ->orderBy('id')
->all(); ->all();
// to return a single customer whose ID is 1: // to return a single customer whose ID is 1:
$customer = Customer::find() $customer = Customer::find()
->where(array('id' => 1)) ->where(['id' => 1])
->one(); ->one();
// or use the following shortcut approach: // or use the following shortcut approach:
@ -88,7 +88,7 @@ $customers = Customer::findBySql($sql)->all();
// to return the number of *active* customers: // to return the number of *active* customers:
$count = Customer::find() $count = Customer::find()
->where(array('status' => $active)) ->where(['status' => $active])
->count(); ->count();
// to return customers in terms of arrays rather than `Customer` objects: // to return customers in terms of arrays rather than `Customer` objects:
@ -158,7 +158,7 @@ $customer = Customer::find($id);
$customer->delete(); $customer->delete();
// to increment the age of all customers by 1 // 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() 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() 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) public function getBigOrders($threshold = 100)
{ {
return $this->hasMany('Order', array('customer_id' => 'id')) return $this->hasMany('Order', ['customer_id' => 'id'])
->where('subtotal > :threshold', array(':threshold' => $threshold)) ->where('subtotal > :threshold', [':threshold' => $threshold])
->orderBy('id'); ->orderBy('id');
} }
} }
@ -244,8 +244,8 @@ class Order extends \yii\db\ActiveRecord
{ {
public function getItems() public function getItems()
{ {
return $this->hasMany('Item', array('id' => 'item_id')) return $this->hasMany('Item', ['id' => 'item_id'])
->viaTable('tbl_order_item', array('order_id' => 'id')); ->viaTable('tbl_order_item', ['order_id' => 'id']);
} }
} }
~~~ ~~~
@ -259,12 +259,12 @@ class Order extends \yii\db\ActiveRecord
{ {
public function getOrderItems() public function getOrderItems()
{ {
return $this->hasMany('OrderItem', array('order_id' => 'id')); return $this->hasMany('OrderItem', ['order_id' => 'id']);
} }
public function getItems() public function getItems()
{ {
return $this->hasMany('Item', array('id' => 'item_id')) return $this->hasMany('Item', ['id' => 'item_id'])
->via('orderItems'); ->via('orderItems');
} }
} }
@ -331,11 +331,11 @@ $orders = $customer->getOrders()->where('subtotal>100')->all();
// eager loading: SELECT * FROM tbl_customer LIMIT 10 // eager loading: SELECT * FROM tbl_customer LIMIT 10
SELECT * FROM tbl_order WHERE customer_id IN (1,2,...) AND subtotal>100 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) { 'orders' => function($query) {
$query->andWhere('subtotal>100'); $query->andWhere('subtotal>100');
}, },
))->all(); ])->all();
~~~ ~~~
@ -437,7 +437,7 @@ class Customer extends \yii\db\ActiveRecord
*/ */
public static function olderThan($query, $age = 30) public static function olderThan($query, $age = 30)
{ {
$query->andWhere('age > :age', array(':age' => $age)); $query->andWhere('age > :age', [':age' => $age]);
} }
} }

74
docs/guide/active-record.md

@ -54,16 +54,16 @@ By default, ActiveRecord assumes that there is an application component named `d
[[Connection]] instance. Usually this component is configured in application configuration file: [[Connection]] instance. Usually this component is configured in application configuration file:
```php ```php
return array( return [
'components' => array( 'components' => [
'db' => array( 'db' => [
'class' => 'yii\db\Connection', 'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=testdb', 'dsn' => 'mysql:host=localhost;dbname=testdb',
'username' => 'demo', 'username' => 'demo',
'password' => 'demo', 'password' => 'demo',
), ],
), ],
); ];
``` ```
Please read the [Database basics](database-basics.md) section to learn more on how to configure and use database connections. 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 ```php
// to retrieve all *active* customers and order them by their ID: // to retrieve all *active* customers and order them by their ID:
$customers = Customer::find() $customers = Customer::find()
->where(array('status' => $active)) ->where(['status' => $active])
->orderBy('id') ->orderBy('id')
->all(); ->all();
@ -91,7 +91,7 @@ $customer = Customer::find(1);
// the above code is equivalent to the following: // the above code is equivalent to the following:
$customer = Customer::find() $customer = Customer::find()
->where(array('id' => 1)) ->where(['id' => 1])
->one(); ->one();
// to retrieve customers using a raw SQL statement: // to retrieve customers using a raw SQL statement:
@ -100,7 +100,7 @@ $customers = Customer::findBySql($sql)->all();
// to return the number of *active* customers: // to return the number of *active* customers:
$count = Customer::find() $count = Customer::find()
->where(array('status' => $active)) ->where(['status' => $active])
->count(); ->count();
// to return customers in terms of arrays rather than `Customer` objects: // to return customers in terms of arrays rather than `Customer` objects:
@ -172,7 +172,7 @@ $customer = Customer::find($id);
$customer->delete(); $customer->delete();
// to increment the age of ALL customers by 1 // 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 > 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() 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() 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) public function getBigOrders($threshold = 100)
{ {
return $this->hasMany('Order', array('customer_id' => 'id')) return $this->hasMany('Order', ['customer_id' => 'id'])
->where('subtotal > :threshold', array(':threshold' => $threshold)) ->where('subtotal > :threshold', [':threshold' => $threshold])
->orderBy('id'); ->orderBy('id');
} }
} }
@ -291,8 +291,8 @@ class Order extends \yii\db\ActiveRecord
{ {
public function getItems() public function getItems()
{ {
return $this->hasMany('Item', array('id' => 'item_id')) return $this->hasMany('Item', ['id' => 'item_id'])
->viaTable('tbl_order_item', array('order_id' => 'id')); ->viaTable('tbl_order_item', ['order_id' => 'id']);
} }
} }
``` ```
@ -306,12 +306,12 @@ class Order extends \yii\db\ActiveRecord
{ {
public function getOrderItems() public function getOrderItems()
{ {
return $this->hasMany('OrderItem', array('order_id' => 'id')); return $this->hasMany('OrderItem', ['order_id' => 'id']);
} }
public function getItems() public function getItems()
{ {
return $this->hasMany('Item', array('id' => 'item_id')) return $this->hasMany('Item', ['id' => 'item_id'])
->via('orderItems'); ->via('orderItems');
} }
} }
@ -379,11 +379,11 @@ $orders = $customer->getOrders()->where('subtotal>100')->all();
// eager loading: SELECT * FROM tbl_customer LIMIT 10 // eager loading: SELECT * FROM tbl_customer LIMIT 10
SELECT * FROM tbl_order WHERE customer_id IN (1,2,...) AND subtotal>100 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) { 'orders' => function($query) {
$query->andWhere('subtotal>100'); $query->andWhere('subtotal>100');
}, },
))->all(); ])->all();
``` ```
@ -483,7 +483,7 @@ class Customer extends \yii\db\ActiveRecord
*/ */
public static function olderThan($query, $age = 30) 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() 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() 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() public function getProduct()
{ {
return $this->hasOne('Product', array('product_id' => 'id')); return $this->hasOne('Product', ['product_id' => 'id']);
} }
public function scenarios() public function scenarios()
{ {
return array( return [
'userCreates' => array( 'userCreates' => [
'attributes' => array('name', 'value'), 'attributes' => ['name', 'value'],
'atomic' => array(self::OP_INSERT), 'atomic' => [self::OP_INSERT],
), ],
); ];
} }
} }
@ -586,17 +586,17 @@ class Product extends \yii\db\ActiveRecord
public function getFeatures() public function getFeatures()
{ {
return $this->hasMany('Feature', array('id' => 'product_id')); return $this->hasMany('Feature', ['id' => 'product_id']);
} }
public function scenarios() public function scenarios()
{ {
return array( return [
'userCreates' => array( 'userCreates' => [
'attributes' => array('title', 'price'), 'attributes' => ['title', 'price'],
'atomic' => array(self::OP_INSERT), 'atomic' => [self::OP_INSERT],
), ],
); ];
} }
public function afterValidate() public function afterValidate()

4
docs/guide/bootstrap-widgets.md

@ -17,11 +17,11 @@ convenient way to include bootstrap assets in your pages with a single line adde
`config` directory: `config` directory:
```php ```php
public $depends = array( public $depends = [
'yii\web\YiiAsset', 'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset', // this line 'yii\bootstrap\BootstrapAsset', // this line
// 'yii\bootstrap\BootstrapThemeAsset' // uncomment to apply bootstrap 2 style to bootstrap 3 // '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 Using bootstrap through Yii asset manager allows you to minimize its resources and combine with your own resources when

20
docs/guide/caching.md

@ -13,23 +13,23 @@ two cache servers. Note, this configuration should be done in file located at `@
in case you're using basic sample application. in case you're using basic sample application.
```php ```php
'components' => array( 'components' => [
'cache' => array( 'cache' => [
'class' => '\yii\caching\MemCache', 'class' => '\yii\caching\MemCache',
'servers' => array( 'servers' => [
array( [
'host' => 'server1', 'host' => 'server1',
'port' => 11211, 'port' => 11211,
'weight' => 100, 'weight' => 100,
), ],
array( [
'host' => 'server2', 'host' => 'server2',
'port' => 11211, 'port' => 11211,
'weight' => 50, 'weight' => 50,
), ],
), ],
), ],
), ],
``` ```
When the application is running, the cache component can be accessed through `Yii::$app->cache` call. When the application is running, the cache component can be accessed through `Yii::$app->cache` call.

40
docs/guide/configuration.md

@ -29,12 +29,12 @@ stored in a PHP file in `/config` directory of the application and looks like th
```php ```php
<?php <?php
return array( return [
'id' => 'applicationId', 'id' => 'applicationId',
'basePath' => dirname(__DIR__), 'basePath' => dirname(__DIR__),
'components' => array( 'components' => [
// ... // ...
), ],
'params' => require(__DIR__ . '/params.php'), 'params' => require(__DIR__ . '/params.php'),
); );
``` ```
@ -53,31 +53,25 @@ Majority of Yii functionality are application components. These are attached to
```php ```php
<?php <?php
return array( return [
'id' => 'applicationId', 'id' => 'applicationId',
'basePath' => dirname(__DIR__), 'basePath' => dirname(__DIR__),
'components' => array( 'components' => [
'cache' => array( 'cache' => ['class' => 'yii\caching\FileCache'],
'class' => 'yii\caching\FileCache', 'user' => ['identityClass' => 'app\models\User'],
), 'errorHandler' => ['errorAction' => 'site/error'],
'user' => array( 'log' => [
'identityClass' => 'app\models\User',
),
'errorHandler' => array(
'errorAction' => 'site/error',
),
'log' => array(
'traceLevel' => YII_DEBUG ? 3 : 0, 'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => array( 'targets' => [
array( [
'class' => 'yii\log\FileTarget', '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 In the above four components are configured: `cache`, `user`, `errorHandler`, `log`. Each entry key is a component ID

21
docs/guide/controller.md

@ -93,10 +93,10 @@ class BlogController extends Controller
$text = $post->getHistory($version); $text = $post->getHistory($version);
} }
return $this->render('view', array( return $this->render('view', [
'post' => $post, 'post' => $post,
'text' => $text, 'text' => $text,
)); ]);
} }
} }
``` ```
@ -128,13 +128,11 @@ class BlogController extends Controller
if(\Yii::$app->request->isPost)) { if(\Yii::$app->request->isPost)) {
$post->load($_POST); $post->load($_POST);
if($post->save()) { if($post->save()) {
$this->redirect(array('view', 'id' => $post->id)); $this->redirect(['view', 'id' => $post->id]);
} }
} }
return $this->render('update', array( return $this->render('update', ['post' => $post]);
'post' => $post,
));
} }
} }
``` ```
@ -167,13 +165,12 @@ public SiteController extends \yii\web\Controller
{ {
public function actions() public function actions()
{ {
return array( return [
'about' => array( 'about' => [
'class' => '@app/actions/Page', 'class' => '@app/actions/Page',
'view' => 'about', 'view' => 'about',
), ],
), ];
);
} }
} }
``` ```

38
docs/guide/database-basics.md

@ -19,11 +19,11 @@ In order to start using database you need to configure database connection compo
to application configuration (for "basic" web application it's `config/web.php`) like the following: to application configuration (for "basic" web application it's `config/web.php`) like the following:
```php ```php
return array( return [
// ... // ...
'components' => array( 'components' => [
// ... // ...
'db' => array( 'db' => [
'class' => 'yii\db\Connection', 'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=mydatabase', // MySQL, MariaDB 'dsn' => 'mysql:host=localhost;dbname=mydatabase', // MySQL, MariaDB
//'dsn' => 'sqlite:/path/to/database/file', // SQLite //'dsn' => 'sqlite:/path/to/database/file', // SQLite
@ -36,10 +36,10 @@ return array(
'username' => 'root', 'username' => 'root',
'password' => '', 'password' => '',
'charset' => 'utf8', 'charset' => 'utf8',
), ],
), ],
// ... // ...
); ];
``` ```
Please refer to the [PHP manual](http://www.php.net/manual/en/function.PDO-construct.php) for more details 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. 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: If you don't want to define the connection as an application component you can instantiate it directly:
```php ```php
$connection = new \yii\db\Connection(array( $connection = new \yii\db\Connection([
'dsn' => $dsn, 'dsn' => $dsn,
'username' => $username, 'username' => $username,
'password' => $password, 'password' => $password,
)); ]);
$connection->open(); $connection->open();
``` ```
@ -118,22 +118,20 @@ Alternatively the following syntax that takes care of proper table and column na
```php ```php
// INSERT // INSERT
$connection->createCommand()->insert('tbl_user', array( $connection->createCommand()->insert('tbl_user', [
'name' => 'Sam', 'name' => 'Sam',
'age' => 30, 'age' => 30,
))->execute(); ])->execute();
// INSERT multiple rows at once // INSERT multiple rows at once
$connection->createCommand()->batchInsert('tbl_user', array('name', 'age'), array( $connection->createCommand()->batchInsert('tbl_user', ['name', 'age'], [
array('Tom', 30), ['Tom', 30],
array('Jane', 20), ['Jane', 20],
array('Linda', 25), ['Linda', 25],
))->execute(); ])->execute();
// UPDATE // UPDATE
$connection->createCommand()->update('tbl_user', array( $connection->createCommand()->update('tbl_user', ['status' => 1], 'age > 30')->execute();
'status' => 1,
), 'age > 30')->execute();
// DELETE // DELETE
$connection->createCommand()->delete('tbl_user', 'status = 0')->execute(); $connection->createCommand()->delete('tbl_user', 'status = 0')->execute();
@ -236,11 +234,11 @@ These can be used as follows:
```php ```php
// CREATE TABLE // CREATE TABLE
$connection->createCommand()->createTable('tbl_post', array( $connection->createCommand()->createTable('tbl_post', [
'id' => 'pk', 'id' => 'pk',
'title' => 'string', 'title' => 'string',
'text' => 'text', 'text' => 'text',
); ];
``` ```
For the full reference check [[\yii\db\Command]]. For the full reference check [[\yii\db\Command]].

46
docs/guide/i18n.md

@ -24,7 +24,7 @@ Target language is what's currently used. It's defined in application configurat
```php ```php
// ... // ...
return array( return [
'id' => 'applicationID', 'id' => 'applicationID',
'basePath' => dirname(__DIR__), 'basePath' => dirname(__DIR__),
'language' => 'ru_RU' // ← here! '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: Yii tries to load approprite translation from one of the message sources defined via `i18n` component configuration:
```php ```php
'components' => array( 'components' => [
// ... // ...
'i18n' => array( 'i18n' => [
'translations' => array( 'translations' => [
'app*' => array( 'app*' => [
'class' => 'yii\i18n\PhpMessageSource', 'class' => 'yii\i18n\PhpMessageSource',
//'basePath' => '@app/messages', //'basePath' => '@app/messages',
//'sourceLanguage' => 'en_US', //'sourceLanguage' => 'en_US',
'fileMap' => array( 'fileMap' => [
'app' => 'app.php', 'app' => 'app.php',
'app/error' => 'error.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 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 ```php
$username = 'Alexander'; $username = 'Alexander';
echo \Yii::t('app', 'Hello, {username}!', array( echo \Yii::t('app', 'Hello, {username}!', [
'username' => $username, 'username' => $username,
)); ]);
``` ```
Note that the parameter assignment is without the brackets. 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 ### Spellout
```php ```php
echo \Yii::t('app', '{n,number} is spelled as {n, spellout}', array( echo \Yii::t('app', '{n,number} is spelled as {n, spellout}', ['n' => 42]);
'n' => 42,
));
``` ```
### Ordinal ### Ordinal
```php ```php
echo \Yii::t('app', 'You are {n, ordinal} visitor here!', array( echo \Yii::t('app', 'You are {n, ordinal} visitor here!', ['n' => 42]);
'n' => 42,
));
``` ```
Will produce "You are 42nd visitor here!". Will produce "You are 42nd visitor here!".
@ -209,9 +205,7 @@ Will produce "You are 42nd visitor here!".
```php ```php
echo \Yii::t('app', 'You are here for {n, duration} already!', array( echo \Yii::t('app', 'You are here for {n, duration} already!', ['n' => 42]);
'n' => 42,
));
``` ```
Will produce "You are here for 47 sec. already!". 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. word in certain situations.
```php ```php
echo \Yii::t('app', 'There {n, plural, =0{are no cats} =1{is one cat} other{are # cats}}!', array( echo \Yii::t('app', 'There {n, plural, =0{are no cats} =1{is one cat} other{are # cats}}!', ['n' => 0]);
'n' => 0,
));
``` ```
Will give us "There are no cats!". 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. provides a default phrase.
```php ```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', 'name' => 'Snoopy',
'gender' => 'dog', 'gender' => 'dog',
)); ]);
``` ```
Will produce "Snoopy is dog and it loves Yii!". Will produce "Snoopy is dog and it loves Yii!".

8
docs/guide/migration.md

@ -82,11 +82,11 @@ class m101129_185401_create_news_table extends \yii\db\Migration
{ {
public function up() public function up()
{ {
$this->db->createCommand()->createTable('tbl_news', array( $this->db->createCommand()->createTable('tbl_news', [
'id' => 'pk', 'id' => 'pk',
'title' => 'string(128) NOT NULL', 'title' => 'string(128) NOT NULL',
'content' => 'text', 'content' => 'text',
))->execute(); ])->execute();
} }
public function down() public function down()
@ -128,11 +128,11 @@ class m101129_185401_create_news_table extends \yii\db\Migration
$transaction=$this->getDbConnection()->beginTransaction(); $transaction=$this->getDbConnection()->beginTransaction();
try try
{ {
$this->db->createCommand()->createTable('tbl_news', array( $this->db->createCommand()->createTable('tbl_news', [
'id' => 'pk', 'id' => 'pk',
'title' => 'string NOT NULL', 'title' => 'string NOT NULL',
'content' => 'text', 'content' => 'text',
))->execute(); ])->execute();
$transaction->commit(); $transaction->commit();
} }
catch(Exception $e) catch(Exception $e)

46
docs/guide/model.md

@ -77,10 +77,10 @@ class LoginForm extends \yii\base\Model
public function attributeLabels() public function attributeLabels()
{ {
return array( return [
'username' => 'Your name', 'username' => 'Your name',
'password' => 'Your password', 'password' => 'Your password',
); ];
} }
} }
``` ```
@ -105,10 +105,10 @@ class User extends \yii\db\ActiveRecord
{ {
public function scenarios() public function scenarios()
{ {
return array( return [
'login' => array('username', 'password'), 'login' => ['username', 'password'],
'register' => array('username', 'email', '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, We may do so by prefixing an exclamation character to the attribute name when declaring it in `scenarios()`. For example,
```php ```php
array('username', 'password', '!secret') ['username', 'password', '!secret']
``` ```
Active model scenario could be set using one of the following ways: 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) public function actionCreate($id = null)
{ {
// first way // first way
$employee = new Employee(array('scenario' => 'managementPanel')); $employee = new Employee(['scenario' => 'managementPanel']);
// second way // second way
$employee = new Employee; $employee = new Employee;
$employee->scenario = 'managementPanel'; $employee->scenario = 'managementPanel';
// third way // third way
$employee = Employee::find()->where('id = :id', array(':id' => $id))->one(); $employee = Employee::find()->where('id = :id', [':id' => $id])->one();
if ($employee !== null) { if ($employee !== null) {
$employee->setScenario('managementPanel'); $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: instance of a [[\yii\validators\Validator]] child class, or an array with the following format:
```php ```php
array( [
'attribute1, attribute2, ...', 'attribute1, attribute2, ...',
'validator class or alias', 'validator class or alias',
// specifies in which scenario(s) this rule is active. // specifies in which scenario(s) this rule is active.
@ -182,7 +182,7 @@ array(
'property1' => 'value1', 'property1' => 'value1',
'property2' => 'value2', 'property2' => 'value2',
// ... // ...
) ]
``` ```
When `validate()` is called, the actual validation rules executed are determined using both of the following criteria: 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: Using the same `attributes` property you can massively assign data from associative array to model attributes:
```php ```php
$attributes = array( $attributes = [
'title' => 'Model attributes', 'title' => 'Model attributes',
'create_time' => time(), 'create_time' => time(),
); ];
$post->attributes = $attributes; $post->attributes = $attributes;
``` ```
@ -238,24 +238,24 @@ assignment is described in `scenarios` method:
```php ```php
function rules() function rules()
{ {
return array( return [
// rule applied when corresponding field is "safe" // rule applied when corresponding field is "safe"
array('username', 'string', 'length' => array(4, 32)), ['username', 'string', 'length' => [4, 32]],
array('first_name', 'string', 'max' => 128), ['first_name', 'string', 'max' => 128],
array('password', 'required'), ['password', 'required'],
// rule applied when scenario is "signup" no matter if field is "safe" or not // 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() function scenarios()
{ {
return array( return [
// on signup allow mass assignment of username // on signup allow mass assignment of username
'signup' => array('username', 'password'), 'signup' => ['username', 'password'],
'update' => array('username', 'first_name'), 'update' => ['username', 'first_name'],
); ];
} }
``` ```

32
docs/guide/performance.md

@ -41,11 +41,11 @@ to save the time of parsing database schema. This can be done by setting the
`protected/config/main.php`: `protected/config/main.php`:
```php ```php
return array( return [
// ... // ...
'components' => array( 'components' => [
// ... // ...
'db' => array( 'db' => [
'class' => 'yii\db\Connection', 'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=mydatabase', 'dsn' => 'mysql:host=localhost;dbname=mydatabase',
'username' => 'root', 'username' => 'root',
@ -57,12 +57,12 @@ return array(
// Name of the cache component used. Default is 'cache'. // Name of the cache component used. Default is 'cache'.
//'schemaCache' => 'cache', //'schemaCache' => 'cache',
), ],
'cache' => array( 'cache' => [
'class' => 'yii\caching\FileCache', 'class' => 'yii\caching\FileCache',
), ],
), ],
); ];
``` ```
Note that `cache` application component should be configured. 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`: application via `protected/config/main.php`:
```php ```php
return array( return [
// ... // ...
'components' => array( 'components' => [
'session' => array( 'session' => [
'class' => 'yii\web\DbSession', 'class' => 'yii\web\DbSession',
// Set the following if want to use DB component other than // 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 // To override default session table set the following
// 'sessionTable' => 'my_session', // 'sessionTable' => 'my_session',
), ],
), ],
); ];
``` ```
You can use `CacheSession` to store sessions using cache. Note that some You can use `CacheSession` to store sessions using cache. Note that some
@ -154,9 +154,7 @@ class PostController extends Controller
public function actionIndex() public function actionIndex()
{ {
$posts = Post::find()->orderBy('id DESC')->limit(100)->asArray()->all(); $posts = Post::find()->orderBy('id DESC')->limit(100)->asArray()->all();
return $this->render('index', array( return $this->render('index', ['posts' => $posts]);
'posts' => $posts,
));
} }
} }
``` ```

44
docs/guide/query-builder.md

@ -40,7 +40,7 @@ $query->select('user_id')->distinct()->from('tbl_post');
Select options can be specified as array. It's especially useful when these are formed dynamically. Select options can be specified as array. It's especially useful when these are formed dynamically.
```php ```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') ->from('tbl_user')
->leftJoin('tbl_post', 'tbl_post.user_id = tbl_user.id'); // <-- join with another table ->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: The simplest is to specify condition in a string:
```php ```php
$query->where('status=:status', array( $query->where('status=:status', [':status' => $status]);
':status' => $status,
));
``` ```
When using this format make sure you're binding parameters and not creating a query by string concatenation. 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 ```php
$query->where('status=:status'); $query->where('status=:status');
$query->addParams(array( $query->addParams([':status' => $status]);
':status' => $status,
));
``` ```
There is another convenient way to use the method called hash format: There is another convenient way to use the method called hash format:
```php ```php
$query->where(array( $query->where([
'status' => 10, 'status' => 10,
'type' => 2, 'type' => 2,
'id' => array(4, 8, 15, 16, 23, 42), 'id' => [4, 8, 15, 16, 23, 42],
)); ]);
``` ```
It will generate the following SQL: 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: If you'll specify value as `null` such as the following:
```php ```php
$query->where(array( $query->where(['status' => null]);
'status' => null,
));
``` ```
SQL generated will be: SQL generated will be:
@ -114,31 +108,31 @@ SQL generated will be:
WHERE (`status` IS NULL) 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: Operator can be one of the following:
- `and`: the operands should be concatenated together using `AND`. For example, - `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, 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. The method will NOT do any quoting or escaping.
- `or`: similar to the `and` operator except that the operands are concatenated using `OR`. - `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 - `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. 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` - `not between`: similar to `between` except the `BETWEEN` is replaced with `NOT BETWEEN`
in the generated condition. in the generated condition.
- `in`: operand 1 should be a column or DB expression, and operand 2 be an array representing - `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, 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. 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. - `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 - `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. 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 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%'`. `name LIKE '%test%' AND name LIKE '%sample%'`.
The method will properly quote the column name and escape values in the range. 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` - `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; $status = 10;
$search = 'yii'; $search = 'yii';
$query->where(array('status' => $status)); $query->where(['status' => $status]);
if (!empty($search)) { if (!empty($search)) {
$query->addWhere('like', 'title', $search); $query->addWhere('like', 'title', $search);
} }
@ -172,10 +166,10 @@ Order
For ordering results `orderBy` and `addOrderBy` could be used: For ordering results `orderBy` and `addOrderBy` could be used:
```php ```php
$query->orderBy(array( $query->orderBy([
'id' => Query::SORT_ASC, 'id' => Query::SORT_ASC,
'name' => Query::SORT_DESC, 'name' => Query::SORT_DESC,
)); ]);
``` ```
Here we are ordering by `id` ascending and then by `name` descending. 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`: If you want to add another field after using `groupBy`:
```php ```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 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: for these are similar to the ones for `where` methods group:
```php ```php
$query->having(array('status' => $status)); $query->having(['status' => $status]);
``` ```
Limit and offset Limit and offset

28
docs/guide/template.md

@ -7,23 +7,23 @@ The `view` component is responsible for rendering views. You can add
a custom template engines by reconfiguring this component's behavior: a custom template engines by reconfiguring this component's behavior:
```php ```php
array( [
'components' => array( 'components' => [
'view' => array( 'view' => [
'class' => 'yii\base\View', 'class' => 'yii\base\View',
'renderers' => array( 'renderers' => [
'tpl' => array( 'tpl' => [
'class' => 'yii\renderers\SmartyViewRenderer', 'class' => 'yii\renderers\SmartyViewRenderer',
), ],
'twig' => array( 'twig' => [
'class' => 'yii\renderers\TwigViewRenderer', 'class' => 'yii\renderers\TwigViewRenderer',
'twigPath' => '@app/vendors/Twig', '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). 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: or `$this->renderPartial()` from your controller:
```php ```php
echo $this->render('renderer.twig', array('username' => 'Alex')); echo $this->render('renderer.twig', ['username' => 'Alex']);
``` ```
### Additional functions ### 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: or `$this->renderPartial()` from your controller:
```php ```php
echo $this->render('renderer.tpl', array('username' => 'Alex')); echo $this->render('renderer.tpl', ['username' => 'Alex']);
``` ```
### Additional functions ### Additional functions

48
docs/guide/upgrade-from-v1.md

@ -40,7 +40,7 @@ it can be properly configured:
```php ```php
class MyClass extends \yii\Object class MyClass extends \yii\Object
{ {
public function __construct($param1, $param2, $config = array()) public function __construct($param1, $param2, $config = [])
{ {
// ... initialization before configuration is applied // ... 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: using a configuration array like the following:
```php ```php
$object = Yii::createObject(array( $object = Yii::createObject([
'class' => 'MyClass', 'class' => 'MyClass',
'property1' => 'abc', 'property1' => 'abc',
'property2' => 'cde', 'property2' => 'cde',
), $param1, $param2); ], $param1, $param2);
``` ```
@ -177,10 +177,10 @@ if (isset($_POST['Post'])) {
$model->save(); $model->save();
$postTags = array(); $postTags = [];
$tagsCount = count($_POST['PostTag']); $tagsCount = count($_POST['PostTag']);
while($tagsCount-- > 0){ while($tagsCount-- > 0){
$postTags[] = new PostTag(array('post_id' => $model->id)); $postTags[] = new PostTag(['post_id' => $model->id]);
} }
Model::loadMultiple($postTags, $_POST); Model::loadMultiple($postTags, $_POST);
``` ```
@ -193,10 +193,10 @@ a list of scenarios and the corresponding attributes that need to be validated w
```php ```php
public function scenarios() public function scenarios()
{ {
return array( return [
'backend' => array('email', 'role'), 'backend' => ['email', 'role'],
'frontend' => array('email', '!name'), 'frontend' => ['email', '!name'],
); ];
} }
``` ```
@ -229,13 +229,13 @@ methods of the `Widget` class. For example,
```php ```php
// Note that you have to "echo" the result to display it // 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 // Passing an array to initialize the object properties
$form = \yii\widgets\ActiveForm::begin(array( $form = \yii\widgets\ActiveForm::begin([
'options' => array('class' => 'form-horizontal'), 'options' => ['class' => 'form-horizontal'],
'fieldConfig' => array('inputOptions' => array('class' => 'input-xlarge')), 'fieldConfig' => ['inputOptions' => ['class' => 'input-xlarge']],
)); ]);
... form inputs here ... ... form inputs here ...
\yii\widgets\ActiveForm::end(); \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 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 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`. `/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 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 ```php
public function behaviors() public function behaviors()
{ {
return array( return [
'access' => array( 'access' => [
'class' => 'yii\web\AccessControl', 'class' => 'yii\web\AccessControl',
'rules' => array( 'rules' => [
array('allow' => true, 'actions' => array('admin'), 'roles' => array('@')), ['allow' => true, 'actions' => ['admin'], 'roles' => ['@']],
), ),
), ),
); );
@ -386,7 +386,7 @@ class Customer extends \yii\db\ActiveRecord
{ {
public function getOrders() 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 ```php
// to retrieve all *active* customers and order them by their ID: // to retrieve all *active* customers and order them by their ID:
$customers = Customer::find() $customers = Customer::find()
->where(array('status' => $active)) ->where(['status' => $active])
->orderBy('id') ->orderBy('id')
->all(); ->all();
// return the customer whose PK is 1 // 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. the same goal.
```php ```php
array( [
'pattern' => 'post/<page:\d+>/<tag>', 'pattern' => 'post/<page:\d+>/<tag>',
'route' => 'post/index', 'route' => 'post/index',
'defaults' => array('page' => 1), 'defaults' => ['page' => 1],
) ]
``` ```

10
docs/guide/validation.md

@ -90,16 +90,16 @@ Converts the attribute value according to a filter.
Typically a callback is either the name of PHP function: Typically a callback is either the name of PHP function:
```php ```php
array('password', 'filter', 'filter' => 'trim'), ['password', 'filter', 'filter' => 'trim'],
``` ```
Or an anonymous function: Or an anonymous function:
```php ```php
array('text', 'filter', 'filter' => function ($value) { ['text', 'filter', 'filter' => function ($value) {
// here we are removing all swear words from text // here we are removing all swear words from text
return $newValue; return $newValue;
}), }],
``` ```
### `in`: [[RangeValidator]] ### `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. 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. - `max` maximum length. If not set, it means no maximum length limit.
- `min` minimum length. If not set, it means no minimum 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]])_ - `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. 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 - `defaultScheme` the default URI scheme. If the input doesn't contain the scheme part, the default scheme will be
prepended to it. _(null)_ prepended to it. _(null)_
- `enableIDN` whether validation process should take into account IDN (internationalized domain names). _(false)_ - `enableIDN` whether validation process should take into account IDN (internationalized domain names). _(false)_

46
docs/guide/view.md

@ -16,9 +16,7 @@ View is typically called from controller action like the following:
```php ```php
public function actionIndex() public function actionIndex()
{ {
return $this->render('index', array( return $this->render('index', ['username' => 'samdark']);
'username' => 'samdark',
));
} }
``` ```
@ -47,13 +45,13 @@ In order to use widget you need to do the following:
```php ```php
// Note that you have to "echo" the result to display it // 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 // Passing an array to initialize the object properties
$form = \yii\widgets\ActiveForm::begin(array( $form = \yii\widgets\ActiveForm::begin([
'options' => array('class' => 'form-horizontal'), 'options' => ['class' => 'form-horizontal'],
'fieldConfig' => array('inputOptions' => array('class' => 'input-xlarge')), 'fieldConfig' => ['inputOptions' => ['class' => 'input-xlarge']],
)); ]);
... form inputs here ... ... form inputs here ...
\yii\widgets\ActiveForm::end(); \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: Adding meta tags such as encoding, description, keywords is easy with view object as well:
```php ```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: 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: 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 ```html
$this->registerMetaTag(array('description' => 'This is my cool website made with Yii!'), 'meta-description'); $this->registerMetaTag(['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 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 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: server. Yii view object has a method to work with these:
```php ```php
$this->registerLinkTag(array( $this->registerLinkTag([
'title' => 'Lives News for Yii Framework', 'title' => 'Lives News for Yii Framework',
'rel' => 'alternate', 'rel' => 'alternate',
'type' => 'application/rss+xml', 'type' => 'application/rss+xml',
'href' => 'http://www.yiiframework.com/rss.xml/', 'href' => 'http://www.yiiframework.com/rss.xml/',
)); ]);
``` ```
The code above will result in 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. need to make sure there's only a single style tag use third argument as was mentioned in meta tags description.
```php ```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 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"> <div class="user-index">
<?php <?php
foreach($users as $user) { foreach($users as $user) {
echo $this->render('_profile', array( echo $this->render('_profile', [
'username' => $user->name, 'username' => $user->name,
'tagline' => $user->tagline, 'tagline' => $user->tagline,
)); ]);
} }
?> ?>
</div> </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: Same way we can reuse it in another view displaying a single user profile:
```php ```php
echo $this->render('_profile', array( echo $this->render('_profile', [
'username' => $user->name, 'username' => $user->name,
'tagline' => $user->tagline, 'tagline' => $user->tagline,
)); ]);
``` ```
### Accessing context ### 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`: from `yii\base\View`. It can be done via application configuration file such as `config/web.php`:
```php ```php
return array( return [
// ... // ...
'components' => array( 'components' => [
'view' => array( 'view' => [
'class' => 'app\components\View', 'class' => 'app\components\View',
), ],
// ... // ...
), ],
); ];
``` ```

14
docs/internals/ar.md

@ -9,16 +9,16 @@ Possible scenario formats supported by ActiveRecord:
```php ```php
public function scenarios() public function scenarios()
{ {
return array( return [
// attributes array, all operations won't be wrapped with transaction // 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 // insert and update operations will be wrapped with transaction, delete won't be wrapped
'scenario2' => array( 'scenario2' => [
'attributes' => array('attribute1', 'attribute2'), 'attributes' => ['attribute1', 'attribute2'],
'atomic' => array(self::OP_INSERT, self::OP_UPDATE), 'atomic' => [self::OP_INSERT, self::OP_UPDATE],
), ],
); ];
} }
``` ```

14
extensions/composer/yii/composer/InstallHandler.php

@ -36,10 +36,10 @@ class InstallHandler
*/ */
public static function setPermissions($event) public static function setPermissions($event)
{ {
$options = array_merge(array( $options = array_merge([
self::PARAM_WRITABLE => array(), self::PARAM_WRITABLE => [],
self::PARAM_EXECUTABLE => array(), self::PARAM_EXECUTABLE => [],
), $event->getComposer()->getPackage()->getExtra()); ], $event->getComposer()->getPackage()->getExtra());
foreach ((array)$options[self::PARAM_WRITABLE] as $path) { foreach ((array)$options[self::PARAM_WRITABLE] as $path) {
echo "Setting writable: $path ..."; echo "Setting writable: $path ...";
@ -70,9 +70,9 @@ class InstallHandler
*/ */
public static function run($event) public static function run($event)
{ {
$options = array_merge(array( $options = array_merge([
self::PARAM_COMMANDS => array(), self::PARAM_COMMANDS => [],
), $event->getComposer()->getPackage()->getExtra()); ], $event->getComposer()->getPackage()->getExtra());
if (!isset($options[self::PARAM_CONFIG])) { if (!isset($options[self::PARAM_CONFIG])) {
throw new Exception('Please specify the "' . self::PARAM_CONFIG . '" parameter in composer.json.'); throw new Exception('Please specify the "' . self::PARAM_CONFIG . '" parameter in composer.json.');

18
extensions/composer/yii/composer/Installer.php

@ -63,7 +63,7 @@ class Installer extends LibraryInstaller
protected function addPackage(PackageInterface $package) protected function addPackage(PackageInterface $package)
{ {
$extension = array('name' => $package->getPrettyName()); $extension = ['name' => $package->getPrettyName()];
$root = $package->getPrettyName(); $root = $package->getPrettyName();
if ($targetDir = $package->getTargetDir()) { if ($targetDir = $package->getTargetDir()) {
@ -112,7 +112,7 @@ class Installer extends LibraryInstaller
{ {
$file = $this->vendorDir . '/yii-extensions.php'; $file = $this->vendorDir . '/yii-extensions.php';
if (!is_file($file)) { if (!is_file($file)) {
return array(); return [];
} }
$extensions = require($file); $extensions = require($file);
/** @var string $vendorDir defined in yii-extensions.php */ /** @var string $vendorDir defined in yii-extensions.php */
@ -147,10 +147,10 @@ class Installer extends LibraryInstaller
*/ */
public static function setPermissions($event) public static function setPermissions($event)
{ {
$options = array_merge(array( $options = array_merge([
self::EXTRA_WRITABLES => array(), self::EXTRA_WRITABLES => [],
self::EXTRA_EXECUTABLES => array(), self::EXTRA_EXECUTABLES => [],
), $event->getComposer()->getPackage()->getExtra()); ], $event->getComposer()->getPackage()->getExtra());
foreach ((array)$options[self::EXTRA_WRITABLES] as $path) { foreach ((array)$options[self::EXTRA_WRITABLES] as $path) {
echo "Setting writable: $path ..."; echo "Setting writable: $path ...";
@ -181,9 +181,9 @@ class Installer extends LibraryInstaller
*/ */
public static function run($event) public static function run($event)
{ {
$options = array_merge(array( $options = array_merge([
self::EXTRA_COMMANDS => array(), self::EXTRA_COMMANDS => [],
), $event->getComposer()->getPackage()->getExtra()); ], $event->getComposer()->getPackage()->getExtra());
if (!isset($options[self::EXTRA_CONFIG])) { if (!isset($options[self::EXTRA_CONFIG])) {
throw new Exception('Please specify the "' . self::EXTRA_CONFIG . '" parameter in composer.json.'); throw new Exception('Please specify the "' . self::EXTRA_CONFIG . '" parameter in composer.json.');

8
extensions/jui/README.md

@ -44,11 +44,11 @@ You can use these widgets in your view files after you have registered the corre
Example: Example:
```php ```php
echo ProgressBar::widget(array( echo ProgressBar::widget([
'clientOptions' => array( 'clientOptions' => [
'value' => 75, 'value' => 75,
), ],
)); ]);
``` ```
For further instructions refer to the yii guide. For further instructions refer to the yii guide.

62
extensions/jui/yii/jui/Accordion.php

@ -17,36 +17,24 @@ use yii\helpers\Html;
* For example: * For example:
* *
* ```php * ```php
* echo Accordion::widget(array( * echo Accordion::widget([
* 'items' => array( * 'items' => [
* array( * [
* 'header' => 'Section 1', * 'header' => 'Section 1',
* 'content' => 'Mauris mauris ante, blandit et, ultrices a, suscipit eget...', * 'content' => 'Mauris mauris ante, blandit et, ultrices a, suscipit eget...',
* ), * ],
* array( * [
* 'header' => 'Section 2', * 'header' => 'Section 2',
* 'headerOptions' => array( * 'headerOptions' => ['tag' => 'h3'],
* 'tag' => 'h3',
* ),
* 'content' => 'Sed non urna. Phasellus eu ligula. Vestibulum sit amet purus...', * 'content' => 'Sed non urna. Phasellus eu ligula. Vestibulum sit amet purus...',
* 'options' => array( * 'options' => ['tag' => 'div'],
* 'tag' => 'div', * ],
* ), * ],
* ), * 'options' => ['tag' => 'div'],
* ), * 'itemOptions' => ['tag' => 'div'],
* 'options' => array( * 'headerOptions' => ['tag' => 'h3'],
* 'tag' => 'div', * 'clientOptions' => ['collapsible' => false],
* ), * ]);
* 'itemOptions' => array(
* 'tag' => 'div',
* ),
* 'headerOptions' => array(
* 'tag' => 'h3',
* ),
* 'clientOptions' => array(
* 'collapsible' => false,
* ),
* ));
* ``` * ```
* *
* @see http://api.jqueryui.com/accordion/ * @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 * - 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: * @var array list of collapsible items. Each item can be an array of the following structure:
* *
* ~~~ * ~~~
* array( * [
* 'header' => 'Item header', * 'header' => 'Item header',
* 'content' => 'Item content', * 'content' => 'Item content',
* // the HTML attributes of the item header container tag. This will overwrite "headerOptions". * // 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". * // 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 * @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: * 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. * - 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 * @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: * 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. * - 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() protected function renderItems()
{ {
$items = array(); $items = [];
foreach ($this->items as $item) { foreach ($this->items as $item) {
if (!isset($item['header'])) { if (!isset($item['header'])) {
throw new InvalidConfigException("The 'header' option is required."); throw new InvalidConfigException("The 'header' option is required.");
@ -120,10 +108,10 @@ class Accordion extends Widget
if (!isset($item['content'])) { if (!isset($item['content'])) {
throw new InvalidConfigException("The 'content' option is required."); 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'); $headerTag = ArrayHelper::remove($headerOptions, 'tag', 'h3');
$items[] = Html::tag($headerTag, $item['header'], $headerOptions); $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'); $tag = ArrayHelper::remove($options, 'tag', 'div');
$items[] = Html::tag($tag, $item['content'], $options); $items[] = Html::tag($tag, $item['content'], $options);
} }

8
extensions/jui/yii/jui/AccordionAsset.php

@ -15,11 +15,11 @@ use yii\web\AssetBundle;
class AccordionAsset extends AssetBundle class AccordionAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.accordion.js', 'jquery.ui.accordion.js',
); ];
public $depends = array( public $depends = [
'yii\jui\CoreAsset', 'yii\jui\CoreAsset',
'yii\jui\EffectAsset', 'yii\jui\EffectAsset',
); ];
} }

22
extensions/jui/yii/jui/AutoComplete.php

@ -16,24 +16,24 @@ use yii\helpers\Html;
* For example: * For example:
* *
* ```php * ```php
* echo AutoComplete::widget(array( * echo AutoComplete::widget([
* 'model' => $model, * 'model' => $model,
* 'attribute' => 'country', * 'attribute' => 'country',
* 'clientOptions' => array( * 'clientOptions' => [
* 'source' => array('USA', 'RUS'), * 'source' => ['USA', 'RUS'],
* ), * ],
* )); * ]);
* ``` * ```
* *
* The following example will use the name property instead: * The following example will use the name property instead:
* *
* ```php * ```php
* echo AutoComplete::widget(array( * echo AutoComplete::widget([
* 'name' => 'country', * 'name' => 'country',
* 'clientOptions' => array( * 'clientOptions' => [
* 'source' => array('USA', 'RUS'), * 'source' => ['USA', 'RUS'],
* ), * ],
* )); * ]);
*``` *```
* *
* @see http://api.jqueryui.com/autocomplete/ * @see http://api.jqueryui.com/autocomplete/

8
extensions/jui/yii/jui/AutoCompleteAsset.php

@ -15,11 +15,11 @@ use yii\web\AssetBundle;
class AutoCompleteAsset extends AssetBundle class AutoCompleteAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.autocomplete.js', 'jquery.ui.autocomplete.js',
); ];
public $depends = array( public $depends = [
'yii\jui\CoreAsset', 'yii\jui\CoreAsset',
'yii\jui\MenuAsset', 'yii\jui\MenuAsset',
); ];
} }

8
extensions/jui/yii/jui/ButtonAsset.php

@ -15,10 +15,10 @@ use yii\web\AssetBundle;
class ButtonAsset extends AssetBundle class ButtonAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.button.js', 'jquery.ui.button.js',
); ];
public $depends = array( public $depends = [
'yii\jui\CoreAsset', 'yii\jui\CoreAsset',
); ];
} }

8
extensions/jui/yii/jui/CoreAsset.php

@ -15,13 +15,13 @@ use yii\web\AssetBundle;
class CoreAsset extends AssetBundle class CoreAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.core.js', 'jquery.ui.core.js',
'jquery.ui.widget.js', 'jquery.ui.widget.js',
'jquery.ui.position.js', 'jquery.ui.position.js',
'jquery.ui.mouse.js', 'jquery.ui.mouse.js',
); ];
public $depends = array( public $depends = [
'yii\web\JqueryAsset', 'yii\web\JqueryAsset',
); ];
} }

18
extensions/jui/yii/jui/DatePicker.php

@ -17,26 +17,26 @@ use yii\helpers\Json;
* For example: * For example:
* *
* ```php * ```php
* echo DatePicker::widget(array( * echo DatePicker::widget([
* 'language' => 'ru', * 'language' => 'ru',
* 'model' => $model, * 'model' => $model,
* 'attribute' => 'country', * 'attribute' => 'country',
* 'clientOptions' => array( * 'clientOptions' => [
* 'dateFormat' => 'yy-mm-dd', * 'dateFormat' => 'yy-mm-dd',
* ), * ],
* )); * ]);
* ``` * ```
* *
* The following example will use the name property instead: * The following example will use the name property instead:
* *
* ```php * ```php
* echo DatePicker::widget(array( * echo DatePicker::widget([
* 'language' => 'ru', * 'language' => 'ru',
* 'name' => 'country', * 'name' => 'country',
* 'clientOptions' => array( * 'clientOptions' => [
* 'dateFormat' => 'yy-mm-dd', * 'dateFormat' => 'yy-mm-dd',
* ), * ],
* )); * ]);
*``` *```
* *
* @see http://api.jqueryui.com/datepicker/ * @see http://api.jqueryui.com/datepicker/
@ -84,7 +84,7 @@ class DatePicker extends InputWidget
*/ */
protected function renderWidget() protected function renderWidget()
{ {
$contents = array(); $contents = [];
if ($this->inline === false) { if ($this->inline === false) {
if ($this->hasModel()) { if ($this->hasModel()) {

8
extensions/jui/yii/jui/DatePickerAsset.php

@ -15,11 +15,11 @@ use yii\web\AssetBundle;
class DatePickerAsset extends AssetBundle class DatePickerAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.datepicker.js', 'jquery.ui.datepicker.js',
); ];
public $depends = array( public $depends = [
'yii\jui\CoreAsset', 'yii\jui\CoreAsset',
'yii\jui\EffectAsset', 'yii\jui\EffectAsset',
); ];
} }

8
extensions/jui/yii/jui/DatePickerRegionalAsset.php

@ -15,10 +15,10 @@ use yii\web\AssetBundle;
class DatePickerRegionalAsset extends AssetBundle class DatePickerRegionalAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.datepicker-i18n.js', 'jquery.ui.datepicker-i18n.js',
); ];
public $depends = array( public $depends = [
'yii\jui\DatePickerAsset', 'yii\jui\DatePickerAsset',
); ];
} }

8
extensions/jui/yii/jui/Dialog.php

@ -15,11 +15,11 @@ use yii\helpers\Html;
* For example: * For example:
* *
* ```php * ```php
* Dialog::begin(array( * Dialog::begin([
* 'clientOptions' => array( * 'clientOptions' => [
* 'modal' => true, * 'modal' => true,
* ), * ],
* )); * ]);
* *
* echo 'Dialog contents here...'; * echo 'Dialog contents here...';
* *

8
extensions/jui/yii/jui/DialogAsset.php

@ -15,13 +15,13 @@ use yii\web\AssetBundle;
class DialogAsset extends AssetBundle class DialogAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.dialog.js', 'jquery.ui.dialog.js',
); ];
public $depends = array( public $depends = [
'yii\jui\CoreAsset', 'yii\jui\CoreAsset',
'yii\jui\ButtonAsset', 'yii\jui\ButtonAsset',
'yii\jui\DraggableAsset', 'yii\jui\DraggableAsset',
'yii\jui\ResizableAsset', 'yii\jui\ResizableAsset',
); ];
} }

8
extensions/jui/yii/jui/Draggable.php

@ -15,11 +15,9 @@ use yii\helpers\Html;
* For example: * For example:
* *
* ```php * ```php
* Draggable::begin(array( * Draggable::begin([
* 'clientOptions' => array( * 'clientOptions' => ['grid' => [50, 20]],
* 'grid' => array(50, 20), * ]);
* ),
* ));
* *
* echo 'Draggable contents here...'; * echo 'Draggable contents here...';
* *

8
extensions/jui/yii/jui/DraggableAsset.php

@ -15,10 +15,10 @@ use yii\web\AssetBundle;
class DraggableAsset extends AssetBundle class DraggableAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.draggable.js', 'jquery.ui.draggable.js',
); ];
public $depends = array( public $depends = [
'yii\jui\CoreAsset', 'yii\jui\CoreAsset',
); ];
} }

8
extensions/jui/yii/jui/Droppable.php

@ -15,11 +15,9 @@ use yii\helpers\Html;
* For example: * For example:
* *
* ```php * ```php
* Droppable::begin(array( * Droppable::begin([
* 'clientOptions' => array( * 'clientOptions' => ['accept' => '.special'],
* 'accept' => '.special', * ]);
* ),
* ));
* *
* echo 'Droppable body here...'; * echo 'Droppable body here...';
* *

8
extensions/jui/yii/jui/DroppableAsset.php

@ -15,10 +15,10 @@ use yii\web\AssetBundle;
class DroppableAsset extends AssetBundle class DroppableAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.droppable.js', 'jquery.ui.droppable.js',
); ];
public $depends = array( public $depends = [
'yii\jui\DraggableAsset', 'yii\jui\DraggableAsset',
); ];
} }

8
extensions/jui/yii/jui/EffectAsset.php

@ -15,10 +15,10 @@ use yii\web\AssetBundle;
class EffectAsset extends AssetBundle class EffectAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.effect-all.js', 'jquery.ui.effect-all.js',
); ];
public $depends = array( public $depends = [
'yii\web\JqueryAsset', 'yii\web\JqueryAsset',
); ];
} }

6
extensions/jui/yii/jui/Menu.php

@ -25,14 +25,14 @@ class Menu extends \yii\widgets\Menu
* For example, [this page](http://api.jqueryui.com/accordion/) shows * For example, [this page](http://api.jqueryui.com/accordion/) shows
* how to use the "Accordion" widget and the supported options (e.g. "header"). * 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. * @var array the event handlers for the underlying jQuery UI widget.
* Please refer to the corresponding jQuery UI widget Web page for possible events. * Please refer to the corresponding jQuery UI widget Web page for possible events.
* For example, [this page](http://api.jqueryui.com/accordion/) shows * For example, [this page](http://api.jqueryui.com/accordion/) shows
* how to use the "Accordion" widget and the supported events (e.g. "create"). * 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)) { if (!empty($this->clientEvents)) {
$js = array(); $js = [];
foreach ($this->clientEvents as $event => $handler) { foreach ($this->clientEvents as $event => $handler) {
$js[] = "jQuery('#$id').on('menu$event', $handler);"; $js[] = "jQuery('#$id').on('menu$event', $handler);";
} }

8
extensions/jui/yii/jui/MenuAsset.php

@ -15,10 +15,10 @@ use yii\web\AssetBundle;
class MenuAsset extends AssetBundle class MenuAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.menu.js', 'jquery.ui.menu.js',
); ];
public $depends = array( public $depends = [
'yii\jui\CoreAsset', 'yii\jui\CoreAsset',
); ];
} }

16
extensions/jui/yii/jui/ProgressBar.php

@ -15,22 +15,20 @@ use yii\helpers\Html;
* For example: * For example:
* *
* ```php * ```php
* echo ProgressBar::widget(array( * echo ProgressBar::widget([
* 'clientOptions' => array( * 'clientOptions' => [
* 'value' => 75, * 'value' => 75,
* ), * ],
* )); * ]);
* ``` * ```
* *
* The following example will show the content enclosed between the [[begin()]] * The following example will show the content enclosed between the [[begin()]]
* and [[end()]] calls within the widget container: * and [[end()]] calls within the widget container:
* *
* ~~~php * ~~~php
* ProgressBar::widget(array( * ProgressBar::widget([
* 'clientOptions' => array( * 'clientOptions' => ['value' => 75],
* 'value' => 75, * ]);
* ),
* ));
* *
* echo '<div class="progress-label">Loading...</div>'; * echo '<div class="progress-label">Loading...</div>';
* *

8
extensions/jui/yii/jui/ProgressBarAsset.php

@ -15,10 +15,10 @@ use yii\web\AssetBundle;
class ProgressBarAsset extends AssetBundle class ProgressBarAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.progressbar.js', 'jquery.ui.progressbar.js',
); ];
public $depends = array( public $depends = [
'yii\jui\CoreAsset', 'yii\jui\CoreAsset',
); ];
} }

10
extensions/jui/yii/jui/Resizable.php

@ -15,11 +15,11 @@ use yii\helpers\Html;
* For example: * For example:
* *
* ```php * ```php
* Resizable::begin(array( * Resizable::begin([
* 'clientOptions' => array( * 'clientOptions' => [
* 'grid' => array(20, 10), * 'grid' => [20, 10],
* ), * ],
* )); * ]);
* *
* echo 'Resizable contents here...'; * echo 'Resizable contents here...';
* *

8
extensions/jui/yii/jui/ResizableAsset.php

@ -15,10 +15,10 @@ use yii\web\AssetBundle;
class ResizableAsset extends AssetBundle class ResizableAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.resizable.js', 'jquery.ui.resizable.js',
); ];
public $depends = array( public $depends = [
'yii\jui\CoreAsset', 'yii\jui\CoreAsset',
); ];
} }

46
extensions/jui/yii/jui/Selectable.php

@ -17,29 +17,29 @@ use yii\helpers\Html;
* For example: * For example:
* *
* ```php * ```php
* echo Selectable::widget(array( * echo Selectable::widget([
* 'items' => array( * 'items' => [
* 'Item 1', * 'Item 1',
* array( * [
* 'content' => 'Item2', * 'content' => 'Item2',
* ), * ],
* array( * [
* 'content' => 'Item3', * 'content' => 'Item3',
* 'options' => array( * 'options' => [
* 'tag' => 'li', * 'tag' => 'li',
* ), * ],
* ), * ],
* ), * ),
* 'options' => array( * 'options' => [
* 'tag' => 'ul', * 'tag' => 'ul',
* ), * ],
* 'itemOptions' => array( * 'itemOptions' => [
* 'tag' => 'li', * 'tag' => 'li',
* ), * ],
* 'clientOptions' => array( * 'clientOptions' => [
* 'tolerance' => 'fit', * 'tolerance' => 'fit',
* ), * ],
* )); * ]);
* ``` * ```
* *
* @see http://api.jqueryui.com/selectable/ * @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 * - 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 * @var array list of selectable items. Each item can be a string representing the item content
* or an array of the following structure: * or an array of the following structure:
* *
* ~~~ * ~~~
* array( * [
* 'content' => 'item content', * 'content' => 'item content',
* // the HTML attributes of the item container tag. This will overwrite "itemOptions". * // 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 * @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: * 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. * - 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() public function renderItems()
{ {
$items = array(); $items = [];
foreach ($this->items as $item) { foreach ($this->items as $item) {
$options = $this->itemOptions; $options = $this->itemOptions;
$tag = ArrayHelper::remove($options, 'tag', 'li'); $tag = ArrayHelper::remove($options, 'tag', 'li');
@ -104,7 +104,7 @@ class Selectable extends Widget
if (!isset($item['content'])) { if (!isset($item['content'])) {
throw new InvalidConfigException("The 'content' option is required."); 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); $tag = ArrayHelper::remove($options, 'tag', $tag);
$items[] = Html::tag($tag, $item['content'], $options); $items[] = Html::tag($tag, $item['content'], $options);
} else { } else {

8
extensions/jui/yii/jui/SelectableAsset.php

@ -15,10 +15,10 @@ use yii\web\AssetBundle;
class SelectableAsset extends AssetBundle class SelectableAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.selectable.js', 'jquery.ui.selectable.js',
); ];
public $depends = array( public $depends = [
'yii\jui\CoreAsset', 'yii\jui\CoreAsset',
); ];
} }

16
extensions/jui/yii/jui/Slider.php

@ -16,26 +16,26 @@ use yii\helpers\Html;
* For example: * For example:
* *
* ```php * ```php
* echo Slider::widget(array( * echo Slider::widget([
* 'model' => $model, * 'model' => $model,
* 'attribute' => 'amount', * 'attribute' => 'amount',
* 'clientOptions' => array( * 'clientOptions' => [
* 'min' => 1, * 'min' => 1,
* 'max' => 10, * 'max' => 10,
* ), * ],
* )); * ]);
* ``` * ```
* *
* The following example will use the name property instead: * The following example will use the name property instead:
* *
* ```php * ```php
* echo Slider::widget(array( * echo Slider::widget([
* 'name' => 'amount', * 'name' => 'amount',
* 'clientOptions' => array( * 'clientOptions' => [
* 'min' => 1, * 'min' => 1,
* 'max' => 10, * 'max' => 10,
* ), * ],
* )); * ]);
*``` *```
* *
* @see http://api.jqueryui.com/slider/ * @see http://api.jqueryui.com/slider/

8
extensions/jui/yii/jui/SliderAsset.php

@ -15,10 +15,10 @@ use yii\web\AssetBundle;
class SliderAsset extends AssetBundle class SliderAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.slider.js', 'jquery.ui.slider.js',
); ];
public $depends = array( public $depends = [
'yii\jui\CoreAsset', 'yii\jui\CoreAsset',
); ];
} }

46
extensions/jui/yii/jui/Sortable.php

@ -17,28 +17,18 @@ use yii\helpers\Html;
* For example: * For example:
* *
* ```php * ```php
* echo Sortable::widget(array( * echo Sortable::widget([
* 'items' => array( * 'items' => [
* 'Item 1', * 'Item 1',
* array( * ['content' => 'Item2'],
* 'content' => 'Item2', * [
* ),
* array(
* 'content' => 'Item3', * 'content' => 'Item3',
* 'options' => array( * 'options' => ['tag' => 'li'],
* 'tag' => 'li', * ],
* ), * ],
* ), * 'options' => ['tag' => 'ul'],
* ), * 'itemOptions' => ['tag' => 'li'],
* 'options' => array( * 'clientOptions' => ['cursor' => 'move'],
* 'tag' => 'ul',
* ),
* 'itemOptions' => array(
* 'tag' => 'li',
* ),
* 'clientOptions' => array(
* '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 * - 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 * @var array list of sortable items. Each item can be a string representing the item content
* or an array of the following structure: * or an array of the following structure:
* *
* ~~~ * ~~~
* array( * [
* 'content' => 'item content', * 'content' => 'item content',
* // the HTML attributes of the item container tag. This will overwrite "itemOptions". * // 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 * @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: * 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. * - 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() public function renderItems()
{ {
$items = array(); $items = [];
foreach ($this->items as $item) { foreach ($this->items as $item) {
$options = $this->itemOptions; $options = $this->itemOptions;
$tag = ArrayHelper::remove($options, 'tag', 'li'); $tag = ArrayHelper::remove($options, 'tag', 'li');
@ -104,7 +94,7 @@ class Sortable extends Widget
if (!isset($item['content'])) { if (!isset($item['content'])) {
throw new InvalidConfigException("The 'content' option is required."); 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); $tag = ArrayHelper::remove($options, 'tag', $tag);
$items[] = Html::tag($tag, $item['content'], $options); $items[] = Html::tag($tag, $item['content'], $options);
} else { } else {

8
extensions/jui/yii/jui/SortableAsset.php

@ -15,10 +15,10 @@ use yii\web\AssetBundle;
class SortableAsset extends AssetBundle class SortableAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.sortable.js', 'jquery.ui.sortable.js',
); ];
public $depends = array( public $depends = [
'yii\jui\CoreAsset', 'yii\jui\CoreAsset',
); ];
} }

16
extensions/jui/yii/jui/Spinner.php

@ -16,24 +16,20 @@ use yii\helpers\Html;
* For example: * For example:
* *
* ```php * ```php
* echo Spinner::widget(array( * echo Spinner::widget([
* 'model' => $model, * 'model' => $model,
* 'attribute' => 'country', * 'attribute' => 'country',
* 'clientOptions' => array( * 'clientOptions' => ['step' => 2],
* 'step' => 2, * ]);
* ),
* ));
* ``` * ```
* *
* The following example will use the name property instead: * The following example will use the name property instead:
* *
* ```php * ```php
* echo Spinner::widget(array( * echo Spinner::widget([
* 'name' => 'country', * 'name' => 'country',
* 'clientOptions' => array( * 'clientOptions' => ['step' => 2],
* 'step' => 2, * ]);
* ),
* ));
*``` *```
* *
* @see http://api.jqueryui.com/spinner/ * @see http://api.jqueryui.com/spinner/

8
extensions/jui/yii/jui/SpinnerAsset.php

@ -15,11 +15,11 @@ use yii\web\AssetBundle;
class SpinnerAsset extends AssetBundle class SpinnerAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.spinner.js', 'jquery.ui.spinner.js',
); ];
public $depends = array( public $depends = [
'yii\jui\CoreAsset', 'yii\jui\CoreAsset',
'yii\jui\ButtonAsset', 'yii\jui\ButtonAsset',
); ];
} }

72
extensions/jui/yii/jui/Tabs.php

@ -17,47 +17,33 @@ use yii\helpers\Html;
* For example: * For example:
* *
* ```php * ```php
* echo Tabs::widget(array( * echo Tabs::widget([
* 'items' => array( * 'items' => [
* array( * [
* 'label' => 'Tab one', * 'label' => 'Tab one',
* 'content' => 'Mauris mauris ante, blandit et, ultrices a, suscipit eget...', * 'content' => 'Mauris mauris ante, blandit et, ultrices a, suscipit eget...',
* ), * ],
* array( * [
* 'label' => 'Tab two', * 'label' => 'Tab two',
* 'content' => 'Sed non urna. Phasellus eu ligula. Vestibulum sit amet purus...', * 'content' => 'Sed non urna. Phasellus eu ligula. Vestibulum sit amet purus...',
* 'options' => array( * 'options' => ['tag' => 'div'],
* 'tag' => 'div', * 'headerOptions' => ['class' => 'my-class'],
* ), * ],
* 'headerOptions' => array( * [
* 'class' => 'my-class',
* ),
* ),
* array(
* 'label' => 'Tab with custom id', * 'label' => 'Tab with custom id',
* 'content' => 'Morbi tincidunt, dui sit amet facilisis feugiat...', * 'content' => 'Morbi tincidunt, dui sit amet facilisis feugiat...',
* 'options' => array( * 'options' => ['id' => 'my-tab'],
* 'id' => 'my-tab', * ],
* ), * [
* ),
* array(
* 'label' => 'Ajax tab', * 'label' => 'Ajax tab',
* 'url' => array('ajax/content'), * 'url' => ['ajax/content'],
* ), * ],
* ), * ),
* 'options' => array( * 'options' => ['tag' => 'div'],
* 'tag' => 'div', * 'itemOptions' => ['tag' => 'div'],
* ), * 'headerOptions' => ['class' => 'my-class'],
* 'itemOptions' => array( * 'clientOptions' => ['collapsible' => false],
* 'tag' => 'div', * ]);
* ),
* 'headerOptions' => array(
* 'class' => 'my-class',
* ),
* 'clientOptions' => array(
* 'collapsible' => false,
* ),
* ));
* ``` * ```
* *
* @see http://api.jqueryui.com/tabs/ * @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 * - 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: * @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. * - options: array, optional, the HTML attributes of the header.
* - headerOptions: array, optional, the HTML attributes for the header container tag. * - 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 * @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: * 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. * - 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 * @var array list of HTML attributes for the header container tags. This will be overwritten
* by the "headerOptions" set in individual [[items]]. * by the "headerOptions" set in individual [[items]].
*/ */
public $headerOptions = array(); public $headerOptions = [];
/** /**
* @var string the default header template to render the link. * @var string the default header template to render the link.
*/ */
@ -127,8 +113,8 @@ class Tabs extends Widget
*/ */
protected function renderItems() protected function renderItems()
{ {
$headers = array(); $headers = [];
$items = array(); $items = [];
foreach ($this->items as $n => $item) { foreach ($this->items as $n => $item) {
if (!isset($item['label'])) { if (!isset($item['label'])) {
throw new InvalidConfigException("The 'label' option is required."); throw new InvalidConfigException("The 'label' option is required.");
@ -139,7 +125,7 @@ class Tabs extends Widget
if (!isset($item['content'])) { if (!isset($item['content'])) {
throw new InvalidConfigException("The 'content' or 'url' option is required."); 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'); $tag = ArrayHelper::remove($options, 'tag', 'div');
if (!isset($options['id'])) { if (!isset($options['id'])) {
$options['id'] = $this->options['id'] . '-tab' . $n; $options['id'] = $this->options['id'] . '-tab' . $n;
@ -147,12 +133,12 @@ class Tabs extends Widget
$url = '#' . $options['id']; $url = '#' . $options['id'];
$items[] = Html::tag($tag, $item['content'], $options); $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); $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'], '{label}' => $this->encodeLabels ? Html::encode($item['label']) : $item['label'],
'{url}' => $url, '{url}' => $url,
)), $headerOptions); ]), $headerOptions);
} }
return Html::tag('ul', implode("\n", $headers)) . "\n" . implode("\n", $items); return Html::tag('ul', implode("\n", $headers)) . "\n" . implode("\n", $items);
} }

8
extensions/jui/yii/jui/TabsAsset.php

@ -15,11 +15,11 @@ use yii\web\AssetBundle;
class TabsAsset extends AssetBundle class TabsAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.tabs.js', 'jquery.ui.tabs.js',
); ];
public $depends = array( public $depends = [
'yii\jui\CoreAsset', 'yii\jui\CoreAsset',
'yii\jui\EffectAsset', 'yii\jui\EffectAsset',
); ];
} }

4
extensions/jui/yii/jui/ThemeAsset.php

@ -15,7 +15,7 @@ use yii\web\AssetBundle;
class ThemeAsset extends AssetBundle class ThemeAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $css = array( public $css = [
'theme/jquery.ui.css', 'theme/jquery.ui.css',
); ];
} }

8
extensions/jui/yii/jui/TooltipAsset.php

@ -15,11 +15,11 @@ use yii\web\AssetBundle;
class TooltipAsset extends AssetBundle class TooltipAsset extends AssetBundle
{ {
public $sourcePath = '@yii/jui/assets'; public $sourcePath = '@yii/jui/assets';
public $js = array( public $js = [
'jquery.ui.tooltip.js', 'jquery.ui.tooltip.js',
); ];
public $depends = array( public $depends = [
'yii\jui\CoreAsset', 'yii\jui\CoreAsset',
'yii\jui\EffectAsset', 'yii\jui\EffectAsset',
); ];
} }

8
extensions/jui/yii/jui/Widget.php

@ -26,21 +26,21 @@ class Widget extends \yii\base\Widget
/** /**
* @var array the HTML attributes for the widget container tag. * @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. * @var array the options for the underlying jQuery UI widget.
* Please refer to the corresponding jQuery UI widget Web page for possible options. * Please refer to the corresponding jQuery UI widget Web page for possible options.
* For example, [this page](http://api.jqueryui.com/accordion/) shows * For example, [this page](http://api.jqueryui.com/accordion/) shows
* how to use the "Accordion" widget and the supported options (e.g. "header"). * 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. * @var array the event handlers for the underlying jQuery UI widget.
* Please refer to the corresponding jQuery UI widget Web page for possible events. * Please refer to the corresponding jQuery UI widget Web page for possible events.
* For example, [this page](http://api.jqueryui.com/accordion/) shows * For example, [this page](http://api.jqueryui.com/accordion/) shows
* how to use the "Accordion" widget and the supported events (e.g. "create"). * 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)) { if (!empty($this->clientEvents)) {
$js = array(); $js = [];
foreach ($this->clientEvents as $event => $handler) { foreach ($this->clientEvents as $event => $handler) {
$js[] = "jQuery('#$id').on('$name$event', $handler);"; $js[] = "jQuery('#$id').on('$name$event', $handler);";
} }

4
extensions/jui/yii/jui/assets.php

@ -1,6 +1,6 @@
<?php <?php
return array( return [
yii\jui\CoreAsset::className(), yii\jui\CoreAsset::className(),
yii\jui\EffectAsset::className(), yii\jui\EffectAsset::className(),
yii\jui\AccordionAsset::className(), yii\jui\AccordionAsset::className(),
@ -20,4 +20,4 @@ return array(
yii\jui\DraggableAsset::className(), yii\jui\DraggableAsset::className(),
yii\jui\DroppableAsset::className(), yii\jui\DroppableAsset::className(),
yii\jui\MenuAsset::className(), yii\jui\MenuAsset::className(),
); ];

2
extensions/mutex/yii/mutex/FileMutex.php

@ -38,7 +38,7 @@ class FileMutex extends Mutex
/** /**
* @var resource[] stores all opened lock files. Keys are lock names and values are file handles. * @var resource[] stores all opened lock files. Keys are lock names and values are file handles.
*/ */
private $_files = array(); private $_files = [];
/** /**

2
extensions/mutex/yii/mutex/Mutex.php

@ -25,7 +25,7 @@ abstract class Mutex extends Component
/** /**
* @var string[] names of the locks acquired in the current PHP process. * @var string[] names of the locks acquired in the current PHP process.
*/ */
private $_locks = array(); private $_locks = [];
/** /**

4
extensions/mutex/yii/mutex/MysqlMutex.php

@ -38,7 +38,7 @@ class MysqlMutex extends Mutex
protected function acquireLock($name, $timeout = 0) protected function acquireLock($name, $timeout = 0)
{ {
return (boolean)$this->db 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(); ->queryScalar();
} }
@ -51,7 +51,7 @@ class MysqlMutex extends Mutex
protected function releaseLock($name) protected function releaseLock($name)
{ {
return (boolean)$this->db return (boolean)$this->db
->createCommand('SELECT RELEASE_LOCK(:name)', array(':name' => $name)) ->createCommand('SELECT RELEASE_LOCK(:name)', [':name' => $name])
->queryScalar(); ->queryScalar();
} }
} }

20
extensions/smarty/README.md

@ -45,20 +45,20 @@ Example:
```php ```php
<?php <?php
// config.php // config.php
return array( return [
//.... //....
'components' => array( 'components' => [
'view' => array( 'view' => [
'class' => 'yii\base\View', 'class' => 'yii\base\View',
'renderers' => array( 'renderers' => [
'tpl' => array( 'tpl' => [
'class' => 'yii\smarty\ViewRenderer', 'class' => 'yii\smarty\ViewRenderer',
//'cachePath' => '@runtime/Smarty/cache', //'cachePath' => '@runtime/Smarty/cache',
), ],
), ],
), ],
), ],
); ];
``` ```
For further instructions refer to the related section in the yii guide. For further instructions refer to the related section in the yii guide.

2
extensions/smarty/yii/smarty/ViewRenderer.php

@ -44,7 +44,7 @@ class ViewRenderer extends BaseViewRenderer
$this->smarty->setCompileDir(Yii::getAlias($this->compilePath)); $this->smarty->setCompileDir(Yii::getAlias($this->compilePath));
$this->smarty->setCacheDir(Yii::getAlias($this->cachePath)); $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']);
} }
/** /**

22
extensions/twig/README.md

@ -44,21 +44,21 @@ Example:
```php ```php
<?php <?php
// config.php // config.php
return array( return [
//.... //....
'components' => array( 'components' => [
'view' => array( 'view' => [
'class' => 'yii\base\View', 'class' => 'yii\base\View',
'renderers' => array( 'renderers' => [
'twig' => array( 'twig' => [
'class' => 'yii\twig\ViewRenderer', 'class' => 'yii\twig\ViewRenderer',
//'cachePath' => '@runtime/Twig/cache', //'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. For further instructions refer to the related section in the yii guide.

10
extensions/twig/yii/twig/ViewRenderer.php

@ -31,7 +31,7 @@ class ViewRenderer extends BaseViewRenderer
* @var array Twig options * @var array Twig options
* @see http://twig.sensiolabs.org/doc/api.html#environment-options * @see http://twig.sensiolabs.org/doc/api.html#environment-options
*/ */
public $options = array(); public $options = [];
/** /**
* @var \Twig_Environment * @var \Twig_Environment
@ -42,12 +42,12 @@ class ViewRenderer extends BaseViewRenderer
{ {
$loader = new \Twig_Loader_String(); $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), 'cache' => Yii::getAlias($this->cachePath),
), $this->options)); ], $this->options));
$this->twig->addFunction('path', new \Twig_Function_Function(function ($path, $args = array()) { $this->twig->addFunction('path', new \Twig_Function_Function(function ($path, $args = []) {
return Html::url(array_merge(array($path), $args)); return Html::url(array_merge([$path], $args));
})); }));
$this->twig->addGlobal('app', \Yii::$app); $this->twig->addGlobal('app', \Yii::$app);

38
framework/yii/BaseYii.php

@ -67,7 +67,7 @@ class BaseYii
* @see import * @see import
* @see autoload * @see autoload
*/ */
public static $classMap = array(); public static $classMap = [];
/** /**
* @var \yii\console\Application|\yii\web\Application the application instance * @var \yii\console\Application|\yii\web\Application the application instance
*/ */
@ -77,28 +77,28 @@ class BaseYii
* @see getAlias * @see getAlias
* @see setAlias * @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]]. * @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 * 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, * name-value pairs for initializing the created class instances. For example,
* *
* ~~~ * ~~~
* array( * [
* 'Bar' => array( * 'Bar' => [
* 'prop1' => 'value1', * 'prop1' => 'value1',
* 'prop2' => 'value2', * 'prop2' => 'value2',
* ), * ],
* 'mycompany\foo\Car' => array( * 'mycompany\foo\Car' => [
* 'prop1' => 'value1', * 'prop1' => 'value1',
* 'prop2' => 'value2', * 'prop2' => 'value2',
* ), * ],
* ) * ]
* ~~~ * ~~~
* *
* @see createObject * @see createObject
*/ */
public static $objectConfig = array(); public static $objectConfig = [];
/** /**
@ -127,7 +127,7 @@ class BaseYii
{ {
foreach ($namespaces as $name => $path) { foreach ($namespaces as $name => $path) {
if ($name !== '') { if ($name !== '') {
$name = trim(strtr($name, array('\\' => '/', '_' => '/')), '/'); $name = trim(strtr($name, ['\\' => '/', '_' => '/']), '/');
if (is_array($path)) { if (is_array($path)) {
$path = reset($path); $path = reset($path);
} }
@ -262,16 +262,16 @@ class BaseYii
if ($pos === false) { if ($pos === false) {
self::$aliases[$root] = $path; self::$aliases[$root] = $path;
} else { } else {
self::$aliases[$root] = array($alias => $path); self::$aliases[$root] = [$alias => $path];
} }
} elseif (is_string(self::$aliases[$root])) { } elseif (is_string(self::$aliases[$root])) {
if ($pos === false) { if ($pos === false) {
self::$aliases[$root] = $path; self::$aliases[$root] = $path;
} else { } else {
self::$aliases[$root] = array( self::$aliases[$root] = [
$alias => $path, $alias => $path,
$root => self::$aliases[$root], $root => self::$aliases[$root],
); ];
} }
} else { } else {
self::$aliases[$root][$alias] = $path; self::$aliases[$root][$alias] = $path;
@ -360,17 +360,17 @@ class BaseYii
* *
* ~~~ * ~~~
* $object = \Yii::createObject('@app/components/GoogleMap'); * $object = \Yii::createObject('@app/components/GoogleMap');
* $object = \Yii::createObject(array( * $object = \Yii::createObject([
* 'class' => '\app\components\GoogleMap', * 'class' => '\app\components\GoogleMap',
* 'apiKey' => 'xyz', * 'apiKey' => 'xyz',
* )); * ]);
* ~~~ * ~~~
* *
* This method can be used to create any object as long as the object's constructor is * This method can be used to create any object as long as the object's constructor is
* defined like the following: * defined like the following:
* *
* ~~~ * ~~~
* public function __construct(..., $config = array()) { * public function __construct(..., $config = []) {
* } * }
* ~~~ * ~~~
* *
@ -384,11 +384,11 @@ class BaseYii
*/ */
public static function createObject($config) public static function createObject($config)
{ {
static $reflections = array(); static $reflections = [];
if (is_string($config)) { if (is_string($config)) {
$class = $config; $class = $config;
$config = array(); $config = [];
} elseif (isset($config['class'])) { } elseif (isset($config['class'])) {
$class = $config['class']; $class = $config['class'];
unset($config['class']); unset($config['class']);
@ -538,7 +538,7 @@ class BaseYii
* [[\yii\base\Application::language|application language]] will be used. * [[\yii\base\Application::language|application language]] will be used.
* @return string the translated message. * @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) { if (self::$app !== null) {
return self::$app->getI18n()->translate($category, $message, $params, $language ?: self::$app->language); return self::$app->getI18n()->translate($category, $message, $params, $language ?: self::$app->language);

2
framework/yii/Yii.php

@ -22,5 +22,5 @@ class Yii extends \yii\BaseYii
{ {
} }
spl_autoload_register(array('Yii', 'autoload'), true, true); spl_autoload_register(['Yii', 'autoload'], true, true);
Yii::$classMap = include(__DIR__ . '/classes.php'); Yii::$classMap = include(__DIR__ . '/classes.php');

4
framework/yii/assets.php

@ -1,6 +1,6 @@
<?php <?php
return array( return [
yii\web\YiiAsset::className(), yii\web\YiiAsset::className(),
yii\web\JqueryAsset::className(), yii\web\JqueryAsset::className(),
yii\validators\PunycodeAsset::className(), yii\validators\PunycodeAsset::className(),
@ -8,4 +8,4 @@ return array(
yii\widgets\ActiveFormAsset::className(), yii\widgets\ActiveFormAsset::className(),
yii\captcha\CaptchaAsset::className(), yii\captcha\CaptchaAsset::className(),
yii\widgets\MaskedInputAsset::className(), yii\widgets\MaskedInputAsset::className(),
); ];

6
framework/yii/base/Action.php

@ -25,7 +25,7 @@ use Yii;
* public function run($id, $type = 'book') { ... } * 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. * 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 * @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 Controller $controller the controller that owns this action
* @param array $config name-value pairs that will be used to initialize the object properties * @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->id = $id;
$this->controller = $controller; $this->controller = $controller;
@ -84,6 +84,6 @@ class Action extends Component
if (Yii::$app->requestedParams === null) { if (Yii::$app->requestedParams === null) {
Yii::$app->requestedParams = $args; Yii::$app->requestedParams = $args;
} }
return call_user_func_array(array($this, 'run'), $args); return call_user_func_array([$this, 'run'], $args);
} }
} }

2
framework/yii/base/ActionEvent.php

@ -37,7 +37,7 @@ class ActionEvent extends Event
* @param Action $action the action associated with this action 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 * @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; $this->action = $action;
parent::__construct($config); parent::__construct($config);

6
framework/yii/base/ActionFilter.php

@ -24,7 +24,7 @@ class ActionFilter extends Behavior
* @var array list of action IDs that this filter should not apply to. * @var array list of action IDs that this filter should not apply to.
* @see only * @see only
*/ */
public $except = array(); public $except = [];
/** /**
* Declares event handlers for the [[owner]]'s events. * Declares event handlers for the [[owner]]'s events.
@ -32,10 +32,10 @@ class ActionFilter extends Behavior
*/ */
public function events() public function events()
{ {
return array( return [
Controller::EVENT_BEFORE_ACTION => 'beforeFilter', Controller::EVENT_BEFORE_ACTION => 'beforeFilter',
Controller::EVENT_AFTER_ACTION => 'afterFilter', Controller::EVENT_AFTER_ACTION => 'afterFilter',
); ];
} }
/** /**

38
framework/yii/base/Application.php

@ -80,7 +80,7 @@ abstract class Application extends Module
/** /**
* @var array IDs of the components that need to be loaded when the application starts. * @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 * @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]]. * Note that the configuration must contain both [[id]] and [[basePath]].
* @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing. * @throws InvalidConfigException if either [[id]] or [[basePath]] configuration is missing.
*/ */
public function __construct($config = array()) public function __construct($config = [])
{ {
Yii::$app = $this; Yii::$app = $this;
if (!isset($config['id'])) { if (!isset($config['id'])) {
@ -188,12 +188,12 @@ abstract class Application extends Module
{ {
if (YII_ENABLE_ERROR_HANDLER) { if (YII_ENABLE_ERROR_HANDLER) {
ini_set('display_errors', 0); ini_set('display_errors', 0);
set_exception_handler(array($this, 'handleException')); set_exception_handler([$this, 'handleException']);
set_error_handler(array($this, 'handleError'), error_reporting()); set_error_handler([$this, 'handleError'], error_reporting());
if ($this->memoryReserveSize > 0) { if ($this->memoryReserveSize > 0) {
$this->_memoryReserve = str_repeat('x', $this->memoryReserveSize); $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() public function registerCoreComponents()
{ {
$this->setComponents(array( $this->setComponents([
'log' => array( 'log' => ['class' => 'yii\log\Logger'],
'class' => 'yii\log\Logger', 'errorHandler' => ['class' => 'yii\base\ErrorHandler'],
), 'formatter' => ['class' => 'yii\base\Formatter'],
'errorHandler' => array( 'i18n' => ['class' => 'yii\i18n\I18N'],
'class' => 'yii\base\ErrorHandler', 'urlManager' => ['class' => 'yii\web\UrlManager'],
), 'view' => ['class' => 'yii\base\View'],
'formatter' => array( ]);
'class' => 'yii\base\Formatter',
),
'i18n' => array(
'class' => 'yii\i18n\I18N',
),
'urlManager' => array(
'class' => 'yii\web\UrlManager',
),
'view' => array(
'class' => 'yii\base\View',
),
));
} }
/** /**

16
framework/yii/base/Behavior.php

@ -37,25 +37,25 @@ class Behavior extends \yii\base\Object
* *
* The callbacks can be any of the followings: * The callbacks can be any of the followings:
* *
* - method in this behavior: `'handleClick'`, equivalent to `array($this, 'handleClick')` * - method in this behavior: `'handleClick'`, equivalent to `[$this, 'handleClick']`
* - object method: `array($object, 'handleClick')` * - object method: `[$object, 'handleClick']`
* - static method: `array('Page', 'handleClick')` * - static method: `['Page', 'handleClick']`
* - anonymous function: `function($event) { ... }` * - anonymous function: `function($event) { ... }`
* *
* The following is an example: * The following is an example:
* *
* ~~~ * ~~~
* array( * [
* 'beforeValidate' => 'myBeforeValidate', * 'beforeValidate' => 'myBeforeValidate',
* 'afterValidate' => 'myAfterValidate', * 'afterValidate' => 'myAfterValidate',
* ) * ]
* ~~~ * ~~~
* *
* @return array events (array keys) and the corresponding event handler methods (array values). * @return array events (array keys) and the corresponding event handler methods (array values).
*/ */
public function events() public function events()
{ {
return array(); return [];
} }
/** /**
@ -69,7 +69,7 @@ class Behavior extends \yii\base\Object
{ {
$this->owner = $owner; $this->owner = $owner;
foreach ($this->events() as $event => $handler) { 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) { if ($this->owner) {
foreach ($this->events() as $event => $handler) { 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; $this->owner = null;
} }

22
framework/yii/base/Component.php

@ -195,7 +195,7 @@ class Component extends Object
$this->ensureBehaviors(); $this->ensureBehaviors();
foreach ($this->_behaviors as $object) { foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) { 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: * the behavior class or an array of the following structure:
* *
* ~~~ * ~~~
* 'behaviorName' => array( * 'behaviorName' => [
* 'class' => 'BehaviorClass', * 'class' => 'BehaviorClass',
* 'property1' => 'value1', * 'property1' => 'value1',
* 'property2' => 'value2', * 'property2' => 'value2',
* ) * ]
* ~~~ * ~~~
* *
* Note that a behavior class must extend from [[Behavior]]. Behavior names can be strings * 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() public function behaviors()
{ {
return array(); return [];
} }
/** /**
@ -369,9 +369,9 @@ class Component extends Object
* *
* ~~~ * ~~~
* function ($event) { ... } // anonymous function * function ($event) { ... } // anonymous function
* array($object, 'handleClick') // $object->handleClick() * [$object, 'handleClick'] // $object->handleClick()
* array('Page', 'handleClick') // Page::handleClick() * ['Page', 'handleClick'] // Page::handleClick()
* 'handleClick' // global function handleClick() * 'handleClick' // global function handleClick()
* ~~~ * ~~~
* *
* An event handler must be defined with the following signature, * 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) public function on($name, $handler, $data = null)
{ {
$this->ensureBehaviors(); $this->ensureBehaviors();
$this->_events[$name][] = array($handler, $data); $this->_events[$name][] = [$handler, $data];
} }
/** /**
@ -408,7 +408,7 @@ class Component extends Object
$this->ensureBehaviors(); $this->ensureBehaviors();
if (isset($this->_events[$name])) { if (isset($this->_events[$name])) {
if ($handler === null) { if ($handler === null) {
$this->_events[$name] = array(); $this->_events[$name] = [];
} else { } else {
$removed = false; $removed = false;
foreach ($this->_events[$name] as $i => $event) { foreach ($this->_events[$name] as $i => $event) {
@ -543,7 +543,7 @@ class Component extends Object
$this->detachBehavior($name); $this->detachBehavior($name);
} }
} }
$this->_behaviors = array(); $this->_behaviors = [];
} }
/** /**
@ -552,7 +552,7 @@ class Component extends Object
public function ensureBehaviors() public function ensureBehaviors()
{ {
if ($this->_behaviors === null) { if ($this->_behaviors === null) {
$this->_behaviors = array(); $this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) { foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior); $this->attachBehaviorInternal($name, $behavior);
} }

28
framework/yii/base/Controller.php

@ -72,7 +72,7 @@ class Controller extends Component
* @param Module $module the module that this controller belongs to. * @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 * @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->id = $id;
$this->module = $module; $this->module = $module;
@ -86,14 +86,14 @@ class Controller extends Component
* action class names or action configuration arrays. For example, * action class names or action configuration arrays. For example,
* *
* ~~~ * ~~~
* return array( * return [
* 'action1' => '@app/components/Action1', * 'action1' => '@app/components/Action1',
* 'action2' => array( * 'action2' => [
* 'class' => '@app/components/Action2', * 'class' => '@app/components/Action2',
* 'property1' => 'value1', * 'property1' => 'value1',
* 'property2' => 'value2', * 'property2' => 'value2',
* ), * ],
* ); * ];
* ~~~ * ~~~
* *
* [[\Yii::createObject()]] will be used later to create the requested action * [[\Yii::createObject()]] will be used later to create the requested action
@ -101,7 +101,7 @@ class Controller extends Component
*/ */
public function actions() 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. * @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully.
* @see createAction * @see createAction
*/ */
public function runAction($id, $params = array()) public function runAction($id, $params = [])
{ {
$action = $this->createAction($id); $action = $this->createAction($id);
if ($action !== null) { if ($action !== null) {
@ -152,7 +152,7 @@ class Controller extends Component
* @see runAction * @see runAction
* @see forward * @see forward
*/ */
public function run($route, $params = array()) public function run($route, $params = [])
{ {
$pos = strpos($route, '/'); $pos = strpos($route, '/');
if ($pos === false) { if ($pos === false) {
@ -173,7 +173,7 @@ class Controller extends Component
*/ */
public function bindActionParams($action, $params) public function bindActionParams($action, $params)
{ {
return array(); return [];
} }
/** /**
@ -244,7 +244,7 @@ class Controller extends Component
*/ */
public function getActionParams() public function getActionParams()
{ {
return array(); return [];
} }
/** /**
@ -303,13 +303,13 @@ class Controller extends Component
* @return string the rendering result. * @return string the rendering result.
* @throws InvalidParamException if the view file or the layout file does not exist. * @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); $viewFile = $this->findViewFile($view);
$output = $this->getView()->renderFile($viewFile, $params, $this); $output = $this->getView()->renderFile($viewFile, $params, $this);
$layoutFile = $this->findLayoutFile(); $layoutFile = $this->findLayoutFile();
if ($layoutFile !== false) { if ($layoutFile !== false) {
return $this->getView()->renderFile($layoutFile, array('content' => $output), $this); return $this->getView()->renderFile($layoutFile, ['content' => $output], $this);
} else { } else {
return $output; return $output;
} }
@ -323,7 +323,7 @@ class Controller extends Component
* @return string the rendering result. * @return string the rendering result.
* @throws InvalidParamException if the view file does not exist. * @throws InvalidParamException if the view file does not exist.
*/ */
public function renderPartial($view, $params = array()) public function renderPartial($view, $params = [])
{ {
$viewFile = $this->findViewFile($view); $viewFile = $this->findViewFile($view);
return $this->getView()->renderFile($viewFile, $params, $this); return $this->getView()->renderFile($viewFile, $params, $this);
@ -336,7 +336,7 @@ class Controller extends Component
* @return string the rendering result. * @return string the rendering result.
* @throws InvalidParamException if the view file does not exist. * @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); return $this->getView()->renderFile($file, $params, $this);
} }

8
framework/yii/base/ErrorException.php

@ -51,7 +51,7 @@ class ErrorException extends Exception
} }
// XDebug has a different key name // XDebug has a different key name
$frame['args'] = array(); $frame['args'] = [];
if (isset($frame['params']) && !isset($frame['args'])) { if (isset($frame['params']) && !isset($frame['args'])) {
$frame['args'] = $frame['params']; $frame['args'] = $frame['params'];
} }
@ -81,7 +81,7 @@ class ErrorException extends Exception
*/ */
public static function isFatalError($error) 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() public function getName()
{ {
$names = array( $names = [
E_ERROR => Yii::t('yii', 'Fatal Error'), E_ERROR => Yii::t('yii', 'Fatal Error'),
E_PARSE => Yii::t('yii', 'Parse Error'), E_PARSE => Yii::t('yii', 'Parse Error'),
E_CORE_ERROR => Yii::t('yii', 'Core Error'), E_CORE_ERROR => Yii::t('yii', 'Core Error'),
@ -103,7 +103,7 @@ class ErrorException extends Exception
E_NOTICE => Yii::t('yii', 'Notice'), E_NOTICE => Yii::t('yii', 'Notice'),
E_RECOVERABLE_ERROR => Yii::t('yii', 'Recoverable Error'), E_RECOVERABLE_ERROR => Yii::t('yii', 'Recoverable Error'),
E_DEPRECATED => Yii::t('yii', 'Deprecated'), E_DEPRECATED => Yii::t('yii', 'Deprecated'),
); ];
return isset($names[$this->getCode()]) ? $names[$this->getCode()] : Yii::t('yii', 'Error'); return isset($names[$this->getCode()]) ? $names[$this->getCode()] : Yii::t('yii', 'Error');
} }
} }

36
framework/yii/base/ErrorHandler.php

@ -112,19 +112,19 @@ class ErrorHandler extends Component
ini_set('display_errors', 1); ini_set('display_errors', 1);
} }
$file = $useErrorView ? $this->errorView : $this->exceptionView; $file = $useErrorView ? $this->errorView : $this->exceptionView;
$response->data = $this->renderFile($file, array( $response->data = $this->renderFile($file, [
'exception' => $exception, 'exception' => $exception,
)); ]);
} }
} elseif ($exception instanceof Arrayable) { } elseif ($exception instanceof Arrayable) {
$response->data = $exception; $response->data = $exception;
} else { } else {
$response->data = array( $response->data = [
'type' => get_class($exception), 'type' => get_class($exception),
'name' => 'Exception', 'name' => 'Exception',
'message' => $exception->getMessage(), 'message' => $exception->getMessage(),
'code' => $exception->getCode(), 'code' => $exception->getCode(),
); ];
} }
if ($exception instanceof HttpException) { if ($exception instanceof HttpException) {
@ -212,9 +212,7 @@ class ErrorHandler extends Component
public function renderPreviousExceptions($exception) public function renderPreviousExceptions($exception)
{ {
if (($previous = $exception->getPrevious()) !== null) { if (($previous = $exception->getPrevious()) !== null) {
return $this->renderFile($this->previousExceptionView, array( return $this->renderFile($this->previousExceptionView, ['exception' => $previous]);
'exception' => $previous,
));
} else { } else {
return ''; return '';
} }
@ -231,7 +229,7 @@ class ErrorHandler extends Component
*/ */
public function renderCallStackItem($file, $line, $class, $method, $index) public function renderCallStackItem($file, $line, $class, $method, $index)
{ {
$lines = array(); $lines = [];
$begin = $end = 0; $begin = $end = 0;
if ($file !== null && $line !== null) { if ($file !== null && $line !== null) {
$line--; // adjust line number from one-based to zero-based $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; $end = $line + $half < $lineCount ? $line + $half : $lineCount - 1;
} }
return $this->renderFile($this->callStackItemView, array( return $this->renderFile($this->callStackItemView, [
'file' => $file, 'file' => $file,
'line' => $line, 'line' => $line,
'class' => $class, 'class' => $class,
@ -254,7 +252,7 @@ class ErrorHandler extends Component
'lines' => $lines, 'lines' => $lines,
'begin' => $begin, 'begin' => $begin,
'end' => $end, 'end' => $end,
)); ]);
} }
/** /**
@ -264,7 +262,7 @@ class ErrorHandler extends Component
public function renderRequest() public function renderRequest()
{ {
$request = ''; $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])) { if (!empty($GLOBALS[$name])) {
$request .= '$' . $name . ' = ' . var_export($GLOBALS[$name], true) . ";\n\n"; $request .= '$' . $name . ' = ' . var_export($GLOBALS[$name], true) . ";\n\n";
} }
@ -300,14 +298,14 @@ class ErrorHandler extends Component
*/ */
public function createServerInformationLink() public function createServerInformationLink()
{ {
static $serverUrls = array( static $serverUrls = [
'http://httpd.apache.org/' => array('apache'), 'http://httpd.apache.org/' => ['apache'],
'http://nginx.org/' => array('nginx'), 'http://nginx.org/' => ['nginx'],
'http://lighttpd.net/' => array('lighttpd'), 'http://lighttpd.net/' => ['lighttpd'],
'http://gwan.com/' => array('g-wan', 'gwan'), 'http://gwan.com/' => ['g-wan', 'gwan'],
'http://iis.net/' => array('iis', 'services'), 'http://iis.net/' => ['iis', 'services'],
'http://php.net/manual/en/features.commandline.webserver.php' => array('development'), 'http://php.net/manual/en/features.commandline.webserver.php' => ['development'],
); ];
if (isset($_SERVER['SERVER_SOFTWARE'])) { if (isset($_SERVER['SERVER_SOFTWARE'])) {
foreach ($serverUrls as $url => $keywords) { foreach ($serverUrls as $url => $keywords) {
foreach ($keywords as $keyword) { foreach ($keywords as $keyword) {

4
framework/yii/base/Exception.php

@ -39,12 +39,12 @@ class Exception extends \Exception implements Arrayable
*/ */
protected function toArrayRecursive($exception) protected function toArrayRecursive($exception)
{ {
$array = array( $array = [
'type' => get_class($exception), 'type' => get_class($exception),
'name' => $exception instanceof self ? $exception->getName() : 'Exception', 'name' => $exception instanceof self ? $exception->getName() : 'Exception',
'message' => $exception->getMessage(), 'message' => $exception->getMessage(),
'code' => $exception->getCode(), 'code' => $exception->getCode(),
); ];
if (($prev = $exception->getPrevious()) !== null) { if (($prev = $exception->getPrevious()) !== null) {
$array['previous'] = $this->toArrayRecursive($prev); $array['previous'] = $this->toArrayRecursive($prev);
} }

10
framework/yii/base/Formatter.php

@ -42,7 +42,7 @@ class Formatter extends Component
public $nullDisplay; public $nullDisplay;
/** /**
* @var array the text to be displayed when formatting a boolean value. The first element corresponds * @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; public $booleanFormat;
/** /**
@ -63,7 +63,7 @@ class Formatter extends Component
public function init() public function init()
{ {
if (empty($this->booleanFormat)) { 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) { if ($this->nullDisplay === null) {
$this->nullDisplay = Yii::t('yii', '(not set)'); $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 * @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 * 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 * 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 * @return string the formatting result
* @throws InvalidParamException if the type is not supported by this class. * @throws InvalidParamException if the type is not supported by this class.
*/ */
@ -94,11 +94,11 @@ class Formatter extends Component
$params = $format; $params = $format;
$format = $f; $format = $f;
} else { } else {
$params = array($value); $params = [$value];
} }
$method = 'as' . $format; $method = 'as' . $format;
if (method_exists($this, $method)) { if (method_exists($this, $method)) {
return call_user_func_array(array($this, $method), $params); return call_user_func_array([$this, $method], $params);
} else { } else {
throw new InvalidParamException("Unknown type: $format"); throw new InvalidParamException("Unknown type: $format");
} }

4
framework/yii/base/InlineAction.php

@ -31,7 +31,7 @@ class InlineAction extends Action
* @param string $actionMethod the controller method that this inline action is associated with * @param 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 * @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; $this->actionMethod = $actionMethod;
parent::__construct($id, $controller, $config); parent::__construct($id, $controller, $config);
@ -50,6 +50,6 @@ class InlineAction extends Action
if (Yii::$app->requestedParams === null) { if (Yii::$app->requestedParams === null) {
Yii::$app->requestedParams = $args; 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);
} }
} }

70
framework/yii/base/Model.php

@ -90,12 +90,12 @@ class Model extends Component implements IteratorAggregate, ArrayAccess
* Each rule is an array with the following structure: * Each rule is an array with the following structure:
* *
* ~~~ * ~~~
* array( * [
* 'attribute list', * 'attribute list',
* 'validator type', * 'validator type',
* 'on' => 'scenario name', * 'on' => 'scenario name',
* ...other parameters... * ...other parameters...
* ) * ]
* ~~~ * ~~~
* *
* where * where
@ -126,18 +126,18 @@ class Model extends Component implements IteratorAggregate, ArrayAccess
* Below are some examples: * Below are some examples:
* *
* ~~~ * ~~~
* array( * [
* // built-in "required" validator * // built-in "required" validator
* array('username', 'required'), * ['username', 'required'],
* // built-in "string" validator customized with "min" and "max" properties * // 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 * // 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 * // 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" * // 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 * 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() 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: * The returned array should be in the following format:
* *
* ~~~ * ~~~
* array( * [
* 'scenario1' => array('attribute11', 'attribute12', ...), * 'scenario1' => ['attribute11', 'attribute12', ...],
* 'scenario2' => array('attribute21', 'attribute22', ...), * 'scenario2' => ['attribute21', 'attribute22', ...],
* ... * ...
* ) * ]
* ~~~ * ~~~
* *
* By default, an active attribute that is considered safe and can be massively assigned. * 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() public function scenarios()
{ {
$scenarios = array(); $scenarios = [];
$defaults = array(); $defaults = [];
/** @var $validator Validator */ /** @var $validator Validator */
foreach ($this->getValidators() as $validator) { foreach ($this->getValidators() as $validator) {
if (empty($validator->on)) { if (empty($validator->on)) {
@ -231,7 +231,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess
public function attributes() public function attributes()
{ {
$class = new ReflectionClass($this); $class = new ReflectionClass($this);
$names = array(); $names = [];
foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) { foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
$name = $property->getName(); $name = $property->getName();
if (!$property->isStatic()) { if (!$property->isStatic()) {
@ -259,7 +259,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess
*/ */
public function attributeLabels() public function attributeLabels()
{ {
return array(); return [];
} }
/** /**
@ -367,7 +367,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess
*/ */
public function getActiveValidators($attribute = null) public function getActiveValidators($attribute = null)
{ {
$validators = array(); $validators = [];
$scenario = $this->getScenario(); $scenario = $this->getScenario();
/** @var $validator Validator */ /** @var $validator Validator */
foreach ($this->getValidators() as $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: * 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 is required.',
* 'Username must contain only word characters.', * 'Username must contain only word characters.',
* ), * ],
* 'email' => array( * 'email' => [
* 'Email address is invalid.', * 'Email address is invalid.',
* ) * ]
* ) * ]
* ~~~ * ~~~
* *
* @see getFirstErrors * @see getFirstErrors
@ -489,9 +489,9 @@ class Model extends Component implements IteratorAggregate, ArrayAccess
public function getErrors($attribute = null) public function getErrors($attribute = null)
{ {
if ($attribute === null) { if ($attribute === null) {
return $this->_errors === null ? array() : $this->_errors; return $this->_errors === null ? [] : $this->_errors;
} else { } 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() public function getFirstErrors()
{ {
if (empty($this->_errors)) { if (empty($this->_errors)) {
return array(); return [];
} else { } else {
$errors = array(); $errors = [];
foreach ($this->_errors as $attributeErrors) { foreach ($this->_errors as $attributeErrors) {
if (isset($attributeErrors[0])) { if (isset($attributeErrors[0])) {
$errors[] = $attributeErrors[0]; $errors[] = $attributeErrors[0];
@ -545,7 +545,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess
public function clearErrors($attribute = null) public function clearErrors($attribute = null)
{ {
if ($attribute === null) { if ($attribute === null) {
$this->_errors = array(); $this->_errors = [];
} else { } else {
unset($this->_errors[$attribute]); 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. * @param array $except list of attributes whose value should NOT be returned.
* @return array attribute values (name => value). * @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) { if ($names === null) {
$names = $this->attributes(); $names = $this->attributes();
} }
@ -657,9 +657,9 @@ class Model extends Component implements IteratorAggregate, ArrayAccess
$scenario = $this->getScenario(); $scenario = $this->getScenario();
$scenarios = $this->scenarios(); $scenarios = $this->scenarios();
if (!isset($scenarios[$scenario])) { if (!isset($scenarios[$scenario])) {
return array(); return [];
} }
$attributes = array(); $attributes = [];
foreach ($scenarios[$scenario] as $attribute) { foreach ($scenarios[$scenario] as $attribute) {
if ($attribute[0] !== '!') { if ($attribute[0] !== '!') {
$attributes[] = $attribute; $attributes[] = $attribute;
@ -677,7 +677,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess
$scenario = $this->getScenario(); $scenario = $this->getScenario();
$scenarios = $this->scenarios(); $scenarios = $this->scenarios();
if (!isset($scenarios[$scenario])) { if (!isset($scenarios[$scenario])) {
return array(); return [];
} }
$attributes = $scenarios[$scenario]; $attributes = $scenarios[$scenario];
foreach ($attributes as $i => $attribute) { foreach ($attributes as $i => $attribute) {

56
framework/yii/base/Module.php

@ -39,11 +39,11 @@ abstract class Module extends Component
/** /**
* @var array custom module parameters (name => value). * @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. * @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]]. * @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, * in the array are used to initialize the corresponding controller properties. For example,
* *
* ~~~ * ~~~
* array( * [
* 'account' => '@app/controllers/UserController', * 'account' => '@app/controllers/UserController',
* 'article' => array( * 'article' => [
* 'class' => '@app/controllers/PostController', * 'class' => '@app/controllers/PostController',
* 'pageTitle' => 'something new', * 'pageTitle' => 'something new',
* ), * ],
* ) * ]
* ~~~ * ~~~
*/ */
public $controllerMap = array(); public $controllerMap = [];
/** /**
* @var string the namespace that controller classes are in. If not set, * @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. * 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 * @var array child modules of this module
*/ */
private $_modules = array(); private $_modules = [];
/** /**
* @var array components registered under this module * @var array components registered under this module
*/ */
private $_components = array(); private $_components = [];
/** /**
* Constructor. * Constructor.
@ -125,7 +125,7 @@ abstract class Module extends Component
* @param Module $parent the parent module (if any) * @param Module $parent the parent module (if any)
* @param array $config name-value pairs that will be used to initialize the object properties * @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->id = $id;
$this->module = $parent; $this->module = $parent;
@ -312,10 +312,10 @@ abstract class Module extends Component
* For example, * For example,
* *
* ~~~ * ~~~
* array( * [
* '@models' => '@app/models', // an existing alias * '@models' => '@app/models', // an existing alias
* '@backend' => __DIR__ . '/../backend', // a directory * '@backend' => __DIR__ . '/../backend', // a directory
* ) * ]
* ~~~ * ~~~
*/ */
public function setAliases($aliases) public function setAliases($aliases)
@ -401,7 +401,7 @@ abstract class Module extends Component
public function getModules($loadedOnly = false) public function getModules($loadedOnly = false)
{ {
if ($loadedOnly) { if ($loadedOnly) {
$modules = array(); $modules = [];
foreach ($this->_modules as $module) { foreach ($this->_modules as $module) {
if ($module instanceof Module) { if ($module instanceof Module) {
$modules[] = $module; $modules[] = $module;
@ -426,15 +426,13 @@ abstract class Module extends Component
* The following is an example for registering two sub-modules: * The following is an example for registering two sub-modules:
* *
* ~~~ * ~~~
* array( * [
* 'comment' => array( * 'comment' => [
* 'class' => 'app\modules\comment\CommentModule', * 'class' => 'app\modules\comment\CommentModule',
* 'db' => 'db', * 'db' => 'db',
* ), * ],
* 'booking' => array( * 'booking' => ['class' => 'app\modules\booking\BookingModule'],
* 'class' => 'app\modules\booking\BookingModule', * ]
* ),
* )
* ~~~ * ~~~
* *
* @param array $modules modules (id => module configuration or instances) * @param array $modules modules (id => module configuration or instances)
@ -506,7 +504,7 @@ abstract class Module extends Component
public function getComponents($loadedOnly = false) public function getComponents($loadedOnly = false)
{ {
if ($loadedOnly) { if ($loadedOnly) {
$components = array(); $components = [];
foreach ($this->_components as $component) { foreach ($this->_components as $component) {
if ($component instanceof Component) { if ($component instanceof Component) {
$components[] = $component; $components[] = $component;
@ -531,16 +529,16 @@ abstract class Module extends Component
* The following is an example for setting two components: * The following is an example for setting two components:
* *
* ~~~ * ~~~
* array( * [
* 'db' => array( * 'db' => [
* 'class' => 'yii\db\Connection', * 'class' => 'yii\db\Connection',
* 'dsn' => 'sqlite:path/to/file.db', * 'dsn' => 'sqlite:path/to/file.db',
* ), * ],
* 'cache' => array( * 'cache' => [
* 'class' => 'yii\caching\DbCache', * 'class' => 'yii\caching\DbCache',
* 'db' => 'db', * 'db' => 'db',
* ), * ],
* ) * ]
* ~~~ * ~~~
* *
* @param array $components components (id => component configuration or instance) * @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. * @return mixed the result of the action.
* @throws InvalidRouteException if the requested route cannot be resolved into an action successfully * @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); $parts = $this->createController($route);
if (is_array($parts)) { 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;
} }
/** /**

2
framework/yii/base/Object.php

@ -38,7 +38,7 @@ class Object implements Arrayable
* *
* @param array $config name-value pairs that will be used to initialize the object properties * @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)) { if (!empty($config)) {
Yii::configure($this, $config); Yii::configure($this, $config);

14
framework/yii/base/Theme.php

@ -21,7 +21,7 @@ use yii\helpers\FileHelper;
* with its themed version if part of its path matches one of the keys in [[pathMap]]. * 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. * 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 * then the themed version for a view file `/web/views/site/index.php` will be
* `/web/themes/basic/site/index.php`. * `/web/themes/basic/site/index.php`.
* *
@ -29,12 +29,12 @@ use yii\helpers\FileHelper;
* component like the following: * component like the following:
* *
* ~~~ * ~~~
* 'view' => array( * 'view' => [
* 'theme' => array( * 'theme' => [
* 'basePath' => '@webroot/themes/basic', * 'basePath' => '@webroot/themes/basic',
* 'baseUrl' => '@web/themes/basic', * 'baseUrl' => '@web/themes/basic',
* ), * ],
* ), * ],
* ~~~ * ~~~
* *
* The above configuration specifies a theme located under the "themes/basic" directory of the Web folder * 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 (empty($this->pathMap)) {
if ($this->basePath !== null) { if ($this->basePath !== null) {
$this->basePath = Yii::getAlias($this->basePath); $this->basePath = Yii::getAlias($this->basePath);
$this->pathMap = array(Yii::$app->getBasePath() => $this->basePath); $this->pathMap = [Yii::$app->getBasePath() => $this->basePath];
} else { } else {
throw new InvalidConfigException('The "basePath" property must be set.'); throw new InvalidConfigException('The "basePath" property must be set.');
} }
} }
$paths = array(); $paths = [];
foreach ($this->pathMap as $from => $to) { foreach ($this->pathMap as $from => $to) {
$from = FileHelper::normalizePath(Yii::getAlias($from)); $from = FileHelper::normalizePath(Yii::getAlias($from));
$to = FileHelper::normalizePath(Yii::getAlias($to)); $to = FileHelper::normalizePath(Yii::getAlias($to));

66
framework/yii/base/View.php

@ -96,21 +96,17 @@ class View extends Component
/** /**
* @var mixed custom parameters that are shared among view templates. * @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. * @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. * 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: * For example, the following configuration enables both Smarty and Twig view renderers:
* *
* ~~~ * ~~~
* array( * [
* 'tpl' => array( * 'tpl' => ['class' => 'yii\smarty\ViewRenderer'],
* 'class' => 'yii\smarty\ViewRenderer', * 'twig' => ['class' => 'yii\twig\ViewRenderer'],
* ), * ]
* 'twig' => array(
* 'class' => 'yii\twig\ViewRenderer',
* ),
* )
* ~~~ * ~~~
* *
* If no renderer is available for the given view file, the view file will be treated as a normal PHP * 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. * is used internally to implement the content caching feature. Do not modify it directly.
* @internal * @internal
*/ */
public $cacheStack = array(); public $cacheStack = [];
/** /**
* @var array a list of placeholders for embedding dynamic contents. This property * @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. * is used internally to implement the content caching feature. Do not modify it directly.
* @internal * @internal
*/ */
public $dynamicPlaceholders = array(); public $dynamicPlaceholders = [];
/** /**
* @var AssetBundle[] list of the registered asset bundles. The keys are the bundle names, and the values * @var AssetBundle[] list of the registered asset bundles. The keys are the bundle names, and the values
* are the registered [[AssetBundle]] objects. * are the registered [[AssetBundle]] objects.
* @see registerAssetBundle * @see registerAssetBundle
*/ */
public $assetBundles = array(); public $assetBundles = [];
/** /**
* @var string the page title * @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. * @throws InvalidParamException if the view cannot be resolved or the view file does not exist.
* @see renderFile * @see renderFile
*/ */
public function render($view, $params = array()) public function render($view, $params = [])
{ {
if ($this->context instanceof Controller) { if ($this->context instanceof Controller) {
return $this->context->renderPartial($view, $params); return $this->context->renderPartial($view, $params);
@ -244,7 +240,7 @@ class View extends Component
* @return string the rendering result * @return string the rendering result
* @throws InvalidParamException if the view file does not exist * @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); $viewFile = Yii::getAlias($viewFile);
if ($this->theme !== null) { 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. * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file.
* @return string the rendering result * @return string the rendering result
*/ */
public function renderPhpFile($_file_, $_params_ = array()) public function renderPhpFile($_file_, $_params_ = [])
{ {
ob_start(); ob_start();
ob_implicit_flush(false); ob_implicit_flush(false);
@ -393,11 +389,11 @@ class View extends Component
*/ */
public function beginBlock($id, $renderInPlace = false) public function beginBlock($id, $renderInPlace = false)
{ {
return Block::begin(array( return Block::begin([
'id' => $id, 'id' => $id,
'renderInPlace' => $renderInPlace, 'renderInPlace' => $renderInPlace,
'view' => $this, 'view' => $this,
)); ]);
} }
/** /**
@ -425,13 +421,13 @@ class View extends Component
* @return ContentDecorator the ContentDecorator widget instance * @return ContentDecorator the ContentDecorator widget instance
* @see ContentDecorator * @see ContentDecorator
*/ */
public function beginContent($viewFile, $params = array()) public function beginContent($viewFile, $params = [])
{ {
return ContentDecorator::begin(array( return ContentDecorator::begin([
'viewFile' => $viewFile, 'viewFile' => $viewFile,
'params' => $params, 'params' => $params,
'view' => $this, 'view' => $this,
)); ]);
} }
/** /**
@ -461,7 +457,7 @@ class View extends Component
* @return boolean whether you should generate the content for caching. * @return boolean whether you should generate the content for caching.
* False if the cached version is available. * False if the cached version is available.
*/ */
public function beginCache($id, $properties = array()) public function beginCache($id, $properties = [])
{ {
$properties['id'] = $id; $properties['id'] = $id;
$properties['view'] = $this; $properties['view'] = $this;
@ -526,11 +522,11 @@ class View extends Component
foreach(array_keys($this->assetBundles) as $bundle) { foreach(array_keys($this->assetBundles) as $bundle) {
$this->registerAssetFiles($bundle); $this->registerAssetFiles($bundle);
} }
echo strtr($content, array( echo strtr($content, [
self::PH_HEAD => $this->renderHeadHtml(), self::PH_HEAD => $this->renderHeadHtml(),
self::PH_BODY_BEGIN => $this->renderBodyBeginHtml(), self::PH_BODY_BEGIN => $this->renderBodyBeginHtml(),
self::PH_BODY_END => $this->renderBodyEndHtml(), self::PH_BODY_END => $this->renderBodyEndHtml(),
)); ]);
unset( unset(
$this->metaTags, $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 * $css as the key. If two CSS code blocks are registered with the same key, the latter
* will overwrite the former. * will overwrite the former.
*/ */
public function registerCss($css, $options = array(), $key = null) public function registerCss($css, $options = [], $key = null)
{ {
$key = $key ?: md5($css); $key = $key ?: md5($css);
$this->css[$key] = Html::style($css, $options); $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 * $url as the key. If two CSS files are registered with the same key, the latter
* will overwrite the former. * will overwrite the former.
*/ */
public function registerCssFile($url, $options = array(), $key = null) public function registerCssFile($url, $options = [], $key = null)
{ {
$key = $key ?: $url; $key = $key ?: $url;
$this->cssFiles[$key] = Html::cssFile($url, $options); $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 * $url as the key. If two JS files are registered with the same key, the latter
* will overwrite the former. * 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; $position = isset($options['position']) ? $options['position'] : self::POS_END;
unset($options['position']); unset($options['position']);
@ -747,15 +743,15 @@ class View extends Component
*/ */
protected function renderHeadHtml() protected function renderHeadHtml()
{ {
$lines = array(); $lines = [];
if (!empty($this->metaTags)) { if (!empty($this->metaTags)) {
$lines[] = implode("\n", $this->metaTags); $lines[] = implode("\n", $this->metaTags);
} }
$request = Yii::$app->getRequest(); $request = Yii::$app->getRequest();
if ($request instanceof \yii\web\Request && $request->enableCsrfValidation) { if ($request instanceof \yii\web\Request && $request->enableCsrfValidation) {
$lines[] = Html::tag('meta', '', array('name' => 'csrf-var', 'content' => $request->csrfVar)); $lines[] = Html::tag('meta', '', ['name' => 'csrf-var', 'content' => $request->csrfVar]);
$lines[] = Html::tag('meta', '', array('name' => 'csrf-token', 'content' => $request->getCsrfToken())); $lines[] = Html::tag('meta', '', ['name' => 'csrf-token', 'content' => $request->getCsrfToken()]);
} }
if (!empty($this->linkTags)) { if (!empty($this->linkTags)) {
@ -771,7 +767,7 @@ class View extends Component
$lines[] = implode("\n", $this->jsFiles[self::POS_HEAD]); $lines[] = implode("\n", $this->jsFiles[self::POS_HEAD]);
} }
if (!empty($this->js[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); return empty($lines) ? '' : implode("\n", $lines);
} }
@ -783,12 +779,12 @@ class View extends Component
*/ */
protected function renderBodyBeginHtml() protected function renderBodyBeginHtml()
{ {
$lines = array(); $lines = [];
if (!empty($this->jsFiles[self::POS_BEGIN])) { if (!empty($this->jsFiles[self::POS_BEGIN])) {
$lines[] = implode("\n", $this->jsFiles[self::POS_BEGIN]); $lines[] = implode("\n", $this->jsFiles[self::POS_BEGIN]);
} }
if (!empty($this->js[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); return empty($lines) ? '' : implode("\n", $lines);
} }
@ -800,16 +796,16 @@ class View extends Component
*/ */
protected function renderBodyEndHtml() protected function renderBodyEndHtml()
{ {
$lines = array(); $lines = [];
if (!empty($this->jsFiles[self::POS_END])) { if (!empty($this->jsFiles[self::POS_END])) {
$lines[] = implode("\n", $this->jsFiles[self::POS_END]); $lines[] = implode("\n", $this->jsFiles[self::POS_END]);
} }
if (!empty($this->js[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])) { if (!empty($this->js[self::POS_READY])) {
$js = "jQuery(document).ready(function(){\n" . implode("\n", $this->js[self::POS_READY]) . "\n});"; $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); return empty($lines) ? '' : implode("\n", $lines);
} }

2
framework/yii/base/ViewEvent.php

@ -36,7 +36,7 @@ class ViewEvent extends Event
* @param string $viewFile the view file path that is being rendered by [[View::renderFile()]]. * @param 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 * @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; $this->viewFile = $viewFile;
parent::__construct($config); parent::__construct($config);

10
framework/yii/base/Widget.php

@ -32,7 +32,7 @@ class Widget extends Component
* is maintained by [[begin()]] and [[end()]] methods. * is maintained by [[begin()]] and [[end()]] methods.
* @internal * @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 * @param array $config name-value pairs that will be used to initialize the object properties
* @return Widget the newly created widget instance * @return Widget the newly created widget instance
*/ */
public static function begin($config = array()) public static function begin($config = [])
{ {
$config['class'] = get_called_class(); $config['class'] = get_called_class();
/** @var Widget $widget */ /** @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 * @param array $config name-value pairs that will be used to initialize the object properties
* @return string the rendering result of the widget. * @return string the rendering result of the widget.
*/ */
public static function widget($config = array()) public static function widget($config = [])
{ {
ob_start(); ob_start();
ob_implicit_flush(false); ob_implicit_flush(false);
@ -165,7 +165,7 @@ class Widget extends Component
* @return string the rendering result. * @return string the rendering result.
* @throws InvalidParamException if the view file does not exist. * @throws InvalidParamException if the view file does not exist.
*/ */
public function render($view, $params = array()) public function render($view, $params = [])
{ {
$viewFile = $this->findViewFile($view); $viewFile = $this->findViewFile($view);
return $this->getView()->renderFile($viewFile, $params, $this); return $this->getView()->renderFile($viewFile, $params, $this);
@ -178,7 +178,7 @@ class Widget extends Component
* @return string the rendering result. * @return string the rendering result.
* @throws InvalidParamException if the view file does not exist. * @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); return $this->getView()->renderFile($file, $params, $this);
} }

14
framework/yii/behaviors/AutoTimestamp.php

@ -21,11 +21,9 @@ use yii\db\ActiveRecord;
* ~~~ * ~~~
* public function behaviors() * public function behaviors()
* { * {
* return array( * return [
* 'timestamp' => array( * 'timestamp' => ['class' => 'yii\behaviors\AutoTimestamp'],
* '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, * The default setting is to update the `create_time` attribute upon AR insertion,
* and update the `update_time` attribute upon AR updating. * and update the `update_time` attribute upon AR updating.
*/ */
public $attributes = array( public $attributes = [
ActiveRecord::EVENT_BEFORE_INSERT => 'create_time', ActiveRecord::EVENT_BEFORE_INSERT => 'create_time',
ActiveRecord::EVENT_BEFORE_UPDATE => 'update_time', ActiveRecord::EVENT_BEFORE_UPDATE => 'update_time',
); ];
/** /**
* @var \Closure|Expression The expression that will be used for generating the timestamp. * @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, * This can be either an anonymous function that returns the timestamp value,
@ -78,7 +76,7 @@ class AutoTimestamp extends Behavior
*/ */
public function updateTimestamp($event) 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)) { if (!empty($attributes)) {
$timestamp = $this->evaluateTimestamp(); $timestamp = $this->evaluateTimestamp();
foreach ($attributes as $attribute) { foreach ($attributes as $attribute) {

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save