Browse Source

Merge branch 'master' into 2.1

Conflicts:
	framework/UPGRADE.md
	framework/base/Security.php
	framework/caching/Cache.php
	framework/caching/XCache.php
	framework/db/QueryBuilder.php
	framework/db/Schema.php
	framework/db/mssql/QueryBuilder.php
	framework/validators/Validator.php
	framework/web/UrlManager.php
	tests/framework/mutex/FileMutexTest.php
tags/3.0.0-alpha1
SilverFire - Dmitry Naumenko 8 years ago
parent
commit
d335fd6ea3
  1. 12
      build/controllers/PhpDocController.php
  2. 6
      composer.json
  3. 380
      composer.lock
  4. 5
      docs/documentation_style_guide.md
  5. 2
      docs/guide-es/caching-http.md
  6. 85
      docs/guide-es/input-multiple-models.md
  7. 2
      docs/guide-es/input-validation.md
  8. 4
      docs/guide-es/rest-controllers.md
  9. 4
      docs/guide-es/security-authorization.md
  10. 2
      docs/guide-fr/input-validation.md
  11. 80
      docs/guide-fr/output-client-scripts.md
  12. 4
      docs/guide-fr/security-authentication.md
  13. 4
      docs/guide-fr/security-authorization.md
  14. 2
      docs/guide-ja/caching-http.md
  15. 2
      docs/guide-ja/input-validation.md
  16. 4
      docs/guide-ja/rest-controllers.md
  17. 4
      docs/guide-ja/security-authentication.md
  18. 4
      docs/guide-ja/security-authorization.md
  19. 2
      docs/guide-pl/caching-http.md
  20. 131
      docs/guide-pl/concept-aliases.md
  21. 89
      docs/guide-pl/concept-autoloading.md
  22. 2
      docs/guide-pl/input-validation.md
  23. 4
      docs/guide-pl/start-databases.md
  24. 2
      docs/guide-pt-BR/caching-http.md
  25. 4
      docs/guide-pt-BR/rest-controllers.md
  26. 4
      docs/guide-pt-BR/security-authentication.md
  27. 4
      docs/guide-pt-BR/security-authorization.md
  28. 2
      docs/guide-ru/README.md
  29. 2
      docs/guide-ru/caching-http.md
  30. 2
      docs/guide-ru/caching-page.md
  31. 2
      docs/guide-ru/db-active-record.md
  32. 224
      docs/guide-ru/db-migrations.md
  33. 42
      docs/guide-ru/input-forms.md
  34. 2
      docs/guide-ru/input-validation.md
  35. 2
      docs/guide-ru/output-data-widgets.md
  36. 4
      docs/guide-ru/rest-controllers.md
  37. 4
      docs/guide-ru/security-authentication.md
  38. 4
      docs/guide-ru/security-authorization.md
  39. 2
      docs/guide-ru/start-databases.md
  40. 2
      docs/guide-zh-CN/caching-http.md
  41. 2
      docs/guide-zh-CN/input-validation.md
  42. 4
      docs/guide-zh-CN/rest-controllers.md
  43. 2
      docs/guide/caching-http.md
  44. 11
      docs/guide/db-active-record.md
  45. 8
      docs/guide/db-migrations.md
  46. 2
      docs/guide/helper-array.md
  47. 72
      docs/guide/input-forms.md
  48. 2
      docs/guide/input-validation.md
  49. 4
      docs/guide/output-client-scripts.md
  50. 6
      docs/guide/output-data-widgets.md
  51. 2
      docs/guide/output-formatting.md
  52. 4
      docs/guide/rest-controllers.md
  53. 6
      docs/guide/rest-quick-start.md
  54. 2
      docs/guide/rest-resources.md
  55. 4
      docs/guide/security-authentication.md
  56. 4
      docs/guide/security-authorization.md
  57. 2
      docs/guide/start-installation.md
  58. 17
      docs/guide/tutorial-core-validators.md
  59. 6
      docs/internals-ja/core-code-style.md
  60. 2
      docs/internals-pl/core-code-style.md
  61. 2
      docs/internals-ru/core-code-style.md
  62. 2
      docs/internals-uk/core-code-style.md
  63. 24
      docs/internals/core-code-style.md
  64. 1
      docs/internals/design-decisions.md
  65. 4
      docs/internals/git-workflow.md
  66. 8
      framework/BaseYii.php
  67. 602
      framework/CHANGELOG.md
  68. 78
      framework/UPGRADE.md
  69. 31
      framework/assets/yii.activeForm.js
  70. 4
      framework/assets/yii.gridView.js
  71. 45
      framework/assets/yii.js
  72. 13
      framework/assets/yii.validation.js
  73. 4
      framework/base/Action.php
  74. 2
      framework/base/ActionEvent.php
  75. 6
      framework/base/ActionFilter.php
  76. 14
      framework/base/Application.php
  77. 8
      framework/base/ArrayAccessTrait.php
  78. 2
      framework/base/Arrayable.php
  79. 2
      framework/base/ArrayableTrait.php
  80. 2
      framework/base/Behavior.php
  81. 2
      framework/base/BootstrapInterface.php
  82. 34
      framework/base/Component.php
  83. 2
      framework/base/Configurable.php
  84. 6
      framework/base/Controller.php
  85. 4
      framework/base/ErrorException.php
  86. 41
      framework/base/ErrorHandler.php
  87. 10
      framework/base/Event.php
  88. 2
      framework/base/Exception.php
  89. 6
      framework/base/ExitException.php
  90. 2
      framework/base/InlineAction.php
  91. 32
      framework/base/Model.php
  92. 2
      framework/base/ModelEvent.php
  93. 84
      framework/base/Module.php
  94. 16
      framework/base/Object.php
  95. 8
      framework/base/Request.php
  96. 4
      framework/base/Response.php
  97. 48
      framework/base/Security.php
  98. 2
      framework/base/Theme.php
  99. 12
      framework/base/View.php
  100. 2
      framework/base/ViewEvent.php
  101. Some files were not shown because too many files have changed in this diff Show More

12
build/controllers/PhpDocController.php

@ -23,7 +23,7 @@ class PhpDocController extends Controller
{
public $defaultAction = 'property';
/**
* @var boolean whether to update class docs directly. Setting this to false will just output docs
* @var bool whether to update class docs directly. Setting this to false will just output docs
* for copy and paste.
*/
public $updateFiles = true;
@ -350,8 +350,8 @@ class PhpDocController extends Controller
$types = explode('|', $matches[2]);
foreach($types as $i => $type) {
switch($type){
case 'int': $types[$i] = 'integer'; break;
case 'bool': $types[$i] = 'boolean'; break;
case 'integer': $types[$i] = 'int'; break;
case 'boolean': $types[$i] = 'bool'; break;
}
}
return '@' . $matches[1] . ' ' . implode('|', $types);
@ -479,9 +479,15 @@ class PhpDocController extends Controller
protected function updateClassPropertyDocs($file, $className, $propertyDoc)
{
try {
$ref = new \ReflectionClass($className);
} catch (\Exception $e) {
$this->stderr("[ERR] Unable to create ReflectionClass for class '$className': " . $e->getMessage() . "\n", Console::FG_RED);
return false;
}
if ($ref->getFileName() != $file) {
$this->stderr("[ERR] Unable to create ReflectionClass for class: $className loaded class is not from file: $file\n", Console::FG_RED);
return false;
}
if (!$ref->isSubclassOf('yii\base\Object') && $className != 'yii\base\Object') {

6
composer.json

@ -57,6 +57,7 @@
"source": "https://github.com/yiisoft/yii2"
},
"minimum-stability": "dev",
"prefer-stable": true,
"replace": {
"yiisoft/yii2": "self.version"
},
@ -75,7 +76,7 @@
},
"require-dev": {
"phpunit/phpunit": "~4.4",
"cebe/indent": "*"
"cebe/indent": "~1.0.2"
},
"suggest": {
"yiisoft/yii2-coding-standards": "you can use this package to check for code style issues when contributing to yii"
@ -85,6 +86,9 @@
"yii\\": "framework/"
}
},
"config": {
"platform": {"php": "5.4"}
},
"bin": [
"framework/yii"
],

380
composer.lock generated

@ -4,8 +4,8 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"hash": "6f7b77a5eff97c17ef7416159427a969",
"content-hash": "c4a9bb575b714fb7901c0c49f9012211",
"hash": "30a97926034335c40273795ce316f36c",
"content-hash": "58ccdf60f6da90c6d1623d9755c0b830",
"packages": [
{
"name": "bower-asset/jquery",
@ -151,16 +151,16 @@
},
{
"name": "cebe/markdown",
"version": "dev-master",
"version": "1.1.1",
"source": {
"type": "git",
"url": "https://github.com/cebe/markdown.git",
"reference": "04bfcaa26356cf86c6c4a2420eb95857a86e03ab"
"reference": "c30eb5e01fe021cc5bba2f9ee0eeef96d4931166"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/cebe/markdown/zipball/04bfcaa26356cf86c6c4a2420eb95857a86e03ab",
"reference": "04bfcaa26356cf86c6c4a2420eb95857a86e03ab",
"url": "https://api.github.com/repos/cebe/markdown/zipball/c30eb5e01fe021cc5bba2f9ee0eeef96d4931166",
"reference": "c30eb5e01fe021cc5bba2f9ee0eeef96d4931166",
"shasum": ""
},
"require": {
@ -207,7 +207,7 @@
"markdown",
"markdown-extra"
],
"time": "2016-06-20 21:09:53"
"time": "2016-09-14 20:40:20"
},
{
"name": "ezyang/htmlpurifier",
@ -255,16 +255,16 @@
},
{
"name": "yiisoft/yii2-composer",
"version": "dev-master",
"version": "2.0.4",
"source": {
"type": "git",
"url": "https://github.com/yiisoft/yii2-composer.git",
"reference": "e882cc327a6935a41f2e8665b9ef0317f6852d4d"
"reference": "7452fd908a5023b8bb5ea1b123a174ca080de464"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/yiisoft/yii2-composer/zipball/e882cc327a6935a41f2e8665b9ef0317f6852d4d",
"reference": "e882cc327a6935a41f2e8665b9ef0317f6852d4d",
"url": "https://api.github.com/repos/yiisoft/yii2-composer/zipball/7452fd908a5023b8bb5ea1b123a174ca080de464",
"reference": "7452fd908a5023b8bb5ea1b123a174ca080de464",
"shasum": ""
},
"require": {
@ -298,22 +298,22 @@
"extension installer",
"yii2"
],
"time": "2016-06-05 20:34:32"
"time": "2016-02-06 00:49:24"
}
],
"packages-dev": [
{
"name": "cebe/indent",
"version": "dev-master",
"version": "1.0.2",
"source": {
"type": "git",
"url": "https://github.com/cebe/indent.git",
"reference": "0f33ba3cb567726a726e7024072232839a0d7cd0"
"reference": "c500ed74d30ed2d7e085f9cf07f8092d32d70776"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/cebe/indent/zipball/0f33ba3cb567726a726e7024072232839a0d7cd0",
"reference": "0f33ba3cb567726a726e7024072232839a0d7cd0",
"url": "https://api.github.com/repos/cebe/indent/zipball/c500ed74d30ed2d7e085f9cf07f8092d32d70776",
"reference": "c500ed74d30ed2d7e085f9cf07f8092d32d70776",
"shasum": ""
},
"bin": [
@ -327,24 +327,26 @@
"authors": [
{
"name": "Carsten Brandt",
"email": "mail@cebe.cc"
"email": "mail@cebe.cc",
"homepage": "http://cebe.cc/",
"role": "Core framework development"
}
],
"description": "a small tool to convert text file indentation",
"time": "2015-11-22 14:46:59"
"time": "2014-05-23 14:40:08"
},
{
"name": "doctrine/instantiator",
"version": "dev-master",
"version": "1.0.5",
"source": {
"type": "git",
"url": "https://github.com/doctrine/instantiator.git",
"reference": "416fb8ad1d095a87f1d21bc40711843cd122fd4a"
"reference": "8e884e78f9f0eb1329e445619e04456e64d8051d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/doctrine/instantiator/zipball/416fb8ad1d095a87f1d21bc40711843cd122fd4a",
"reference": "416fb8ad1d095a87f1d21bc40711843cd122fd4a",
"url": "https://api.github.com/repos/doctrine/instantiator/zipball/8e884e78f9f0eb1329e445619e04456e64d8051d",
"reference": "8e884e78f9f0eb1329e445619e04456e64d8051d",
"shasum": ""
},
"require": {
@ -385,138 +387,41 @@
"constructor",
"instantiate"
],
"time": "2016-03-31 10:24:22"
},
{
"name": "phpdocumentor/reflection-common",
"version": "dev-master",
"source": {
"type": "git",
"url": "https://github.com/phpDocumentor/ReflectionCommon.git",
"reference": "144c307535e82c8fdcaacbcfc1d6d8eeb896687c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpDocumentor/ReflectionCommon/zipball/144c307535e82c8fdcaacbcfc1d6d8eeb896687c",
"reference": "144c307535e82c8fdcaacbcfc1d6d8eeb896687c",
"shasum": ""
},
"require": {
"php": ">=5.5"
},
"require-dev": {
"phpunit/phpunit": "^4.6"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"phpDocumentor\\Reflection\\": [
"src"
]
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jaap van Otterdijk",
"email": "opensource@ijaap.nl"
}
],
"description": "Common reflection classes used by phpdocumentor to reflect the code structure",
"homepage": "http://www.phpdoc.org",
"keywords": [
"FQSEN",
"phpDocumentor",
"phpdoc",
"reflection",
"static analysis"
],
"time": "2015-12-27 11:43:31"
"time": "2015-06-14 21:17:01"
},
{
"name": "phpdocumentor/reflection-docblock",
"version": "3.1.0",
"version": "2.0.4",
"source": {
"type": "git",
"url": "https://github.com/phpDocumentor/ReflectionDocBlock.git",
"reference": "9270140b940ff02e58ec577c237274e92cd40cdd"
"reference": "d68dbdc53dc358a816f00b300704702b2eaff7b8"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/9270140b940ff02e58ec577c237274e92cd40cdd",
"reference": "9270140b940ff02e58ec577c237274e92cd40cdd",
"url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/d68dbdc53dc358a816f00b300704702b2eaff7b8",
"reference": "d68dbdc53dc358a816f00b300704702b2eaff7b8",
"shasum": ""
},
"require": {
"php": ">=5.5",
"phpdocumentor/reflection-common": "^1.0@dev",
"phpdocumentor/type-resolver": "^0.2.0",
"webmozart/assert": "^1.0"
"php": ">=5.3.3"
},
"require-dev": {
"mockery/mockery": "^0.9.4",
"phpunit/phpunit": "^4.4"
"phpunit/phpunit": "~4.0"
},
"type": "library",
"autoload": {
"psr-4": {
"phpDocumentor\\Reflection\\": [
"src/"
]
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Mike van Riel",
"email": "me@mikevanriel.com"
}
],
"description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.",
"time": "2016-06-10 09:48:41"
},
{
"name": "phpdocumentor/type-resolver",
"version": "0.2",
"source": {
"type": "git",
"url": "https://github.com/phpDocumentor/TypeResolver.git",
"reference": "b39c7a5b194f9ed7bd0dd345c751007a41862443"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/b39c7a5b194f9ed7bd0dd345c751007a41862443",
"reference": "b39c7a5b194f9ed7bd0dd345c751007a41862443",
"shasum": ""
},
"require": {
"php": ">=5.5",
"phpdocumentor/reflection-common": "^1.0"
},
"require-dev": {
"mockery/mockery": "^0.9.4",
"phpunit/phpunit": "^5.2||^4.8.24"
"suggest": {
"dflydev/markdown": "~1.0",
"erusev/parsedown": "~1.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
"dev-master": "2.0.x-dev"
}
},
"autoload": {
"psr-4": {
"phpDocumentor\\Reflection\\": [
"psr-0": {
"phpDocumentor": [
"src/"
]
}
@ -528,23 +433,23 @@
"authors": [
{
"name": "Mike van Riel",
"email": "me@mikevanriel.com"
"email": "mike.vanriel@naenius.com"
}
],
"time": "2016-06-10 07:14:17"
"time": "2015-02-03 12:10:50"
},
{
"name": "phpspec/prophecy",
"version": "dev-master",
"version": "v1.6.1",
"source": {
"type": "git",
"url": "https://github.com/phpspec/prophecy.git",
"reference": "d883566b83ae601a50b38b249e92450dc57cf875"
"reference": "58a8137754bc24b25740d4281399a4a3596058e0"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpspec/prophecy/zipball/d883566b83ae601a50b38b249e92450dc57cf875",
"reference": "d883566b83ae601a50b38b249e92450dc57cf875",
"url": "https://api.github.com/repos/phpspec/prophecy/zipball/58a8137754bc24b25740d4281399a4a3596058e0",
"reference": "58a8137754bc24b25740d4281399a4a3596058e0",
"shasum": ""
},
"require": {
@ -593,30 +498,29 @@
"spy",
"stub"
],
"time": "2016-07-19 16:08:43"
"time": "2016-06-07 08:13:47"
},
{
"name": "phpunit/php-code-coverage",
"version": "dev-master",
"version": "2.2.4",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-code-coverage.git",
"reference": "40103f9b335f1d84daed099f180b9de12ba080e7"
"reference": "eabf68b476ac7d0f73793aada060f1c1a9bf8979"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/40103f9b335f1d84daed099f180b9de12ba080e7",
"reference": "40103f9b335f1d84daed099f180b9de12ba080e7",
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/eabf68b476ac7d0f73793aada060f1c1a9bf8979",
"reference": "eabf68b476ac7d0f73793aada060f1c1a9bf8979",
"shasum": ""
},
"require": {
"php": "^5.6 || ^7.0",
"php": ">=5.3.3",
"phpunit/php-file-iterator": "~1.3",
"phpunit/php-text-template": "~1.2",
"phpunit/php-token-stream": "^1.4.2",
"sebastian/code-unit-reverse-lookup": "~1.0",
"sebastian/environment": "^1.3.2 || ^2.0",
"sebastian/version": "~1.0|~2.0"
"phpunit/php-token-stream": "~1.3",
"sebastian/environment": "^1.3.2",
"sebastian/version": "~1.0"
},
"require-dev": {
"ext-xdebug": ">=2.1.4",
@ -656,11 +560,11 @@
"testing",
"xunit"
],
"time": "2015-08-04 03:45:55"
"time": "2015-10-06 15:47:00"
},
{
"name": "phpunit/php-file-iterator",
"version": "dev-master",
"version": "1.4.1",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-file-iterator.git",
@ -792,16 +696,16 @@
},
{
"name": "phpunit/php-token-stream",
"version": "dev-master",
"version": "1.4.8",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-token-stream.git",
"reference": "cab6c6fefee93d7b7c3a01292a0fe0884ea66644"
"reference": "3144ae21711fb6cac0b1ab4cbe63b75ce3d4e8da"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/cab6c6fefee93d7b7c3a01292a0fe0884ea66644",
"reference": "cab6c6fefee93d7b7c3a01292a0fe0884ea66644",
"url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/3144ae21711fb6cac0b1ab4cbe63b75ce3d4e8da",
"reference": "3144ae21711fb6cac0b1ab4cbe63b75ce3d4e8da",
"shasum": ""
},
"require": {
@ -837,20 +741,20 @@
"keywords": [
"tokenizer"
],
"time": "2015-09-23 14:46:55"
"time": "2015-09-15 10:49:45"
},
{
"name": "phpunit/phpunit",
"version": "4.8.x-dev",
"version": "4.8.27",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git",
"reference": "41433b0d64caa3f2a73e415596dfa73490c262fc"
"reference": "c062dddcb68e44b563f66ee319ddae2b5a322a90"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/41433b0d64caa3f2a73e415596dfa73490c262fc",
"reference": "41433b0d64caa3f2a73e415596dfa73490c262fc",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/c062dddcb68e44b563f66ee319ddae2b5a322a90",
"reference": "c062dddcb68e44b563f66ee319ddae2b5a322a90",
"shasum": ""
},
"require": {
@ -909,11 +813,11 @@
"testing",
"xunit"
],
"time": "2016-08-28 06:58:45"
"time": "2016-07-21 06:48:14"
},
{
"name": "phpunit/phpunit-mock-objects",
"version": "2.3.x-dev",
"version": "2.3.8",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit-mock-objects.git",
@ -968,53 +872,8 @@
"time": "2015-10-02 06:51:40"
},
{
"name": "sebastian/code-unit-reverse-lookup",
"version": "dev-master",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/code-unit-reverse-lookup.git",
"reference": "c36f5e7cfce482fde5bf8d10d41a53591e0198fe"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/c36f5e7cfce482fde5bf8d10d41a53591e0198fe",
"reference": "c36f5e7cfce482fde5bf8d10d41a53591e0198fe",
"shasum": ""
},
"require": {
"php": ">=5.6"
},
"require-dev": {
"phpunit/phpunit": "~5"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sebastian@phpunit.de"
}
],
"description": "Looks up which function or method a line of code belongs to",
"homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/",
"time": "2016-02-13 06:45:14"
},
{
"name": "sebastian/comparator",
"version": "dev-master",
"version": "1.2.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/comparator.git",
@ -1078,7 +937,7 @@
},
{
"name": "sebastian/diff",
"version": "dev-master",
"version": "1.4.1",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/diff.git",
@ -1130,28 +989,28 @@
},
{
"name": "sebastian/environment",
"version": "dev-master",
"version": "1.3.8",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/environment.git",
"reference": "b429478521ee551c5622fec271a2b3bf99de1619"
"reference": "be2c607e43ce4c89ecd60e75c6a85c126e754aea"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/b429478521ee551c5622fec271a2b3bf99de1619",
"reference": "b429478521ee551c5622fec271a2b3bf99de1619",
"url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/be2c607e43ce4c89ecd60e75c6a85c126e754aea",
"reference": "be2c607e43ce4c89ecd60e75c6a85c126e754aea",
"shasum": ""
},
"require": {
"php": "^5.6 || ^7.0"
"php": "^5.3.3 || ^7.0"
},
"require-dev": {
"phpunit/phpunit": "^5.0"
"phpunit/phpunit": "^4.8 || ^5.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.0.x-dev"
"dev-master": "1.3.x-dev"
}
},
"autoload": {
@ -1176,11 +1035,11 @@
"environment",
"hhvm"
],
"time": "2016-08-18 05:48:30"
"time": "2016-08-18 05:49:44"
},
{
"name": "sebastian/exporter",
"version": "dev-master",
"version": "1.2.2",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/exporter.git",
@ -1298,16 +1157,16 @@
},
{
"name": "sebastian/recursion-context",
"version": "dev-master",
"version": "1.0.2",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/recursion-context.git",
"reference": "7ff5b1b3dcc55b8ab8ae61ef99d4730940856ee7"
"reference": "913401df809e99e4f47b27cdd781f4a258d58791"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/7ff5b1b3dcc55b8ab8ae61ef99d4730940856ee7",
"reference": "7ff5b1b3dcc55b8ab8ae61ef99d4730940856ee7",
"url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/913401df809e99e4f47b27cdd781f4a258d58791",
"reference": "913401df809e99e4f47b27cdd781f4a258d58791",
"shasum": ""
},
"require": {
@ -1347,7 +1206,7 @@
],
"description": "Provides functionality to recursively process PHP variables",
"homepage": "http://www.github.com/sebastianbergmann/recursion-context",
"time": "2016-01-28 05:39:29"
"time": "2015-11-11 19:50:13"
},
{
"name": "sebastian/version",
@ -1386,31 +1245,25 @@
},
{
"name": "symfony/yaml",
"version": "dev-master",
"version": "v2.8.13",
"source": {
"type": "git",
"url": "https://github.com/symfony/yaml.git",
"reference": "aa8be2235b5dd4e472424552390609f61996f5ab"
"reference": "396784cd06b91f3db576f248f2402d547a077787"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/yaml/zipball/aa8be2235b5dd4e472424552390609f61996f5ab",
"reference": "aa8be2235b5dd4e472424552390609f61996f5ab",
"url": "https://api.github.com/repos/symfony/yaml/zipball/396784cd06b91f3db576f248f2402d547a077787",
"reference": "396784cd06b91f3db576f248f2402d547a077787",
"shasum": ""
},
"require": {
"php": ">=5.5.9"
},
"require-dev": {
"symfony/console": "~2.8|~3.0"
},
"suggest": {
"symfony/console": "For validating YAML files using the lint command"
"php": ">=5.3.9"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.2-dev"
"dev-master": "2.8-dev"
}
},
"autoload": {
@ -1437,57 +1290,7 @@
],
"description": "Symfony Yaml Component",
"homepage": "https://symfony.com",
"time": "2016-09-02 02:14:06"
},
{
"name": "webmozart/assert",
"version": "dev-master",
"source": {
"type": "git",
"url": "https://github.com/webmozart/assert.git",
"reference": "8444f2ac9f86342665cdae47b6d3ea6e07794456"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/webmozart/assert/zipball/8444f2ac9f86342665cdae47b6d3ea6e07794456",
"reference": "8444f2ac9f86342665cdae47b6d3ea6e07794456",
"shasum": ""
},
"require": {
"php": "^5.3.3 || ^7.0"
},
"require-dev": {
"phpunit/phpunit": "^4.6",
"sebastian/version": "^1.0.1"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.2-dev"
}
},
"autoload": {
"psr-4": {
"Webmozart\\Assert\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Bernhard Schussek",
"email": "bschussek@gmail.com"
}
],
"description": "Assertions to validate method input/output with nice error messages.",
"keywords": [
"assert",
"check",
"validate"
],
"time": "2016-08-18 09:30:53"
"time": "2016-10-21 20:59:10"
}
],
"aliases": [],
@ -1495,7 +1298,7 @@
"stability-flags": {
"bower-asset/jquery": 0
},
"prefer-stable": false,
"prefer-stable": true,
"prefer-lowest": false,
"platform": {
"php": ">=5.4.0",
@ -1503,5 +1306,8 @@
"ext-ctype": "*",
"lib-pcre": "*"
},
"platform-dev": []
"platform-dev": [],
"platform-overrides": {
"php": "5.4"
}
}

5
docs/documentation_style_guide.md

@ -50,6 +50,11 @@ containing the translations. The following shows an example for German:
* Yii 2.0 or Yii 2 (not Yii2 or Yii2.0)
* Each "page" of the guide is referred to as a "section".
* References to Code objects:
- Refer to classes using the full namespace: `yii\base\Model`
- Refer to class properties using the static syntax even if they are not static: `yii\base\Model::$validators`
- Refer to class methods using the static syntax even if they are not static and include parenthesis to make it clear, that it is a method: `yii\base\Model::validate()`
- references to code objects should be writting in `[[]]` to generate links to the API documentation. E.g. `[[yii\base\Model]]`, `[[yii\base\Model::$validators]]`, or `[[yii\base\Model::validate()]]`.
## Capitalizations

2
docs/guide-es/caching-http.md

@ -28,7 +28,7 @@ la página. El formato de la función de llamada de retorno debe ser el siguient
/**
* @param Action $action el objeto acción que se está controlando actualmente
* @param array $params el valor de la propiedad "params"
* @return integer un sello de tiempo UNIX que representa el tiempo de modificación de la página
* @return int un sello de tiempo UNIX que representa el tiempo de modificación de la página
*/
function ($action, $params)
```

85
docs/guide-es/input-multiple-models.md

@ -0,0 +1,85 @@
Obtención de datos para los modelos de múltiples
================================
Cuando se trata de algunos datos complejos, es posible que puede que tenga que utilizar varios modelos diferentes para recopilar
la entrada del usuario. Por ejemplo, suponiendo que la información de inicio de sesión del usuario se almacena en la tabla `user`,
mientras que el perfil de usuario la información se almacena en la tabla `Profile`, es posible que desee para recoger los datos
de entrada sobre un usuario a través de un modelo `User` y un modelo `Profile`. Con el modelo de Yii y apoyo formulario,
puede solucionar este problema de una manera que no es mucho diferente de la manipulación de un solo modelo.
En lo que sigue, vamos a mostrar cómo se puede crear un formulario que permitirá recoger datos tanto para los modelos `User` y
`Profile`.
En primer lugar, la acción del controlador para la recogida de los datos del usuario y del perfil se puede escribir de la
siguiente manera,
```php
namespace app\controllers;
use Yii;
use yii\base\Model;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use app\models\User;
use app\models\Profile;
class UserController extends Controller
{
public function actionUpdate($id)
{
$user = User::findOne($id);
if (!$user) {
throw new NotFoundHttpException("The user was not found.");
}
$profile = Profile::findOne($user->profile_id);
if (!$profile) {
throw new NotFoundHttpException("The user has no profile.");
}
$user->scenario = 'update';
$profile->scenario = 'update';
if ($user->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post())) {
$isValid = $user->validate();
$isValid = $profile->validate() && $isValid;
if ($isValid) {
$user->save(false);
$profile->save(false);
return $this->redirect(['user/view', 'id' => $id]);
}
}
return $this->render('update', [
'user' => $user,
'profile' => $profile,
]);
}
}
```
En la acción `update`, primero cargamos los modelos `User` y `Profile` que se actualicen desde la base de datos. Luego llamamos
[[yii\base\Model::load()]] para llenar estos dos modelos con la entrada del usuario. Si tiene éxito, se validará
los dos modelos y guardarlos. De lo contrario vamos a renderizar la vista `update` que tiene el siguiente contenido:
```php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
$form = ActiveForm::begin([
'id' => 'user-update-form',
'options' => ['class' => 'form-horizontal'],
]) ?>
<?= $form->field($user, 'username') ?>
...other input fields...
<?= $form->field($profile, 'website') ?>
<?= Html::submitButton('Update', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end() ?>
```
Como se puede ver, en el `update` vista que haría que los campos de entrada utilizando dos modelos `User` y `Profile`.

2
docs/guide-es/input-validation.md

@ -176,7 +176,7 @@ La propiedad [[yii\validators\Validator::when|when]] toma un método invocable P
/**
* @param Model $model el modelo siendo validado
* @param string $attribute al atributo siendo validado
* @return boolean si la regla debe ser aplicada o no
* @return bool si la regla debe ser aplicada o no
*/
function ($model, $attribute)
```

4
docs/guide-es/rest-controllers.md

@ -143,6 +143,10 @@ public function checkAccess($action, $model = null, $params = [])
{
// check if the user can access $action and $model
// throw ForbiddenHttpException if access should be denied
if ($action === 'update' || $action === 'delete') {
if ($model->author_id !== \Yii::$app->user->id)
throw new \yii\web\ForbiddenHttpException(sprintf('You can only %s articles that you\'ve created.', $action));
}
}
```

4
docs/guide-es/security-authorization.md

@ -362,10 +362,10 @@ class AuthorRule extends Rule
public $name = 'isAuthor';
/**
* @param string|integer $user el ID de usuario.
* @param string|int $user el ID de usuario.
* @param Item $item el rol o permiso asociado a la regla
* @param array $params parámetros pasados a ManagerInterface::checkAccess().
* @return boolean un valor indicando si la regla permite al rol o permiso con el que está asociado.
* @return bool un valor indicando si la regla permite al rol o permiso con el que está asociado.
*/
public function execute($user, $item, $params)
{

2
docs/guide-fr/input-validation.md

@ -145,7 +145,7 @@ La propriété [[yii\validators\Validator::when|when]] accepte une fonction de r
/**
* @param Model $model le modèle en cours de validation
* @param string $attribute l'attribut en cours de validation
* @return boolean `true` si la règle doit être appliqué, `false` si non
* @return bool `true` si la règle doit être appliqué, `false` si non
*/
function ($model, $attribute)
```

80
docs/guide-fr/output-client-scripts.md

@ -0,0 +1,80 @@
Travail avec des scripts clients
===================================
> Note: cette section est encore en développement.
### Enregistrement des scripts
Avec l'objet [[yii\web\View]] vous êtes en mesure d'enregistrer des scripts. Il existe deux méthodes dédiées pour cela :
[[yii\web\View::registerJs()|registerJs()]] pour les scripts en ligne et [[yii\web\View::registerJsFile()|registerJsFile()]] pour les scripts externes.
Les scripts en ligne sont utiles pour la configuration et le code généré dynamiquement. La méthode pour les ajouter est la suivante :
```php
$this->registerJs("var options = ".json_encode($options).";", View::POS_END, 'my-options');
```
Le premier argument est le code JS réel à insérer dans la page. Le deuxième argument détermine à quel endroit le script doit être inséré dans la page. Les valeurs possibles sont :
- [[yii\web\View::POS_HEAD|View::POS_HEAD]] pour le placer dans la section d'entête (`<head></head>`).
- [[yii\web\View::POS_BEGIN|View::POS_BEGIN]] pour le placer juste après la balise d'ouverture du corps de la page (`<body>`).
- [[yii\web\View::POS_END|View::POS_END]] pour le placer juste avant la balise de fermeture du corps de la page (`</body>`).
- [[yii\web\View::POS_READY|View::POS_READY]] pour l'exéuter sur l'événement « document `ready` ». Cela enregistre [[yii\web\JqueryAsset|jQuery]] automatiquement.
- [[yii\web\View::POS_LOAD|View::POS_LOAD]] pour l'exécuter sur l'événement « document `load` » . Cela enregistre [[yii\web\JqueryAsset|jQuery]] automatiquement.
Le dernier argument est un identifiant unique du script utilisé pour identifier le bloc de code et remplacer un bloc existant de même identifiant au lieu de simplement l'ajouter. Si vous ne le fournissez pas, le code JS lui-même est utilisé en tant qu'identifiant.
Un script externe peut être ajouté comme expliqué ci-dessous :
```php
$this->registerJsFile('http://example.com/js/main.js', ['depends' => [\yii\web\JqueryAsset::className()]]);
```
Les arguments pour [[yii\web\View::registerJsFile()|registerJsFile()]] sont semblables à ceux utilisés pour [[yii\web\View::registerCssFile()|registerCssFile()]]. Dans l'exemple précédent, nous enregistrons le fichier `main.js` avec une dépendance sur `JqueryAsset`. Cela siginifie que le fichier `main.js` sera ajouté APRÈS `jquery.js`. Sans la spécification de cette dépendance, l'ordre relatif entre `main.js` et `jquery.js` resterait indéfini.
Comme pour [[yii\web\View::registerCssFile()|registerCssFile()]], il est également fortement recommandé que vous utilisiez les [paquets de ressources](structure-assets.md) (asset bundles) pour enregistrer des fichiers JS externes plutôt que d'utiliser [[yii\web\View::registerJsFile()|registerJsFile()]].
### Enregistrement de paquets de ressources
Comme cela a été mentionné plus tôt, il est préférable d'utiliser des paquets de ressources plutôt que d'utiliser CSS et JavaScript directement. Vous pouvez obtenir des détails sur les paquets de ressources dans la section [Ressources](structure-assets.md) de ce guide. Comme lors de l'utilisation des paquets de ressources déjà définis, c'est très simple :
```php
\frontend\assets\AppAsset::register($this);
```
### Enregistrement des CSS
Vous pouvez enregistrer les CSS en utilisant [[yii\web\View::registerCss()|registerCss()]] ou [[yii\web\View::registerCssFile()|registerCssFile()]]. Le premier enregistre un bloc de code CSS tandis que le second enregistre un fichier CSS externe. Par exemple :
```php
$this->registerCss("body { background: #f00; }");
```
Le code ci-dessus provoque l'ajout de ce qui suit à la section « head » :
```html
<style>
body { background: #f00; }
</style>
```
Si vous désirez spécifier des propriétés additionnelles du style balise, passez un tableau des paires nom-valeur en tant que troisième argument. Si vous avez besoin de vous assurer qu'il y a seulement une balise style unique, utilisez un quatrième argument comme cela a été mentionné dans la description des balises méta.
```php
$this->registerCssFile("http://example.com/css/themes/black-and-white.css", [
'depends' => [BootstrapAsset::className()],
'media' => 'print',
], 'css-print-theme');
```
Le code ci-dessus provoque l'ajout d'un lien vers un fichier CSS à la section « head » de la page.
* Le premier argument spécifie le fichier CSS à enregistrer.
* Le deuxième argument spécifie l'attribut HTML pour la balise `<link>` résultant. L'option `depends` fait l'objet d'une interprétation particulière. Elle spécifie de quel paquet de ressources ce fichier dépend. Dans ce cas, le paquet de ressources dont le ficher dépend est [[yii\bootstrap\BootstrapAsset|BootstrapAsset]]. Cela veut dire que le fichier CSS sera ajouté *après* les fichiers CSS contenus dans [[yii\bootstrap\BootstrapAsset|BootstrapAsset]].
* Le dernier argument spécifie un identifiant pour ce fichier CSS. S'il n'est pas fourni, l'URL du fichier CSS est utilisée à sa place.
Il est fortement recommandé que vous utilisiez des [paquets de ressources](structure-assets.md) pour enregistrer des fichers CSS externes plutôt que [[yii\web\View::registerCssFile()|registerCssFile()]]. L'utilisation des paquets de ressources vous permet de combiner et de comprimer plusieurs fichiers CSS, ce qui est souhaitable pour les sites Web à trafic intense.

4
docs/guide-fr/security-authentication.md

@ -55,7 +55,7 @@ class User extends ActiveRecord implements IdentityInterface
/**
* Trouve une identité à partir de l'identifiant donné.
*
* @param string|integer $id l'identifiant à rechercher
* @param string|int $id l'identifiant à rechercher
* @return IdentityInterface|null l'objet identité qui correspond à l'identifiant donné
*/
public static function findIdentity($id)
@ -92,7 +92,7 @@ class User extends ActiveRecord implements IdentityInterface
/**
* @param string $authKey
* @return boolean si la clé d'authentification est valide pour l'utilisateur courant
* @return bool si la clé d'authentification est valide pour l'utilisateur courant
*/
public function validateAuthKey($authKey)
{

4
docs/guide-fr/security-authorization.md

@ -311,10 +311,10 @@ class AuthorRule extends Rule
public $name = 'isAuthor';
/**
* @param string|integer $user l'identifiant de l'utilisateur.
* @param string|int $user l'identifiant de l'utilisateur.
* @param Item $item le rôle ou la permission avec laquelle cette règle est associée
* @param array $params les paramètres passés à ManagerInterface::checkAccess().
* @return boolean une valeur indiquant si la règles autorise le rôle ou la permission qui lui est associé.
* @return bool une valeur indiquant si la règles autorise le rôle ou la permission qui lui est associé.
*/
public function execute($user, $item, $params)
{

2
docs/guide-ja/caching-http.md

@ -23,7 +23,7 @@ HTTP キャッシュ
/**
* @param Action $action 現在扱っているアクションオブジェクト
* @param array $params "params" プロパティの値
* @return integer ページの更新時刻を表す UNIX タイムスタンプ
* @return int ページの更新時刻を表す UNIX タイムスタンプ
*/
function ($action, $params)
```

2
docs/guide-ja/input-validation.md

@ -162,7 +162,7 @@ public function rules()
/**
* @param Model $model 検証されるモデル
* @param string $attribute 検証される属性
* @return boolean 規則が適用されるか否か
* @return bool 規則が適用されるか否か
*/
function ($model, $attribute)
```

4
docs/guide-ja/rest-controllers.md

@ -172,6 +172,10 @@ public function checkAccess($action, $model = null, $params = [])
{
// ユーザが $action と $model に対する権限を持つかどうかをチェック
// アクセスを拒否すべきときは ForbiddenHttpException を投げる
if ($action === 'update' || $action === 'delete') {
if ($model->author_id !== \Yii::$app->user->id)
throw new \yii\web\ForbiddenHttpException(sprintf('You can only %s articles that you\'ve created.', $action));
}
}
```

4
docs/guide-ja/security-authentication.md

@ -63,7 +63,7 @@ class User extends ActiveRecord implements IdentityInterface
/**
* 与えられた ID によってユーザ識別情報を探す
*
* @param string|integer $id 探すための ID
* @param string|int $id 探すための ID
* @return IdentityInterface|null 与えられた ID に合致する Identity オブジェクト
*/
public static function findIdentity($id)
@ -100,7 +100,7 @@ class User extends ActiveRecord implements IdentityInterface
/**
* @param string $authKey
* @return boolean 認証キーが現在のユーザに対して有効か否か
* @return bool 認証キーが現在のユーザに対して有効か否か
*/
public function validateAuthKey($authKey)
{

4
docs/guide-ja/security-authorization.md

@ -363,10 +363,10 @@ class AuthorRule extends Rule
public $name = 'isAuthor';
/**
* @param string|integer $user ユーザ ID
* @param string|int $user ユーザ ID
* @param Item $item この規則が関連付けられているロールまたは許可
* @param array $params ManagerInterface::checkAccess() に渡されたパラメータ
* @return boolean 関連付けられたロールまたは許可を認めるか否かを示す値
* @return bool 関連付けられたロールまたは許可を認めるか否かを示す値
*/
public function execute($user, $item, $params)
{

2
docs/guide-pl/caching-http.md

@ -26,7 +26,7 @@ typu PHP callable i zwracać uniksowy znacznik czasu informujący o czasie modyf
/**
* @param Action $action aktualnie przetwarzany obiekt akcji
* @param array $params wartość właściwości "params"
* @return integer uniksowy znacznik czasu modyfikacji strony
* @return int uniksowy znacznik czasu modyfikacji strony
*/
function ($action, $params)
```

131
docs/guide-pl/concept-aliases.md

@ -0,0 +1,131 @@
Aliasy
======
Aliasy używane są do reprezentowania ścieżek do plików lub adresów URL i pozwalają uniknąć konieczności wielokrotnego definiowania ich
w kodzie aplikacji. Alias musi zaczynać się od znaku `@`, dla odróżnienia od zwykłej ścieżki i adresu URL. W przypadku zdefiniowania
aliasu bez tego znaku, będzie on automatycznie dodany na początku.
Yii korzysta z wielu predefiniowanych aliasów. Dla przykładu, alias `@yii` reprezentuje ścieżkę instalacji frameworka, a `@web` bazowy
adres URL aktualnie uruchomionej aplikacji Web.
Definiowanie aliasów <span id="defining-aliases"></span>
--------------------
Możesz zdefiniować alias do ścieżki pliku lub adresu URL wywołując [[Yii::setAlias()]]:
```php
// alias do ścieżki pliku
Yii::setAlias('@foo', '/path/to/foo');
// alias do adresu URL
Yii::setAlias('@bar', 'http://www.example.com');
```
> Note: *nie* jest konieczne, aby aliasowana ścieżka pliku lub URL wskazywał istniejący plik lub zasób.
Mając już zdefiniowany alias, możesz rozbudować go, tworząc nowy alias (bez konieczności wywołania [[Yii::setAlias()]]), dodając
ukośnik `/` i kolejne segmenty ścieżki. Aliasy zdefiniowane za pomocą [[Yii::setAlias()]] nazywane są *bazowymi aliasami*, a te, które
je rozbudowują *aliasami pochodnymi*. Dla przykładu, `@foo` jest aliasem bazowym, a `@foo/bar/file.php` pochodnym.
Możesz definiować aliasy używając innych aliasów (zarówno bazowych, jak i pochodnych):
```php
Yii::setAlias('@foobar', '@foo/bar');
```
Aliasy bazowe są zwykle definiowane podczas fazy [bootstrappingu](runtime-bootstrapping.md).
Możliwe jest wywołanie [[Yii::setAlias()]] już w [skrypcie wejściowym](structure-entry-scripts.md).
[Aplikacja](structure-applications.md) dla wygody deweloperów posiada właściwość `aliases`, którą można zmodyfikować
w [konfiguracji](concept-configurations.md):
```php
return [
// ...
'aliases' => [
'@foo' => '/path/to/foo',
'@bar' => 'http://www.example.com',
],
];
```
Rozwiązywanie aliasów <span id="resolving-aliases"></span>
---------------------
Możesz wywołać [[Yii::getAlias()]], aby rozwiązać alias, czyli zamienić go na ścieżkę pliku lub adres URL, który reprezentuje.
Dotyczy to zarówno bazowych aliasów, jak i pochodnych:
```php
echo Yii::getAlias('@foo'); // wyświetla: /path/to/foo
echo Yii::getAlias('@bar'); // wyświetla: http://www.example.com
echo Yii::getAlias('@foo/bar/file.php'); // wyświetla: /path/to/foo/bar/file.php
```
Ścieżka/URL reprezentowany przez pochodny alias jest ustalany poprzez zamianę części z bazowym aliasem na jego rozwiązaną
reprezentację.
> Note: Metoda [[Yii::getAlias()]] nie sprawdza, czy reprezentowana ścieżka/URL wskazuje na istniejący plik lub zasób.
Alias bazowy może również zawierać ukośnik `/`. Metoda [[Yii::getAlias()]] potrafi określić, która część aliasu jest aliasem bazowym
i prawidłowo określić odpowiadającą mu ścieżkę pliku lub URL:
```php
Yii::setAlias('@foo', '/path/to/foo');
Yii::setAlias('@foo/bar', '/path2/bar');
Yii::getAlias('@foo/test/file.php'); // wyświetla: /path/to/foo/test/file.php
Yii::getAlias('@foo/bar/file.php'); // wyświetla: /path2/bar/file.php
```
Gdyby `@foo/bar` nie był zdefiniowany jako bazowy alias, ostatnia instrukcja wyświetliłaby `/path/to/foo/bar/file.php`.
Korzystanie z aliasów <span id="using-aliases"></span>
---------------------
Aliasy są rozwiązywane automatycznie w wielu miejscach w Yii bez konieczności wywołania bezpośrednio metody [[Yii::getAlias()]].
Przykładowo, [[yii\caching\FileCache::cachePath]] akceptuje zarówno ścieżkę pliku, jak i alias ją reprezentujący, odróżniając je
od siebie dzięki prefiksowi `@`.
```php
use yii\caching\FileCache;
$cache = new FileCache([
'cachePath' => '@runtime/cache',
]);
```
Aby sprawdzić, czy dana właściwość lub parametr metody wspierają użycie aliasów, zapoznaj się z dokumentacją API.
Predefiniowane aliasy <span id="predefined-aliases"></span>
---------------------
Yii predefiniuje zestaw aliasów do łatwego wskazywania często używanych ścieżek plików i adresów URL:
- `@yii`, folder, w którym znajduje się plik `BaseYii.php` (nazywany także folderem frameworka).
- `@app`, [[yii\base\Application::basePath|bazowa ścieżka]] aktualnie używanej aplikacji.
- `@runtime`, [[yii\base\Application::runtimePath|ścieżka cyklu życia]] aktualnie używanej aplikacji. Domyślnie wskazuje na
`@app/runtime`.
- `@webroot`, folder bazowy Web aktualnie używanej aplikacji Web. Określany jest jako lokalizacja folderu zawierającego
[skrypt wejścia](structure-entry-scripts.md).
- `@web`, bazowy adres URL aktualnie używanej aplikacji Web. Wskazuje na tą samą wartość co [[yii\web\Request::baseUrl]].
- `@vendor`, [[yii\base\Application::vendorPath|folder pakietów composera]]. Domyślnie wskazuje na `@app/vendor`.
- `@bower`, bazowy folder zawierający [pakiety bowera](http://bower.io/). Domyślnie wskazuje na `@vendor/bower`.
- `@npm`, bazowy folder zawierający [pakiety npm](https://www.npmjs.org/). Domyślnie wskazuje na `@vendor/npm`.
Alias `@yii` jest definiowany poprzez dołączenie pliku `Yii.php` w [skrypcie wejścia](structure-entry-scripts.md).
Pozostałe aliasy są definiowane w konstruktorze aplikacji podczas ładowania [konfiguracji](concept-configurations.md).
Aliasy rozszerzeń <span id="extension-aliases"></span>
-----------------
Instalacja [rozszerzenia](structure-extensions.md) za pomocą composera automatycznie definiuje dla niego alias.
Każdy z takich aliasów jest nazwany zgodnie z bazową przestrzenią nazw rozszerzenia określonej w swoim pliku `composer.json`
i reprezentuje bazowy folder pakietu. Dla przykładu, instalując rozszerzenie `yiisoft/yii2-jui` automatycznie uzyskasz alias
`@yii/jui` zdefiniowany podczas fazy [bootstrappingu](runtime-bootstrapping.md), będący odpowiednikiem wywołania:
```php
Yii::setAlias('@yii/jui', 'VendorPath/yiisoft/yii2-jui');
```

89
docs/guide-pl/concept-autoloading.md

@ -0,0 +1,89 @@
Autoładowanie klas
==================
Yii opiera się na [mechanizmie automatycznego ładowania klas](http://www.php.net/manual/pl/language.oop5.autoload.php) służącym do
zlokalizowania i dołączenia wszystkich wymaganych plików klas. Wbudowany wysoce wydajny autoloader klas, zgodny ze
[standardem PSR-4](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md), jest instalowany po załączeniu
pliku `Yii.php`.
> Note: Dla uproszczenia opisów, w tej sekcji zostanie omówione jedynie autoładowanie klas. Należy mieć jednak na uwadze, że poniższe
informacje odnoszą się również do autoładowania interfejsów i traitów.
Korzystanie z autoloadera Yii <span id="using-yii-autoloader"></span>
-----------------------------
Aby skorzystać z autoloadera klas Yii, powinieneś przestrzegać dwóch prostych zasad tworzenia i nazywania własnych klas:
* Każda klasa musi znajdować się w [przestrzeni nazw](http://php.net/manual/pl/language.namespaces.php) (np. `foo\bar\MyClass`)
* Każda klasa musi być zapisana jako oddzielny plik, do którego ścieżka określona jest poniższym algorytmem:
```php
// $className jest w pełni uściśloną nazwą klasy bez początkowego odwrotnego ukośnika
$classFile = Yii::getAlias('@' . str_replace('\\', '/', $className) . '.php');
```
Przykładowo, jeśli nazwa klasy i przestrzeń nazw to `foo\bar\MyClass`, odpowiadającym ścieżce pliku klasy [aliasem](concept-aliases.md)
jest `@foo/bar/MyClass.php`. Aby ten alias mógł być przetłumaczony na ścieżkę pliku, `@foo` lub `@foo/bar` musi być
[aliasem bazowym](concept-aliases.md#defining-aliases).
Używając [podstawowego szablonu projektu](start-installation.md), możesz umieścić swoje klasy w bazowej przestrzeni nazw `app`, dzięki
czemu mogą być autoładowane przez Yii bez potrzeby definiowania nowego aliasu. Dzieje się tak dzięki temu, że `@app` jest
[predefiniowanym aliasem](concept-aliases.md#predefined-aliases) i klasa `app\components\MyClass` może być odszukana w pliku
`AppBasePath/components/MyClass.php`, zgodnie z opisanym algorytmem.
W [zaawansowanym szablonie projektu](https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/README.md) każdy poziom
aplikacji posiada swój własny bazowy alias. Dla przykładu, front-end określony jest przez bazowy alias `@frontend`, a back-end -
`@backend`. Dzięki temu możesz umieścić klasy front-endu w przestrzeni nazw `frontend`, a klasy back-endu w przestrzeni nazw `backend`.
Wszystkie te klasy będą automatycznie załadowane przez autoloader Yii.
Mapa klas <span id="class-map"></span>
---------
Autoloader klas Yii wspiera mechanizm *mapy klas*, która mapuje nazwy klas do odpowiadających im ścieżek plików.
Kiedy autoloader ładuje klasę, najpierw sprawdza czy klasa znajduje się w mapie. Jeśli tak, odpowiadająca nazwie ścieżka pliku zostanie
dołączona od razu, bez dalszej weryfikacji, co jest powodem, dla którego autoładowanie klas jest błyskawiczne. Wszystkie podstawowe
klasy Yii są autoładowane właśnie w ten sposób.
Możesz dodać klasę do mapy klas, przechowywanej w `Yii::$classMap`, za pomocą instrukcji:
```php
Yii::$classMap['foo\bar\MyClass'] = 'path/to/MyClass.php';
```
Do określenia ścieżek plików klas można użyć [aliasów](concept-aliases.md). Zapisywanie mapy klas powinno odbywać się w procesie
[bootstrappingu](runtime-bootstrapping.md), aby mapa była gotowa zanim rozpocznie się korzystanie z klas.
Korzystanie z innych autoloaderów <span id="using-other-autoloaders"></span>
---------------------------------
Ponieważ Yii opiera się głównie na composerze, jako menedżerze pakietów zależności, zalecane jest również zainstalowanie autoloadera
composera. Jeśli używasz zewnętrznych bibliotek, korzystających z własnych autoloaderów, powinieneś również je zainstalować.
Używając autoloadera Yii razem z innymi autoloaderami, powinieneś dołączyć plik `Yii.php` *po* wszystkich pozostałych autoloaderach. Dzięki temu
autoloader Yii jako pierwszy odpowie na żądanie autoładowania klasy. Dla przykładu, poniższy kod znajduje się
w [skrypcie wejściowym](structure-entry-scripts.md) [podstawowego szablonu projektu](start-installation.md). Pierwsza linia jest
instrukcją instalacji autoloadera composera, a druga instaluje autoloader Yii:
```php
require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
```
Możesz używać jedynie autoloadera composera bez autoloadera Yii, ale wydajność autoładowania klas może być wtedy obniżona i, dodatkowo,
musisz przestrzegać zasad ustalonych przez composera, aby Twoje klasy mogły być autoładowane.
> Info: Jeśli nie chcesz korzystać z autoloadera Yii, musisz stworzyć swoją własną wersję pliku `Yii.php` i dołączyć ją
w [skrypcie wejściowym](structure-entry-scripts.md).
Autoładowanie klas rozszerzeń <span id="autoloading-extension-classes"></span>
-----------------------------
Autoloader Yii potrafi również automatycznie ładować klasy [rozszerzeń](structure-extensions.md). Jedynym wymaganiem ze strony
rozszerzenia jest prawidłowy zapis sekcji `autoload` w swoim pliku `composer.json`. Szczegóły na temat specyfikacji `autoload` znajdują
się [dokumentacji composera](https://getcomposer.org/doc/04-schema.md#autoload).
Jeśli nie korzystasz z autoloadera Yii, autoloader composera załaduje dla Ciebie automatycznie klasy rozszerzeń.

2
docs/guide-pl/input-validation.md

@ -166,7 +166,7 @@ Właściwość [[yii\validators\Validator::when|when]] pobiera możliwą do wywo
/**
* @param Model $model model, który podlega walidacji
* @param string $attribute atrybut, który podlega walidacji
* @return boolean wartość zwrotna; czy reguła powinna zostać zastosowana
* @return bool wartość zwrotna; czy reguła powinna zostać zastosowana
*/
function ($model, $attribute)
```

4
docs/guide-pl/start-databases.md

@ -44,7 +44,7 @@ INSERT INTO `country` VALUES ('RU','Russia',146519759);
INSERT INTO `country` VALUES ('US','United States',322976000);
```
W tym miejscu masz już utworzoną bazę danych o nazwie `yii2basic`, posiadającą tabelę `country` z trzeba kolumnami. Tabela zawiera 10 wierszy danych.
W tym miejscu masz już utworzoną bazę danych o nazwie `yii2basic`, posiadającą tabelę `country` z trzema kolumnami. Tabela zawiera 10 wierszy danych.
Konfiguracja połączenia z bazą danych <span id="configuring-db-connection"></span>
---------------------------
@ -69,7 +69,7 @@ return [
Plik `config/db.php` jest typowym narzędziem [konfiguracyjnym](concept-configurations.md) opartym na plikach.
Ten szczególny plik konfiguracyjny określa parametry potrzebne do utworzenia oraz zainicjalizowania instancji [[yii\db\Connection|Connection]], dzięki czemu będziesz mógł wywoływać
komendy SQL dp swojej bazy przez aplikację.
komendy SQL do swojej bazy przez aplikację.
Powyższa konfiguracja może być dostępna z poziomu kodu aplikacji używając wyrażenia `Yii::$app->db`.

2
docs/guide-pt-BR/caching-http.md

@ -21,7 +21,7 @@ Você pode configurar a propriedade [[yii\filters\HttpCache::lastModified]] para
/**
* @param Action $action O Objeto da ação que está sendo manipulada no momento
* @param array $params o valor da propriedade "params"
* @return integer uma data(timestamp) UNIX timestamp representando o tempo da
* @return int uma data(timestamp) UNIX timestamp representando o tempo da
* última modificação na página
*/
function ($action, $params)

4
docs/guide-pt-BR/rest-controllers.md

@ -120,6 +120,10 @@ public function checkAccess($action, $model = null, $params = [])
{
// verifica se o usuário pode acessar $action and $model
// lança a ForbiddenHttpException se o acesso for negado
if ($action === 'update' || $action === 'delete') {
if ($model->author_id !== \Yii::$app->user->id)
throw new \yii\web\ForbiddenHttpException(sprintf('You can only %s articles that you\'ve created.', $action));
}
}
```

4
docs/guide-pt-BR/security-authentication.md

@ -57,7 +57,7 @@ class User extends ActiveRecord implements IdentityInterface
/**
* Localiza uma identidade pelo ID informado
*
* @param string|integer $id o ID a ser localizado
* @param string|int $id o ID a ser localizado
* @return IdentityInterface|null o objeto da identidade que corresponde ao ID informado
*/
public static function findIdentity($id)
@ -94,7 +94,7 @@ class User extends ActiveRecord implements IdentityInterface
/**
* @param string $authKey
* @return boolean se a chave de autenticação do usuário atual for válida
* @return bool se a chave de autenticação do usuário atual for válida
*/
public function validateAuthKey($authKey)
{

4
docs/guide-pt-BR/security-authorization.md

@ -314,10 +314,10 @@ class AuthorRule extends Rule
public $name = 'isAuthor';
/**
* @param string|integer $user the user ID.
* @param string|int $user the user ID.
* @param Item $item the role or permission that this rule is associated with
* @param array $params parameters passed to ManagerInterface::checkAccess().
* @return boolean a value indicating whether the rule permits the role or permission it is associated with.
* @return bool a value indicating whether the rule permits the role or permission it is associated with.
*/
public function execute($user, $item, $params)
{

2
docs/guide-ru/README.md

@ -80,7 +80,7 @@ All Rights Reserved.
* [Миграции](db-migrations.md) - Контроль версий схемы данных при работе в команде.
* [Sphinx](https://github.com/yiisoft/yii2-sphinx/blob/master/docs/guide/README.md)
* [Redis](https://github.com/yiisoft/yii2-redis/blob/master/docs/guide/README.md)
* [MongoDB](https://github.com/yiisoft/yii2-mongodb/blob/master/docs/guide/README.md)
* [MongoDB](https://github.com/yiisoft/yii2-mongodb/blob/master/docs/guide-ru/README.md)
* [ElasticSearch](https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/README.md)

2
docs/guide-ru/caching-http.md

@ -20,7 +20,7 @@ HTTP кэширование
/**
* @param Action $action объект действия, которое в настоящее время обрабатывается
* @param array $params значение свойства "params"
* @return integer временная метка UNIX timestamp, возвращающая время последнего изменения страницы
* @return int временная метка UNIX timestamp, возвращающая время последнего изменения страницы
*/
function ($action, $params)
```

2
docs/guide-ru/caching-page.md

@ -31,7 +31,7 @@ public function behaviors()
и варьируется в зависимости от текущего языка приложения. Кэшированная страница должна быть признана просроченной, если
общее количество постов изменилось.
Кэширование страниц очень похоже на [кэширования фрагментов](caching-fragment.md). В обоих случаях поддерживаются параметры
Кэширование страниц очень похоже на [кэширование фрагментов](caching-fragment.md). В обоих случаях поддерживаются параметры
`duration` (продолжительность), `dependencies` (зависимости), `variations` (вариации), и `enabled` (включен). Главное
отличие заключается в том, что кэширование страницы реализовано в виде [фильтра действия](structure-filters.md),
а кэширование фрагмента в виде [виджета](structure-widgets.md).

2
docs/guide-ru/db-active-record.md

@ -475,7 +475,7 @@ $customer->loadDefaultValues();
Однако, механизм приведения типов имеет несколько ограничений:
* Числа с плавающей точкой не будут обработаны, а будут представленны как строки, в противном случае они могут потерять точность.
* Ковертация целх чисел завист от разрядности используемой операциооной системы. В частности: значения колонок, объявленных
* Ковертация целых чисел завист от разрядности используемой операциооной системы. В частности: значения колонок, объявленных
как 'unsigned integer' или 'big integer' будут приведены к целому типу PHP только на 64-х разрядных системах, в то время
как на 32-х разрядных - они будут представленны как строки.

224
docs/guide-ru/db-migrations.md

@ -39,7 +39,7 @@ Yii предоставляет набор инструментов для миг
yii migrate/create <name>
```
Требуемый аргумент `name` даёт краткое описание новой миграции. Например, если миграция о создании новой таблицы с именем *news*, Вы можете использовать имя `create_news_table` и выполнить следующую команду:
Требуемый аргумент `name` даёт краткое описание новой миграции. Например, если миграция о создании новой таблицы с именем *news*, вы можете использовать имя `create_news_table` и выполнить следующую команду:
```
yii migrate/create create_news_table
@ -86,7 +86,7 @@ class m150101_185401_create_news_table extends Migration
* `<YYMMDD_HHMMSS>` относится к UTC дате-времени при котором команда создания миграции была выполнена.
* `<Name>` это тоже самое значение аргумента `name` которое вы прописываете в команду.
В классе миграции, Вы должны прописать код в методе `up()` когда делаете изменения в структуре базы данных.
В классе миграции, вы должны прописать код в методе `up()` когда делаете изменения в структуре базы данных.
Вы также можете написать код в методе `down()`, чтобы отменить сделанные `up()` изменения. Метод `up` вызывается для обновления базы данных с помощью данной миграции, а метод `down()` вызывается для отката изменений базы данных.
Следующий код показывает как можно реализовать класс миграции, чтобы создать таблицу `news`:
@ -245,6 +245,125 @@ class m150811_220037_create_post_table extends Migration
> Note: первичный ключ добавляется автоматически и по умолчанию называется `id`. Если вам необходимо другое имя,
> указать его можно через опцию `--fields=name:primaryKey`.
### Внешние ключи
Начиная с версии 2.0.8, генератор поддерживает создание внешних ключей через ключевое слово `foreignKey`.
```php
yii migrate/create create_post_table --fields="author_id:integer:notNull:foreignKey(user),category_id:integer:defaultValue(1):foreignKey,title:string,body:text"
```
сгенерирует
```php
/**
* Handles the creation for table `post`.
* Has foreign keys to the tables:
*
* - `user`
* - `category`
*/
class m160328_040430_create_post_table extends Migration
{
/**
* @inheritdoc
*/
public function up()
{
$this->createTable('post', [
'id' => $this->primaryKey(),
'author_id' => $this->integer()->notNull(),
'category_id' => $this->integer()->defaultValue(1),
'title' => $this->string(),
'body' => $this->text(),
]);
// creates index for column `author_id`
$this->createIndex(
'idx-post-author_id',
'post',
'author_id'
);
// add foreign key for table `user`
$this->addForeignKey(
'fk-post-author_id',
'post',
'author_id',
'user',
'id',
'CASCADE'
);
// creates index for column `category_id`
$this->createIndex(
'idx-post-category_id',
'post',
'category_id'
);
// add foreign key for table `category`
$this->addForeignKey(
'fk-post-category_id',
'post',
'category_id',
'category',
'id',
'CASCADE'
);
}
/**
* @inheritdoc
*/
public function down()
{
// drops foreign key for table `user`
$this->dropForeignKey(
'fk-post-author_id',
'post'
);
// drops index for column `author_id`
$this->dropIndex(
'idx-post-author_id',
'post'
);
// drops foreign key for table `category`
$this->dropForeignKey(
'fk-post-category_id',
'post'
);
// drops index for column `category_id`
$this->dropIndex(
'idx-post-category_id',
'post'
);
$this->dropTable('post');
}
}
```
Положение ключевого слова `foreignKey` в описании поля не изменяет сгенерированный код. Это значит, что:
- `author_id:integer:notNull:foreignKey(user)`
- `author_id:integer:foreignKey(user):notNull`
- `author_id:foreignKey(user):integer:notNull`
Генерируют один и тот же код.
Ключевое слово `foreignKey` может принимать в скобках параметр, который будет использован в качестве имени таблицы для внешнего ключа. Если параметр не был передан, то имя таблицы будет извлечено из названия поля.
В приведенном выше примере `author_id:integer:notNull:foreignKey(user)` будет генерировать поле `author_id` с внешним ключом на таблицу `user`, а `category_id:integer:defaultValue(1):foreignKey` сгенерирует поле `author_id` с внешним ключом на таблицу `category`.
Начиная с версии 2.0.11, ключевое слово `foreignKey` может принимать второй параметр, который следует указывать через пробел.
Этот параметр будет использован в качестве имени поля внешнего ключа.
В случае, если второй параметр не будет передан, то поле для внешнего ключа будет извлечено из схемы таблицы.
Тем не менее, это справедливо только в тех случаях, когда таблица имеется в базе данных, первичный ключ задан и не является составным.
В иных случаях будет использоваться имя по умолчанию `id`.
### Удаление таблицы
@ -336,30 +455,99 @@ yii migrate/create create_junction_table_for_post_and_tag_tables
сгенерирует
```php
class m150811_220037_create_junction_post_and_tag extends Migration
/**
* Handles the creation for table `post_tag`.
* Has foreign keys to the tables:
*
* - `post`
* - `tag`
*/
class m160328_041642_create_junction_table_for_post_and_tag_tables extends Migration
{
/**
* @inheritdoc
*/
public function up()
{
$this->createTable('post_tag', [
'post_id' => $this->integer(),
'tag_id' => $this->integer(),
'PRIMARY KEY(post_id, tag_id)'
'created_at' => $this->dateTime(),
'PRIMARY KEY(post_id, tag_id)',
]);
$this->createIndex('idx-post_tag-post_id', 'post_tag', 'post_id');
$this->createIndex('idx-post_tag-tag_id', 'post_tag', 'tag_id');
$this->addForeignKey('fk-post_tag-post_id', 'post_tag', 'post_id', 'post', 'id', 'CASCADE');
$this->addForeignKey('fk-post_tag-tag_id', 'post_tag', 'tag_id', 'tag', 'id', 'CASCADE');
}
// creates index for column `post_id`
$this->createIndex(
'idx-post_tag-post_id',
'post_tag',
'post_id'
);
// add foreign key for table `post`
$this->addForeignKey(
'fk-post_tag-post_id',
'post_tag',
'post_id',
'post',
'id',
'CASCADE'
);
// creates index for column `tag_id`
$this->createIndex(
'idx-post_tag-tag_id',
'post_tag',
'tag_id'
);
// add foreign key for table `tag`
$this->addForeignKey(
'fk-post_tag-tag_id',
'post_tag',
'tag_id',
'tag',
'id',
'CASCADE'
);
}
/**
* @inheritdoc
*/
public function down()
{
// drops foreign key for table `post`
$this->dropForeignKey(
'fk-post_tag-post_id',
'post_tag'
);
// drops index for column `post_id`
$this->dropIndex(
'idx-post_tag-post_id',
'post_tag'
);
// drops foreign key for table `tag`
$this->dropForeignKey(
'fk-post_tag-tag_id',
'post_tag'
);
// drops index for column `tag_id`
$this->dropIndex(
'idx-post_tag-tag_id',
'post_tag'
);
$this->dropTable('post_tag');
}
}
```
Начиная с версии 2.0.11, имена полей для внешних ключей промежуточной таблицы будут извлечены из объединяемых таблиц.
Тем не менее, это справедливо только в тех случаях, когда таблица имеется в базе данных, первичный ключ задан и не является составным.
В других иных случаях для поля будет сгенерировано значение по умолчанию `id`.
### Транзакции Миграций <span id="transactional-migrations"></span>
@ -445,13 +633,13 @@ class m150101_185401_create_news_table extends Migration
## Применение Миграций <span id="applying-migrations"></span>
Для обновления базы данных до последней структуры, Вы должны применить все новые миграции, используя следующую команду:
Для обновления базы данных до последней структуры, вы должны применить все новые миграции, используя следующую команду:
```
yii migrate
```
Эта команда выведет список всех миграций, которые не применялись до сих пор. Если Вы подтвердите, что Вы хотите применить эти миграций, то этим самым запустите метод `up()` или `safeUp()` в каждом новом классе миграции, один за другим, в порядке их временного значения timestamp.
Эта команда выведет список всех миграций, которые не применялись до сих пор. Если вы подтвердите, что вы хотите применить эти миграций, то этим самым запустите метод `up()` или `safeUp()` в каждом новом классе миграции, один за другим, в порядке их временного значения timestamp.
Для каждой миграции которая была успешно проведена, эта команда будет вставлять строку в таблицу базы данных с именем
`migration` записав успешное проведение миграции. Это позволяет инструменту миграции выявлять какие миграции были применены, а какие - нет.
@ -496,7 +684,7 @@ yii migrate/redo # перезагрузить последнюю прим
yii migrate/redo 3 # перезагрузить 3 последние применённые миграции
```
> Note: Если миграция не является обратимой, Вы не сможете её перезагрузить.
> Note: Если миграция не является обратимой, вы не сможете её перезагрузить.
## Список Миграций <span id="listing-migrations"></span>
@ -598,7 +786,7 @@ return [
## Миграции в Несколько Баз Данных <span id="migrating-multiple-databases"></span>
По умолчанию, миграции применяются для базы данных, указанной в `db` [компоненте приложения](structure-application-components.md).
Если Вы хотите применить миграцию к другой базе данных, Вы можете определить параметр `db` в командной строке как показано ниже,
Если вы хотите применить миграцию к другой базе данных, вы можете определить параметр `db` в командной строке как показано ниже,
```
yii migrate --db=db2
@ -606,7 +794,7 @@ yii migrate --db=db2
Приведенная выше команда применит миграции к базе данных `db2`.
Иногда может случиться так, что Вы захотите применить *некоторые* из миграций к одной базе данных, а некоторые другие к другой базе данных. Для достижения этой цели, при реализации класса миграции, необходимо явно указать идентификатор ID компонента базы данных, который миграция будет использовать, следующим образом:
Иногда может случиться так, что вы захотите применить *некоторые* из миграций к одной базе данных, а некоторые другие к другой базе данных. Для достижения этой цели, при реализации класса миграции, необходимо явно указать идентификатор ID компонента базы данных, который миграция будет использовать, следующим образом:
```php
<?php
@ -627,9 +815,9 @@ class m150101_185401_create_news_table extends Migration
Если у вас есть несколько миграций, которые используют ту же другую базу данных, то рекомендуется создать базовый класс миграций выше кода `init()`. Затем каждый класс миграции может расширяться от этого базового класса.
> Совет: Кроме установки свойства [[yii\db\Migration::db|db]], Вы также можете работать с разными базами данных путем создания нового соединения с конкретной базой данных в классе Вашей миграции. Можно использовать [DAO методы](db-dao.md) с этими соединениями для манипулирования различными базами данных.
> Совет: Кроме установки свойства [[yii\db\Migration::db|db]], вы также можете работать с разными базами данных путем создания нового соединения с конкретной базой данных в классе Вашей миграции. Можно использовать [DAO методы](db-dao.md) с этими соединениями для манипулирования различными базами данных.
Другая стратегия, которую Вы можете выбрать, чтобы перенести (мигрировать) несколько баз данных - это сохранить миграции различных баз данных в разные директории. Затем вы можете перенести эти базы данных в нужные базы следующими командами:
Другая стратегия, которую вы можете выбрать, чтобы перенести (мигрировать) несколько баз данных - это сохранить миграции различных баз данных в разные директории. Затем вы можете перенести эти базы данных в нужные базы следующими командами:
```
yii migrate --migrationPath=@app/migrations/db1 --db=db1

42
docs/guide-ru/input-forms.md

@ -1,16 +1,16 @@
Создание форм
==============
Основной способ использования форм в Yii является использование [[yii\widgets\ActiveForm]]. Этот подход должен быть
Основным способом использования форм в Yii является использование [[yii\widgets\ActiveForm]]. Этот подход должен быть
применён, когда форма основана на модели. Кроме того, имеются дополнительные методы в [[yii\helpers\Html]], которые
используются для добавления кнопок и текстовых подсказок к любой форме.
Форма, которая отображается на стороне клиента, в большинстве случаев, соответствует [модели](structure-models.md).
Модель, в свою очередь, проверяет данные из элементов формы на сервере (посмотрите раздел [Валидация](input-validation.md)
Модель, в свою очередь, проверяет данные из элементов формы на сервере (смотрите раздел [Валидация](input-validation.md)
для более подробных сведений). Когда создаётся форма, основанная на модели, необходимо определить, что же является моделью.
Модель может основываться на классе [Active Record](db-active-record.md), который описывает некоторые данные из базы данных,
или модель может основываться на базовом классе Model (происходит от [[yii\base\Model]]), который позволяет использовать
произвольный набор элементов формы, например, форма входа.
или же на базовом классе Model (происходит от [[yii\base\Model]]), который позволяет использовать
произвольный набор элементов формы (например, форма входа).
В следующем примере показано, как создать модель формы, основанной на базовом классе Model:
@ -55,37 +55,28 @@ $form = ActiveForm::begin([
В вышеизложенном коде, [[yii\widgets\ActiveForm::begin()|ActiveForm::begin()]] не только создаёт экземпляр формы, но
также и знаменует её начало. Весь контент, расположенный между [[yii\widgets\ActiveForm::begin()|ActiveForm::begin()]]
и [[yii\widgets\ActiveForm::end()|ActiveForm::end()]], будет завёрнут в HTML `<form>` тег. Вы можете настроить некоторые
настройки виджета через передачу массива в его `begin` метод, также как и в любом другом виджете. В этом случае, дополнительный
CSS класс и идентификатор ID будет прикреплён к открывающемуся тегу `<form>`. Для просмотра всех доступных настроек,
пожалуйста обратитесь к API документации [[yii\widgets\ActiveForm]].
и [[yii\widgets\ActiveForm::end()|ActiveForm::end()]], будет завёрнут в HTML-тег `<form>`. Вы можете изменить некоторые
настройки виджета через передачу массива в его `begin` метод, также как и в любом другом виджете. В этом случае, дополнительный CSS класс и идентификатор ID будет прикреплён к открывающемуся тегу `<form>`. Для просмотра всех доступных настроек,пожалуйста, обратитесь к API документации [[yii\widgets\ActiveForm]].
Для создания в форме элемента с меткой и любой применимой Javascript валидацией, вызывается [[yii\widgets\ActiveForm::field()|ActiveForm::field()]],
который возвращает экземпляр [[yii\widgets\ActiveField]]. Когда этот метод вызывается непосредственно, то результатом
будет текстовый элемент (`input type="text"`). Для того, чтобы настроить элемент, можно вызвать одни за одним дополнительные
методы [[yii\widgets\ActiveField|ActiveField]]:
Для создания в форме элемента с меткой и любой применимой Javascript валидацией, вызывается [[yii\widgets\ActiveForm::field()|ActiveForm::field()]],который возвращает экземпляр [[yii\widgets\ActiveField]]. Когда этот метод вызывается непосредственно, то результатом будет текстовый элемент (`input type="text"`). Для того, чтобы настроить элемент, можно вызвать один за одним дополнительные методы [[yii\widgets\ActiveField|ActiveField]]:
```php
// элемент формы password
<?= $form->field($model, 'password')->passwordInput() ?>
echo $form->field($model, 'password')->passwordInput();
// добавлена подсказка hint и настроена метка label
<?= $form->field($model, 'username')->textInput()->hint('Пожалуйста, введите имя')->label('Имя') ?>
echo $form->field($model, 'username')->textInput()->hint('Пожалуйста, введите имя')->label('Имя');
// создание HTML5 email элемента
<?= $form->field($model, 'email')->input('email') ?>
echo $form->field($model, 'email')->input('email');
```
Впоследствии будет созданы `<label>`, `<input>` и другие теги в соответствии с [[yii\widgets\ActiveField::$template|template]],
который определён в элементе. Имя элемента формы определяется автоматически из моделей [[yii\base\Model::formName()|form name]]
Впоследствии будут созданы `<label>`, `<input>` и другие теги в соответствии с [[yii\widgets\ActiveField::$template|template]], который определён в элементе. Имя элемента формы определяется автоматически из моделей [[yii\base\Model::formName()|form name]]
и их атрибутов. Например, имя элемента для атрибута `username` в коде, приведённом выше, будет `LoginForm[username]`.
Это правило именования будет учитываться на стороне сервера при получении массива результатов `$_POST['LoginForm']`
для всех элементов формы входа (Login Form).
> Tip: Если в форме только одна модель и вы хотите упростить имена полей ввода, то можете сделать это
> перекрыв метод [[yii\base\Model::formName()|formName()]] модели так, чтобы он возвращал пустую строку.
> Это может пригодиться для получения более красивых URL при филтьтрации моделей
в [GridView](output-data-widgets.md#grid-view).
> Tip: Если в форме только одна модель, и вы хотите упростить имена полей ввода, то можете сделать это, переопределив метод [[yii\base\Model::formName()|formName()]] модели так, чтобы он возвращал пустую строку. Это может пригодиться для получения более красивых URL при фильтрации моделей в [GridView](output-data-widgets.md#grid-view).
Специфический атрибут модели может быть задан через более сложный способ. Например, при загрузке файлов или выборе
Специфический атрибут модели может быть задан более сложным способом. Например, при загрузке файлов или выборе
нескольких значений из списка, в качестве значений атрибуту модели нужно передать массив, для этого к имени можно добавить
`[]`:
@ -101,12 +92,9 @@ echo $form->field($model, 'items[]')->checkboxList(['a' => 'Item A', 'b' => 'Ite
> Имена и идентификаторы форм и их элементов не должны совпадать с элементами форм, такими как `submit`, `length`, или `method`. Конфликты имен могут вызывать трудно диагностируемые ошибки. Подробнее о способах избегания подобных проблем смотрите [DOMLint](http://kangax.github.io/domlint/).
Дополнительные HTML элементы могут быть добавлены к форме используя обычный HTML или методы из класса помощника [[yii\helpers\Html|Html]],
как это было сделано с помощью [[yii\helpers\Html::submitButton()|Html::submitButton()]] в примере, что выше.
Дополнительные HTML элементы можно добавить к форме, используя обычный HTML или методы из класса помощника [[yii\helpers\Html|Html]], как это было сделано с помощью [[yii\helpers\Html::submitButton()|Html::submitButton()]] в примере, приведённом выше.
> Tip: Если вы использует Twitter Bootstrap CSS в своём приложении, то воспользуйтесь
> [[yii\bootstrap\ActiveForm]] вместо [[yii\widgets\ActiveForm]]. Он добавит к ActiveForm дополнительные стили, которые
> сработают в рамках bootstrap CSS.
> Tip: Если вы использует Twitter Bootstrap CSS в своём приложении, то воспользуйтесь [[yii\bootstrap\ActiveForm]] вместо [[yii\widgets\ActiveForm]]. Он добавит к ActiveForm дополнительные стили, которые сработают в рамках bootstrap CSS.
> Tip: для добавления "звёздочки" к обязательным элементам формы воспользуйтесь следующим CSS:
>

2
docs/guide-ru/input-validation.md

@ -162,7 +162,7 @@ public function rules()
/**
* @param Model $model модель используемая для проверки
* @param string $attribute атрибут для проверки
* @return boolean следует ли применять правило
* @return bool следует ли применять правило
*/
function ($model, $attribute)
```

2
docs/guide-ru/output-data-widgets.md

@ -31,6 +31,8 @@ echo DetailView::widget([
[ // name свойство зависимой модели owner
'label' => 'Owner',
'value' => $model->owner->name,
'contentOptions' => ['class' => 'bg-red'], // настройка HTML атрибутов для тега, соответсвующего value
'captionOptions' => ['tooltip' => 'Tooltip'], // настройка HTML атрибутов для тега, соответсвующего label
],
'created_at:datetime', // дата создания в формате datetime
],

4
docs/guide-ru/rest-controllers.md

@ -144,6 +144,10 @@ public function checkAccess($action, $model = null, $params = [])
{
// проверить, имеет ли пользователь доступ к $action и $model
// выбросить ForbiddenHttpException, если доступ следует запретить
if ($action === 'update' || $action === 'delete') {
if ($model->author_id !== \Yii::$app->user->id)
throw new \yii\web\ForbiddenHttpException(sprintf('You can only %s articles that you\'ve created.', $action));
}
}
```

4
docs/guide-ru/security-authentication.md

@ -71,7 +71,7 @@ class User extends ActiveRecord implements IdentityInterface
/**
* Finds an identity by the given ID.
*
* @param string|integer $id the ID to be looked for
* @param string|int $id the ID to be looked for
* @return IdentityInterface|null the identity object that matches the given ID.
*/
public static function findIdentity($id)
@ -108,7 +108,7 @@ class User extends ActiveRecord implements IdentityInterface
/**
* @param string $authKey
* @return boolean if auth key is valid for current user
* @return bool if auth key is valid for current user
*/
public function validateAuthKey($authKey)
{

4
docs/guide-ru/security-authorization.md

@ -358,10 +358,10 @@ class AuthorRule extends Rule
public $name = 'isAuthor';
/**
* @param string|integer $user the user ID.
* @param string|int $user the user ID.
* @param Item $item the role or permission that this rule is associated width.
* @param array $params parameters passed to ManagerInterface::checkAccess().
* @return boolean a value indicating whether the rule permits the role or permission it is associated with.
* @return bool a value indicating whether the rule permits the role or permission it is associated with.
*/
public function execute($user, $item, $params)
{

2
docs/guide-ru/start-databases.md

@ -223,4 +223,4 @@ http://hostname/index.php?r=country%2Findex&page=2
В этом разделе вы научились работать с базой данных. Также вы научились получать и отображать данные с постраничной разбивкой с помощью [[yii\data\Pagination]] и [[yii\widgets\LinkPager]].
В следующем разделе вы научитесь использовать мощный инструмент генерации кода, называемый [Gii](tool-gii.md), чтобы с его помощью быстро осуществлять некоторые часто используемые функции, такие, как операции Create-Read-Update-Delete (CRUD) для работы с данными в таблице базы данных. На самом деле код, который вы только что написали, в Yii может быть полностью сгенерирован автоматически с использованием Gii.
В следующем разделе вы научитесь использовать мощный инструмент генерации кода, называемый [Gii](start-gii.md), чтобы с его помощью быстро осуществлять некоторые часто используемые функции, такие, как операции Create-Read-Update-Delete (CRUD) для работы с данными в таблице базы данных. На самом деле код, который вы только что написали, в Yii может быть полностью сгенерирован автоматически с использованием Gii.

2
docs/guide-zh-CN/caching-http.md

@ -20,7 +20,7 @@ HTTP 缓存
/**
* @param Action $action 当前处理的操作对象
* @param array $params “params” 属性的值
* @return integer 页面修改时的 Unix 时间戳
* @return int 页面修改时的 Unix 时间戳
*/
function ($action, $params)
```

2
docs/guide-zh-CN/input-validation.md

@ -126,7 +126,7 @@ public function rules()
/**
* @param Model $model 要验证的模型对象
* @param string $attribute 待测特性名
* @return boolean 返回是否启用该规则
* @return bool 返回是否启用该规则
*/
function ($model, $attribute)
```

4
docs/guide-zh-CN/rest-controllers.md

@ -134,6 +134,10 @@ public function checkAccess($action, $model = null, $params = [])
{
// 检查用户能否访问 $action 和 $model
// 访问被拒绝应抛出ForbiddenHttpException
if ($action === 'update' || $action === 'delete') {
if ($model->author_id !== \Yii::$app->user->id)
throw new \yii\web\ForbiddenHttpException(sprintf('You can only %s articles that you\'ve created.', $action));
}
}
```

2
docs/guide/caching-http.md

@ -25,7 +25,7 @@ the page modification time. The signature of the PHP callable should be as follo
/**
* @param Action $action the action object that is being handled currently
* @param array $params the value of the "params" property
* @return integer a UNIX timestamp representing the page modification time
* @return int a UNIX timestamp representing the page modification time
*/
function ($action, $params)
```

11
docs/guide/db-active-record.md

@ -1140,6 +1140,17 @@ Since version 2.0.7, Yii provides a shortcut for this. You may now define and us
$query->joinWith(['orders o'])->orderBy('o.id');
```
The above syntax works for simple relations. If you need an alias for an intermediate table when joining over
nested relations, e.g. `$query->joinWith(['orders.product'])`,
you need to nest the joinWith calls like in the following example:
```php
$query->joinWith(['orders o' => function($q) {
$q->joinWith('product p');
}])
->where('o.amount > 100');
```
### Inverse Relations <span id="inverse-relations"></span>
Relation declarations are often reciprocal between two Active Record classes. For example, `Customer` is related

8
docs/guide/db-migrations.md

@ -419,6 +419,11 @@ column named `author_id` with a foreign key to the `user` table while
`category_id:integer:defaultValue(1):foreignKey` will generate a column
`category_id` with a foreign key to the `category` table.
Since 2.0.11, `foreignKey` keyword accepts a second parameter, separated by whitespace.
It accepts the name of the related column for the foreign key generated.
If no second parameter is passed, the column name will be fetched from table schema.
If no schema exists, primary key isn't set or is composite, default name `id` will be used.
### Drop Table
```php
@ -602,6 +607,9 @@ class m160328_041642_create_junction_table_for_post_and_tag_tables extends Migra
}
```
Since 2.0.11 foreign key column names for junction tables are fetched from table schema.
In case table isn't defined in schema, isn't set or is composite, default name `id` is used.
### Transactional Migrations <span id="transactional-migrations"></span>
While performing complex DB migrations, it is important to ensure each migration to either succeed or fail as a whole

2
docs/guide/helper-array.md

@ -88,7 +88,7 @@ if (!ArrayHelper::keyExists('username', $data1, false) || !ArrayHelper::keyExist
Often you need to get a column of values from array of data rows or objects. Common example is getting a list of IDs.
```php
$data = [
$array = [
['id' => '123', 'data' => 'abc'],
['id' => '345', 'data' => 'def'],
];

72
docs/guide/input-forms.md

@ -1,6 +1,8 @@
Creating Forms
==============
ActiveRecord based forms: ActiveForm
-----------------------
The primary way of using forms in Yii is through [[yii\widgets\ActiveForm]]. This approach should be preferred when
the form is based upon a model. Additionally, there are some useful methods in [[yii\helpers\Html]] that are typically
used for adding buttons and help text to any form.
@ -52,6 +54,7 @@ $form = ActiveForm::begin([
<?php ActiveForm::end() ?>
```
### Wrapping with `begin()` and `end()` <span id="wrapping-with-begin-and-end"></span>
In the above code, [[yii\widgets\ActiveForm::begin()|ActiveForm::begin()]] not only creates a form instance, but also marks the beginning of the form.
All of the content placed between [[yii\widgets\ActiveForm::begin()|ActiveForm::begin()]] and
[[yii\widgets\ActiveForm::end()|ActiveForm::end()]] will be wrapped within the HTML `<form>` tag.
@ -59,6 +62,7 @@ As with any widget, you can specify some options as to how the widget should be
the `begin` method. In this case, an extra CSS class and identifying ID are passed to be used in the opening `<form>` tag.
For all available options, please refer to the API documentation of [[yii\widgets\ActiveForm]].
### ActiveField <span id="activefield"></span>.
In order to create a form element in the form, along with the element's label, and any applicable JavaScript validation,
the [[yii\widgets\ActiveForm::field()|ActiveForm::field()]] method is called, which returns an instance of [[yii\widgets\ActiveField]].
When the result of this method is echoed directly, the result is a regular (text) input.
@ -119,26 +123,76 @@ class like it is done in the above example with [[yii\helpers\Html::submitButton
> }
> ```
Creating Drop-down List <span id="creating-activeform-dropdownlist"></span>
Creating Lists <span id="creating-activeform-lists"></span>
-----------------------
We can use ActiveForm [dropDownList()](http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html#dropDownList()-detail)
method to create a drop-down list:
There are 3 types of lists:
* Dropdown lists
* Radio lists
* Checkbox lists
To create a list, you have to prepare the items. This can be done manually:
```php
use app\models\ProductCategory;
$items = [
1 => 'item 1',
2 => 'item 2'
]
```
or by retrieval from the DB:
```php
$items = Category::find()
->select(['id', 'label'])
->indexBy('id')
->column();
```
These `$items` have to be processed by the different list widgets.
The value of the form field (and the current active item) will be automatically set
by the current value of the `$model`'s attribute.
/* @var $this yii\web\View */
#### Creating a drop-down list <span id="creating-activeform-dropdownlist"></span>
We can use ActiveField [[\yii\widgets\ActiveField::dropDownList()]] method to create a drop-down list:
```php
/* @var $form yii\widgets\ActiveForm */
/* @var $model app\models\Product */
echo $form->field($model, 'product_category')->dropdownList(
ProductCategory::find()->select(['category_name', 'id'])->indexBy('id')->column(),
echo $form->field($model, 'category')->dropdownList([
1 => 'item 1',
2 => 'item 2'
],
['prompt'=>'Select Category']
);
```
The value of your model field will be automatically pre-selected.
#### Creating a radio list <span id="creating-activeform-radioList"></span>
We can use ActiveField [[\yii\widgets\ActiveField::radioList()]] method to create a radio list:
```php
/* @var $form yii\widgets\ActiveForm */
echo $form->field($model, 'category')->radioList([
1 => 'radio 1',
2 => 'radio 2'
]);
```
#### Creating a checkbox List <span id="creating-activeform-checkboxList"></span>
We can use ActiveField [[\yii\widgets\ActiveField::checkboxList()]] method to create a checkbox list:
```php
/* @var $form yii\widgets\ActiveForm */
echo $form->field($model, 'category')->checkboxList([
1 => 'checkbox 1',
2 => 'checkbox 2'
]);
```
Working with Pjax <span id="working-with-pjax"></span>
-----------------------

2
docs/guide/input-validation.md

@ -176,7 +176,7 @@ The [[yii\validators\Validator::when|when]] property takes a PHP callable with t
/**
* @param Model $model the model being validated
* @param string $attribute the attribute being validated
* @return boolean whether the rule should be applied
* @return bool whether the rule should be applied
*/
function ($model, $attribute)
```

4
docs/guide/output-client-scripts.md

@ -72,8 +72,8 @@ body { background: #f00; }
</style>
```
If you want to specify additional properties of the style tag, pass an array of name-values to the third argument.
If you need to make sure there's only a single style tag use fourth argument as was mentioned in meta tags description.
If you want to specify additional properties of the style tag, pass an array of name-values to the second argument.
If you need to make sure there's only a single style tag use third argument as was mentioned in meta tags description.
```php
$this->registerCssFile("http://example.com/css/themes/black-and-white.css", [

6
docs/guide/output-data-widgets.md

@ -29,6 +29,8 @@ echo DetailView::widget([
[ // the owner name of the model
'label' => 'Owner',
'value' => $model->owner->name,
'contentOptions' => ['class' => 'bg-red'], // to HTML customize attributes of value tag
'captionOptions' => ['tooltip' => 'Tooltip'], // to HTML customize attributes of label tag
],
'created_at:datetime', // creation date formatted as datetime
],
@ -343,8 +345,8 @@ For filtering data, the GridView needs a [model](structure-models.md) that repre
usually taken from the filter fields in the GridView table.
A common practice when using [active records](db-active-record.md) is to create a search Model class
that provides needed functionality (it can be generated for you by [Gii](start-gii.md)). This class defines the validation
rules for the search and provides a `search()` method that will return the data provider with an
adjusted query that respects the search criteria.
rules to show filter controls on the GridView table and to provide a `search()` method that will return the data
provider with an adjusted query that processes the search criteria.
To add the search capability for the `Post` model, we can create a `PostSearch` model like the following example:

2
docs/guide/output-formatting.md

@ -21,7 +21,7 @@ echo $formatter->asEmail('cebe@example.com');
echo $formatter->asBoolean(true);
// it also handles display of null values:
// output: (Not set)
// output: (not set)
echo $formatter->asDate(null);
```

4
docs/guide/rest-controllers.md

@ -178,6 +178,10 @@ public function checkAccess($action, $model = null, $params = [])
{
// check if the user can access $action and $model
// throw ForbiddenHttpException if access should be denied
if ($action === 'update' || $action === 'delete') {
if ($model->author_id !== \Yii::$app->user->id)
throw new \yii\web\ForbiddenHttpException(sprintf('You can only %s articles that you\'ve created.', $action));
}
}
```

6
docs/guide/rest-quick-start.md

@ -60,6 +60,9 @@ Then, modify the configuration of the `urlManager` component in your application
The above configuration mainly adds a URL rule for the `user` controller so that the user data
can be accessed and manipulated with pretty URLs and meaningful HTTP verbs.
> Note: Yii will automatically pluralize controller names for use in endpoints (see [Trying it Out](#trying-it-out) section below).
> You can configure this using the [[yii\rest\UrlRule::$pluralize]] property.
## Enabling JSON Input <span id="enabling-json-input"></span>
@ -93,9 +96,6 @@ for accessing the user data. The APIs you have created include:
* `OPTIONS /users`: show the supported verbs regarding endpoint `/users`;
* `OPTIONS /users/123`: show the supported verbs regarding endpoint `/users/123`.
> Info: Yii will automatically pluralize controller names for use in endpoints.
> You can configure this using the [[yii\rest\UrlRule::$pluralize]] property.
You may access your APIs with the `curl` command like the following,
```

2
docs/guide/rest-resources.md

@ -98,7 +98,7 @@ public function fields()
### Overriding `extraFields()` <span id="overriding-extra-fields"></span>
By default, [[yii\base\Model::extraFields()]] returns nothing, while [[yii\db\ActiveRecord::extraFields()]]
By default, [[yii\base\Model::extraFields()]] returns an empty array, while [[yii\db\ActiveRecord::extraFields()]]
returns the names of the relations that have been populated from DB.
The return data format of `extraFields()` is the same as that of `fields()`. Usually, `extraFields()`

4
docs/guide/security-authentication.md

@ -71,7 +71,7 @@ class User extends ActiveRecord implements IdentityInterface
/**
* Finds an identity by the given ID.
*
* @param string|integer $id the ID to be looked for
* @param string|int $id the ID to be looked for
* @return IdentityInterface|null the identity object that matches the given ID.
*/
public static function findIdentity($id)
@ -108,7 +108,7 @@ class User extends ActiveRecord implements IdentityInterface
/**
* @param string $authKey
* @return boolean if auth key is valid for current user
* @return bool if auth key is valid for current user
*/
public function validateAuthKey($authKey)
{

4
docs/guide/security-authorization.md

@ -362,10 +362,10 @@ class AuthorRule extends Rule
public $name = 'isAuthor';
/**
* @param string|integer $user the user ID.
* @param string|int $user the user ID.
* @param Item $item the role or permission that this rule is associated with
* @param array $params parameters passed to ManagerInterface::checkAccess().
* @return boolean a value indicating whether the rule permits the role or permission it is associated with.
* @return bool a value indicating whether the rule permits the role or permission it is associated with.
*/
public function execute($user, $item, $params)
{

2
docs/guide/start-installation.md

@ -53,7 +53,7 @@ by running `composer self-update`.
> Please refer to the [Composer documentation about Github API tokens](https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens)
> for instructions on how to do this.
### Installing Yii
### Installing Yii <span id="installing-from-composer"></span>
With Composer installed, you can install Yii by running the following commands under a Web-accessible folder:

17
docs/guide/tutorial-core-validators.md

@ -67,8 +67,11 @@ to make sure an input is the same as the verification code displayed by [[yii\ca
// validates if the value of "password" attribute equals to that of "password_repeat"
['password', 'compare'],
// same as above but with explicitly specifying the attribute to compare with
['password', 'compare', 'compareAttribute' => 'password_repeat'],
// validates if age is greater than or equal to 30
['age', 'compare', 'compareValue' => 30, 'operator' => '>='],
['age', 'compare', 'compareValue' => 30, 'operator' => '>=', 'type' => 'number'],
]
```
@ -91,7 +94,9 @@ is as specified by the `operator` property.
* `>=`: check if value being validated is greater than or equal to the value being compared with.
* `<`: check if value being validated is less than the value being compared with.
* `<=`: check if value being validated is less than or equal to the value being compared with.
- `type`: The default comparison type is '[[yii\validators\CompareValidator::TYPE_STRING|string]]', which means the values are
compared byte by byte. When comparing numbers, make sure to set the [[yii\validators\CompareValidator::$type|$type]]
to '[[yii\validators\CompareValidator::TYPE_NUMBER|number]]' to enable numeric comparison.
### Comparing date values
@ -118,9 +123,14 @@ is set to `false` on the compare validator too.
## [[yii\validators\DateValidator|date]] <span id="date"></span>
The [[yii\validators\DateValidator|date]] validator comes with three different
shortcuts:
```php
[
[['from_date', 'to_date'], 'date'],
[['from_datetime', 'to_datetime'], 'datetime'],
[['some_time'], 'time'],
]
```
@ -144,6 +154,9 @@ specified via [[yii\validators\DateValidator::timestampAttribute|timestampAttrib
[[yii\validators\DateValidator::$timestampAttributeFormat|$timestampAttributeFormat]] and
[[yii\validators\DateValidator::$timestampAttributeTimeZone|$timestampAttributeTimeZone]].
Note, that when using `timestampAttribute`, the input value will be converted to a unix timestamp, which by definition is in UTC, so
a conversion from the [[yii\validators\DateValidator::timeZone|input time zone]] to UTC will be performed.
- Since version 2.0.4 it is also possible to specify a [[yii\validators\DateValidator::$min|minimum]] or
[[yii\validators\DateValidator::$max|maximum]] timestamp.

6
docs/internals-ja/core-code-style.md

@ -145,7 +145,7 @@ class Foo
### 4.4 Doc ブロック
`@param`、`@var`、`@property` および `@return``boolean`、`integer`、`string`、`array` または `null` として型を宣言しなければなりません。
`@param`、`@var`、`@property` および `@return``bool`、`int`、`string`、`array` または `null` として型を宣言しなければなりません。
`Model` または `ActiveRecord` のようなクラス名を使うことも出来ます。
型付きの配列に対しては `ClassName[]` を使います。
@ -301,10 +301,10 @@ switch ($this->phpType) {
break;
case 'integer':
case 'int':
$a = (integer)$value;
$a = (int) $value;
break;
case 'boolean':
$a = (boolean)$value;
$a = (bool) $value;
break;
default:
$a = null;

2
docs/internals-pl/core-code-style.md

@ -143,7 +143,7 @@ class Foo
### 4.4 Bloki dokumentacji
`@param`, `@var`, `@property` oraz `@return` muszą używać typów zadeklarowanych jako `boolean`, `integer`, `string`, `array` lub `null`.
`@param`, `@var`, `@property` oraz `@return` muszą używać typów zadeklarowanych jako `bool`, `int`, `string`, `array` lub `null`.
Można również używać nazw klas jak `Model` lub `ActiveRecord`. Dla typowanych tablic należy używać `ClassName[]`.
### 4.5 Konstruktory

2
docs/internals-ru/core-code-style.md

@ -137,7 +137,7 @@ class Foo
### 4.4 Блоки Документации
`@param`, `@var`, `@property` и `@return` должны описывать типы `boolean`, `integer`, `string`, `array` или `null`. Вы можете использовать и имена классов, например `Model` или `ActiveRecord`. Для типизированных массивов используйте `ClassName[]`.
`@param`, `@var`, `@property` и `@return` должны описывать типы `bool`, `int`, `string`, `array` или `null`. Вы можете использовать и имена классов, например `Model` или `ActiveRecord`. Для типизированных массивов используйте `ClassName[]`.
### 4.5 Конструкторы

2
docs/internals-uk/core-code-style.md

@ -134,7 +134,7 @@ class Foo
### 4.4 Блоки документації PHPDoc (Doc-блоки)
`@param`, `@var`, `@property` та `@return` повинні оголошувати типи як `boolean`, `integer`, `string`, `array` чи `null`. Також можна використовувати імена класів, як наприклад: `Model` або `ActiveRecord`. Для типізованих масивів використовуйте `ClassName[]`.
`@param`, `@var`, `@property` та `@return` повинні оголошувати типи як `bool`, `int`, `string`, `array` чи `null`. Також можна використовувати імена класів, як наприклад: `Model` або `ActiveRecord`. Для типізованих масивів використовуйте `ClassName[]`.
### 4.5 Конструктори

24
docs/internals/core-code-style.md

@ -142,9 +142,29 @@ class Foo
}
```
### 4.4 Doc blocks
### 4.4 PHPDoc blocks
`@param`, `@var`, `@property` and `@return` must declare types as `boolean`, `integer`, `string`, `array` or `null`. You can use a class names as well such as `Model` or `ActiveRecord`. For a typed arrays use `ClassName[]`.
- `@param`, `@var`, `@property` and `@return` must declare types as `bool`, `int`, `string`, `array` or `null`.
You can use a class names as well such as `Model` or `ActiveRecord`.
- For a typed arrays use `ClassName[]`.
- The first line of the PHPDoc must describe the purpose of the method.
- If method checks something (`isActive`, `hasClass`, etc) the first line should start with `Checks whether`.
- `@return` should explicitly describe what exactly will be returned.
```php
/**
* Checkes whether the IP is in subnet range
*
* @param string $ip an IPv4 or IPv6 address
* @param int $cidr the CIDR lendth
* @param string $range subnet in CIDR format e.g. `10.0.0.0/8` or `2001:af::/64`
* @return bool whether the IP is in subnet range
*/
private function inRange($ip, $cidr, $range)
{
// ...
}
```
### 4.5 Constructors

1
docs/internals/design-decisions.md

@ -23,3 +23,4 @@ the core developers.
Also although unsigned int doubles the size, if you have a table that needs such big number space,
then it's safer to use bigint or mediumint rather than relying on unsigned.
<https://github.com/yiisoft/yii/pull/1923#issuecomment-11881967>
6. [Helpers vs separate non-static classes](https://github.com/yiisoft/yii2/pull/12661#issuecomment-251599463)

4
docs/internals/git-workflow.md

@ -21,6 +21,8 @@ git clone git@github.com:YOUR-GITHUB-USERNAME/yii2.git
If you have trouble setting up Git with GitHub in Linux, or are getting errors like "Permission Denied (publickey)",
then you must [setup your Git installation to work with GitHub](http://help.github.com/linux-set-up-git/)
> Tip: if you're not fluent with Git, we recommend reading excellent free [Pro Git book](https://git-scm.com/book/en/v2).
### 2. Add the main Yii repository as an additional git remote called "upstream"
Change to the directory where you cloned Yii, normally, "yii2". Then enter the following command:
@ -33,7 +35,7 @@ git remote add upstream git://github.com/yiisoft/yii2.git
The following steps are not necessary if you want to work only on translations or documentation.
- run `composer update` to install dependencies (assuming you have [composer installed globally](https://getcomposer.org/doc/00-intro.md#globally)).
- run `composer install` to install dependencies (assuming you have [composer installed globally](https://getcomposer.org/doc/00-intro.md#globally)).
> Note: If you see errors like `Problem 1 The requested package bower-asset/jquery could not be found in any version, there may be a typo in the package name.`, you will need to run `composer global require "fxp/composer-asset-plugin:^1.2.0"`

8
framework/BaseYii.php

@ -93,7 +93,7 @@ class BaseYii
*/
public static function getVersion()
{
return '2.0.10-dev';
return '2.0.11-dev';
}
/**
@ -120,9 +120,9 @@ class BaseYii
* Note, this method does not check if the returned path exists or not.
*
* @param string $alias the alias to be translated.
* @param boolean $throwException whether to throw an exception if the given alias is invalid.
* @param bool $throwException whether to throw an exception if the given alias is invalid.
* If this is false and an invalid alias is given, false will be returned by this method.
* @return string|boolean the path corresponding to the alias, false if the root alias is not previously registered.
* @return string|bool the path corresponding to the alias, false if the root alias is not previously registered.
* @throws InvalidParamException if the alias is invalid while $throwException is true.
* @see setAlias()
*/
@ -160,7 +160,7 @@ class BaseYii
* A root alias is an alias that has been registered via [[setAlias()]] previously.
* If a given alias matches multiple root aliases, the longest one will be returned.
* @param string $alias the alias
* @return string|boolean the root alias, or false if no root alias is found
* @return string|bool the root alias, or false if no root alias is found
*/
public static function getRootAlias($alias)
{

602
framework/CHANGELOG.md

File diff suppressed because it is too large Load Diff

78
framework/UPGRADE.md

@ -1,19 +1,55 @@
Upgrading Instructions for Yii Framework v2
===========================================
Upgrading Instructions for Yii Framework 2.0
============================================
!!!IMPORTANT!!!
This file contains the upgrade notes for Yii 2.0. These notes highlight changes that
could break your application when you upgrade Yii from one version to another.
Even though we try to ensure backwards compabitilty (BC) as much as possible, sometimes
it is not possible or very complicated to avoid it and still create a good solution to
a problem. You may also want to check out the [versioning policy](https://github.com/yiisoft/yii2/blob/master/docs/internals/versions.md) for further details.
The following upgrading instructions are cumulative. That is,
Upgrading in general is as simple as updating your dependency in your composer.json and
running `composer update`. In a big application however there may be more things to consider,
which are explained in the following.
> Note: This document assumes you have composer [installed globally](http://www.yiiframework.com/doc-2.0/guide-start-installation.html#installing-composer) so that you can run the `composer` command. If you have a `composer.phar` file
inside of your project you need to replace `composer` with `php composer.phar` in the following.
> Tip: Upgrading dependencies of a complex software project always comes at the risk of breaking something, so make sure
you have a backup (you should be doing this anyway ;) ).
Before upgrading, make sure you have a global installation of the latest version of the
[composer asset plugin](https://github.com/fxpio/composer-asset-plugin)
as well as a stable version of Composer:
composer self-update
composer global require "fxp/composer-asset-plugin:^1.2.0" --no-plugins
The simple way to upgrade Yii, for example to version 2.0.10 (replace this with the version you want) will be running `composer require`:
composer require "yiisoft/yii2:~2.0.10"
This however may fail due to changes in the dependencies of yiisoft/yii2, which may change due to security updates
in other libraries or by adding support for newer versions. `composer require` will not update any other packages
as a safety feature.
The better way to upgrade is to change the `composer.json` file to require the new Yii version and then
run `composer update` by specifying all packages that are allowed to be updated.
composer update yiisoft/yii2 yiisoft/yii2-composer bower-asset/jquery.inputmask
The above command will only update the specified packages and leave the versions of all other dependencies intact.
This helps to update packages step by step without causing a lot of package version changes that might break in some way.
If you feel lucky you can of course update everything to the latest version by running `composer update` without
any restrictions.
After upgrading you should check whether your application still works as expected and no tests are broken.
See the following notes on which changes to consider when upgrading from one version to another.
> Note: The following upgrading instructions are cumulative. That is,
if you want to upgrade from version A to version C and there is
version B between A and C, you need to follow the instructions
for both A and B.
Make sure you have global install of latest version of composer asset plugin as well as a stable version of composer:
```
php composer.phar self-update
php composer.phar global require "fxp/composer-asset-plugin:^1.2.0"
```
Upgrade to Yii 2.1.0
--------------------
@ -49,11 +85,31 @@ Upgrade to Yii 2.1.0
If you are using `yii\web\Request::resolve()` or `yii\web\UrlManager::parseRequest()` directly, make sure that
all potential exceptions are handled correctly or set `yii\web\UrlNormalizer::$normalizer` to `false` to disable normalizer.
Upgrade from Yii 2.0.9
----------------------
* RBAC: `getChildRoles()` method was added to `\yii\rbac\ManagerInterface`. If you've implemented your own RBAC manager
you need to implement new method.
* Microsoft SQL `NTEXT` data type [was marked as deprecated](https://msdn.microsoft.com/en-us/library/ms187993.aspx) in MSSQL so
`\yii\db\mssql\Schema::TYPE_TEXT` was changed from `'ntext'` to `'nvarchar(max)'
* Method `yii\web\Request::getBodyParams()` has been changed to pass full value of 'content-type' header to the second
argument of `yii\web\RequestParserInterface::parse()`. If you create your own custom parser, which relies on `$contentType`
argument, ensure to process it correctly as it may content additional data.
* `yii\rest\Serializer` has been changed to return a JSON array for collection data in all cases to be consistent among pages
for data that is not indexed starting by 0. If your API relies on the Serializer to return data as JSON objects indexed by
PHP array keys, you should set `yii\rest\Serializer::$preserveKeys` to `true`.
Upgrade from Yii 2.0.8
----------------------
* Part of code from `yii\web\User::loginByCookie()` method was moved to new `getIdentityAndDurationFromCookie()`
and `removeIdentityCookie()` methods. If you override `loginByCookie()` method, update it in order use new methods.
* Fixture console command syntax was changed from `yii fixture "*" -User` to `yii fixture "*, -User"`. Upgrade your
scripts if necessary.
@ -236,7 +292,7 @@ Upgrade from Yii 2.0 Beta
It is also a good idea to upgrade composer itself to the latest version if you see any problems:
```
php composer.phar self-update
composer self-update
```
* If you used `clearAll()` or `clearAllAssignments()` of `yii\rbac\DbManager`, you should replace

31
framework/assets/yii.activeForm.js

@ -100,7 +100,15 @@
* - jqXHR: a jqXHR object
* - textStatus: the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror").
*/
ajaxComplete: 'ajaxComplete'
ajaxComplete: 'ajaxComplete',
/**
* afterInit event is triggered after yii activeForm init.
* The signature of the event handler should be:
* function (event)
* where
* - event: an Event object.
*/
afterInit: 'afterInit'
};
// NOTE: If you change any of these defaults, make sure you update yii\widgets\ActiveForm::getClientOptions() as well
@ -124,7 +132,9 @@
// the URL for performing AJAX-based validation. If not set, it will use the the form's action
validationUrl: undefined,
// whether to scroll to first visible error after validation.
scrollToError: true
scrollToError: true,
// offset in pixels that should be added when scrolling to the first error.
scrollToErrorOffset: 0
};
// NOTE: If you change any of these defaults, make sure you update yii\widgets\ActiveField::getClientOptions() as well
@ -217,6 +227,8 @@
});
$form.on('submit.yiiActiveForm', methods.submitForm);
}
var event = $.Event(events.afterInit);
$form.trigger(event);
});
},
@ -341,7 +353,7 @@
delete messages[i];
}
}
if ($.isEmptyObject(messages) && needAjaxValidation) {
if (needAjaxValidation && ($.isEmptyObject(messages) || data.submitting)) {
var $button = data.submitObject,
extData = '&' + data.settings.ajaxParam + '=' + $form.attr('id');
if ($button && $button.length && $button.attr('name')) {
@ -618,7 +630,12 @@
if (data.settings.scrollToError) {
var top = $form.find($.map(errorAttributes, function(attribute) {
return attribute.input;
}).join(',')).first().closest(':visible').offset().top;
}).join(',')).first().closest(':visible').offset().top - data.settings.scrollToErrorOffset;
if (top < 0) {
top = 0;
} else if (top > $(document).height()) {
top = $(document).height();
}
var wtop = $(window).scrollTop();
if (top < wtop || top > wtop + $(window).height()) {
$(window).scrollTop(top);
@ -628,9 +645,11 @@
} else {
data.validated = true;
if (data.submitObject) {
data.submitObject.trigger("click");
} else {
applyButtonOptions($form, data.submitObject);
}
$form.submit();
if (data.submitObject) {
restoreButtonOptions($form);
}
}
} else {

4
framework/assets/yii.gridView.js

@ -118,6 +118,10 @@
var pos = settings.filterUrl.indexOf('?');
var url = pos < 0 ? settings.filterUrl : settings.filterUrl.substring(0, pos);
var hashPos = settings.filterUrl.indexOf('#');
if (hashPos >= 0) {
url += settings.filterUrl.substring(pos);
}
$grid.find('form.gridview-filter-form').remove();
var $form = $('<form/>', {

45
framework/assets/yii.js

@ -208,7 +208,7 @@ window.yii = (function ($) {
var newForm = !$form.length;
if (newForm) {
if (!action || !action.match(/(^\/|:\/\/)/)) {
if (!action || !/(^\/|:\/\/)/.test(action)) {
action = window.location.href;
}
$form = $('<form/>', {method: method, action: action});
@ -216,11 +216,11 @@ window.yii = (function ($) {
if (target) {
$form.attr('target', target);
}
if (!method.match(/(get|post)/i)) {
if (!/(get|post)/i.test(method)) {
$form.append($('<input/>', {name: '_method', value: method, type: 'hidden'}));
method = 'POST';
}
if (!method.match(/(get|head|options)/i)) {
if (!/(get|head|options)/i.test(method)) {
var csrfParam = pub.getCsrfParam();
if (csrfParam) {
$form.append($('<input/>', {name: csrfParam, value: pub.getCsrfToken(), type: 'hidden'}));
@ -289,8 +289,8 @@ window.yii = (function ($) {
for (i = 0; i < pairs.length; i++) {
pair = pairs[i].split('=');
var name = decodeURIComponent(pair[0]);
var value = decodeURIComponent(pair[1]);
var name = decodeURIComponent(pair[0].replace(/\+/g, '%20'));
var value = decodeURIComponent(pair[1].replace(/\+/g, '%20'));
if (name.length) {
if (params[name] !== undefined) {
if (!$.isArray(params[name])) {
@ -400,10 +400,14 @@ window.yii = (function ($) {
function initScriptFilter() {
var hostInfo = getHostInfo();
var loadedScripts = {};
var loadedScripts = $('script[src]').map(function () {
var scripts = $('script[src]').map(function () {
return this.src.charAt(0) === '/' ? hostInfo + this.src : this.src;
}).toArray();
for (var i = 0, len = scripts.length; i < len; i++) {
loadedScripts[scripts[i]] = true;
}
$.ajaxPrefilter('script', function (options, originalOptions, xhr) {
if (options.dataType == 'jsonp') {
@ -411,12 +415,33 @@ window.yii = (function ($) {
}
var url = options.url.charAt(0) === '/' ? hostInfo + options.url : options.url;
if ($.inArray(url, loadedScripts) === -1) {
loadedScripts.push(url);
} else {
if (!isReloadable(url)) {
if (url in loadedScripts) {
var item = loadedScripts[url];
// If the concurrent XHR request is running and URL is not reloadable
if (item !== true && !isReloadable(url)) {
// Abort the current XHR request when previous finished successfully
item.done(function () {
if (xhr && xhr.readyState !== 4) {
xhr.abort();
}
});
// Or abort previous XHR if the current one is loaded faster
xhr.done(function () {
if (item && item.readyState !== 4) {
item.abort();
}
});
} else if (!isReloadable(url)) {
xhr.abort();
}
} else {
loadedScripts[url] = xhr.done(function () {
loadedScripts[url] = true;
}).fail(function () {
delete loadedScripts[url];
});
}
});

13
framework/assets/yii.validation.js

@ -136,7 +136,7 @@ yii.validation = (function ($) {
return;
}
if (typeof value === 'string' && !value.match(options.pattern)) {
if (typeof value === 'string' && !options.pattern.test(value)) {
pub.addMessage(messages, options.message, value);
return;
}
@ -180,7 +180,7 @@ yii.validation = (function ($) {
return;
}
if (!options.not && !value.match(options.pattern) || options.not && value.match(options.pattern)) {
if (!options.not && !options.pattern.test(value) || options.not && options.pattern.test(value)) {
pub.addMessage(messages, options.message, value);
}
},
@ -211,7 +211,7 @@ yii.validation = (function ($) {
} else if ((matches[5] + '@' + matches[6]).length > 254) {
valid = false;
} else {
valid = value.match(options.pattern) || (options.allowName && value.match(options.fullPattern));
valid = options.pattern.test(value) || (options.allowName && options.fullPattern.test(value));
}
}
@ -225,15 +225,14 @@ yii.validation = (function ($) {
return;
}
if (options.defaultScheme && !value.match(/:\/\//)) {
if (options.defaultScheme && !/:\/\//.test(value)) {
value = options.defaultScheme + '://' + value;
}
var valid = true;
if (options.enableIDN) {
var regexp = /^([^:]+):\/\/([^\/]+)(.*)$/,
matches = regexp.exec(value);
var matches = /^([^:]+):\/\/([^\/]+)(.*)$/.exec(value);
if (matches === null) {
valid = false;
} else {
@ -241,7 +240,7 @@ yii.validation = (function ($) {
}
}
if (!valid || !value.match(options.pattern)) {
if (!valid || !options.pattern.test(value)) {
pub.addMessage(messages, options.message, value);
}
},

4
framework/base/Action.php

@ -28,6 +28,8 @@ use Yii;
* And the parameters provided for the action are: `['id' => 1]`.
* Then the `run()` method will be invoked as `run(1)` automatically.
*
* For more details and usage information on Action, see the [guide article on actions](guide:structure-controllers).
*
* @property string $uniqueId The unique ID of this action among the whole application. This property is
* read-only.
*
@ -103,7 +105,7 @@ class Action extends Component
* You may override this method to do preparation work for the action run.
* If the method returns false, it will cancel the action.
*
* @return boolean whether to run the action.
* @return bool whether to run the action.
*/
protected function beforeRun()
{

2
framework/base/ActionEvent.php

@ -26,7 +26,7 @@ class ActionEvent extends Event
*/
public $result;
/**
* @var boolean whether to continue running the action. Event handlers of
* @var bool whether to continue running the action. Event handlers of
* [[Controller::EVENT_BEFORE_ACTION]] may set this property to decide whether
* to continue running the current action.
*/

6
framework/base/ActionFilter.php

@ -15,6 +15,8 @@ namespace yii\base;
*
* Check implementation of [[\yii\filters\AccessControl]], [[\yii\filters\PageCache]] and [[\yii\filters\HttpCache]] as examples on how to use it.
*
* For more details and usage information on ActionFilter, see the [guide article on filters](guide:structure-filters).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
@ -93,7 +95,7 @@ class ActionFilter extends Behavior
* This method is invoked right before an action is to be executed (after all possible filters.)
* You may override this method to do last-minute preparation for the action.
* @param Action $action the action to be executed.
* @return boolean whether the action should continue to be executed.
* @return bool whether the action should continue to be executed.
*/
public function beforeAction($action)
{
@ -136,7 +138,7 @@ class ActionFilter extends Behavior
/**
* Returns a value indicating whether the filter is active for the given action.
* @param Action $action the action being filtered
* @return boolean whether the filter is active for the given action.
* @return bool whether the filter is active for the given action.
*/
protected function isActive($action)
{

14
framework/base/Application.php

@ -12,6 +12,8 @@ use Yii;
/**
* Application is the base class for all application classes.
*
* For more details and usage information on Application, see the [guide article on applications](guide:structure-applications).
*
* @property \yii\web\AssetManager $assetManager The asset manager application component. This property is
* read-only.
* @property \yii\rbac\ManagerInterface $authManager The auth manager application component. Null is returned
@ -95,10 +97,6 @@ abstract class Application extends Module
*/
public $name = 'My Application';
/**
* @var string the version of this application.
*/
public $version = '1.0';
/**
* @var string the charset currently used for the application.
*/
public $charset = 'UTF-8';
@ -120,7 +118,7 @@ abstract class Application extends Module
*/
public $controller;
/**
* @var string|boolean the layout that should be applied for views in this application. Defaults to 'main'.
* @var string|bool the layout that should be applied for views in this application. Defaults to 'main'.
* If this is false, layout will be disabled.
*/
public $layout = 'main';
@ -176,7 +174,7 @@ abstract class Application extends Module
*/
public $bootstrap = [];
/**
* @var integer the current application state during a request handling life cycle.
* @var int the current application state during a request handling life cycle.
* This property is managed by the application. Do not modify this property.
*/
public $state;
@ -362,7 +360,7 @@ abstract class Application extends Module
/**
* Runs the application.
* This is the main entrance of an application.
* @return integer the exit status (0 means normal, non-zero values mean abnormal)
* @return int the exit status (0 means normal, non-zero values mean abnormal)
*/
public function run()
{
@ -627,7 +625,7 @@ abstract class Application extends Module
* Terminates the application.
* This method replaces the `exit()` function by ensuring the application life cycle is completed
* before terminating the application.
* @param integer $status the exit status (value 0 means normal exit while other values mean abnormal exit).
* @param int $status the exit status (value 0 means normal exit while other values mean abnormal exit).
* @param Response $response the response to be sent. If not set, the default application [[response]] component will be used.
* @throws ExitException if the application is in testing mode
*/

8
framework/base/ArrayAccessTrait.php

@ -34,7 +34,7 @@ trait ArrayAccessTrait
/**
* Returns the number of data items.
* This method is required by Countable interface.
* @return integer number of data elements.
* @return int number of data elements.
*/
public function count()
{
@ -44,7 +44,7 @@ trait ArrayAccessTrait
/**
* This method is required by the interface [[\ArrayAccess]].
* @param mixed $offset the offset to check on
* @return boolean
* @return bool
*/
public function offsetExists($offset)
{
@ -53,7 +53,7 @@ trait ArrayAccessTrait
/**
* This method is required by the interface [[\ArrayAccess]].
* @param integer $offset the offset to retrieve element.
* @param int $offset the offset to retrieve element.
* @return mixed the element at the offset, null if no element is found at the offset
*/
public function offsetGet($offset)
@ -63,7 +63,7 @@ trait ArrayAccessTrait
/**
* This method is required by the interface [[\ArrayAccess]].
* @param integer $offset the offset to set element
* @param int $offset the offset to set element
* @param mixed $item the element value
*/
public function offsetSet($offset, $item)

2
framework/base/Arrayable.php

@ -85,7 +85,7 @@ interface Arrayable
* @param array $expand the additional fields that the output array should contain.
* Fields not specified in [[extraFields()]] will be ignored. If this parameter is empty, no extra fields
* will be returned.
* @param boolean $recursive whether to recursively return array representation of embedded objects.
* @param bool $recursive whether to recursively return array representation of embedded objects.
* @return array the array representation of the object
*/
public function toArray(array $fields = [], array $expand = [], $recursive = true);

2
framework/base/ArrayableTrait.php

@ -110,7 +110,7 @@ trait ArrayableTrait
* @param array $fields the fields being requested. If empty, all fields as specified by [[fields()]] will be returned.
* @param array $expand the additional fields being requested for exporting. Only fields declared in [[extraFields()]]
* will be considered.
* @param boolean $recursive whether to recursively return array representation of embedded objects.
* @param bool $recursive whether to recursively return array representation of embedded objects.
* @return array the array representation of the object
*/
public function toArray(array $fields = [], array $expand = [], $recursive = true)

2
framework/base/Behavior.php

@ -15,6 +15,8 @@ namespace yii\base;
* and make them directly accessible via the component. It can also respond to the events triggered in the component
* and thus intercept the normal code execution.
*
* For more details and usage information on Behavior, see the [guide article on behaviors](guide:concept-behaviors).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/

2
framework/base/BootstrapInterface.php

@ -47,6 +47,8 @@ namespace yii\base;
*
* As you can see, you can register a bootstrapping class in terms of either a class name or a configuration class.
*
* For more details and usage information on BootstrapInterface, see the [guide article on bootstrapping applications](guide:structure-applications).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/

34
framework/base/Component.php

@ -90,6 +90,8 @@ use Yii;
* where `as tree` stands for attaching a behavior named `tree`, and the array will be passed to [[\Yii::createObject()]]
* to create the behavior object.
*
* For more details and usage information on Component, see the [guide article on components](guide:concept-components).
*
* @property Behavior[] $behaviors List of behaviors attached to this component. This property is read-only.
*
* @author Qiang Xue <qiang.xue@gmail.com>
@ -209,7 +211,7 @@ class Component extends Object
* Do not call this method directly as it is a PHP magic method that
* will be implicitly called when executing `isset($component->property)`.
* @param string $name the property name or the event name
* @return boolean whether the named property is set
* @return bool whether the named property is set
* @see http://php.net/manual/en/function.isset.php
*/
public function __isset($name)
@ -305,9 +307,9 @@ class Component extends Object
* - an attached behavior has a property of the given name (when `$checkBehaviors` is true).
*
* @param string $name the property name
* @param boolean $checkVars whether to treat member variables as properties
* @param boolean $checkBehaviors whether to treat behaviors' properties as properties of this component
* @return boolean whether the property is defined
* @param bool $checkVars whether to treat member variables as properties
* @param bool $checkBehaviors whether to treat behaviors' properties as properties of this component
* @return bool whether the property is defined
* @see canGetProperty()
* @see canSetProperty()
*/
@ -326,9 +328,9 @@ class Component extends Object
* - an attached behavior has a readable property of the given name (when `$checkBehaviors` is true).
*
* @param string $name the property name
* @param boolean $checkVars whether to treat member variables as properties
* @param boolean $checkBehaviors whether to treat behaviors' properties as properties of this component
* @return boolean whether the property can be read
* @param bool $checkVars whether to treat member variables as properties
* @param bool $checkBehaviors whether to treat behaviors' properties as properties of this component
* @return bool whether the property can be read
* @see canSetProperty()
*/
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
@ -356,9 +358,9 @@ class Component extends Object
* - an attached behavior has a writable property of the given name (when `$checkBehaviors` is true).
*
* @param string $name the property name
* @param boolean $checkVars whether to treat member variables as properties
* @param boolean $checkBehaviors whether to treat behaviors' properties as properties of this component
* @return boolean whether the property can be written
* @param bool $checkVars whether to treat member variables as properties
* @param bool $checkBehaviors whether to treat behaviors' properties as properties of this component
* @return bool whether the property can be written
* @see canGetProperty()
*/
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
@ -384,8 +386,8 @@ class Component extends Object
* - an attached behavior has a method with the given name (when `$checkBehaviors` is true).
*
* @param string $name the property name
* @param boolean $checkBehaviors whether to treat behaviors' methods as methods of this component
* @return boolean whether the property is defined
* @param bool $checkBehaviors whether to treat behaviors' methods as methods of this component
* @return bool whether the property is defined
*/
public function hasMethod($name, $checkBehaviors = true)
{
@ -435,7 +437,7 @@ class Component extends Object
/**
* Returns a value indicating whether there is any handler attached to the named event.
* @param string $name the event name
* @return boolean whether there is any handler attached to the event.
* @return bool whether there is any handler attached to the event.
*/
public function hasEventHandlers($name)
{
@ -468,7 +470,7 @@ class Component extends Object
* @param callable $handler the event handler
* @param mixed $data the data to be passed to the event handler when the event is triggered.
* When the event handler is invoked, this data can be accessed via [[Event::data]].
* @param boolean $append whether to append new event handler to the end of the existing
* @param bool $append whether to append new event handler to the end of the existing
* handler list. If false, the new handler will be inserted at the beginning of the existing
* handler list.
* @see off()
@ -489,7 +491,7 @@ class Component extends Object
* @param string $name event name
* @param callable $handler the event handler to be removed.
* If it is null, all handlers attached to the named event will be removed.
* @return boolean if a handler is found and detached
* @return bool if a handler is found and detached
* @see on()
*/
public function off($name, $handler = null)
@ -650,7 +652,7 @@ class Component extends Object
/**
* Attaches a behavior to this component.
* @param string|integer $name the name of the behavior. If this is an integer, it means the behavior
* @param string|int $name the name of the behavior. If this is an integer, it means the behavior
* is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name
* will be detached first.
* @param string|array|Behavior $behavior the behavior to be attached

2
framework/base/Configurable.php

@ -23,6 +23,8 @@ namespace yii\base;
* This interface is mainly used by [[\yii\di\Container]] so that it can pass object configuration as the
* last parameter to the implementing class' constructor.
*
* For more details and usage information on Configurable, see the [guide article on configurations](guide:concept-configurations).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0.3
*/

6
framework/base/Controller.php

@ -12,6 +12,8 @@ use Yii;
/**
* Controller is the base class for classes containing controller logic.
*
* For more details and usage information on Controller, see the [guide article on controllers](guide:structure-controllers).
*
* @property Module[] $modules All ancestor modules that this controller is located within. This property is
* read-only.
* @property string $route The route (module ID, controller ID and action ID) of the current request. This
@ -261,7 +263,7 @@ class Controller extends Component implements ViewContextInterface
* ```
*
* @param Action $action the action to be executed.
* @return boolean whether the action should continue to run.
* @return bool whether the action should continue to run.
*/
public function beforeAction($action)
{
@ -473,7 +475,7 @@ class Controller extends Component implements ViewContextInterface
/**
* Finds the applicable layout file.
* @param View $view the view object to render the layout file.
* @return string|boolean the layout file path, or false if layout is not needed.
* @return string|bool the layout file path, or false if layout is not needed.
* Please refer to [[render()]] on how to specify this parameter.
* @throws InvalidParamException if an invalid path alias is used to specify the layout.
*/

4
framework/base/ErrorException.php

@ -12,6 +12,8 @@ use Yii;
/**
* ErrorException represents a PHP error.
*
* For more details and usage information on ErrorException, see the [guide article on handling errors](guide:runtime-handling-errors).
*
* @author Alexander Makarov <sam@rmcreative.ru>
* @since 2.0
*/
@ -76,7 +78,7 @@ class ErrorException extends \ErrorException
* Returns if error is one of fatal type.
*
* @param array $error error got from error_get_last()
* @return boolean if error is one of fatal type
* @return bool if error is one of fatal type
*/
public static function isFatalError($error)
{

41
framework/base/ErrorHandler.php

@ -17,6 +17,8 @@ use yii\web\HttpException;
* ErrorHandler is configured as an application component in [[\yii\base\Application]] by default.
* You can access that instance via `Yii::$app->errorHandler`.
*
* For more details and usage information on ErrorHandler, see the [guide article on handling errors](guide:runtime-handling-errors).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Makarov <sam@rmcreative.ru>
* @author Carsten Brandt <mail@cebe.cc>
@ -25,11 +27,11 @@ use yii\web\HttpException;
abstract class ErrorHandler extends Component
{
/**
* @var boolean whether to discard any existing page output before error display. Defaults to true.
* @var bool whether to discard any existing page output before error display. Defaults to true.
*/
public $discardExistingOutput = true;
/**
* @var integer the size of the reserved memory. A portion of memory is pre-allocated so that
* @var int the size of the reserved memory. A portion of memory is pre-allocated so that
* when an out-of-memory issue occurs, the error handler is able to handle the error with
* the help of this reserved memory. If you set this value to be 0, no memory will be reserved.
* Defaults to 256KB.
@ -116,10 +118,26 @@ abstract class ErrorHandler extends Component
}
} catch (\Exception $e) {
// an other exception could be thrown while displaying the exception
$this->handleFallbackExceptionMessage($e, $exception);
} catch (\Throwable $e) {
// additional check for \Throwable introduced in PHP 7
$this->handleFallbackExceptionMessage($e, $exception);
}
$this->exception = null;
}
/**
* Handles exception thrown during exception processing in [[handleException()]].
* @param \Exception|\Throwable $exception Exception that was thrown during main exception processing.
* @param \Exception $previousException Main exception processed in [[handleException()]].
* @since 2.0.11
*/
protected function handleFallbackExceptionMessage($exception, $previousException) {
$msg = "An Error occurred while handling another error:\n";
$msg .= (string) $e;
$msg .= "\nPrevious exception:\n";
$msg .= (string) $exception;
$msg .= "\nPrevious exception:\n";
$msg .= (string) $previousException;
if (YII_DEBUG) {
if (PHP_SAPI === 'cli') {
echo $msg . "\n";
@ -137,22 +155,19 @@ abstract class ErrorHandler extends Component
exit(1);
}
$this->exception = null;
}
/**
* Handles HHVM execution errors such as warnings and notices.
*
* This method is used as a HHVM error handler. It will store exception that will
* be used in fatal error handler
*
* @param integer $code the level of the error raised.
* @param int $code the level of the error raised.
* @param string $message the error message.
* @param string $file the filename that the error was raised in.
* @param integer $line the line number the error was raised at.
* @param int $line the line number the error was raised at.
* @param mixed $context
* @param mixed $backtrace trace of error
* @return boolean whether the normal error handler continues.
* @return bool whether the normal error handler continues.
*
* @throws ErrorException
* @since 2.0.6
@ -177,11 +192,11 @@ abstract class ErrorHandler extends Component
*
* This method is used as a PHP error handler. It will simply raise an [[ErrorException]].
*
* @param integer $code the level of the error raised.
* @param int $code the level of the error raised.
* @param string $message the error message.
* @param string $file the filename that the error was raised in.
* @param integer $line the line number the error was raised at.
* @return boolean whether the normal error handler continues.
* @param int $line the line number the error was raised at.
* @return bool whether the normal error handler continues.
*
* @throws ErrorException
*/

10
framework/base/Event.php

@ -19,6 +19,8 @@ namespace yii\base;
* Additionally, when attaching an event handler, extra data may be passed
* and be available via the [[data]] property when the event handler is invoked.
*
* For more details and usage information on Event, see the [guide article on events](guide:concept-events).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
@ -37,7 +39,7 @@ class Event extends Object
*/
public $sender;
/**
* @var boolean whether the event is handled. Defaults to `false`.
* @var bool whether the event is handled. Defaults to `false`.
* When a handler sets this to be `true`, the event processing will stop and
* ignore the rest of the uninvoked event handlers.
*/
@ -78,7 +80,7 @@ class Event extends Object
* @param callable $handler the event handler.
* @param mixed $data the data to be passed to the event handler when the event is triggered.
* When the event handler is invoked, this data can be accessed via [[Event::data]].
* @param boolean $append whether to append new event handler to the end of the existing
* @param bool $append whether to append new event handler to the end of the existing
* handler list. If `false`, the new handler will be inserted at the beginning of the existing
* handler list.
* @see off()
@ -102,7 +104,7 @@ class Event extends Object
* @param string $name the event name.
* @param callable $handler the event handler to be removed.
* If it is `null`, all handlers attached to the named event will be removed.
* @return boolean whether a handler is found and detached.
* @return bool whether a handler is found and detached.
* @see on()
*/
public static function off($class, $name, $handler = null)
@ -147,7 +149,7 @@ class Event extends Object
* to the named event.
* @param string|object $class the object or the fully qualified class name specifying the class-level event.
* @param string $name the event name.
* @return boolean whether there is any handler attached to the event.
* @return bool whether there is any handler attached to the event.
*/
public static function hasHandlers($class, $name)
{

2
framework/base/Exception.php

@ -10,6 +10,8 @@ namespace yii\base;
/**
* Exception represents a generic exception for all purposes.
*
* For more details and usage information on Exception, see the [guide article on handling errors](guide:runtime-handling-errors).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/

6
framework/base/ExitException.php

@ -18,16 +18,16 @@ namespace yii\base;
class ExitException extends \Exception
{
/**
* @var integer the exit status code
* @var int the exit status code
*/
public $statusCode;
/**
* Constructor.
* @param integer $status the exit status code
* @param int $status the exit status code
* @param string $message error message
* @param integer $code error code
* @param int $code error code
* @param \Exception $previous The previous exception used for the exception chaining.
*/
public function __construct($status = 0, $message = null, $code = 0, \Exception $previous = null)

2
framework/base/InlineAction.php

@ -15,6 +15,8 @@ use Yii;
* The name of the controller method is available via [[actionMethod]] which
* is set by the [[controller]] who creates this action.
*
* For more details and usage information on InlineAction, see the [guide article on actions](guide:structure-controllers).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/

32
framework/base/Model.php

@ -35,6 +35,8 @@ use yii\validators\Validator;
*
* You may directly use Model to store model data, or extend it with customization.
*
* For more details and usage information on Model, see the [guide article on models](guide:structure-models).
*
* @property \yii\validators\Validator[] $activeValidators The validators applicable to the current
* [[scenario]]. This property is read-only.
* @property array $attributes Attribute values (name => value).
@ -328,8 +330,8 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab
* @param array $attributeNames list of attribute names that should be validated.
* If this parameter is empty, it means any attribute listed in the applicable
* validation rules should be validated.
* @param boolean $clearErrors whether to call [[clearErrors()]] before performing validation
* @return boolean whether the validation is successful without any error.
* @param bool $clearErrors whether to call [[clearErrors()]] before performing validation
* @return bool whether the validation is successful without any error.
* @throws InvalidParamException if the current scenario is unknown.
*/
public function validate($attributeNames = null, $clearErrors = true)
@ -365,7 +367,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab
* The default implementation raises a `beforeValidate` event.
* You may override this method to do preliminary checks before validation.
* Make sure the parent implementation is invoked so that the event can be raised.
* @return boolean whether the validation should be executed. Defaults to true.
* @return bool whether the validation should be executed. Defaults to true.
* If false is returned, the validation will stop and the model is considered invalid.
*/
public function beforeValidate()
@ -463,7 +465,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab
* before the model is loaded with data.
*
* @param string $attribute attribute name
* @return boolean whether the attribute is required
* @return bool whether the attribute is required
*/
public function isAttributeRequired($attribute)
{
@ -478,7 +480,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab
/**
* Returns a value indicating whether the attribute is safe for massive assignments.
* @param string $attribute attribute name
* @return boolean whether the attribute is safe for massive assignments
* @return bool whether the attribute is safe for massive assignments
* @see safeAttributes()
*/
public function isAttributeSafe($attribute)
@ -489,7 +491,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab
/**
* Returns a value indicating whether the attribute is active in the current scenario.
* @param string $attribute attribute name
* @return boolean whether the attribute is active in the current scenario
* @return bool whether the attribute is active in the current scenario
* @see activeAttributes()
*/
public function isAttributeActive($attribute)
@ -526,7 +528,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab
/**
* Returns a value indicating whether there is any validation error.
* @param string|null $attribute attribute name. Use null to check all attributes.
* @return boolean whether there is any error.
* @return bool whether there is any error.
*/
public function hasErrors($attribute = null)
{
@ -534,7 +536,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab
}
/**
* Returns the errors for all attribute or a single attribute.
* Returns the errors for all attributes or a single attribute.
* @param string $attribute attribute name. Use null to retrieve errors for all attributes.
* @property array An array of errors for all attributes. Empty array is returned if no error.
* The result is a two-dimensional array. See [[getErrors()]] for detailed description.
@ -633,7 +635,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab
/**
* Removes errors for all attributes or a single attribute.
* @param string $attribute attribute name. Use null to remove errors for all attribute.
* @param string $attribute attribute name. Use null to remove errors for all attributes.
*/
public function clearErrors($attribute = null)
{
@ -684,7 +686,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab
/**
* Sets the attribute values in a massive way.
* @param array $values attribute values (name => value) to be assigned to the model.
* @param boolean $safeOnly whether the assignments should only be done to the safe attributes.
* @param bool $safeOnly whether the assignments should only be done to the safe attributes.
* A safe attribute is one that is associated with a validation rule in the current [[scenario]].
* @see safeAttributes()
* @see attributes()
@ -814,7 +816,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab
* @param array $data the data array to load, typically `$_POST` or `$_GET`.
* @param string $formName the form name to use to load the data into the model.
* If not set, [[formName()]] is used.
* @return boolean whether `load()` found the expected form in `$data`.
* @return bool whether `load()` found the expected form in `$data`.
*/
public function load($data, $formName = null)
{
@ -845,7 +847,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab
* @param string $formName the form name to be used for loading the data into the models.
* If not set, it will use the [[formName()]] value of the first model in `$models`.
* This parameter is available since version 2.0.1.
* @return boolean whether at least one of the models is successfully populated.
* @return bool whether at least one of the models is successfully populated.
*/
public static function loadMultiple($models, $data, $formName = null)
{
@ -883,7 +885,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab
* @param array $attributeNames list of attribute names that should be validated.
* If this parameter is empty, it means any attribute listed in the applicable
* validation rules should be validated.
* @return boolean whether all models are valid. False will be returned if one
* @return bool whether all models are valid. False will be returned if one
* or multiple models have validation error.
*/
public static function validateMultiple($models, $attributeNames = null)
@ -965,7 +967,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab
* This method is required by the SPL interface [[\ArrayAccess]].
* It is implicitly called when you use something like `isset($model[$offset])`.
* @param mixed $offset the offset to check on.
* @return boolean whether or not an offset exists.
* @return bool whether or not an offset exists.
*/
public function offsetExists($offset)
{
@ -988,7 +990,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab
* Sets the element at the specified offset.
* This method is required by the SPL interface [[\ArrayAccess]].
* It is implicitly called when you use something like `$model[$offset] = $item;`.
* @param integer $offset the offset to set element
* @param int $offset the offset to set element
* @param mixed $item the element value
*/
public function offsetSet($offset, $item)

2
framework/base/ModelEvent.php

@ -16,7 +16,7 @@ namespace yii\base;
class ModelEvent extends Event
{
/**
* @var boolean whether the model is in valid status. Defaults to true.
* @var bool whether the model is in valid status. Defaults to true.
* A model is in valid status if it passes validations or certain checks.
*/
public $isValid = true;

84
framework/base/Module.php

@ -21,6 +21,8 @@ use yii\di\ServiceLocator;
* [[components|Components]] may be registered with the module so that they are globally
* accessible within the module.
*
* For more details and usage information on Module, see the [guide article on modules](guide:structure-modules).
*
* @property array $aliases List of path aliases to be defined. The array keys are alias names (must start
* with `@`) and the array values are the corresponding paths or aliases. See [[setAliases()]] for an example.
* This property is write-only.
@ -31,6 +33,7 @@ use yii\di\ServiceLocator;
* @property array $modules The modules (indexed by their IDs).
* @property string $uniqueId The unique ID of the module. This property is read-only.
* @property string $viewPath The root directory of view files. Defaults to "[[basePath]]/views".
* @property string|callable $version The version of this module.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
@ -60,7 +63,7 @@ class Module extends ServiceLocator
*/
public $module;
/**
* @var string|boolean the layout that should be applied for views within this module. This refers to a view name
* @var string|bool the layout that should be applied for views within this module. This refers to a view name
* relative to [[layoutPath]]. If this is not set, it means the layout value of the [[module|parent module]]
* will be taken. If this is `false`, layout will be disabled within this module.
*/
@ -123,6 +126,22 @@ class Module extends ServiceLocator
* @var array child modules of this module
*/
private $_modules = [];
/**
* @var string|callable the version of this module.
* Version can be specified as a PHP callback, which can accept module instance as an argument and should
* return the actual version. For example:
*
* ```php
* function (Module $module) {
* //return string|int
* }
* ```
*
* If not set, [[defaultVersion()]] will be used to determine actual value.
*
* @since 2.0.11
*/
private $_version;
/**
@ -283,6 +302,57 @@ class Module extends ServiceLocator
}
/**
* Returns current module version.
* If version is not explicitly set, [[defaultVersion()]] method will be used to determine its value.
* @return string the version of this module.
* @since 2.0.11
*/
public function getVersion()
{
if ($this->_version === null) {
$this->_version = $this->defaultVersion();
} else {
if (!is_scalar($this->_version)) {
$this->_version = call_user_func($this->_version, $this);
}
}
return $this->_version;
}
/**
* Sets current module version.
* @param string|callable $version the version of this module.
* Version can be specified as a PHP callback, which can accept module instance as an argument and should
* return the actual version. For example:
*
* ```php
* function (Module $module) {
* //return string
* }
* ```
*
* @since 2.0.11
*/
public function setVersion($version)
{
$this->_version = $version;
}
/**
* Returns default module version.
* Child class may override this method to provide more specific version detection.
* @return string the version of this module.
* @since 2.0.11
*/
protected function defaultVersion()
{
if ($this->module === null) {
return '1.0';
}
return $this->module->getVersion();
}
/**
* Defines path aliases.
* This method calls [[Yii::setAlias()]] to register the path aliases.
* This method is provided so that you can define path aliases when configuring a module.
@ -311,7 +381,7 @@ class Module extends ServiceLocator
* Checks whether the child module of the specified ID exists.
* This method supports checking the existence of both child and grand child modules.
* @param string $id module ID. For grand child modules, use ID path relative to this module (e.g. `admin/content`).
* @return boolean whether the named module exists. Both loaded and unloaded modules
* @return bool whether the named module exists. Both loaded and unloaded modules
* are considered.
*/
public function hasModule($id)
@ -331,7 +401,7 @@ class Module extends ServiceLocator
* This method supports retrieving both child modules and grand child modules.
* @param string $id module ID (case-sensitive). To retrieve grand child modules,
* use ID path relative to this module (e.g. `admin/content`).
* @param boolean $load whether to load the module if it is not yet loaded.
* @param bool $load whether to load the module if it is not yet loaded.
* @return Module|null the module instance, `null` if the module does not exist.
* @see hasModule()
*/
@ -381,7 +451,7 @@ class Module extends ServiceLocator
/**
* Returns the sub-modules in this module.
* @param boolean $loadedOnly whether to return the loaded sub-modules only. If this is set `false`,
* @param bool $loadedOnly whether to return the loaded sub-modules only. If this is set `false`,
* then all sub-modules registered in this module will be returned, whether they are loaded or not.
* Loaded modules will be returned as objects, while unloaded modules as configuration arrays.
* @return array the modules (indexed by their IDs).
@ -452,7 +522,9 @@ class Module extends ServiceLocator
$oldController = Yii::$app->controller;
Yii::$app->controller = $controller;
$result = $controller->runAction($actionID, $params);
if ($oldController !== null) {
Yii::$app->controller = $oldController;
}
return $result;
} else {
@ -479,7 +551,7 @@ class Module extends ServiceLocator
* part of the route which will be treated as the action ID. Otherwise, `false` will be returned.
*
* @param string $route the route consisting of module, controller and action IDs.
* @return array|boolean If the controller is created successfully, it will be returned together
* @return array|bool If the controller is created successfully, it will be returned together
* with the requested action ID. Otherwise `false` will be returned.
* @throws InvalidConfigException if the controller class and its file do not match.
*/
@ -598,7 +670,7 @@ class Module extends ServiceLocator
* ```
*
* @param Action $action the action to be executed.
* @return boolean whether the action should continue to be executed.
* @return bool whether the action should continue to be executed.
*/
public function beforeAction($action)
{

16
framework/base/Object.php

@ -161,7 +161,7 @@ class Object implements Configurable
*
* Note that if the property is not defined, false will be returned.
* @param string $name the property name or the event name
* @return boolean whether the named property is set (not null).
* @return bool whether the named property is set (not null).
* @see http://php.net/manual/en/function.isset.php
*/
public function __isset($name)
@ -220,8 +220,8 @@ class Object implements Configurable
* - the class has a member variable with the specified name (when `$checkVars` is true);
*
* @param string $name the property name
* @param boolean $checkVars whether to treat member variables as properties
* @return boolean whether the property is defined
* @param bool $checkVars whether to treat member variables as properties
* @return bool whether the property is defined
* @see canGetProperty()
* @see canSetProperty()
*/
@ -239,8 +239,8 @@ class Object implements Configurable
* - the class has a member variable with the specified name (when `$checkVars` is true);
*
* @param string $name the property name
* @param boolean $checkVars whether to treat member variables as properties
* @return boolean whether the property can be read
* @param bool $checkVars whether to treat member variables as properties
* @return bool whether the property can be read
* @see canSetProperty()
*/
public function canGetProperty($name, $checkVars = true)
@ -257,8 +257,8 @@ class Object implements Configurable
* - the class has a member variable with the specified name (when `$checkVars` is true);
*
* @param string $name the property name
* @param boolean $checkVars whether to treat member variables as properties
* @return boolean whether the property can be written
* @param bool $checkVars whether to treat member variables as properties
* @return bool whether the property can be written
* @see canGetProperty()
*/
public function canSetProperty($name, $checkVars = true)
@ -272,7 +272,7 @@ class Object implements Configurable
* The default implementation is a call to php function `method_exists()`.
* You may override this method when you implemented the php magic method `__call()`.
* @param string $name the method name
* @return boolean whether the method is defined
* @return bool whether the method is defined
*/
public function hasMethod($name)
{

8
framework/base/Request.php

@ -12,7 +12,9 @@ use Yii;
/**
* Request represents a request that is handled by an [[Application]].
*
* @property boolean $isConsoleRequest The value indicating whether the current request is made via console.
* For more details and usage information on Request, see the [guide article on requests](guide:runtime-requests).
*
* @property bool $isConsoleRequest The value indicating whether the current request is made via console.
* @property string $scriptFile Entry script file path (processed w/ realpath()).
*
* @author Qiang Xue <qiang.xue@gmail.com>
@ -32,7 +34,7 @@ abstract class Request extends Component
/**
* Returns a value indicating whether the current request is made via command line
* @return boolean the value indicating whether the current request is made via console
* @return bool the value indicating whether the current request is made via console
*/
public function getIsConsoleRequest()
{
@ -41,7 +43,7 @@ abstract class Request extends Component
/**
* Sets the value indicating whether the current request is made via command line
* @param boolean $value the value indicating whether the current request is made via command line
* @param bool $value the value indicating whether the current request is made via command line
*/
public function setIsConsoleRequest($value)
{

4
framework/base/Response.php

@ -10,13 +10,15 @@ namespace yii\base;
/**
* Response represents the response of an [[Application]] to a [[Request]].
*
* For more details and usage information on Response, see the [guide article on responses](guide:runtime-responses).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Response extends Component
{
/**
* @var integer the exit status. Exit statuses should be in the range 0 to 254.
* @var int the exit status. Exit statuses should be in the range 0 to 254.
* The status 0 means the program terminates successfully.
*/
public $exitStatus = 0;

48
framework/base/Security.php

@ -23,6 +23,8 @@ use Yii;
* > Note: this class requires 'OpenSSL' PHP extension for random key/string generation on Windows and
* for encryption/decryption on all platforms. For the highest security level PHP version >= 5.5.0 is recommended.
*
* For more details and usage information on Security, see the [guide article on security](guide:security-overview).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Tom Worster <fsb@thefsb.org>
* @author Klimov Paul <klimov.paul@gmail.com>
@ -67,12 +69,22 @@ class Security extends Component
*/
public $authKeyInfo = 'AuthorizationKey';
/**
* @var integer derivation iterations count.
* @var int derivation iterations count.
* Set as high as possible to hinder dictionary password attacks.
*/
public $derivationIterations = 100000;
/**
* @var integer Default cost used for password hashing.
* @var string strategy, which should be used to generate password hash.
* Available strategies:
* - 'password_hash' - use of PHP `password_hash()` function with PASSWORD_DEFAULT algorithm.
* This option is recommended, but it requires PHP version >= 5.5.0
* - 'crypt' - use PHP `crypt()` function.
* @deprecated Since version 2.0.7, [[generatePasswordHash()]] ignores [[passwordHashStrategy]] and
* uses `password_hash()` when available or `crypt()` when not.
*/
public $passwordHashStrategy;
/**
* @var int Default cost used for password hashing.
* Allowed value is between 4 and 31.
* @see generatePasswordHash()
* @since 2.0.6
@ -124,7 +136,7 @@ class Security extends Component
* Verifies and decrypts data encrypted with [[encryptByPassword()]].
* @param string $data the encrypted data to decrypt
* @param string $password the password to use for decryption
* @return boolean|string the decrypted data or false on authentication failure
* @return bool|string the decrypted data or false on authentication failure
* @see encryptByPassword()
*/
public function decryptByPassword($data, $password)
@ -137,7 +149,7 @@ class Security extends Component
* @param string $data the encrypted data to decrypt
* @param string $inputKey the input to use for encryption and authentication
* @param string $info optional context and application specific information, see [[hkdf()]]
* @return boolean|string the decrypted data or false on authentication failure
* @return bool|string the decrypted data or false on authentication failure
* @see encryptByKey()
*/
public function decryptByKey($data, $inputKey, $info = null)
@ -149,7 +161,7 @@ class Security extends Component
* Encrypts data.
*
* @param string $data data to be encrypted
* @param boolean $passwordBased set true to use password-based key derivation
* @param bool $passwordBased set true to use password-based key derivation
* @param string $secret the encryption password or key
* @param string $info context/application specific information, e.g. a user ID
* See [RFC 5869 Section 3.2](https://tools.ietf.org/html/rfc5869#section-3.2) for more details.
@ -200,11 +212,11 @@ class Security extends Component
* Decrypts data.
*
* @param string $data encrypted data to be decrypted.
* @param boolean $passwordBased set true to use password-based key derivation
* @param bool $passwordBased set true to use password-based key derivation
* @param string $secret the decryption password or key
* @param string $info context/application specific information, @see encrypt()
*
* @return boolean|string the decrypted data or false on authentication failure
* @return bool|string the decrypted data or false on authentication failure
* @throws InvalidConfigException on OpenSSL not loaded
* @throws Exception on OpenSSL error
* @see encrypt()
@ -254,7 +266,7 @@ class Security extends Component
* @param string $info optional info to bind the derived key material to application-
* and context-specific information, e.g. a user ID or API version, see
* [RFC 5869](https://tools.ietf.org/html/rfc5869)
* @param integer $length length of the output key in bytes. If 0, the output key is
* @param int $length length of the output key in bytes. If 0, the output key is
* the length of the hash algorithm output.
* @throws InvalidParamException when HMAC generation fails.
* @return string the derived key
@ -299,9 +311,9 @@ class Security extends Component
* @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256'
* @param string $password the source password
* @param string $salt the random salt
* @param integer $iterations the number of iterations of the hash algorithm. Set as high as
* @param int $iterations the number of iterations of the hash algorithm. Set as high as
* possible to hinder dictionary password attacks.
* @param integer $length length of the output key in bytes. If 0, the output key is
* @param int $length length of the output key in bytes. If 0, the output key is
* the length of the hash algorithm output.
* @return string the derived key
* @throws InvalidParamException when hash generation fails due to invalid params given.
@ -360,7 +372,7 @@ class Security extends Component
* @param string $data the data to be protected
* @param string $key the secret key to be used for generating hash. Should be a secure
* cryptographic key.
* @param boolean $rawHash whether the generated hash value is in raw binary format. If false, lowercase
* @param bool $rawHash whether the generated hash value is in raw binary format. If false, lowercase
* hex digits will be generated.
* @return string the data prefixed with the keyed hash
* @throws InvalidConfigException when HMAC generation fails.
@ -385,7 +397,7 @@ class Security extends Component
* @param string $key the secret key that was previously used to generate the hash for the data in [[hashData()]].
* function to see the supported hashing algorithms on your system. This must be the same
* as the value passed to [[hashData()]] when generating the hash for the data.
* @param boolean $rawHash this should take the same value as when you generate the data using [[hashData()]].
* @param bool $rawHash this should take the same value as when you generate the data using [[hashData()]].
* It indicates whether the hash value in the data is in binary format. If false, it means the hash value consists
* of lowercase hex digits only.
* hex digits will be generated.
@ -421,7 +433,7 @@ class Security extends Component
* Note that output may not be ASCII.
* @see generateRandomString() if you need a string.
*
* @param integer $length the number of bytes to generate
* @param int $length the number of bytes to generate
* @return string the generated random bytes
* @throws InvalidParamException if wrong length is specified
* @throws Exception on failure.
@ -532,7 +544,7 @@ class Security extends Component
* Generates a random string of specified length.
* The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.
*
* @param integer $length the length of the key in characters
* @param int $length the length of the key in characters
* @return string the generated random key
* @throws Exception on failure.
*/
@ -573,7 +585,7 @@ class Security extends Component
* ```
*
* @param string $password The password to be hashed.
* @param integer $cost Cost parameter used by the Blowfish hash algorithm.
* @param int $cost Cost parameter used by the Blowfish hash algorithm.
* The higher the value of cost,
* the longer it takes to generate the hash and to verify a password against it. Higher cost
* therefore slows down a brute-force attack. For best protection against brute-force attacks,
@ -610,7 +622,7 @@ class Security extends Component
* Verifies a password against a hash.
* @param string $password The password to verify.
* @param string $hash The hash to verify the password against.
* @return boolean whether the password is correct.
* @return bool whether the password is correct.
* @throws InvalidParamException on bad password/hash parameters or if crypt() with Blowfish hash is not available.
* @see generatePasswordHash()
*/
@ -648,7 +660,7 @@ class Security extends Component
* "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters
* from the alphabet "./0-9A-Za-z".
*
* @param integer $cost the cost parameter
* @param int $cost the cost parameter
* @return string the random salt value.
* @throws InvalidParamException if the cost parameter is out of the range of 4 to 31.
*/
@ -674,7 +686,7 @@ class Security extends Component
* @see http://codereview.stackexchange.com/questions/13512
* @param string $expected string to compare.
* @param string $actual user-supplied string.
* @return boolean whether strings are equal.
* @return bool whether strings are equal.
*/
public function compareString($expected, $actual)
{

2
framework/base/Theme.php

@ -61,6 +61,8 @@ use yii\helpers\FileHelper;
* that contains the entry script of the application. If your theme is designed to handle modules,
* you may configure the [[pathMap]] property like described above.
*
* For more details and usage information on Theme, see the [guide article on theming](guide:output-theming).
*
* @property string $basePath The root path of this theme. All resources of this theme are located under this
* directory.
* @property string $baseUrl The base URL (without ending slash) for this theme. All resources of this theme

12
framework/base/View.php

@ -18,7 +18,9 @@ use yii\widgets\FragmentCache;
*
* View provides a set of methods (e.g. [[render()]]) for rendering purpose.
*
* @property string|boolean $viewFile The view file currently being rendered. False if no view file is being
* For more details and usage information on View, see the [guide article on views](guide:structure-views).
*
* @property string|bool $viewFile The view file currently being rendered. False if no view file is being
* rendered. This property is read-only.
*
* @author Qiang Xue <qiang.xue@gmail.com>
@ -257,7 +259,7 @@ class View extends Component
}
/**
* @return string|boolean the view file currently being rendered. False if no view file is being rendered.
* @return string|bool the view file currently being rendered. False if no view file is being rendered.
*/
public function getViewFile()
{
@ -270,7 +272,7 @@ class View extends Component
* If you override this method, make sure you call the parent implementation first.
* @param string $viewFile the view file to be rendered.
* @param array $params the parameter array passed to the [[render()]] method.
* @return boolean whether to continue rendering the view file.
* @return bool whether to continue rendering the view file.
*/
public function beforeRender($viewFile, $params)
{
@ -393,7 +395,7 @@ class View extends Component
* Begins recording a block.
* This method is a shortcut to beginning [[Block]]
* @param string $id the block ID.
* @param boolean $renderInPlace whether to render the block content in place.
* @param bool $renderInPlace whether to render the block content in place.
* Defaults to false, meaning the captured block will not be displayed.
* @return Block the Block widget instance
*/
@ -464,7 +466,7 @@ class View extends Component
*
* @param string $id a unique ID identifying the fragment to be cached.
* @param array $properties initial property values for [[FragmentCache]]
* @return boolean whether you should generate the content for caching.
* @return bool whether you should generate the content for caching.
* False if the cached version is available.
*/
public function beginCache($id, $properties = [])

2
framework/base/ViewEvent.php

@ -31,7 +31,7 @@ class ViewEvent extends Event
*/
public $output;
/**
* @var boolean whether to continue rendering the view file. Event handlers of
* @var bool whether to continue rendering the view file. Event handlers of
* [[View::EVENT_BEFORE_RENDER]] may set this property to decide whether
* to continue rendering the current view file.
*/

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

Loading…
Cancel
Save