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. 14
      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. 4
      docs/guide-es/input-validation.md
  8. 4
      docs/guide-es/rest-controllers.md
  9. 16
      docs/guide-es/security-authorization.md
  10. 54
      docs/guide-fr/input-validation.md
  11. 80
      docs/guide-fr/output-client-scripts.md
  12. 42
      docs/guide-fr/security-authentication.md
  13. 56
      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. 8
      docs/guide-ja/security-authentication.md
  18. 4
      docs/guide-ja/security-authorization.md
  19. 56
      docs/guide-pl/caching-http.md
  20. 131
      docs/guide-pl/concept-aliases.md
  21. 89
      docs/guide-pl/concept-autoloading.md
  22. 96
      docs/guide-pl/input-validation.md
  23. 4
      docs/guide-pl/start-databases.md
  24. 18
      docs/guide-pt-BR/caching-http.md
  25. 4
      docs/guide-pt-BR/rest-controllers.md
  26. 22
      docs/guide-pt-BR/security-authentication.md
  27. 6
      docs/guide-pt-BR/security-authorization.md
  28. 2
      docs/guide-ru/README.md
  29. 10
      docs/guide-ru/caching-http.md
  30. 2
      docs/guide-ru/caching-page.md
  31. 2
      docs/guide-ru/db-active-record.md
  32. 232
      docs/guide-ru/db-migrations.md
  33. 42
      docs/guide-ru/input-forms.md
  34. 88
      docs/guide-ru/input-validation.md
  35. 12
      docs/guide-ru/output-data-widgets.md
  36. 4
      docs/guide-ru/rest-controllers.md
  37. 20
      docs/guide-ru/security-authentication.md
  38. 14
      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. 15
      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. 18
      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. 40
      docs/guide/security-authentication.md
  56. 18
      docs/guide/security-authorization.md
  57. 2
      docs/guide/start-installation.md
  58. 17
      docs/guide/tutorial-core-validators.md
  59. 8
      docs/internals-ja/core-code-style.md
  60. 28
      docs/internals-pl/core-code-style.md
  61. 4
      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. 33
      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. 69
      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. 86
      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

14
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)
{
$ref = new \ReflectionClass($className);
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`.

4
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)
```
@ -410,7 +410,7 @@ class CountryValidator extends Validator
}
```
Si quieres que tu validador soporte la validación de un valor sin modelo, deberías también sobrescribir
Si quieres que tu validador soporte la validación de un valor sin modelo, deberías también sobrescribir
el método[[yii\validators\Validator::validate()]]. Puedes también sobrescribir [[yii\validators\Validator::validateValue()]]
en vez de `validateAttribute()` y `validate()` porque por defecto los últimos dos métodos son implementados
llamando a `validateValue()`.

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));
}
}
```

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

@ -8,9 +8,9 @@ dos métodos de autorización: Filtro de Control de Acceso y Control Basado en R
## Filtro de Control de Acceso <span id="access-control-filter"></span>
Filtro de Control de Acceso (ACF) es un único método de autorización implementado como [[yii\filters\AccessControl]], el cual
es mejor utilizado por aplicaciones que sólo requieran un control de acceso simple. Como su nombre lo indica, ACF es
es mejor utilizado por aplicaciones que sólo requieran un control de acceso simple. Como su nombre lo indica, ACF es
un [filtro](structure-filters.md) de acción que puede ser utilizado en un controlador o en un módulo. Cuando un usuario solicita
la ejecución de una acción, ACF comprobará una lista de [[yii\filters\AccessControl::rules|reglas de acceso]]
la ejecución de una acción, ACF comprobará una lista de [[yii\filters\AccessControl::rules|reglas de acceso]]
para determinar si el usuario tiene permitido acceder a dicha acción.
El siguiente código muestra cómo utilizar ACF en el controlador `site`:
@ -48,7 +48,7 @@ class SiteController extends Controller
En el código anterior, ACF es adjuntado al controlador `site` en forma de behavior (comportamiento). Esta es la forma típica de utilizar
un filtro de acción. La opción `only` especifica que el ACF debe ser aplicado solamente a las acciones `login`, `logout` y `signup`.
Las acciones restantes en el controlador `site` no están sujetas al control de acceso. La opción `rules` lista
Las acciones restantes en el controlador `site` no están sujetas al control de acceso. La opción `rules` lista
las [[yii\filters\AccessRule|reglas de acceso]], y se lee como a continuación:
- Permite a todos los usuarios invitados (sin autenticar) acceder a las acciones `login` y `signup`. La opción `roles`
@ -57,7 +57,7 @@ las [[yii\filters\AccessRule|reglas de acceso]], y se lee como a continuación:
a los "usuarios autenticados".
ACF ejecuta la comprobación de autorización examinando las reglas de acceso una a una desde arriba hacia abajo hasta que encuentra
una regla que aplique al contexto de ejecución actual. El valor `allow` de la regla que coincida será entonces utilizado
una regla que aplique al contexto de ejecución actual. El valor `allow` de la regla que coincida será entonces utilizado
para juzgar si el usuario está autorizado o no. Si ninguna de las reglas coincide, significa que el usuario NO está autorizado,
y el ACF detendrá la ejecución de la acción.
@ -97,7 +97,7 @@ La comparación es sensible a mayúsculas. Si la opción está vacía o no defin
- `?`: coincide con el usuario invitado (sin autenticar)
- `@`: coincide con el usuario autenticado
El utilizar otro nombre de rol invocará una llamada a [[yii\web\User::can()]], que requiere habilitar RBAC
El utilizar otro nombre de rol invocará una llamada a [[yii\web\User::can()]], que requiere habilitar RBAC
(a ser descrito en la próxima subsección). Si la opción está vacía o no definida, significa que la regla se aplica a todos los roles.
* [[yii\filters\AccessRule::ips|ips]]: especifica con qué [[yii\web\Request::userIP|dirección IP del cliente]] coincide esta regla.
@ -231,7 +231,7 @@ return [
necesita declararse `authManager` adicionalmente a `config/web.php`.
> En el caso de yii2-advanced-app, `authManager` sólo debe declararse en `common/config/main.php`.
`DbManager` utiliza cuatro tablas de la BD para almacenar los datos:
`DbManager` utiliza cuatro tablas de la BD para almacenar los datos:
- [[yii\rbac\DbManager::$itemTable|itemTable]]: la tabla para almacenar los ítems de autorización. Por defecto "auth_item".
- [[yii\rbac\DbManager::$itemChildTable|itemChildTable]]: la tabla para almacentar la jerarquía de los ítems de autorización. Por defecto "auth_item_child".
@ -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)
{

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

@ -45,12 +45,12 @@ La méthode [[yii\base\Model::rules()|rules()]] doit retourner un tableau de rè
```php
[
// obligatoire, spécifie quels attributs doivent être validés par cette règle.
// Pour un attribut unique, vous pouvez utiliser le nom de l'attribut directement
// Pour un attribut unique, vous pouvez utiliser le nom de l'attribut directement
// sans le mettre dans un tableau
['attribute1', 'attribute2', ...],
// obligatoire, spécifier le type de cette règle.
// Il peut s'agir d'un nom de classe, d'un alias de validateur ou du nom d'une méthode de validation
// Il peut s'agir d'un nom de classe, d'un alias de validateur ou du nom d'une méthode de validation
'validator',
// facultatif, spécifie dans quel(s) scénario(s) cette règle doit être appliquée
@ -64,23 +64,23 @@ La méthode [[yii\base\Model::rules()|rules()]] doit retourner un tableau de rè
]
```
Pour chacune des règles vous devez spécifier au moins à quels attributs la règle s'applique et quel est le type de cette règle. Vous pouvez spécifier le type de la règle sous l'une des formes suivantes :
Pour chacune des règles vous devez spécifier au moins à quels attributs la règle s'applique et quel est le type de cette règle. Vous pouvez spécifier le type de la règle sous l'une des formes suivantes :
* l'alias d'un validateur du noyau, comme `required`, `in`, `date`, etc. Reportez-vous à la sous-section [Validateurs du noyau](tutorial-core-validators.md) pour une liste complète des validateurs du noyau.
* le nom d'une méthode de validation dans la classe du modèle, ou une fonction anonyme. Reportez-vous à la sous-section [Inline Validators](#inline-validators) pour plus de détails.
* un nom de classe de validateur pleinement qualifié. Reportez-vous à la sous-section [Validateurs autonomes](#standalone-validators) pour plus de détails.
Une règle peut être utilisée pour valider un ou plusieurs attributs, et un attribut peut être validé par une ou plusieurs règles. Une règle peut s'appliquer dans certains [scenarios](structure-models.md#scenarios) seulement en spécifiant l'option `on`. Si vous ne spécifiez pas l'option `on`, la règle s'applique à tous les scénarios.
Une règle peut être utilisée pour valider un ou plusieurs attributs, et un attribut peut être validé par une ou plusieurs règles. Une règle peut s'appliquer dans certains [scenarios](structure-models.md#scenarios) seulement en spécifiant l'option `on`. Si vous ne spécifiez pas l'option `on`, la règle s'applique à tous les scénarios.
Quand la méthode `validate()` est appelée, elle suit les étapes suivantes pour effectuer l'examen de validation :
1. Détermine quels attributs doivent être validés en obtenant la liste des attributs de [[yii\base\Model::scenarios()]] en utilisant le [[yii\base\Model::scenario|scenario]] courant. Ces attributs sont appelés *attributs actifs*.
1. Détermine quels attributs doivent être validés en obtenant la liste des attributs de [[yii\base\Model::scenarios()]] en utilisant le [[yii\base\Model::scenario|scenario]] courant. Ces attributs sont appelés *attributs actifs*.
2. Détermine quelles règles de validation doivent être appliquées en obtenant la liste des règles de [[yii\base\Model::rules()]] en utilisant le [[yii\base\Model::scenario|scenario]] courant. Ces règles sont appelées *règles actives*.
3. Utilise chacune des règles actives pour valider chacun des attributs qui sont associés à cette règle. Les règles sont évaluées dans l'ordre dans lequel elles sont listées.
3. Utilise chacune des règles actives pour valider chacun des attributs qui sont associés à cette règle. Les règles sont évaluées dans l'ordre dans lequel elles sont listées.
Selon les étapes de validation décrites ci-dessus, un attribut est validé si, et seulement si, il est un attribut actif déclaré dans `scenarios()` et est associé à une ou plusieurs règles actives déclarées dans `rules()`.
> Note: il est pratique le nommer les règles, c.-à-d.
> Note: il est pratique le nommer les règles, c.-à-d.
>
> ```php
> public function rules()
@ -105,7 +105,7 @@ Selon les étapes de validation décrites ci-dessus, un attribut est validé si,
### Personnalisation des messages d'erreur <span id="customizing-error-messages"></span>
La plupart des validateurs possèdent des messages d'erreurs qui sont ajoutés au modèle en cours de validation lorsque ses attributs ne passent pas la validation. Par exemple, le validateur [[yii\validators\RequiredValidator|required]] ajoute le message "Username cannot be blank." (Le nom d'utilisateur ne peut être vide.) au modèle lorsque l'attribut `username` ne passe pas la règle de validation utilisant ce validateur.
La plupart des validateurs possèdent des messages d'erreurs qui sont ajoutés au modèle en cours de validation lorsque ses attributs ne passent pas la validation. Par exemple, le validateur [[yii\validators\RequiredValidator|required]] ajoute le message "Username cannot be blank." (Le nom d'utilisateur ne peut être vide.) au modèle lorsque l'attribut `username` ne passe pas la règle de validation utilisant ce validateur.
Vous pouvez personnaliser le message d'erreur d'une règle en spécifiant la propriété `message` lors de la déclaration de la règle, comme ceci :
@ -118,14 +118,14 @@ public function rules()
}
```
Quelques validateurs peuvent prendre en charge des messages d'erreur additionnels pour décrire précisément les différentes causes de non validation. Par exemple, le validateur [[yii\validators\NumberValidator|number]] prend en charge[[yii\validators\NumberValidator::tooBig|tooBig (trop grand)]] et [[yii\validators\NumberValidator::tooSmall|tooSmall (trop petit)]] pour décrire la cause de non validation lorsque la valeur à valider est trop grande ou trop petite, respectivement. Vous pouvez configurer ces messages d'erreur comme vous configureriez d'autres propriétés de validateurs dans une règle de validation.
Quelques validateurs peuvent prendre en charge des messages d'erreur additionnels pour décrire précisément les différentes causes de non validation. Par exemple, le validateur [[yii\validators\NumberValidator|number]] prend en charge[[yii\validators\NumberValidator::tooBig|tooBig (trop grand)]] et [[yii\validators\NumberValidator::tooSmall|tooSmall (trop petit)]] pour décrire la cause de non validation lorsque la valeur à valider est trop grande ou trop petite, respectivement. Vous pouvez configurer ces messages d'erreur comme vous configureriez d'autres propriétés de validateurs dans une règle de validation.
### Événement de validation <span id="validation-events"></span>
Losque la méthode [[yii\base\Model::validate()]] est appelée, elle appelle deux méthodes que vous pouvez redéfinir pour personnaliser le processus de validation :
* [[yii\base\Model::beforeValidate()]]: la mise en œuvre par défaut déclenche un événement [[yii\base\Model::EVENT_BEFORE_VALIDATE]]. Vous pouvez, soit redéfinir cette méthode, soit répondre à cet événement pour accomplir un travail de pré-traitement (p. ex. normaliser les données entrées) avant que l'examen de validation n'ait lieu. La méthode retourne une valeur booléenne indiquant si l'examen de validation doit avoir lieu ou pas.
* [[yii\base\Model::beforeValidate()]]: la mise en œuvre par défaut déclenche un événement [[yii\base\Model::EVENT_BEFORE_VALIDATE]]. Vous pouvez, soit redéfinir cette méthode, soit répondre à cet événement pour accomplir un travail de pré-traitement (p. ex. normaliser les données entrées) avant que l'examen de validation n'ait lieu. La méthode retourne une valeur booléenne indiquant si l'examen de validation doit avoir lieu ou pas.
* [[yii\base\Model::afterValidate()]]: la mise en œuvre par défaut déclenche un événement [[yii\base\Model::EVENT_AFTER_VALIDATE]]. Vous pouvez, soit redéfinir cette méthode, soit répondre à cet événement pour accomplir un travail de post-traitement après que l'examen de validation a eu lieu.
@ -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)
```
@ -163,7 +163,7 @@ Si vous avez aussi besoin de la prise en charge côté client de la validation c
### Filtrage des données <span id="data-filtering"></span>
Les entrées utilisateur nécessitent souvent d'être filtrées ou pré-traitées. Par exemple, vous désirez peut-être vous débarrasser des espaces devant et derrière l'entrée `username`. Vous pouvez utiliser les règles de validation pour le faire.
Les entrées utilisateur nécessitent souvent d'être filtrées ou pré-traitées. Par exemple, vous désirez peut-être vous débarrasser des espaces devant et derrière l'entrée `username`. Vous pouvez utiliser les règles de validation pour le faire.
Les exemples suivants montrent comment se débarrasser des espaces dans les entrées et transformer des entrées vides en `nulls` en utilisant les validateurs du noyau [trim](tutorial-core-validators.md#trim) et [default](tutorial-core-validators.md#default) :
@ -176,7 +176,7 @@ return [
Vous pouvez également utiliser le validateur plus général [filter](tutorial-core-validators.md#filter) pour accomplir un filtrage plus complexe des données.
Comme vous le voyez, ces règles de validation ne pratiquent pas un examen de validation proprement dit. Plus exactement, elles traitent les valeurs et les sauvegardent dans les attributs en cours de validation.
Comme vous le voyez, ces règles de validation ne pratiquent pas un examen de validation proprement dit. Plus exactement, elles traitent les valeurs et les sauvegardent dans les attributs en cours de validation.
### Gestion des entrées vides <span id="handling-empty-inputs"></span>
@ -185,7 +185,7 @@ Lorsque les entrées sont soumises par des formulaires HTML, vous devez souvent
```php
return [
// définit "username" et "email" comme *null* si elles sont vides
// définit "username" et "email" comme *null* si elles sont vides
[['username', 'email'], 'default'],
// définit "level" à 1 si elle est vide
@ -206,7 +206,7 @@ Par défaut, une entrée est considérée vide si sa valeur est une chaîne de c
## Validation ad hoc <span id="ad-hoc-validation"></span>
Parfois vous avez besoin de faire une *validation ad hoc* pour des valeurs qui ne sont pas liées à un modèle.
Parfois vous avez besoin de faire une *validation ad hoc* pour des valeurs qui ne sont pas liées à un modèle.
Si vous n'avez besoin d'effectuer qu'un seul type de validation (p. ex. valider une adresse de courriel), vous pouvez appeler la méthode [[yii\validators\Validator::validate()|validate()]] du validateur désiré, comme ceci :
@ -221,7 +221,7 @@ if ($validator->validate($email, $error)) {
}
```
> Note: tous les validateurs ne prennent pas en charge ce type de validation. Le validateur du noyau [unique](tutorial-core-validators.md#unique), qui est conçu pour travailler avec un modèle uniquement, en est un exemple.
> Note: tous les validateurs ne prennent pas en charge ce type de validation. Le validateur du noyau [unique](tutorial-core-validators.md#unique), qui est conçu pour travailler avec un modèle uniquement, en est un exemple.
Si vous avez besoin de validations multiples pour plusieurs valeurs, vous pouvez utiliser [[yii\base\DynamicModel]] qui prend en charge, à la fois les attributs et les règles à la volée. Son utilisation ressemble à ce qui suit :
@ -241,7 +241,7 @@ public function actionSearch($name, $email)
}
```
La méthode [[yii\base\DynamicModel::validateData()]] crée une instance de `DynamicModel`, définit les attributs utilisant les données fournies (`name` et `email` dans cet exemple), puis appelle [[yii\base\Model::validate()]] avec les règles données.
La méthode [[yii\base\DynamicModel::validateData()]] crée une instance de `DynamicModel`, définit les attributs utilisant les données fournies (`name` et `email` dans cet exemple), puis appelle [[yii\base\Model::validate()]] avec les règles données.
En alternative, vous pouvez utiliser la syntaxe plus *classique* suivante pour effectuer la validation ad hoc :
@ -266,7 +266,7 @@ Après l'examen de validation, vous pouvez vérifier si la validation a réussi
## Création de validateurs <span id="creating-validators"></span>
En plus de pouvoir utiliser les [validateurs du noyau](tutorial-core-validators.md) inclus dans les versions publiées de Yii, vous pouvez également créer vos propres validateurs. Vous pouvez créer des validateurs en ligne et des validateurs autonomes.
En plus de pouvoir utiliser les [validateurs du noyau](tutorial-core-validators.md) inclus dans les versions publiées de Yii, vous pouvez également créer vos propres validateurs. Vous pouvez créer des validateurs en ligne et des validateurs autonomes.
### Validateurs en ligne <span id="inline-validators"></span>
@ -281,7 +281,7 @@ Un validateur en ligne est un validateur défini sous forme de méthode de modè
function ($attribute, $params)
```
Si un attribut ne réussit pas l'examen de validation, la méthode/fonction doit appeler [[yii\base\Model::addError()]] pour sauvegarder le message d'erreur dans le modèle de manière à ce qu'il puisse être retrouvé plus tard pour être présenté à l'utilisateur.
Si un attribut ne réussit pas l'examen de validation, la méthode/fonction doit appeler [[yii\base\Model::addError()]] pour sauvegarder le message d'erreur dans le modèle de manière à ce qu'il puisse être retrouvé plus tard pour être présenté à l'utilisateur.
Voici quelques exemples :
@ -351,7 +351,7 @@ class CountryValidator extends Validator
Si vous voulez que votre validateur prennent en charge la validation d'une valeur sans modèle, vous devez redéfinir la méthode [[yii\validators\Validator::validate()]]. Vous pouvez aussi redéfinir [[yii\validators\Validator::validateValue()]] au lieu de `validateAttribute()` et `validate()`, parce que, par défaut, les deux dernières méthodes sont appelées en appelant `validateValue()`.
Ci-dessous, nous présentons un exemple de comment utiliser la classe de validateur précédente dans votre modèle.
Ci-dessous, nous présentons un exemple de comment utiliser la classe de validateur précédente dans votre modèle.
```php
namespace app\models;
@ -380,7 +380,7 @@ class EntryForm extends Model
## Validation côté client <span id="client-side-validation"></span>
La validation côté client basée sur JavaScript est souhaitable lorsque l'utilisateur fournit les entrées via des formulaires HTML, parce que cela permet à l'utilisateur de détecter plus vite les erreurs et lui apporte ainsi un meilleur ressenti. Vous pouvez utiliser ou implémenter un validateur qui prend en charge la validation côté client *en plus* de la validation côté serveur.
La validation côté client basée sur JavaScript est souhaitable lorsque l'utilisateur fournit les entrées via des formulaires HTML, parce que cela permet à l'utilisateur de détecter plus vite les erreurs et lui apporte ainsi un meilleur ressenti. Vous pouvez utiliser ou implémenter un validateur qui prend en charge la validation côté client *en plus* de la validation côté serveur.
> Info: bien que la validation côté client soit souhaitable, ce n'est pas une obligation. Son but principal est d'apporter un meilleur ressenti à l'utilisateur. Comme pour les données venant de l'utilisateur, vous ne devriez jamais faire confiance à la validation côté client. Pour cette raison, vous devez toujours effectuer la validation côté serveur en appelant [[yii\base\Model::validate()]], comme nous l'avons décrit dans les sous-sections précédentes.
@ -433,7 +433,7 @@ Le formulaire HTML construit par le code suivant contient deux champs de saisie
En arrière plan, [[yii\widgets\ActiveForm]] lit les règles de validation déclarées dans le modèle et génère le code JavaScript approprié pour la prise en charge de la validation côté client. Lorsqu'un utilisateur modifie la valeur d'un champ de saisie ou soumet le formulaire, le code JavaScript est appelé.
Si vous désirez inhiber la validation côté client complètement, vous pouvez configurer la propriété [[yii\widgets\ActiveForm::enableClientValidation]] à `false` (faux). Vous pouvez aussi inhiber la validation côté client pour des champs de saisie individuels en configurant leur propriété [[yii\widgets\ActiveField::enableClientValidation]] à `false`. Lorsque `enableClientValidation` est configurée à la fois au niveau du champ et au niveau du formulaire, c'est la première configuration qui prévaut.
Si vous désirez inhiber la validation côté client complètement, vous pouvez configurer la propriété [[yii\widgets\ActiveForm::enableClientValidation]] à `false` (faux). Vous pouvez aussi inhiber la validation côté client pour des champs de saisie individuels en configurant leur propriété [[yii\widgets\ActiveField::enableClientValidation]] à `false`. Lorsque `enableClientValidation` est configurée à la fois au niveau du champ et au niveau du formulaire, c'est la première configuration qui prévaut.
### Mise en œuvre de la validation côté client <span id="implementing-client-side-validation"></span>
@ -445,7 +445,7 @@ Pour créer un validateur qui prend en charge la validation côté client, vous
- `messages`: un tableau utilisé pour contenir les messages d'erreurs pour l'attribut;
- `deferred`: un tableau dans lequel les objets différés peuvent être poussés (explication dans la prochaine sous-section).
Dans l'exemple suivant, nous créons un `StatusValidator` qui valide une entrée si elle représente l'identifiant d'une donnée existante ayant un état valide. Le validateur prend en charge à la fois la validation côté serveur et la validation côté client.
Dans l'exemple suivant, nous créons un `StatusValidator` qui valide une entrée si elle représente l'identifiant d'une donnée existante ayant un état valide. Le validateur prend en charge à la fois la validation côté serveur et la validation côté client.
```php
namespace app\components;
@ -511,7 +511,7 @@ JS;
Dans ce qui précède, la variable `deferred` est fournie par Yii, et représente un tableau de d'objets différés. La méthode `$.get()` crée un objet différé qui est poussé dans le tableau `deferred`.
Vous pouvez aussi créer explicitement un objet différé et appeler sa méthode `resolve()` lorsque la fonction de rappel asynchrone est activée . L'exemple suivant montre comment valider les dimensions d'une image à charger sur le serveur du côté client.
Vous pouvez aussi créer explicitement un objet différé et appeler sa méthode `resolve()` lorsque la fonction de rappel asynchrone est activée . L'exemple suivant montre comment valider les dimensions d'une image à charger sur le serveur du côté client.
```php
public function clientValidateAttribute($model, $attribute, $view)
@ -538,7 +538,7 @@ JS;
> Note: La méthode `resolve()` doit être appelée après que l'attribut a été validé. Autrement la validation principale du formulaire ne se terminera pas.
Pour faire simple, le tableau `deferred` est doté d'une méthode raccourci `add()` qui crée automatiquement un objet différé et l'ajoute au tableau `deferred`. En utilisant cette méthode, vous pouvez simplifier l'exemple ci-dessus comme suit :
Pour faire simple, le tableau `deferred` est doté d'une méthode raccourci `add()` qui crée automatiquement un objet différé et l'ajoute au tableau `deferred`. En utilisant cette méthode, vous pouvez simplifier l'exemple ci-dessus comme suit :
```php
public function clientValidateAttribute($model, $attribute, $view)
@ -567,7 +567,7 @@ JS;
Quelques validations ne peuvent avoir lieu que côté serveur, parce que seul le serveur dispose des informations nécessaires. Par exemple, pour valider l'unicité d'un nom d'utilisateur, il est nécessaire de consulter la table des utilisateurs côté serveur. Vous pouvez utiliser la validation basée sur AJAX dans ce cas. Elle provoquera une requête AJAX en arrière plan pour exécuter l'examen de validation tout en laissant à l'utilisateur le même ressenti que lors d'une validation côté client normale.
Pour activer la validation AJAX pour un unique champ de saisie, configurez la propriété [[yii\widgets\ActiveField::enableAjaxValidation|enableAjaxValidation]] de ce champ à `true` et spécifiez un `identifiant` unique de formulaire :
Pour activer la validation AJAX pour un unique champ de saisie, configurez la propriété [[yii\widgets\ActiveField::enableAjaxValidation|enableAjaxValidation]] de ce champ à `true` et spécifiez un `identifiant` unique de formulaire :
```php
use yii\widgets\ActiveForm;
@ -592,7 +592,7 @@ $form = ActiveForm::begin([
]);
```
> Note: lorsque la propriété `enableAjaxValidation` est configurée à la fois au niveau du champ et au niveau du formulaire, la première configuration prévaut.
> Note: lorsque la propriété `enableAjaxValidation` est configurée à la fois au niveau du champ et au niveau du formulaire, la première configuration prévaut.
Vous devez aussi préparer le serveur de façon à ce qu'il puisse prendre en charge les requêtes de validation AJAX . Cela peut se faire à l'aide d'un fragment de code comme celui qui suit dans les actions de contrôleur :

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.

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

@ -4,7 +4,7 @@ Authentification
L'authentification est le processus qui consiste à vérifier l'identité d'un utilisateur. Elle utilise ordinairement un identifiant (p. ex. un nom d'utilisateur ou une adresse de courriels) et un jeton secret (p. ex. un mot de passe ou un jeton d'accès) pour juger si l'utilisateur est bien qui il prétend être. L'authentification est à la base de la fonctionnalité de connexion.
Yii fournit une base structurée d'authentification qui interconnecte des composants variés pour prendre en charge la connexion. Pour utiliser cette base structurée, vous devez essentiellement accomplir les tâches suivantes :
* Configurer le composant d'application [[yii\web\User|user]] ;
* Créer une classe qui implémente l'interface [[yii\web\IdentityInterface]].
@ -13,7 +13,7 @@ Yii fournit une base structurée d'authentification qui interconnecte des compo
Le composant d'application [[yii\web\User|user]] gère l'état d'authentification de l'utilisateur. Il requiert que vous spécifiiez une [[yii\web\User::identityClass|classe d'identité]] contenant la logique réelle d'authentification.
Dans la configuration suivante de l'application, la [[yii\web\User::identityClass|classe d'identité]] pour [[yii\web\User|user]] est configurée sous le nom `app\models\User` dont la mise en œuvre est expliquée dans la sous-section suivante :
```php
return [
'components' => [
@ -30,12 +30,12 @@ return [
La [[yii\web\User::identityClass|classe d'identité]] doit implémenter l'interface [[yii\web\IdentityInterface]] qui comprend les méthodes suivantes :
* [[yii\web\IdentityInterface::findIdentity()|findIdentity()]]: cette méthode recherche une instance de la classe d'identité à partir de l'identifiant utilisateur spécifié. Elle est utilisée lorsque vous devez conserver l'état de connexion via et durant la session.
* [[yii\web\IdentityInterface::findIdentityByAccessToken()|findIdentityByAccessToken()]]: cette méthode recherche une instance de la classe d'identité à partir du jeton d'accès spécifié. Elle est utilisée lorsque vous avez besoin d'authentifier un utilisateur par un jeton secret (p. ex. dans une application pleinement REST sans état).
* [[yii\web\IdentityInterface::findIdentityByAccessToken()|findIdentityByAccessToken()]]: cette méthode recherche une instance de la classe d'identité à partir du jeton d'accès spécifié. Elle est utilisée lorsque vous avez besoin d'authentifier un utilisateur par un jeton secret (p. ex. dans une application pleinement REST sans état).
* [[yii\web\IdentityInterface::getId()|getId()]]: cette méthode retourne l'identifiant de l'utilisateur que cette instance de la classe d'identité représente.
* [[yii\web\IdentityInterface::getAuthKey()|getAuthKey()]]: cette méthode retourne une clé utilisée pour vérifier la connexion basée sur les témoins de connexion (*cookies*). La clé est stockée dans le témoin de connexion `login` et est ensuite comparée avec la version côté serveur pour s'assurer que le témoin de connexion est valide.
* [[yii\web\IdentityInterface::validateAuthKey()|validateAuthKey()]]: cette méthode met en œuvre la logique de vérification de la clé de connexion basée sur les témoins de connexion.
* [[yii\web\IdentityInterface::validateAuthKey()|validateAuthKey()]]: cette méthode met en œuvre la logique de vérification de la clé de connexion basée sur les témoins de connexion.
Si une méthode particulière n'est pas nécessaire, vous devez l'implémenter avec un corps vide. Par exemple, si votre application est une application sans état et pleinement REST, vous devez seulement implémenter [[yii\web\IdentityInterface::findIdentityByAccessToken()|findIdentityByAccessToken()]] et [[yii\web\IdentityInterface::getId()|getId()]] et laisser toutes les autres méthodes avec un corps vide.
Si une méthode particulière n'est pas nécessaire, vous devez l'implémenter avec un corps vide. Par exemple, si votre application est une application sans état et pleinement REST, vous devez seulement implémenter [[yii\web\IdentityInterface::findIdentityByAccessToken()|findIdentityByAccessToken()]] et [[yii\web\IdentityInterface::getId()|getId()]] et laisser toutes les autres méthodes avec un corps vide.
Dans l'exemple qui suit, une [[yii\web\User::identityClass|classe d'identité]] est mise en œuvre en tant que classe [Active Record](db-active-record.md) associée à la table de base de données `user`.
@ -55,8 +55,8 @@ class User extends ActiveRecord implements IdentityInterface
/**
* Trouve une identité à partir de l'identifiant donné.
*
* @param string|integer $id l'identifiant à rechercher
* @return IdentityInterface|null l'objet identité qui correspond à l'identifiant donné
* @param string|int $id l'identifiant à rechercher
* @return IdentityInterface|null l'objet identité qui correspond à l'identifiant donné
*/
public static function findIdentity($id)
{
@ -64,7 +64,7 @@ class User extends ActiveRecord implements IdentityInterface
}
/**
* Trouve une identité à partir du jeton donné
* Trouve une identité à partir du jeton donné
*
* @param string $token le jeton à rechercher
* @return IdentityInterface|null l'objet identité qui correspond au jeton donné
@ -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)
{
@ -107,7 +107,7 @@ Comme nous l'avons expliqué précédemment, vous devez seulement implémenter `
class User extends ActiveRecord implements IdentityInterface
{
......
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
@ -121,12 +121,12 @@ class User extends ActiveRecord implements IdentityInterface
}
```
> Note: ne confondez pas la classe d'identité `User` avec la classe [[yii\web\User]]. La première est la classe mettant en œuvre la logique d'authentification. Elle est souvent mise en œuvre sous forme de classe [Active Record](db-active-record.md) associée à un moyen de stockage persistant pour conserver les éléments d'authentification de l'utilisateur. La deuxième est une classe de composant d'application qui gère l'état d'authentification de l'utilisateur.
> Note: ne confondez pas la classe d'identité `User` avec la classe [[yii\web\User]]. La première est la classe mettant en œuvre la logique d'authentification. Elle est souvent mise en œuvre sous forme de classe [Active Record](db-active-record.md) associée à un moyen de stockage persistant pour conserver les éléments d'authentification de l'utilisateur. La deuxième est une classe de composant d'application qui gère l'état d'authentification de l'utilisateur.
## Utilisation de [[yii\web\User]] <span id="using-user"></span>
Vous utilisez [[yii\web\User]] essentiellement en terme de composant d'application `user`.
Vous utilisez [[yii\web\User]] essentiellement en terme de composant d'application `user`.
Vous pouvez détecter l'identité de l'utilisateur courant en utilisant l'expression `Yii::$app->user->identity`. Elle retourne une instance de la [[yii\web\User::identityClass|classe d'identité]] représentant l'utilisateur connecté actuellement ou `null` si l'utilisateur courant n'est pas authentifié (soit un simple visiteur). Le code suivant montre comment retrouver les autres informations relatives à l'authentification à partir de [[yii\web\User]]:
@ -137,26 +137,26 @@ $identity = Yii::$app->user->identity;
// l'identifiant de l'utilisateur courant. Null si l'utilisateur n'est pas authentifié.
$id = Yii::$app->user->id;
// si l'utilisateur courant est un visiteur (non authentifié).
// si l'utilisateur courant est un visiteur (non authentifié).
$isGuest = Yii::$app->user->isGuest;
```
Pour connecter un utilisateur, vous devez utiliser le code suivant :
```php
// trouve une identité d'utilisateur à partir du nom d'utilisateur spécifié
// notez que vous pouvez vouloir vérifier le mot de passe si besoin.
// trouve une identité d'utilisateur à partir du nom d'utilisateur spécifié
// notez que vous pouvez vouloir vérifier le mot de passe si besoin.
$identity = User::findOne(['username' => $username]);
// connecte l'utilisateur
// connecte l'utilisateur
Yii::$app->user->login($identity);
```
La méthode [[yii\web\User::login()]] assigne l'identité de l'utilisateur courant à [[yii\web\User]]. Si la session est [[yii\web\User::enableSession|activée]], elle conserve l'identité de façon à ce que l'état d'authentification de l'utilisateur soit maintenu durant la session tout entière. Si la connexion basée sur les témoins de connexion (*cookies*) est [[yii\web\User::enableAutoLogin|activée]], elle sauvegarde également l'identité dans un témoin de connexion de façon à ce que l'état d'authentification de l'utilisateur puisse être récupéré du témoin de connexion durant toute la période de validité du témoin de connexion.
Pour activer la connexion basée sur les témoins de connexion, vous devez configurer [[yii\web\User::enableAutoLogin]] à `true` (vrai) dans la configuration de l'application. Vous devez également fournir une durée de vie lorsque vous appelez la méthode [[yii\web\User::login()]].
Pour activer la connexion basée sur les témoins de connexion, vous devez configurer [[yii\web\User::enableAutoLogin]] à `true` (vrai) dans la configuration de l'application. Vous devez également fournir une durée de vie lorsque vous appelez la méthode [[yii\web\User::login()]].
Pour déconnecter un utilisateur, appelez simplement
Pour déconnecter un utilisateur, appelez simplement
```php
Yii::$app->user->logout();
@ -167,13 +167,13 @@ Notez que déconnecter un utilisateur n'a de sens que si la session est activée
## Événement d'authentification <span id="auth-events"></span>
La classe [[yii\web\User]] lève quelques événements durant le processus de connexion et celui de déconnexion.
La classe [[yii\web\User]] lève quelques événements durant le processus de connexion et celui de déconnexion.
* [[yii\web\User::EVENT_BEFORE_LOGIN|EVENT_BEFORE_LOGIN]]: levé au début de [[yii\web\User::login()]].
Si le gestionnaire d'événement définit la propriété [[yii\web\UserEvent::isValid|isValid]] de l'objet événement à `false` (faux), le processus de connexion avorte.
* [[yii\web\User::EVENT_AFTER_LOGIN|EVENT_AFTER_LOGIN]]: levé après une connexion réussie.
* [[yii\web\User::EVENT_BEFORE_LOGOUT|EVENT_BEFORE_LOGOUT]]: levé au début de [[yii\web\User::logout()]].
Si le gestionnaire d'événement définit la propriété [[yii\web\UserEvent::isValid|isValid]] à `false` (faux) le processus de déconnexion avorte.
* [[yii\web\User::EVENT_AFTER_LOGOUT|EVENT_AFTER_LOGOUT]]: levé après une déconnexion réussie.
Si le gestionnaire d'événement définit la propriété [[yii\web\UserEvent::isValid|isValid]] à `false` (faux) le processus de déconnexion avorte.
* [[yii\web\User::EVENT_AFTER_LOGOUT|EVENT_AFTER_LOGOUT]]: levé après une déconnexion réussie.
Vous pouvez répondre à ces événements pour mettre en œuvre des fonctionnalités telles que l'audit de connexion, les statistiques d'utilisateurs en ligne. Par exemple, dans le gestionnaire pour l'événement [[yii\web\User::EVENT_AFTER_LOGIN|EVENT_AFTER_LOGIN]], vous pouvez enregistrer le temps de connexion et l'adresse IP dans la tale `user`.

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

@ -1,7 +1,7 @@
Autorisation
=============
L'autorisation est le processus qui vérifie si un utilisateur dispose des permissions suffisantes pour faire quelque chose. Yii fournit deux méthodes d'autorisation : le filtre de contrôle d'accès (ACF — Access Control Filter) et le contrôle d'accès basé sur les rôles (RBAC — Role-Based Access Control).
L'autorisation est le processus qui vérifie si un utilisateur dispose des permissions suffisantes pour faire quelque chose. Yii fournit deux méthodes d'autorisation : le filtre de contrôle d'accès (ACF — Access Control Filter) et le contrôle d'accès basé sur les rôles (RBAC — Role-Based Access Control).
## Filtre de contrôle d'accès <span id="access-control-filter"></span>
@ -43,8 +43,8 @@ class SiteController extends Controller
Dans le code précédent, le filtre de contrôle d'accès est attaché au contrôleur `site` en tant que comportement (*behavior*). C'est la manière typique d'utiliser un filtre d'action. L'option `only` spécifie que le filtre de contrôle d'accès doit seulement être appliqué aux actions `login`, `logout` et `signup`. Toutes les autres actions dans le contrôleur `site`ne sont pas sujettes au contrôle d'accès. L'option `rules` liste les [[yii\filters\AccessRule|règles d'accès]], qui se lisent comme suit :
- Autorise tous les visiteurs (non encore authentifiés) à accéder aux actions `login` et `signup`. l'option `roles` contient un point d'interrogation `?` qui est un signe particulier représentant les « visiteurs non authentifiés ».
- Autorise les utilisateurs authentifiés à accéder à l'action `logout`. L'arobase `@` est un autre signe particulier représentant les « utilisateurs authentifiés ».
- Autorise tous les visiteurs (non encore authentifiés) à accéder aux actions `login` et `signup`. l'option `roles` contient un point d'interrogation `?` qui est un signe particulier représentant les « visiteurs non authentifiés ».
- Autorise les utilisateurs authentifiés à accéder à l'action `logout`. L'arobase `@` est un autre signe particulier représentant les « utilisateurs authentifiés ».
Le filtre de contrôle d'accès effectue les vérifications d'autorisation en examinant les règles d'accès une par une en commençant par le haut, jusqu'à ce qu'il trouve une règle qui correspond au contexte d'exécution courant. La valeur `allow` de la règle correspondante est utilisée ensuite pour juger si l'utilisateur est autorisé ou pas. Si aucune des règles ne correspond, cela signifie que l'utilisateur n'est PAS autorisé, et le filtre de contrôle d'accès arrête la suite de l'exécution de l'action.
@ -69,24 +69,24 @@ Les [[yii\filters\AccessRule|règles d'accès]] acceptent beaucoup d'options. Ci
* [[yii\filters\AccessRule::allow|allow]]: spécifie s'il s'agit d'une règle "allow" (autorise) ou "deny" (refuse).
* [[yii\filters\AccessRule::actions|actions]]: spécifie à quelles actions cette règle correspond. Ce doit être un tableau d'identifiants d'action. La comparaison est sensible à la casse. Si cette option est vide ou non définie, cela signifie que la règle s'applique à toutes les actions.
* [[yii\filters\AccessRule::actions|actions]]: spécifie à quelles actions cette règle correspond. Ce doit être un tableau d'identifiants d'action. La comparaison est sensible à la casse. Si cette option est vide ou non définie, cela signifie que la règle s'applique à toutes les actions.
* [[yii\filters\AccessRule::controllers|controllers]]: spécifie à quels contrôleurs cette règle correspond. Ce doit être un tableau d'identifiants de contrôleurs. Si cette option est vide ou non définie, la règle s'applique à tous les contrôleurs.
* [[yii\filters\AccessRule::controllers|controllers]]: spécifie à quels contrôleurs cette règle correspond. Ce doit être un tableau d'identifiants de contrôleurs. Si cette option est vide ou non définie, la règle s'applique à tous les contrôleurs.
* [[yii\filters\AccessRule::roles|roles]]: spécifie à quels rôles utilisateur cette règle correspond. Deux rôles spéciaux sont reconnus, et ils sont vérifiés via [[yii\web\User::isGuest]]:
- `?`: correspond à un visiteur non authentifié.
- `@`: correspond à un visiteur authentifié.
L'utilisation d'autres noms de rôle déclenche l'appel de [[yii\web\User::can()]], qui requiert l'activation du contrôle d'accès basé sur les rôles qui sera décrit dans la prochaine sous-section. Si cette option est vide ou non définie, cela signifie que la règle s'applique à tous les rôles.
L'utilisation d'autres noms de rôle déclenche l'appel de [[yii\web\User::can()]], qui requiert l'activation du contrôle d'accès basé sur les rôles qui sera décrit dans la prochaine sous-section. Si cette option est vide ou non définie, cela signifie que la règle s'applique à tous les rôles.
* [[yii\filters\AccessRule::ips|ips]]: spécifie à quelles [[yii\web\Request::userIP|adresses IP de client]] cette règle correspond. Une adresse IP peut contenir le caractère générique `*` à la fin pour indiquer que la règle correspond à des adresses IP ayant le même préfixe. Par exemple, '192.168.*' correspond à toutes les adresse IP dans le segment '192.168.'. Si cette option est vide ou non définie, cela signifie que la règle s'applique à toutes les adresses IP.
* [[yii\filters\AccessRule::verbs|verbs]]: spécifie à quelles méthodes de requête (p. ex. `GET`, `POST`) cette règle correspond. La comparaison est insensible à la casse.
* [[yii\filters\AccessRule::verbs|verbs]]: spécifie à quelles méthodes de requête (p. ex. `GET`, `POST`) cette règle correspond. La comparaison est insensible à la casse.
* [[yii\filters\AccessRule::matchCallback|matchCallback]]: spécifie une fonction de rappel PHP qui peut être appelée pour déterminer si cette règle s'applique.
* [[yii\filters\AccessRule::matchCallback|matchCallback]]: spécifie une fonction de rappel PHP qui peut être appelée pour déterminer si cette règle s'applique.
* [[yii\filters\AccessRule::denyCallback|denyCallback]]: spécifie une fonction de rappel PHP qui peut être appelée lorsqu'une règle refuse l'accès.
* [[yii\filters\AccessRule::denyCallback|denyCallback]]: spécifie une fonction de rappel PHP qui peut être appelée lorsqu'une règle refuse l'accès.
Ci-dessous nous présentons un exemple qui montre comment utiliser l'option `matchCallback`, qui vous permet d'écrire une logique d'accès arbitraire :
@ -125,26 +125,26 @@ class SiteController extends Controller
## Contrôle d'accès basé sur les rôles <span id="rbac"></span>
Le contrôle d'accès basé sur les rôles (Role-Based Access Control – RBAC) fournit un contrôle d'accès centralisé simple mais puissant. Reportez-vous à [Wikipedia](http://en.wikipedia.org/wiki/Role-based_access_control) pour des détails comparatifs entre le contrôle d'accès basé sur les rôles et d'autres schéma de contrôle d'accès plus traditionnels.
Le contrôle d'accès basé sur les rôles (Role-Based Access Control – RBAC) fournit un contrôle d'accès centralisé simple mais puissant. Reportez-vous à [Wikipedia](http://en.wikipedia.org/wiki/Role-based_access_control) pour des détails comparatifs entre le contrôle d'accès basé sur les rôles et d'autres schéma de contrôle d'accès plus traditionnels.
Yii met en œuvre un contrôle d'accès basé sur les rôles général hiérarchisé, qui suit le [modèle NIST RBAC](http://csrc.nist.gov/rbac/sandhu-ferraiolo-kuhn-00.pdf). Il fournit la fonctionnalité de contrôle d'accès basé sur les rôles via le [composant d'application](structure-application-components.md)[[yii\RBAC\ManagerInterface|authManager]].
L'utilisation du contrôle d'accès basé sur les rôles implique deux partie de travail. La première partie est de construire les données d'autorisation du contrôle d'accès basé sur les rôles, et la seconde partie est d'utiliser les données d'autorisation pour effectuer les vérifications d'autorisation d'accès là où elles sont nécessaires.
L'utilisation du contrôle d'accès basé sur les rôles implique deux partie de travail. La première partie est de construire les données d'autorisation du contrôle d'accès basé sur les rôles, et la seconde partie est d'utiliser les données d'autorisation pour effectuer les vérifications d'autorisation d'accès là où elles sont nécessaires.
Pour faciliter la description qui suit, nous allons d'abord introduire quelques concepts sur le contrôle d'accès basé sur les rôles.
Pour faciliter la description qui suit, nous allons d'abord introduire quelques concepts sur le contrôle d'accès basé sur les rôles.
### Concepts de base <span id="basic-concepts"></span>
Un rôle représente une collection de *permissions* (p. ex. créer des articles, mettre des articles à jour). Un rôle peut être assigné à un ou plusieurs utilisateurs. Pour vérifier qu'un utilisateur dispose d'une permission spécifiée, nous pouvons vérifier si un rôle contenant cette permission a été assigné à l'utilisateur.
Un rôle représente une collection de *permissions* (p. ex. créer des articles, mettre des articles à jour). Un rôle peut être assigné à un ou plusieurs utilisateurs. Pour vérifier qu'un utilisateur dispose d'une permission spécifiée, nous pouvons vérifier si un rôle contenant cette permission a été assigné à l'utilisateur.
Associée à chacun des rôles, il peut y avoir une *règle*. Une règle représente un morceau de code à exécuter lors de l'accès pour vérifier si le rôle correspondant, ou la permission correspondante, s'applique à l'utilisateur courant. Par exemple, la permission « mettre un article à jour » peut disposer d'une règle qui vérifie si l'utilisateur courant est celui qui a créé l'article. Durant la vérification de l'accès, si l'utilisateur n'est PAS le créateur de l'article, il est considéré comme ne disposant pas la permission « mettre un article à jour ».
Associée à chacun des rôles, il peut y avoir une *règle*. Une règle représente un morceau de code à exécuter lors de l'accès pour vérifier si le rôle correspondant, ou la permission correspondante, s'applique à l'utilisateur courant. Par exemple, la permission « mettre un article à jour » peut disposer d'une règle qui vérifie si l'utilisateur courant est celui qui a créé l'article. Durant la vérification de l'accès, si l'utilisateur n'est PAS le créateur de l'article, il est considéré comme ne disposant pas la permission « mettre un article à jour ».
À la fois les rôles et les permissions peuvent être organisés en une hiérarchie. En particulier, un rôle peut être constitué d'autres rôles ou permissions; Yii met en œuvre une hiérarchie *d'ordre partiel* qui inclut la hiérarchie plus spécifique dite *en arbre*. Tandis qu'un rôle peut contenir une permission, l'inverse n'est pas vrai.
À la fois les rôles et les permissions peuvent être organisés en une hiérarchie. En particulier, un rôle peut être constitué d'autres rôles ou permissions; Yii met en œuvre une hiérarchie *d'ordre partiel* qui inclut la hiérarchie plus spécifique dite *en arbre*. Tandis qu'un rôle peut contenir une permission, l'inverse n'est pas vrai.
### Configuration du contrôle d'accès basé sur les rôles <span id="configuring-rbac"></span>
Avant que nous ne nous lancions dans la définition des données d'autorisation et effectuions la vérification d'autorisation d'accès, nous devons configurer le composant d'application [[yii\base\Application::authManager|gestionnaire d'autorisations (*authManager*)]]. Yii fournit deux types de gestionnaires d'autorisations : [[yii\rbac\PhpManager]] et [[yii\rbac\DbManager]]. Le premier utilise un script PHP pour stocker les données d'autorisation, tandis que le second stocke les données d'autorisation dans une base de données. Vous pouvez envisager d'utiliser le premier si votre application n'a pas besoin d'une gestion des rôles et des permissions très dynamique.
Avant que nous ne nous lancions dans la définition des données d'autorisation et effectuions la vérification d'autorisation d'accès, nous devons configurer le composant d'application [[yii\base\Application::authManager|gestionnaire d'autorisations (*authManager*)]]. Yii fournit deux types de gestionnaires d'autorisations : [[yii\rbac\PhpManager]] et [[yii\rbac\DbManager]]. Le premier utilise un script PHP pour stocker les données d'autorisation, tandis que le second stocke les données d'autorisation dans une base de données. Vous pouvez envisager d'utiliser le premier si votre application n'a pas besoin d'une gestion des rôles et des permissions très dynamique.
#### Utilisation de `PhpManager` <span id="using-php-manager"></span>
@ -165,7 +165,7 @@ return [
Le gestionnaire `authManager` peut désormais être obtenu via `\Yii::$app->authManager`.
Par défaut, [[yii\rbac\PhpManager]] stocke les données du contrôle d'accès basé sur les rôles dans des fichiers du dossier `@app/rbac`. Assurez-vous que le dossier et tous les fichiers qui sont dedans sont accessibles en écriture par le processus du serveur Web si la hiérarchie des permissions a besoin d'être changée en ligne.
Par défaut, [[yii\rbac\PhpManager]] stocke les données du contrôle d'accès basé sur les rôles dans des fichiers du dossier `@app/rbac`. Assurez-vous que le dossier et tous les fichiers qui sont dedans sont accessibles en écriture par le processus du serveur Web si la hiérarchie des permissions a besoin d'être changée en ligne.
#### Utilisation de `DbManager` <span id="using-db-manager"></span>
@ -187,7 +187,7 @@ return [
> Dans le cas du modèle yii2-advanced-app, la propriété `authManager` doit être déclarée seulement une fois dans `common/config/main.php`.
`DbManager` utilise quatre tables de base de données pour stocker ses données :
`DbManager` utilise quatre tables de base de données pour stocker ses données :
- [[yii\rbac\DbManager::$itemTable|itemTable]]: la table pour stocker les items d'autorisation. Valeur par défaut « auth_item ».
- [[yii\rbac\DbManager::$itemChildTable|itemChildTable]]: la table pour stocker la hiérarchie des items d'autorisation. Valeur par défaut « auth_item_child ».
@ -228,7 +228,7 @@ class RbacController extends Controller
{
$auth = Yii::$app->authManager;
// ajoute une permission "createPost"
// ajoute une permission "createPost"
$createPost = $auth->createPermission('createPost');
$createPost->description = 'Créer un article';
$auth->add($createPost);
@ -264,7 +264,7 @@ Après avoir exécuté la commande `yii rbac/init` vous vous retrouverez avec la
![Hiérarchie simple du contrôle d'accès basé sur les rôles](images/rbac-hierarchy-1.png "Simple RBAC hierarchy")
Le rôle *Author* peut créer des articles, le rôle *admin* peut mettre les articles à jour et faire tout ce que le rôle *author* peut faire.
Le rôle *Author* peut créer des articles, le rôle *admin* peut mettre les articles à jour et faire tout ce que le rôle *author* peut faire.
Si votre application autorise l'enregistrement des utilisateurs, vous devez assigner des rôles à ces nouveaux utilisateurs une fois. Par exemple, afin que tous les utilisateurs enregistrés deviennent des auteurs (rôle *author*) dans votre modèle de projet avancé, vous devez modifier la méthode `frontend\models\SignupForm::signup()` comme indiqué ci-dessous :
@ -311,10 +311,10 @@ class AuthorRule extends Rule
public $name = 'isAuthor';
/**
* @param string|integer $user l'identifiant de l'utilisateur.
* @param Item $item le rôle ou la permission avec laquelle cette règle est associée
* @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)
{
@ -377,7 +377,7 @@ Ici que se passe-t-il si l'utilisateur courant est John:
![Vérification d'autorisation d'accès](images/rbac-access-check-2.png "Access check")
Nous commençons à `updatePost` et passons par `updateOwnPost`. Afin d'obtenir l'autorisation, la méthode `execute()` de `AuthorRule` doit retourner `true` (vrai). La méthode reçoit ses paramètres `$params` de l'appel à la méthode `can()` et sa valeur est ainsi `['post' => $post]`. Si tout est bon, nous arrivons à `author` auquel John est assigné.
Nous commençons à `updatePost` et passons par `updateOwnPost`. Afin d'obtenir l'autorisation, la méthode `execute()` de `AuthorRule` doit retourner `true` (vrai). La méthode reçoit ses paramètres `$params` de l'appel à la méthode `can()` et sa valeur est ainsi `['post' => $post]`. Si tout est bon, nous arrivons à `author` auquel John est assigné.
Dans le cas de Jane, c'est un peu plus simple puisqu'elle a le rôle admin:
@ -427,11 +427,11 @@ Si toutes les opérations CRUD sont gérées ensemble, alors c'est une bonne id
### Utilisation des rôles par défaut <span id="using-default-roles"></span>
Un rôle par défaut est un rôle qui est assigné *implicitement* à tous les *utilisateurs*. L'appel de la méthode [[yii\rbac\ManagerInterface::assign()]] n'est pas nécessaire, et les données d'autorisations ne contiennent pas ses informations d'assignation.
Un rôle par défaut est un rôle qui est assigné *implicitement* à tous les *utilisateurs*. L'appel de la méthode [[yii\rbac\ManagerInterface::assign()]] n'est pas nécessaire, et les données d'autorisations ne contiennent pas ses informations d'assignation.
Un rôle par défaut est ordinairement associé à une règle qui détermine si le rôle s'applique à l'utilisateur en cours de vérification.
Les rôles par défaut sont souvent utilisés dans des applications qui ont déjà une sorte d'assignation de rôles. Par exemple, un application peut avoir une colonne « group » dans sa table des utilisateurs pour représenter à quel groupe de privilèges chacun des utilisateurs appartient. Si chaque groupe de privilèges peut être mis en correspondance avec un rôle du contrôle d'accès basé sur les rôles, vous pouvez utiliser la fonctionnalité de rôle par défaut pour assigner automatiquement un rôle du contrôle d'accès basé sur les rôles à chacun des utilisateurs. Prenons un exemple pour montrer comment cela se fait.
Les rôles par défaut sont souvent utilisés dans des applications qui ont déjà une sorte d'assignation de rôles. Par exemple, un application peut avoir une colonne « group » dans sa table des utilisateurs pour représenter à quel groupe de privilèges chacun des utilisateurs appartient. Si chaque groupe de privilèges peut être mis en correspondance avec un rôle du contrôle d'accès basé sur les rôles, vous pouvez utiliser la fonctionnalité de rôle par défaut pour assigner automatiquement un rôle du contrôle d'accès basé sur les rôles à chacun des utilisateurs. Prenons un exemple pour montrer comment cela se fait.
Supposons que dans la table des utilisateurs, il existe en colonne `group` qui utilise la valeur 1 pour représenter le groupe des administrateurs et la valeur 2 pour représenter le groupe des auteurs. Vous envisagez d'avoir deux rôles dans le contrôle d'accès basé sur les rôles `admin` et`author` pour représenter les permissions de ces deux groupes respectivement. Vous pouvez configurer le contrôle d'accès basé sur les rôles comme suit :
@ -443,7 +443,7 @@ use Yii;
use yii\rbac\Rule;
/**
* Vérifie si le groupe utilisateurs correspond
* Vérifie si le groupe utilisateurs correspond
*/
class UserGroupRule extends Rule
{
@ -497,4 +497,4 @@ return [
];
```
Désormais, si vous effectuez une vérification d'autorisation d'accès, les deux rôles `admin` et `author` seront vérifiés en évaluant les règles qui leur sont associées. Si les règles retournent `true` (vrai), cela signifie que le rôle s'applique à l'utilisateur courant. En se basant sur la mise en œuvre des règles ci-dessus, cela signifie que si la valeur du `group` d'un utilisateur est 1, le rôle `admin` s'applique à l'utilisateur, si la valeur du `group` est 2, le rôle `author` s'applique.
Désormais, si vous effectuez une vérification d'autorisation d'accès, les deux rôles `admin` et `author` seront vérifiés en évaluant les règles qui leur sont associées. Si les règles retournent `true` (vrai), cela signifie que le rôle s'applique à l'utilisateur courant. En se basant sur la mise en œuvre des règles ci-dessus, cela signifie que si la valeur du `group` d'un utilisateur est 1, le rôle `admin` s'applique à l'utilisateur, si la valeur du `group` est 2, le rôle `author` s'applique.

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));
}
}
```

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

@ -18,7 +18,7 @@ Yii はさまざまなコンポーネントを結び付けてログインをサ
実際の認証ロジックを含む [[yii\web\User::identityClass|ユーザ識別情報クラス]] は、あなたが指定しなければなりません。
下記のアプリケーション構成情報においては、[[yii\web\User|user]] の [[yii\web\User::identityClass|ユーザ識別情報クラス]] は `app\models\User` であると構成されています。
`app\models\User` の実装については、次の項で説明します。
```php
return [
'components' => [
@ -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)
{
@ -116,7 +116,7 @@ class User extends ActiveRecord implements IdentityInterface
class User extends ActiveRecord implements IdentityInterface
{
......
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {

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)
{

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

@ -1,12 +1,12 @@
Pamięć podręczna HTTP
=====================
Oprócz pamięci podręcznej tworzonej po stronie serwera, która została opisana w poprzednich rozdziałach, aplikacje mogą również
skorzystać z pamięci podręcznej tworzonej po stronie klienta, aby zaoszczędzić czas poświęcany na ponowne generowanie i przesyłanie
Oprócz pamięci podręcznej tworzonej po stronie serwera, która została opisana w poprzednich rozdziałach, aplikacje mogą również
skorzystać z pamięci podręcznej tworzonej po stronie klienta, aby zaoszczędzić czas poświęcany na ponowne generowanie i przesyłanie
identycznej zawartości strony.
Aby skorzystać z tego mechanizmu, należy skonfigurować [[yii\filters\HttpCache]] jako filtr kontrolera akcji, których wyrenderowana
zwrotka może być zapisana w pamięci podręcznej po stronie klienta. [[yii\filters\HttpCache|HttpCache]] obsługuje tylko żądania typu
Aby skorzystać z tego mechanizmu, należy skonfigurować [[yii\filters\HttpCache]] jako filtr kontrolera akcji, których wyrenderowana
zwrotka może być zapisana w pamięci podręcznej po stronie klienta. [[yii\filters\HttpCache|HttpCache]] obsługuje tylko żądania typu
`GET` i `HEAD` i dla tych typów tylko trzy nagłówki HTTP związane z pamięcią podręczną:
* [[yii\filters\HttpCache::lastModified|Last-Modified]]
@ -16,17 +16,17 @@ zwrotka może być zapisana w pamięci podręcznej po stronie klienta. [[yii\fil
## Nagłówek `Last-Modified` <span id="last-modified"></span>
Nagłówek `Last-Modified` korzysta ze znacznika czasu, aby określić, czy strona została zmodyfikowana od momentu jej ostatniego zapisu
Nagłówek `Last-Modified` korzysta ze znacznika czasu, aby określić, czy strona została zmodyfikowana od momentu jej ostatniego zapisu
w pamięci podręcznej.
Możesz skonfigurować właściwość [[yii\filters\HttpCache::lastModified]], aby przesyłać nagłowek `Last-Modified`. Właściwość powinna być
Możesz skonfigurować właściwość [[yii\filters\HttpCache::lastModified]], aby przesyłać nagłowek `Last-Modified`. Właściwość powinna być
typu PHP callable i zwracać uniksowy znacznik czasu informujący o czasie modyfikacji strony. Sygnatura metody jest następująca:
```php
/**
* @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)
```
@ -49,20 +49,20 @@ public function behaviors()
}
```
Kod ten uruchamia pamięć podręczną HTTP wyłącznie dla akcji `index`, która powinna wygenerować nagłówek HTTP `Last-Modified` oparty
o datę ostatniej aktualizacji postów. Przeglądarka, wyświetlając stronę `index` po raz pierwszy, otrzymuje jej zawartość wygenerowaną
przez serwer; każda kolejna wizyta, przy założeniu, że żaden post nie został zmodyfikowany w międzyczasie, skutkuje wyświetleniem
wersji strony przechowywanej w pamięci podręcznej po stronie klienta, zamiast generować ją ponownie przez serwer.
Kod ten uruchamia pamięć podręczną HTTP wyłącznie dla akcji `index`, która powinna wygenerować nagłówek HTTP `Last-Modified` oparty
o datę ostatniej aktualizacji postów. Przeglądarka, wyświetlając stronę `index` po raz pierwszy, otrzymuje jej zawartość wygenerowaną
przez serwer; każda kolejna wizyta, przy założeniu, że żaden post nie został zmodyfikowany w międzyczasie, skutkuje wyświetleniem
wersji strony przechowywanej w pamięci podręcznej po stronie klienta, zamiast generować ją ponownie przez serwer.
W rezultacie, renderowanie zawartości po stronie serwera i przesyłanie jej do klienta jest pomijane.
## Nagłowek `ETag` <span id="etag"></span>
Nagłowek "Entity Tag" (lub w skrócie `ETag`) wykorzystuje skrót hash jako reprezentację strony. W momencie, gdy strona się zmieni, jej
hash również automatycznie ulega zmianie. Porównując hash przechowywany po stronie klienta z hashem wygenerowanym przez serwer,
Nagłowek "Entity Tag" (lub w skrócie `ETag`) wykorzystuje skrót hash jako reprezentację strony. W momencie, gdy strona się zmieni, jej
hash również automatycznie ulega zmianie. Porównując hash przechowywany po stronie klienta z hashem wygenerowanym przez serwer,
mechanizm pamięci podręcznej ustala, czy strona się zmieniła i powinna być ponownie przesłana.
Możesz skonfigurować właściwość [[yii\filters\HttpCache::etagSeed]], aby przesłać nagłowek `ETag`.
Możesz skonfigurować właściwość [[yii\filters\HttpCache::etagSeed]], aby przesłać nagłowek `ETag`.
Właściwość powinna być typu PHP callable i zwracać ziarno do wygenerowania hasha ETag. Sygnatura metody jest następująca:
```php
@ -92,17 +92,17 @@ public function behaviors()
}
```
Kod ten uruchamia pamięć podręczną HTTP wyłącznie dla akcji `view`, która powinna wygenerować nagłówek HTTP `ETag` oparty o tytuł
i zawartość przeglądanego posta. Przeglądarka, wyświetlając stronę `view` po raz pierwszy, otrzymuje jej zawartość wygenerowaną
przez serwer; każda kolejna wizyta, przy założeniu, że ani tytuł, ani zawartość posta nie została zmodyfikowana w międzyczasie,
skutkuje wyświetleniem wersji strony przechowywanej w pamięci podręcznej po stronie klienta, zamiast generować ją ponownie przez
serwer.
Kod ten uruchamia pamięć podręczną HTTP wyłącznie dla akcji `view`, która powinna wygenerować nagłówek HTTP `ETag` oparty o tytuł
i zawartość przeglądanego posta. Przeglądarka, wyświetlając stronę `view` po raz pierwszy, otrzymuje jej zawartość wygenerowaną
przez serwer; każda kolejna wizyta, przy założeniu, że ani tytuł, ani zawartość posta nie została zmodyfikowana w międzyczasie,
skutkuje wyświetleniem wersji strony przechowywanej w pamięci podręcznej po stronie klienta, zamiast generować ją ponownie przez
serwer.
W rezultacie, renderowanie zawartości po stronie serwera i przesyłanie jej do klienta jest pomijane.
ETagi pozwalają na bardziej skomplikowane i precyzyjne strategie przechowywania w pamięci podręcznej niż nagłówki `Last-Modified`.
Dla przykładu, ETag może być zmieniony dla strony w momencie, gdy użyty na niej będzie nowy szablon wyglądu.
Zasobożerne generowanie ETagów może przekreślić cały zysk z użycia `HttpCache` i wprowadzić niepotrzebny narzut, ponieważ muszą być one
Zasobożerne generowanie ETagów może przekreślić cały zysk z użycia `HttpCache` i wprowadzić niepotrzebny narzut, ponieważ muszą być one
określane przy każdym żądaniu. Z tego powodu należy używać jak najprostszych metod generujących.
> Note: Aby spełnić wymagania [RFC 7232](http://tools.ietf.org/html/rfc7232#section-2.4),
@ -112,7 +112,7 @@ określane przy każdym żądaniu. Z tego powodu należy używać jak najprostsz
## Nagłówek `Cache-Control` <span id="cache-control"></span>
Nagłówek `Cache-Control` określa ogólną politykę obsługi pamięci podręcznej stron. Możesz go przesłać konfigurując właściwość
Nagłówek `Cache-Control` określa ogólną politykę obsługi pamięci podręcznej stron. Możesz go przesłać konfigurując właściwość
[[yii\filters\HttpCache::cacheControlHeader]] z wartością nagłówka. Domyślnie przesyłany jest następujący nagłówek:
```
@ -121,16 +121,16 @@ Cache-Control: public, max-age=3600
## Ogranicznik pamięci podręcznej sesji <span id="session-cache-limiter"></span>
Kiedy strona używa mechanizmu sesji, PHP automatycznie wysyła związane z pamięcią podręczną nagłówki HTTP, określone
w `session.cache_limiter` w ustawieniach PHP INI. Mogą one kolidować z funkcjonalnością `HttpCache`, a nawet całkowicie ją wyłączyć -
aby temu zapobiec, `HttpCache` blokuje to automatyczne wysyłanie. Jeśli jednak chcesz zmienić to zachowanie, powinieneś skonfigurować
właściwość [[yii\filters\HttpCache::sessionCacheLimiter]]. Powinna ona przyjmować wartość zawierającą łańcuch znaków `public`,
`private`, `private_no_expire` i `nocache`. Szczegóły dotyczące tego zapisu znajdziesz w dokumentacji PHP dla
Kiedy strona używa mechanizmu sesji, PHP automatycznie wysyła związane z pamięcią podręczną nagłówki HTTP, określone
w `session.cache_limiter` w ustawieniach PHP INI. Mogą one kolidować z funkcjonalnością `HttpCache`, a nawet całkowicie ją wyłączyć -
aby temu zapobiec, `HttpCache` blokuje to automatyczne wysyłanie. Jeśli jednak chcesz zmienić to zachowanie, powinieneś skonfigurować
właściwość [[yii\filters\HttpCache::sessionCacheLimiter]]. Powinna ona przyjmować wartość zawierającą łańcuch znaków `public`,
`private`, `private_no_expire` i `nocache`. Szczegóły dotyczące tego zapisu znajdziesz w dokumentacji PHP dla
[session_cache_limiter()](http://www.php.net/manual/pl/function.session-cache-limiter.php).
## Korzyści dla SEO <span id="seo-implications"></span>
Boty silników wyszukiwarek zwykle respektują ustawienia nagłówków pamięci podręcznej. Niektóre automaty mają limit ilości stron
zaindeksowanych w pojedynczej domenie w danej jednostce czasu, dlatego też wprowadzenie nagłówków dla pamięci podręcznej może
Boty silników wyszukiwarek zwykle respektują ustawienia nagłówków pamięci podręcznej. Niektóre automaty mają limit ilości stron
zaindeksowanych w pojedynczej domenie w danej jednostce czasu, dlatego też wprowadzenie nagłówków dla pamięci podręcznej może
w znaczącym stopniu przyspieszyć cały proces indeksacji, poprzez redukcję ilości stron, które trzeba przeanalizować.

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ń.

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

@ -4,9 +4,9 @@ Walidacja danych wejściowych
Jedna z głównych zasad mówi, że nigdy nie należy ufać danym otrzymanym od użytkownika oraz że zawsze należy walidować je przed użyciem.
Rozważmy [model](structure-models.md) wypełniony danymi pobranymi od użytkownika. Możemy zweryfikować je poprzez wywołanie metody [[yii\base\Model::validate()|validate()]].
Metoda zwróci wartość `boolean` wskazującą, czy walidacja się powiodła, czy też nie. Jeśli nie, można pobrać informacje o błędach za pomocą właściwości
Metoda zwróci wartość `boolean` wskazującą, czy walidacja się powiodła, czy też nie. Jeśli nie, można pobrać informacje o błędach za pomocą właściwości
[[yii\base\Model::errors|errors]].
Dla przykładu,
Dla przykładu,
```php
$model = new \app\models\ContactForm();
@ -28,7 +28,7 @@ if ($model->validate()) {
## Deklaracja zasad <span id="declaring-rules"></span>
Aby metoda [[yii\base\Model::validate()|validate()]] naprawdę zadziałała, należy zdefiniować zasady walidacji dla atrybutów, które mają jej podlegać.
Powinno zostać to zrobione przez nadpisanie metody [[yii\base\Model::rules()|rules()]]. Poniższy przykład pokazuje jak zostały zadeklarowane zasady walidacji dla modelu
Powinno zostać to zrobione przez nadpisanie metody [[yii\base\Model::rules()|rules()]]. Poniższy przykład pokazuje jak zostały zadeklarowane zasady walidacji dla modelu
`ContactForm`:
```php
@ -66,10 +66,10 @@ Metoda [[yii\base\Model::rules()|rules()]] powinna zwracać tablicę zasad, gdzi
]
```
Dla każdej z zasad musisz określić co najmniej jeden atrybut, którego ma ona dotyczyć, oraz określić rodzaj zasady jako
Dla każdej z zasad musisz określić co najmniej jeden atrybut, którego ma ona dotyczyć, oraz określić rodzaj zasady jako
jedną z następujących form:
* alias walidatora podstawowego, np. `required`, `in`, `date` itd. Zajrzyj do sekcji [Podstawowe walidatory](tutorial-core-validators.md),
* alias walidatora podstawowego, np. `required`, `in`, `date` itd. Zajrzyj do sekcji [Podstawowe walidatory](tutorial-core-validators.md),
aby uzyskać pełną listę walidatorów podstawowych.
* nazwa metody walidacji w klasie modelu lub funkcja anonimowa. Po więcej szczegółów zajrzyj do sekcji [Walidatory wbudowane](#inline-validators).
* pełna nazwa klasy walidatora. Po więcej szczegółów zajrzyj do sekcji [Walidatory niezależne](#standalone-validators).
@ -80,14 +80,14 @@ Jeśli nie dodasz opcji `on` oznacza to, że zasada zostanie użyta w każdym sc
Wywołanie metody [[yii\base\Model::validate()|validate()]] powoduje podjęcie następujących kroków w celu wykonania walidacji:
1. Określenie, które atrybuty powinny zostać zweryfikowane poprzez pobranie ich listy z metody [[yii\base\Model::scenarios()|scenarios()]], używając aktualnego
1. Określenie, które atrybuty powinny zostać zweryfikowane poprzez pobranie ich listy z metody [[yii\base\Model::scenarios()|scenarios()]], używając aktualnego
[[yii\base\Model::scenario|scenariusza]]. Wybrane atrybuty nazywane są *atrybutami aktywnymi*.
2. Określenie, które zasady walidacji powinny zostać użyte przez pobranie ich listy z metody [[yii\base\Model::rules()|rules()]], używając aktualnego
2. Określenie, które zasady walidacji powinny zostać użyte przez pobranie ich listy z metody [[yii\base\Model::rules()|rules()]], używając aktualnego
[[yii\base\Model::scenario|scenariusza]]. Wybrane zasady nazywane są *zasadami aktywnymi*.
3. Użycie każdej aktywnej zasady do walidacji każdego aktywnego atrybutu, który jest powiązany z konkretną zasadą. Zasady walidacji są wykonywane w kolejności,
3. Użycie każdej aktywnej zasady do walidacji każdego aktywnego atrybutu, który jest powiązany z konkretną zasadą. Zasady walidacji są wykonywane w kolejności,
w jakiej zostały zapisane.
Odnosząc się do powyższych kroków, atrybut zostanie zwalidowany wtedy i tylko wtedy, gdy jest on aktywnym atrybutem zadeklarowanym w
Odnosząc się do powyższych kroków, atrybut zostanie zwalidowany wtedy i tylko wtedy, gdy jest on aktywnym atrybutem zadeklarowanym w
[[yii\base\Model::scenarios()|scenarios()]] oraz jest powiązany z jedną lub wieloma aktywnymi zasadami zadeklarowanymi w [[yii\base\Model::rules()|rules()]].
> Note: Czasem użyteczne jest nadanie nazwy zasadzie np.
@ -131,8 +131,8 @@ public function rules()
```
Niektóre walidatory mogą wspierać dodatkowe wiadomości błedów, aby bardziej precyzyjnie określić problemy powstałe przy walidacji.
Dla przykładu, walidator [[yii\validators\NumberValidator|number]] dodaje [[yii\validators\NumberValidator::tooBig|tooBig]] oraz
[[yii\validators\NumberValidator::tooSmall|tooSmall]] do opisania sytuacji, kiedy poddawana walidacji liczba jest za duża lub za mała.
Dla przykładu, walidator [[yii\validators\NumberValidator|number]] dodaje [[yii\validators\NumberValidator::tooBig|tooBig]] oraz
[[yii\validators\NumberValidator::tooSmall|tooSmall]] do opisania sytuacji, kiedy poddawana walidacji liczba jest za duża lub za mała.
Możesz skonfigurować te wiadomości tak, jak pozostałe właściwości walidatorów podczas deklaracji zasady.
@ -140,10 +140,10 @@ Możesz skonfigurować te wiadomości tak, jak pozostałe właściwości walidat
Podczas wywołania metody [[yii\base\Model::validate()|validate()]] zostaną wywołane dwie metody, które możesz nadpisać, aby dostosować proces walidacji:
* [[yii\base\Model::beforeValidate()|beforeValidate()]]: domyślna implementacja wywoła zdarzenie [[yii\base\Model::EVENT_BEFORE_VALIDATE|EVENT_BEFORE_VALIDATE]].
Możesz nadpisać tę metodę lub odnieść się do zdarzenia, aby wykonać dodatkowe operacje przed walidacją.
* [[yii\base\Model::beforeValidate()|beforeValidate()]]: domyślna implementacja wywoła zdarzenie [[yii\base\Model::EVENT_BEFORE_VALIDATE|EVENT_BEFORE_VALIDATE]].
Możesz nadpisać tę metodę lub odnieść się do zdarzenia, aby wykonać dodatkowe operacje przed walidacją.
Metoda powinna zwracać wartość `boolean` wskazującą, czy walidacja powinna zostać przeprowadzona, czy też nie.
* [[yii\base\Model::afterValidate()|afterValidate()]]: domyślna implementacja wywoła zdarzenie [[yii\base\Model::EVENT_AFTER_VALIDATE|EVENT_AFTER_VALIDATE]].
* [[yii\base\Model::afterValidate()|afterValidate()]]: domyślna implementacja wywoła zdarzenie [[yii\base\Model::EVENT_AFTER_VALIDATE|EVENT_AFTER_VALIDATE]].
Możesz nadpisać tę metodę lub odnieść się do zdarzenia, aby wykonać dodatkowe operacje po zakończonej walidacji.
@ -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)
```
@ -188,10 +188,10 @@ Dla przykładu,
### Filtrowanie danych <span id="data-filtering"></span>
Dane od użytkownika często muszą zostać przefiltrowane. Dla przykładu, możesz chcieć wyciąć znaki spacji na początku i na końcu pola `username`.
Dane od użytkownika często muszą zostać przefiltrowane. Dla przykładu, możesz chcieć wyciąć znaki spacji na początku i na końcu pola `username`.
Aby osiągnąć ten cel, możesz również użyć zasad walidacji.
Poniższy przykład pokazuje, jak wyciąć znaki spacji z pola oraz zmienić puste pole na wartość `null` przy użyciu podstawowych walidatorów
Poniższy przykład pokazuje, jak wyciąć znaki spacji z pola oraz zmienić puste pole na wartość `null` przy użyciu podstawowych walidatorów
[trim](tutorial-core-validators.md#trim) oraz [default](tutorial-core-validators.md#default):
```php
@ -203,7 +203,7 @@ Poniższy przykład pokazuje, jak wyciąć znaki spacji z pola oraz zmienić pus
Możesz użyć również bardziej ogólnego walidatora [filter](tutorial-core-validators.md#filter), aby przeprowadzić złożone filtrowanie.
Jak pewnie zauważyłeś, te zasady walidacji tak naprawdę nie walidują danych. Zamiast tego przetwarzają wartości, a następnie przypisują je do atrybutów,
Jak pewnie zauważyłeś, te zasady walidacji tak naprawdę nie walidują danych. Zamiast tego przetwarzają wartości, a następnie przypisują je do atrybutów,
które zostały poddane walidacji.
@ -240,9 +240,9 @@ Dla przykładu,
## Walidacja "Ad Hoc" <span id="ad-hoc-validation"></span>
Czasami potrzebna będzie walidacja *ad hoc* dla wartości które nie są powiązane z żadnym modelem.
Czasami potrzebna będzie walidacja *ad hoc* dla wartości które nie są powiązane z żadnym modelem.
Jeśli potrzebujesz wykonać tylko jeden typ walidacji (np. walidację adresu email), możesz wywołać metodę
Jeśli potrzebujesz wykonać tylko jeden typ walidacji (np. walidację adresu email), możesz wywołać metodę
[[yii\validators\Validator::validate()|validate()]] wybranego walidatora, tak jak poniżej:
```php
@ -256,10 +256,10 @@ if ($validator->validate($email, $error)) {
}
```
> Note: Nie każdy walidator wspiera tego typu walidację. Dla przykładu, podstawowy walidator [unique](tutorial-core-validators.md#unique)
> Note: Nie każdy walidator wspiera tego typu walidację. Dla przykładu, podstawowy walidator [unique](tutorial-core-validators.md#unique)
> został zaprojektowany do pracy wyłącznie z modelami.
Jeśli potrzebujesz przeprowadzić wielokrotne walidacje, możesz użyć modelu [[yii\base\DynamicModel|DynamicModel]],
Jeśli potrzebujesz przeprowadzić wielokrotne walidacje, możesz użyć modelu [[yii\base\DynamicModel|DynamicModel]],
który wspiera deklarację atrybutów oraz zasad walidacji "w locie".
Dla przykładu,
@ -279,7 +279,7 @@ public function actionSearch($name, $email)
}
```
Metoda [[yii\base\DynamicModel::validateData()|validateData()]] tworzy instancję `DynamicModel`, definiuje atrybuty używając przekazanych danych
Metoda [[yii\base\DynamicModel::validateData()|validateData()]] tworzy instancję `DynamicModel`, definiuje atrybuty używając przekazanych danych
(`name` oraz `email` w tym przykładzie), a następnie wywołuje metodę [[yii\base\Model::validate()|validate()]] z podanymi zasadami walidacji.
Alternatywnie, możesz użyć bardziej "klasycznego" zapisu to przeprowadzenia tego typu walidacji:
@ -300,7 +300,7 @@ public function actionSearch($name, $email)
}
```
Po walidacji możesz sprawdzić, czy przebiegła ona poprawnie, poprzez wywołanie metody [[yii\base\DynamicModel::hasErrors()|hasErrors()]],
Po walidacji możesz sprawdzić, czy przebiegła ona poprawnie, poprzez wywołanie metody [[yii\base\DynamicModel::hasErrors()|hasErrors()]],
a następnie pobrać błędy walidacji z właściwości [[yii\base\DynamicModel::errors|errors]], tak jak w przypadku zwykłego modelu.
Możesz również uzyskać dostęp do dynamicznych atrybutów tej instancji, np. `$model->name` i `$model->email`.
@ -316,7 +316,7 @@ Wbudowany walidator jest zdefiniowaną w modelu metodą lub funkcją anonimową.
```php
/**
* @param string $attribute atrybut podlegający walidacji
* @param mixed $params wartość parametru podanego w zasadzie walidacji
* @param mixed $params wartość parametru podanego w zasadzie walidacji
*/
function ($attribute, $params)
```
@ -359,7 +359,7 @@ class MyForm extends Model
```
> Note: Domyślnie wbudowane walidatory nie zostaną zastosowane, jeśli ich powiązane atrybuty otrzymają puste wartości lub wcześniej nie przeszły którejś z zasad walidacji.
> Jeśli chcesz się upewnić, że zasada zawsze zostanie zastosowana, możesz skonfigurować właściwość [[yii\validators\Validator::skipOnEmpty|skipOnEmpty]] i/lub
> Jeśli chcesz się upewnić, że zasada zawsze zostanie zastosowana, możesz skonfigurować właściwość [[yii\validators\Validator::skipOnEmpty|skipOnEmpty]] i/lub
> [[yii\validators\Validator::skipOnError|skipOnError]], przypisując jej wartość `false` w deklaracji zasady walidacji. Dla przykładu:
>
> ```php
@ -371,9 +371,9 @@ class MyForm extends Model
### Walidatory niezależne <span id="standalone-validators"></span>
Walidator niezależy jest klasą rozszerzającą [[yii\validators\Validator|Validator]] lub klasy po nim dziedziczące.
Walidator niezależy jest klasą rozszerzającą [[yii\validators\Validator|Validator]] lub klasy po nim dziedziczące.
Możesz zaimplementować jego logikę walidacji poprzez nadpisanie metody [[yii\validators\Validator::validateAttribute()|validateAttribute()]].
Jeśli atrybut nie przejdzie walidacji, wywołaj metodę [[yii\base\Model::addError()|addError()]] do zapisania wiadomości błędu w modelu, tak jak w
Jeśli atrybut nie przejdzie walidacji, wywołaj metodę [[yii\base\Model::addError()|addError()]] do zapisania wiadomości błędu w modelu, tak jak w
[walidatorach wbudowanych](#inline-validators).
@ -396,7 +396,7 @@ class CountryValidator extends Validator
```
Jeśli chcesz, aby walidator wspierał walidację wartości bez modelu, powinieneś nadpisać metodę [[yii\validators\Validator::validate()|validate()]].
Możesz nadpisać także [[yii\validators\Validator::validateValue()|validateValue()]] zamiast `validateAttribute()` oraz `validate()`,
Możesz nadpisać także [[yii\validators\Validator::validateValue()|validateValue()]] zamiast `validateAttribute()` oraz `validate()`,
ponieważ domyślnie te dwie metody są implementowane użyciem metody `validateValue()`.
Poniżej znajduje się przykład użycia powyższej klasy walidatora w modelu.
@ -428,20 +428,20 @@ class EntryForm extends Model
## Walidacja po stronie klienta <span id="client-side-validation"></span>
Walidacja po stronie klienta, bazująca na kodzie JavaScript jest wskazana, kiedy użytkownicy dostarczają dane przez formularz HTML,
ponieważ pozwala na szybszą walidację błędów, a tym samym zapewnia lepszą ich obsługę dla użytkownika. Możesz użyć lub zaimplementować walidator,
Walidacja po stronie klienta, bazująca na kodzie JavaScript jest wskazana, kiedy użytkownicy dostarczają dane przez formularz HTML,
ponieważ pozwala na szybszą walidację błędów, a tym samym zapewnia lepszą ich obsługę dla użytkownika. Możesz użyć lub zaimplementować walidator,
który wspiera walidację po stronie klienta jako *dodatek* do walidacji po stronie serwera.
> Info: Walidacja po stronie klienta nie jest wymagana. Głównym jej celem jest poprawa jakości korzystania z formularzy dla użytkowników.
> Podobnie jak w przypadku danych wejściowych pochodzących od użytkowników, nigdy nie powinieneś ufać walidacji przeprowadanej po stronie klienta.
> Z tego powodu należy zawsze przeprowadzać główną walidację po stronie serwera wywołując metodę [[yii\base\Model::validate()|validate()]],
> Podobnie jak w przypadku danych wejściowych pochodzących od użytkowników, nigdy nie powinieneś ufać walidacji przeprowadanej po stronie klienta.
> Z tego powodu należy zawsze przeprowadzać główną walidację po stronie serwera wywołując metodę [[yii\base\Model::validate()|validate()]],
> tak jak zostało to opisane w poprzednich sekcjach.
### Używanie walidacji po stronie klienta <span id="using-client-side-validation"></span>
Wiele [podstawowych walidatorów](tutorial-core-validators.md) domyślnie wspiera walidację po stronie klienta. Wszystko, co musisz zrobić, to użyć widżetu
[[yii\widgets\ActiveForm|ActiveForm]] do zbudowania formularza HTML. Dla przykładu, model `LoginForm` poniżej deklaruje dwie zasady: jedną, używającą podstawowego walidatora
[required](tutorial-core-validators.md#required), który wspiera walidację po stronie klienta i serwera, oraz drugą, w której użyto walidatora wbudowanego `validatePassword`,
Wiele [podstawowych walidatorów](tutorial-core-validators.md) domyślnie wspiera walidację po stronie klienta. Wszystko, co musisz zrobić, to użyć widżetu
[[yii\widgets\ActiveForm|ActiveForm]] do zbudowania formularza HTML. Dla przykładu, model `LoginForm` poniżej deklaruje dwie zasady: jedną, używającą podstawowego walidatora
[required](tutorial-core-validators.md#required), który wspiera walidację po stronie klienta i serwera, oraz drugą, w której użyto walidatora wbudowanego `validatePassword`,
który wspiera tylko walidację po stronie serwera.
```php
@ -488,24 +488,24 @@ Jeśli wyślesz formularz bez wpisywania jakichkolwiek danych, otrzymasz komunik
<?php yii\widgets\ActiveForm::end(); ?>
```
"Za kulisami", widżet [[yii\widgets\ActiveForm|ActiveForm]] odczyta wszystkie zasady walidacji zadeklarowane w modelu i wygeneruje odpowiedni kod JavaScript
"Za kulisami", widżet [[yii\widgets\ActiveForm|ActiveForm]] odczyta wszystkie zasady walidacji zadeklarowane w modelu i wygeneruje odpowiedni kod JavaScript
dla walidatorów wspierających walidację po stronie klienta. Kiedy użytkownik zmieni wartość w polu lub spróbuje wysłać formularz, zostanie wywołana walidacja po stronie klienta.
Jeśli chcesz wyłączyć całkowicie walidację po stronie klienta, możesz ustawić właściwość [[yii\widgets\ActiveForm::enableClientValidation|enableClientValidation]] na `false`.
Możesz również wyłączyć ten rodzaj walidacji dla konkretnego pola, przez ustawienie jego właściwości
[[yii\widgets\ActiveField::enableClientValidation|enableClientValidation]] na `false`. Jeśli właściwość `enableClientValidation` zostanie skonfigurowana na poziomie pola
Możesz również wyłączyć ten rodzaj walidacji dla konkretnego pola, przez ustawienie jego właściwości
[[yii\widgets\ActiveField::enableClientValidation|enableClientValidation]] na `false`. Jeśli właściwość `enableClientValidation` zostanie skonfigurowana na poziomie pola
formularza i w samym formularzu jednocześnie, pierwszeństwo będzie miała opcja określona w formularzu.
### Implementacja walidacji po stronie klienta <span id="implementing-client-side-validation"></span>
Aby utworzyć walidator wspierający walidację po stronie klienta, powinieneś zaimplementować metodę
[[yii\validators\Validator::clientValidateAttribute()|clientValidateAttribute()]], która zwraca kod JavaScript, odpowiedzialny za przeprowadzenie walidacji.
Aby utworzyć walidator wspierający walidację po stronie klienta, powinieneś zaimplementować metodę
[[yii\validators\Validator::clientValidateAttribute()|clientValidateAttribute()]], która zwraca kod JavaScript, odpowiedzialny za przeprowadzenie walidacji.
W kodzie JavaScript możesz użyć następujących predefiniowanych zmiennych:
- `attribute`: nazwa atrybutu podlegającego walidacji.
- `value`: wartość atrybutu podlegająca walidacji.
- `messages`: tablica używana do przechowywania wiadomości błędów dla danego atrybutu.
- `messages`: tablica używana do przechowywania wiadomości błędów dla danego atrybutu.
- `deferred`: tablica, do której można dodać zakolejkowane obiekty (wyjaśnione w późniejszej podsekcji).
W poniższym przykładzie, tworzymy walidator `StatusValidator`, który sprawdza, czy wartość danego atrybutu jest wartością znajdującą się na liście statusów w bazie danych.
@ -556,7 +556,7 @@ JS;
> ]
> ```
> Tip: Jeśli musisz dodać ręcznie walidację po stronie klienta np. podczas dynamicznego dodawania pól formularza lub przeprowadzania specjalnej logiki w obrębie interfejsu
> Tip: Jeśli musisz dodać ręcznie walidację po stronie klienta np. podczas dynamicznego dodawania pól formularza lub przeprowadzania specjalnej logiki w obrębie interfejsu
> użytkownika, zapoznaj się z rozdziałem [Praca z ActiveForm za pomocą JavaScript](https://github.com/samdark/yii2-cookbook/blob/master/book/forms-activeform-js.md)
> w Yii 2.0 Cookbook.
@ -639,10 +639,10 @@ JS;
Niektóre walidacje mogą zostać wykonane tylko po stronie serwera, ponieważ tylko serwer posiada niezbędne informacje do ich przeprowadzenia.
Dla przykładu, aby sprawdzić, czy login został już zajęty, musimy sprawdzić tabelę użytkowników w bazie danych.
W tym właśnie przypadku możesz użyć walidacji AJAX. Wywoła ona żądanie AJAX w tle, aby spradzić to pole.
W tym właśnie przypadku możesz użyć walidacji AJAX. Wywoła ona żądanie AJAX w tle, aby spradzić to pole.
Aby uaktywnić walidację AJAX dla pojedyńczego pola formularza, ustaw właściwość [[yii\widgets\ActiveField::enableAjaxValidation|enableAjaxValidation]] na `true`
oraz zdefiniuj unikalne `id` formularza:
Aby uaktywnić walidację AJAX dla pojedyńczego pola formularza, ustaw właściwość [[yii\widgets\ActiveField::enableAjaxValidation|enableAjaxValidation]] na `true`
oraz zdefiniuj unikalne `id` formularza:
```php
use yii\widgets\ActiveForm;
@ -682,8 +682,8 @@ if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Powyższy kod sprawdzi, czy zapytanie zostało wysłane przy użyciu AJAXa. Jeśli tak, w odpowiedzi zwróci wynik walidacji w formacie JSON.
> Info: Możesz również użyć [walidacji kolejkowej](#deferred-validation) do wykonania walidacji AJAX,
> Info: Możesz również użyć [walidacji kolejkowej](#deferred-validation) do wykonania walidacji AJAX,
> jednakże walidacja AJAXowa opisana w tej sekcji jest bardziej systematyczna i wymaga mniej wysiłku przy kodowaniu.
Kiedy zarówno `enableClientValidation`, jak i `enableAjaxValidation` ustawione są na `true`, walidacja za pomocą AJAX zostanie uruchomiona dopiero po udanej
Kiedy zarówno `enableClientValidation`, jak i `enableAjaxValidation` ustawione są na `true`, walidacja za pomocą AJAX zostanie uruchomiona dopiero po udanej
walidacji po stronie klienta.

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`.

18
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)
@ -47,7 +47,7 @@ public function behaviors()
O código acima afirma que o cache HTTP deve ser habilitado apenas para a ação `index`. Este deve
gerar um cabeçalho HTTP `last-modified` baseado na última data de alteração dos*posts*. Quando um
navegador visitar a página `index` pela primeira vez, a página será gerada no servidor e enviada para
navegador visitar a página `index` pela primeira vez, a página será gerada no servidor e enviada para
o navegador; Se o navegador visitar a mesma página novamente e não houver modificação dos *posts* durante este
período, o servidor não irá remontará a página e o navegador usará a versão em cache no cliente.
Como resultado, a renderização do conteúdo na página não será executada no servidor.
@ -91,20 +91,20 @@ public function behaviors()
O código acima afirma que o cache de HTTP deve ser habilitado apenas para a ação `view`. Este deve
gerar um cabeçalho HTTP `ETag` baseado no título e no conteúdo do *post* requisitado. Quando um navegador visitar
a página `view` pela primeira vez, a página será gerada no servidor e enviada para ele; Se o navegador visitar
a página `view` pela primeira vez, a página será gerada no servidor e enviada para ele; Se o navegador visitar
a mesma página novamente e não houver alteração para o título e o conteúdo do *post*, o servidor não remontará
a página e o navegador usará a versão que estiver no cache do cliente. Como resultado, a renderização do
a página e o navegador usará a versão que estiver no cache do cliente. Como resultado, a renderização do
conteúdo na página não será executada no servidor.
ETags permite estratégias mais complexas e/ou mais precisas do que o uso do cabeçalho de `Last-modified`.
Por exemplo, um ETag pode ser invalidado se o site tiver sido alterado para um novo tema.
Gerações muito complexas de ETags podem contrariar o propósito de se usar `HttpCache` e introduzir despesas desnecessárias ao processamento, já que eles precisam ser reavaliados a cada requisição.
Gerações muito complexas de ETags podem contrariar o propósito de se usar `HttpCache` e introduzir despesas desnecessárias ao processamento, já que eles precisam ser reavaliados a cada requisição.
Tente encontrar uma expressão simples que invalida o cache se o conteúdo da página for modificado.
> Observação: Em concordância com a [RFC 7232](http://tools.ietf.org/html/rfc7232#section-2.4), o
`HttpCache` enviará os cabeçalhos `ETag` e `Last-Modified` se ambos forem assim configurados.
E se o cliente enviar ambos o cabeçalhos `If-None-Match` e `If-Modified-Since`, apenas o primeiro será
E se o cliente enviar ambos o cabeçalhos `If-None-Match` e `If-Modified-Since`, apenas o primeiro será
respeitado.
@ -120,16 +120,16 @@ Cache-Control: public, max-age=3600
## Limitador de Cache na Sessão <span id="session-cache-limiter"></span>
Quando uma página usa sessão, o PHP automaticamente enviará alguns cabeçalhos HTTP relacionados ao cache
como especificado na configuração `session.cache_limiter` do PHP.INI. Estes cabeçalhos podem interferir ou
como especificado na configuração `session.cache_limiter` do PHP.INI. Estes cabeçalhos podem interferir ou
desabilitar o cache que você deseja do `HttpCache`. Para prevenir-se deste problema, por padrão, o `HttpCache`
desabilitará o envio destes cabeçalhos automaticamente. Se você quiser modificar estes comportamentos, deve
configurar a propriedade [[yii\filters\HttpCache::sessionCacheLimiter]]. A propriedade pode receber um valor string, como: `public`, `private`, `private_no_expire` e `nocache`. Por favor, consulte o manual do
configurar a propriedade [[yii\filters\HttpCache::sessionCacheLimiter]]. A propriedade pode receber um valor string, como: `public`, `private`, `private_no_expire` e `nocache`. Por favor, consulte o manual do
PHP sobre [session_cache_limiter()](http://www.php.net/manual/en/function.session-cache-limiter.php)
para mais explicações sobre estes valores.
## Implicações para SEO <span id="seo-implications"></span>
Os bots do motor de buscas tendem a respeitar cabeçalhos de cache. Já que alguns rastreadores têm um limite sobre a quantidade de páginas por domínio que eles processam em um certo espaço de tempo, introduzir cabeçalhos de cache podem
Os bots do motor de buscas tendem a respeitar cabeçalhos de cache. Já que alguns rastreadores têm um limite sobre a quantidade de páginas por domínio que eles processam em um certo espaço de tempo, introduzir cabeçalhos de cache podem
ajudar na indexação do seu site já que eles reduzem o número de páginas que precisam ser processadas.

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));
}
}
```

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

@ -4,7 +4,7 @@ Autenticação
Autenticação é o processo de verificação da identidade do usuário. Geralmente é usado um identificador (ex. um nome de usuário ou endereço de e-mail) e um token secreto (ex. uma senha ou um token de acesso) para determinar se o usuário é quem ele diz ser. Autenticação é a base do recurso de login.
O Yii fornece um framework de autenticação com vários componentes que dão suporte ao login. Para usar este framework, você precisará primeiramente fazer o seguinte:
* Configurar o componente [[yii\web\User|user]] da aplicação;
* Criar uma classe que implementa a interface [[yii\web\IdentityInterface]].
@ -14,7 +14,7 @@ O Yii fornece um framework de autenticação com vários componentes que dão su
O componente [[yii\web\User|user]] da aplicação gerencia o status de autenticação dos usuários. Ele requer que você especifique uma [[yii\web\User::identityClass|classe de identidade]] que contém a atual lógia de autenticação.
Na cofiguração abaixo, a [[yii\web\User::identityClass|classe de identidade]] do
[[yii\web\User|user]] é configurada para ser `app\models\User` cuja implementação é explicada na próxima subseção:
```php
return [
'components' => [
@ -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)
{
@ -110,7 +110,7 @@ e gravá-la na tabela `user`:
class User extends ActiveRecord implements IdentityInterface
{
......
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
@ -129,7 +129,7 @@ class User extends ActiveRecord implements IdentityInterface
## Usando o [[yii\web\User]] <span id="using-user"></span>
Você usa o [[yii\web\User]] principalmente como um componente `user` da aplicação.
Você usa o [[yii\web\User]] principalmente como um componente `user` da aplicação.
É possível detectar a identidade do usuário atual utilizando a expressão `Yii::$app->user->identity`. Ele retorna uma instância da [[yii\web\User::identityClass|classe de identidade]] representando o atual usuário logado, ou `null` se o usuário corrente não estiver autenticado (acessando como convidado). O código a seguir mostra como recuperar outras informações relacionadas à autenticação de [[yii\web\User]]:
@ -151,13 +151,13 @@ Para logar um usuário, você pode usar o seguinte código:
// observe que você pode querer checar a senha se necessário
$identity = User::findOne(['username' => $username]);
// logar o usuário
// logar o usuário
Yii::$app->user->login($identity);
```
O método [[yii\web\User::login()]] define a identidade do usuário atual para o [[yii\web\User]]. Se a sessão estiver [[yii\web\User::enableSession|habilitada]], ele vai manter a identidade na sessão para que o status de autenticação do usuário seja mantido durante toda a sessão. Se o login via cookie (ex. login "remember me") estiver [[yii\web\User::enableAutoLogin|habilitada]], ele também guardará a identidade em um cookie para que o estado de autenticação do usuário possa ser recuperado a partir do cookie enquanto o cookie permanece válido.
A fim de permitir login via cookie, você pode configurar [[yii\web\User::enableAutoLogin]] como `true` na configuração da aplicação. Você também precisará fornecer um parâmetro de tempo de duração quando chamar o método [[yii\web\User::login()]].
A fim de permitir login via cookie, você pode configurar [[yii\web\User::enableAutoLogin]] como `true` na configuração da aplicação. Você também precisará fornecer um parâmetro de tempo de duração quando chamar o método [[yii\web\User::login()]].
Para realizar o logout de um usuário, simplesmente chame:
@ -173,12 +173,12 @@ Observe que o logout de um usuário só tem sentido quando a sessão está habil
A classe [[yii\web\User]] dispara alguns eventos durante os processos de login e logout:
* [[yii\web\User::EVENT_BEFORE_LOGIN|EVENT_BEFORE_LOGIN]]: disparado no início de [[yii\web\User::login()]].
Se o manipulador de evento define a propriedade [[yii\web\UserEvent::isValid|isValid]] do objeto de evento para `false`, o processo de login será cancelado.
Se o manipulador de evento define a propriedade [[yii\web\UserEvent::isValid|isValid]] do objeto de evento para `false`, o processo de login será cancelado.
* [[yii\web\User::EVENT_AFTER_LOGIN|EVENT_AFTER_LOGIN]]: dispara após de um login com sucesso.
* [[yii\web\User::EVENT_BEFORE_LOGOUT|EVENT_BEFORE_LOGOUT]]: dispara no início de [[yii\web\User::logout()]]. Se o manipulador de evento define a propriedade [[yii\web\UserEvent::isValid|isValid]] do objeto de evento para `false`, o processo de logout será cancelado.
* [[yii\web\User::EVENT_BEFORE_LOGOUT|EVENT_BEFORE_LOGOUT]]: dispara no início de [[yii\web\User::logout()]]. Se o manipulador de evento define a propriedade [[yii\web\UserEvent::isValid|isValid]] do objeto de evento para `false`, o processo de logout será cancelado.
* [[yii\web\User::EVENT_AFTER_LOGOUT|EVENT_AFTER_LOGOUT]]: dispara após um logout com sucesso.
Você pode responder a estes eventos implementando funcionalidades, tais como auditoria de login, estatísticas de usuários on-line. Por exemplo, no manipulador
Você pode responder a estes eventos implementando funcionalidades, tais como auditoria de login, estatísticas de usuários on-line. Por exemplo, no manipulador
[[yii\web\User::EVENT_AFTER_LOGIN|EVENT_AFTER_LOGIN]], você pode registrar o tempo de login e endereço IP na tabela `user`.

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

@ -191,7 +191,7 @@ return [
];
```
`DbManager` usa quatro tabelas de banco de dados para armazenar seus dados:
`DbManager` usa quatro tabelas de banco de dados para armazenar seus dados:
- [[yii\rbac\DbManager::$itemTable|itemTable]]: tabela para armazenar itens de autorização. O padrão é "auth_item".
- [[yii\rbac\DbManager::$itemChildTable|itemChildTable]]: tabela para armazenar hierarquia de itens de autorização. O padrão é "auth_item_child".
@ -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)

10
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)
```
@ -43,7 +43,7 @@ public function behaviors()
}
```
Приведенный выше код устанавливает, что HTTP кэширование должно быть включено только для действия `index`. Он
Приведенный выше код устанавливает, что HTTP кэширование должно быть включено только для действия `index`. Он
генерирует `Last-Modified` HTTP заголовок на основе времени последнего сообщения. Когда браузер в первый раз посещает страницу `index`, то страница будет сгенерирована на сервере и отправлена в браузер; если браузер снова зайдёт на эту страницу и с тех пор ни один пост не обновится, то сервер не будет пересоздавать страницу и браузер будет использовать закэшированную на стороне клиента версию. В результате, будет пропущено как создание страницы на стороне сервера, так и передача содержания страницы клиенту.
@ -80,13 +80,13 @@ public function behaviors()
}
```
Приведенный выше код устанавливает, что HTTP кэширование должно быть включено только для действия `view`. Он
Приведенный выше код устанавливает, что HTTP кэширование должно быть включено только для действия `view`. Он
генерирует `ETag` HTTP заголовок на основе заголовка и содержания последнего сообщения. Когда браузер в первый раз посещает страницу `view`, то страница будет сгенерирована на сервере и отправлена в браузер; если браузер снова зайдёт на эту страницу и с тех пор ни один пост не обновится, то сервер не будет пересоздавать страницу и браузер будет использовать закэшированную на стороне клиента версию. В результате, будет пропущено как создание страницы на стороне сервера, так и передача содержание страницы клиенту.
ETags позволяет применять более сложные и/или более точные стратегии кэширования, чем заголовок `Last-Modified`.
ETags позволяет применять более сложные и/или более точные стратегии кэширования, чем заголовок `Last-Modified`.
Например, ETag станет невалидным (некорректным), если на сайте была включена другая тема
Ресурсоёмкая генерация ETag может противоречить цели использования `HttpCache` и внести излишнюю нагрузку,
Ресурсоёмкая генерация ETag может противоречить цели использования `HttpCache` и внести излишнюю нагрузку,
т.к. он должен пересоздаваться при каждом запросе. Попробуйте найти простое выражение, которое инвалидирует кэш, если содержание страницы было изменено.
> Note: В соответствии с [RFC 7232](http://tools.ietf.org/html/rfc7232#section-2.4),

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-х разрядных - они будут представленны как строки.

232
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`:
@ -167,7 +167,7 @@ class m150101_185401_create_news_table extends Migration
```php
yii migrate/create create_post_table
```
```
сгенерирует
@ -189,10 +189,10 @@ class m150811_220037_create_post_table extends Migration
```
Чтобы сразу создать поля таблицы, укажите их через опцию `--fields`.
```php
yii migrate/create create_post_table --fields=title:string,body:text
```
```
сгенерирует
@ -219,7 +219,7 @@ class m150811_220037_create_post_table extends Migration
```php
yii migrate/create create_post_table --fields=title:string(12):notNull:unique,body:text
```
```
сгенерирует
@ -245,12 +245,131 @@ 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`.
### Удаление таблицы
```php
yii migrate/create drop_post_table --fields=title:string(12):notNull:unique,body:text
```
```
сгенерирует
@ -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>
@ -565,7 +753,7 @@ yii migrate/mark 1392853618 # используя вре
* `fields`: массив конфигураций столбцов, который используется для генерации кода миграции. По умолчанию пуст. Формат
каждой конфигурации `ИМЯ_СТОЛБЦА:ТИП_СТОЛБЦА:ДЕКОРАТОР_СТОЛБЦА`. Например, `--fields=name:string(12):notNull` даст нам
столбец типа строка размера 12 с ограничением `not null`.
В следующем примере показано, как можно использовать эти параметры.
@ -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:
>

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

@ -86,9 +86,9 @@ public function rules()
используя текущий [[yii\base\Model::scenario|scenario]]. Эти правила называются - *активными правилами*.
3. Каждое активное правило проверяет каждый активный атрибут, который ассоциируется с правилом.
Правила проверки выполняются в том порядке, как они перечислены.
Согласно вышеизложенным пунктам, атрибут будет проверяться, если и только если он является
активным атрибутом, объявленным в `scenarios()` и связан с одним или несколькими активными правилами,
Согласно вышеизложенным пунктам, атрибут будет проверяться, если и только если он является
активным атрибутом, объявленным в `scenarios()` и связан с одним или несколькими активными правилами,
объявленными в `rules()`.
> Note: Правилам валидации полезно давать имена. Например:
@ -103,7 +103,7 @@ public function rules()
> }
> ```
>
> В случае наследования предыдущей модели, именованные правила можно модифицировать или удалить:
> В случае наследования предыдущей модели, именованные правила можно модифицировать или удалить:
>
> ```php
> public function rules()
@ -162,13 +162,13 @@ public function rules()
/**
* @param Model $model модель используемая для проверки
* @param string $attribute атрибут для проверки
* @return boolean следует ли применять правило
* @return bool следует ли применять правило
*/
function ($model, $attribute)
```
Если вам нужна поддержка условной проверки на стороне клиента, вы должны настроить свойство метода
[[yii\validators\Validator::whenClient|whenClient]] которое принимает строку, представляющую JavaScript
[[yii\validators\Validator::whenClient|whenClient]] которое принимает строку, представляющую JavaScript
функцию, возвращаемое значение определяет, следует ли применять правило или нет. Например:
```php
@ -183,7 +183,7 @@ function ($model, $attribute)
### Фильтрация данных <span id="data-filtering"></span>
Пользователь часто вводит данные которые нужно предварительно отфильтровать или предварительно обработать(очистить).
Например, вы хотите обрезать пробелы вокруг `username`. Вы можете использовать правила валидации для
Например, вы хотите обрезать пробелы вокруг `username`. Вы можете использовать правила валидации для
достижения этой цели.
В следующих примерах показано, как обрезать пробелы в входных данных и превратить пустые входные данные в `NULL`
@ -206,8 +206,8 @@ return [
### Обработка пустых входных данных <span id="handling-empty-inputs"></span>
Если входные данные представлены из HTML-формы, часто нужно присвоить некоторые значения
по умолчанию для входных данных, если они не заполнены. Вы можете сделать это с помощью
Если входные данные представлены из HTML-формы, часто нужно присвоить некоторые значения
по умолчанию для входных данных, если они не заполнены. Вы можете сделать это с помощью
валидатора [default](tutorial-core-validators.md#default). Например:
```php
@ -259,8 +259,8 @@ if ($validator->validate($email, $error)) {
> Note: Не все валидаторы поддерживают такой тип проверки. Примером может служить
[unique](tutorial-core-validators.md#unique) валидатор, который предназначен для работы с моделью.
Если необходимо выполнить несколько проверок в отношении нескольких значений,
вы можете использовать [[yii\base\DynamicModel]], который поддерживает объявление, как
Если необходимо выполнить несколько проверок в отношении нескольких значений,
вы можете использовать [[yii\base\DynamicModel]], который поддерживает объявление, как
атрибутов так и правил "на лету". Его использование выглядит следующим образом:
```php
@ -279,7 +279,7 @@ public function actionSearch($name, $email)
}
```
Метод [[yii\base\DynamicModel::validateData()]] создает экземпляр `DynamicModel`, определяет
Метод [[yii\base\DynamicModel::validateData()]] создает экземпляр `DynamicModel`, определяет
атрибуты, используя приведенные данные (`name` и `email` в этом примере), и затем вызывает
[[yii\base\Model::validate()]]
с данными правилами.
@ -301,7 +301,7 @@ public function actionSearch($name, $email)
}
}
```
После валидации, вы можете проверить успешность выполнения вызвав
После валидации, вы можете проверить успешность выполнения вызвав
метод [[yii\base\DynamicModel::hasErrors()|hasErrors()]] и затем получить ошибки проверки вызвав
метод [[yii\base\DynamicModel::errors|errors]] как это делают нормальные модели.
Вы можете также получить доступ к динамическим атрибутам, определенным через экземпляр модели, например,
@ -310,7 +310,7 @@ public function actionSearch($name, $email)
## Создание Валидаторов <span id="creating-validators"></span>
Кроме того, используя [основные валидаторы](tutorial-core-validators.md), включенные в релизы Yii, вы также можете
Кроме того, используя [основные валидаторы](tutorial-core-validators.md), включенные в релизы Yii, вы также можете
создавать свои собственные валидаторы. Вы можете создавать встроенные валидаторы или автономные валидаторы.
@ -327,8 +327,8 @@ public function actionSearch($name, $email)
function ($attribute, $params)
```
Если атрибут не прошел проверку, метод/функция должна вызвать [[yii\base\Model::addError()]],
чтобы сохранить сообщение об ошибке в модели, для того чтобы позже можно было получить сообщение об ошибке для
Если атрибут не прошел проверку, метод/функция должна вызвать [[yii\base\Model::addError()]],
чтобы сохранить сообщение об ошибке в модели, для того чтобы позже можно было получить сообщение об ошибке для
представления конечным пользователям.
Ниже приведены некоторые примеры:
@ -366,7 +366,7 @@ class MyForm extends Model
```
> Note: по умолчанию, встроенные валидаторы не будут применяться, если связанные с ними атрибуты
получат пустые входные данные, или если они уже не смогли пройти некоторые правила валидации.
получат пустые входные данные, или если они уже не смогли пройти некоторые правила валидации.
Если вы хотите, чтобы, это правило применялось всегда, вы можете настроить свойства
[[yii\validators\Validator::skipOnEmpty|skipOnEmpty]] и/или [[yii\validators\Validator::skipOnError|skipOnError]]
свойства `false` в правиле объявления. Например:
@ -383,7 +383,7 @@ class MyForm extends Model
Автономный валидатор - это класс, расширяющий [[yii\validators\Validator]] или его дочерних класс.
Вы можете реализовать свою логику проверки путем переопределения метода
[[yii\validators\Validator::validateAttribute()]]. Если атрибут не прошел проверку, вызвать
[[yii\base\Model::addError()]],
[[yii\base\Model::addError()]],
чтобы сохранить сообщение об ошибке в модели, как это делают [встроенные валидаторы](#inline-validators). Например:
```php
@ -403,23 +403,23 @@ class CountryValidator extends Validator
```
Если вы хотите, чтобы ваш валидатор поддерживал проверку значений, без модели, также необходимо переопределить
[[yii\validators\Validator::validate()]]. Вы можете также
[[yii\validators\Validator::validate()]]. Вы можете также
переопределить [[yii\validators\Validator::validateValue()]]
вместо `validateAttribute()` и `validate()`, потому что по умолчанию последние два метода
вместо `validateAttribute()` и `validate()`, потому что по умолчанию последние два метода
реализуются путем вызова `validateValue()`.
## Валидация на стороне клиента <span id="client-side-validation"></span>
Проверка на стороне клиента на основе JavaScript целесообразна, когда конечные пользователи вводят
входные данные через HTML-формы, так как эта проверка позволяет пользователям узнать, ошибки ввода
быстрее, и таким образом улучшает ваш пользовательский интерфейс. Вы можете использовать или
Проверка на стороне клиента на основе JavaScript целесообразна, когда конечные пользователи вводят
входные данные через HTML-формы, так как эта проверка позволяет пользователям узнать, ошибки ввода
быстрее, и таким образом улучшает ваш пользовательский интерфейс. Вы можете использовать или
реализовать валидатор, который поддерживает валидацию на стороне клиента *в дополнение* к проверке на стороне сервера.
> Info: Проверка на стороне клиента желательна, но необязательна. Её основная цель заключается в
предоставлении пользователям более удобного интерфейса. Так как входные данные, поступают от конечных
пользователей, вы никогда не должны доверять верификации на стороне клиента. По этой причине, вы всегда
должны выполнять верификацию на стороне сервера путем вызова [[yii\base\Model::validate()]],
предоставлении пользователям более удобного интерфейса. Так как входные данные, поступают от конечных
пользователей, вы никогда не должны доверять верификации на стороне клиента. По этой причине, вы всегда
должны выполнять верификацию на стороне сервера путем вызова [[yii\base\Model::validate()]],
как описано в предыдущих пунктах.
@ -477,21 +477,21 @@ HTML-форма построена с помощью следующего код
<?php yii\widgets\ActiveForm::end(); ?>
```
Класс [[yii\widgets\ActiveForm]] будет читать правила проверки заявленные в модели и генерировать
соответствующий код JavaScript для валидаторов, которые поддерживают проверку на стороне клиента.
Когда пользователь изменяет значение поля ввода или отправляет форму, JavaScript на стороне клиента
Класс [[yii\widgets\ActiveForm]] будет читать правила проверки заявленные в модели и генерировать
соответствующий код JavaScript для валидаторов, которые поддерживают проверку на стороне клиента.
Когда пользователь изменяет значение поля ввода или отправляет форму, JavaScript на стороне клиента
будет срабатывать и проверять введенные данные.
Если вы хотите отключить проверку на стороне клиента полностью, вы можете настроить свойство
[[yii\widgets\ActiveForm::enableClientValidation]] установив значение `false`. Вы также можете отключить
проверку на стороне клиента отдельных полей ввода, настроив их с помощью свойства
[[yii\widgets\ActiveForm::enableClientValidation]] установив значение `false`. Вы также можете отключить
проверку на стороне клиента отдельных полей ввода, настроив их с помощью свойства
[[yii\widgets\ActiveField::enableClientValidation]] установив значение `false`.
### Реализация проверки на стороне клиента <span id="implementing-client-side-validation"></span>
Чтобы создать валидатор, который поддерживает проверку на стороне клиента, вы должны реализовать метод
[[yii\validators\Validator::clientValidateAttribute()]] возвращающий фрагмент кода JavaScript,
Чтобы создать валидатор, который поддерживает проверку на стороне клиента, вы должны реализовать метод
[[yii\validators\Validator::clientValidateAttribute()]] возвращающий фрагмент кода JavaScript,
который выполняет проверку на стороне клиента. В JavaScript-коде, вы можете использовать следующие предопределенные переменные:
- `attribute`: имя атрибута для проверки.
@ -499,7 +499,7 @@ HTML-форма построена с помощью следующего код
- `messages`: массив, используемый для хранения сообщений об ошибках, проверки значения атрибута.
- `deferred`: массив, который содержит отложенные объекты (описано в следующем подразделе).
В следующем примере мы создаем `StatusValidator` который проверяет, if an input is a valid
В следующем примере мы создаем `StatusValidator` который проверяет, if an input is a valid
status input against the existing status data.
Валидатор поддерживает оба способа проверки и на стороне сервера и на стороне клиента.
@ -538,9 +538,9 @@ JS;
}
```
> Tip: приведенный выше код даётся, в основном, чтобы продемонстрировать, как осуществляется
> поддержка проверки на стороне клиента. На практике вы можете использовать
> [in](tutorial-core-validators.md#in) основные валидаторы для достижения той же цели.
> Tip: приведенный выше код даётся, в основном, чтобы продемонстрировать, как осуществляется
> поддержка проверки на стороне клиента. На практике вы можете использовать
> [in](tutorial-core-validators.md#in) основные валидаторы для достижения той же цели.
> Вы можете написать проверку, как правило, например:
>
> ```php
@ -551,8 +551,8 @@ JS;
### Отложенная валидация <span id="deferred-validation"></span>
Если Вам необходимо выполнить асинхронную проверку на стороне клиента, вы можете создавать
[Deferred objects](http://api.jquery.com/category/deferred-object/). Например, чтобы выполнить
Если Вам необходимо выполнить асинхронную проверку на стороне клиента, вы можете создавать
[Deferred objects](http://api.jquery.com/category/deferred-object/). Например, чтобы выполнить
пользовательские AJAX проверки, вы можете использовать следующий код:
```php
@ -571,7 +571,7 @@ JS;
В примере выше переменная `deferred` предусмотренная Yii, которая является массивом Отложенных объектов.
`$.get()` метод jQuery создает Отложенный объект, который помещается в массив `deferred`.
Также можно явно создать Отложенный объект и вызвать его методом `resolve()`, тогда выполняется асинхронный
Также можно явно создать Отложенный объект и вызвать его методом `resolve()`, тогда выполняется асинхронный
вызов к серверу. В следующем примере показано, как проверить размеры загружаемого файла изображения
на стороне клиента.
@ -629,7 +629,7 @@ JS;
### AJAX валидация <span id="ajax-validation"></span>
Некоторые проверки можно сделать только на стороне сервера, потому что только сервер имеет необходимую информацию.
Например, чтобы проверить логин пользователя на уникальность, необходимо проверить логин в
Например, чтобы проверить логин пользователя на уникальность, необходимо проверить логин в
базе данных на стороне сервера. Вы можете использовать проверку на основе AJAX в этом случае.
Это вызовет AJAX-запрос в фоновом режиме, чтобы проверить логин пользователя, сохраняя при этом валидацию
на стороне клиента. Выполняя её перед запросом к серверу.
@ -650,7 +650,7 @@ echo $form->field($model, 'username', ['enableAjaxValidation' => true]);
ActiveForm::end();
```
Чтобы включить AJAX-валидацию для всей формы, Вы должны свойство
Чтобы включить AJAX-валидацию для всей формы, Вы должны свойство
[[yii\widgets\ActiveForm::enableAjaxValidation|enableAjaxValidation]] выбрать как `true` для формы:
```php
@ -672,8 +672,8 @@ if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
}
```
Приведенный выше код будет проверять, является ли текущий запрос AJAX. Если да,
он будет отвечать на этот запрос, предварительно выполнив проверку и возвратит ошибки в
Приведенный выше код будет проверять, является ли текущий запрос AJAX. Если да,
он будет отвечать на этот запрос, предварительно выполнив проверку и возвратит ошибки в
случае их появления в формате JSON.
> Info: Вы также можете использовать [Deferred Validation](#deferred-validation) AJAX валидации.

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

@ -26,13 +26,15 @@ DetailView использует свойство [[yii\widgets\DetailView::$attr
echo DetailView::widget([
'model' => $model,
'attributes' => [
'title', // title свойство (обычный текст)
'description:html', // description свойство, как HTML
[ // name свойство зависимой модели owner
'title', // title свойство (обычный текст)
'description:html', // description свойство, как HTML
[ // name свойство зависимой модели owner
'label' => 'Owner',
'value' => $model->owner->name,
'value' => $model->owner->name,
'contentOptions' => ['class' => 'bg-red'], // настройка HTML атрибутов для тега, соответсвующего value
'captionOptions' => ['tooltip' => 'Tooltip'], // настройка HTML атрибутов для тега, соответсвующего label
],
'created_at:datetime', // дата создания в формате datetime
'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));
}
}
```

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

@ -1,13 +1,13 @@
Аутентификация
==============
Аутентификация — это процесс проверки подлинности пользователя. Обычно используется идентификатор
Аутентификация — это процесс проверки подлинности пользователя. Обычно используется идентификатор
(например, `username` или адрес электронной почты) и секретный токен (например, пароль или ключ доступа), чтобы судить о
том, что пользователь именно тот, за кого себя выдаёт. Аутентификация является основной функцией формы входа.
Yii предоставляет фреймворк авторизации с различными компонентами, обеспечивающими процесс входа.
Для использования этого фреймворка вам нужно проделать следующее:
* Настроить компонент приложения [[yii\web\User|user]];
* Создать класс, реализующий интерфейс [[yii\web\IdentityInterface]].
@ -15,10 +15,10 @@ Yii предоставляет фреймворк авторизации с ра
## Настройка [[yii\web\User]] <span id="configuring-user"></span>
Компонент [[yii\web\User|user]] управляет статусом аутентификации пользователя.
Он требует, чтобы вы указали [[yii\web\User::identityClass|identity class]], который будет содержать
Он требует, чтобы вы указали [[yii\web\User::identityClass|identity class]], который будет содержать
текущую логику аутентификации. В следующей конфигурации приложения, [[yii\web\User::identityClass|identity class]] для
[[yii\web\User|user]] задан как `app\models\User`, реализация которого будет объяснена в следующем разделе:
```php
return [
'components' => [
@ -38,7 +38,7 @@ return [
* [[yii\web\IdentityInterface::findIdentity()|findIdentity()]]: Этот метод находит экземпляр `identity class`,
используя ID пользователя. Этот метод используется, когда необходимо поддерживать состояние аутентификации через сессии.
* [[yii\web\IdentityInterface::findIdentityByAccessToken()|findIdentityByAccessToken()]]: Этот метод находит экземпляр `identity class`,
используя токен доступа. Метод используется, когда требуется аутентифицировать пользователя
используя токен доступа. Метод используется, когда требуется аутентифицировать пользователя
только по секретному токену (например в RESTful приложениях, не сохраняющих состояние между запросами).
* [[yii\web\IdentityInterface::getId()|getId()]]: Этот метод возвращает ID пользователя, представленного данным экземпляром `identity`.
* [[yii\web\IdentityInterface::getAuthKey()|getAuthKey()]]: Этот метод возвращает ключ, используемый для основанной на `cookie` аутентификации.
@ -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)
{
@ -125,7 +125,7 @@ class User extends ActiveRecord implements IdentityInterface
class User extends ActiveRecord implements IdentityInterface
{
......
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
@ -176,7 +176,7 @@ $identity = User::findOne(['username' => $username]);
Yii::$app->user->login($identity);
```
Метод [[yii\web\User::login()]] устанавливает `identity` текущего пользователя в [[yii\web\User]]. Если сессии
Метод [[yii\web\User::login()]] устанавливает `identity` текущего пользователя в [[yii\web\User]]. Если сессии
[[yii\web\User::enableSession|включены]], то `identity` будет сохраняться в сессии, так что состояние
статуса аутентификации будет поддерживаться на всём протяжении сессии. Если [[yii\web\User::enableAutoLogin|включен]] вход, основанный на cookie (так называемый "запомни меня" вход), то `identity` также будет сохранена
в `cookie` так, чтобы статус аутентификации пользователя мог быть восстановлен на протяжении всего времени жизни `cookie`.
@ -205,7 +205,7 @@ Yii::$app->user->logout();
* [[yii\web\User::EVENT_AFTER_LOGIN|EVENT_AFTER_LOGIN]]: вызывается после успешного входа.
* [[yii\web\User::EVENT_BEFORE_LOGOUT|EVENT_BEFORE_LOGOUT]]: вызывается перед вызовом [[yii\web\User::logout()]].
Если обработчик устанавливает свойство [[yii\web\UserEvent::isValid|isValid]] объекта в `false`,
процесс выхода будет прерван.
процесс выхода будет прерван.
* [[yii\web\User::EVENT_AFTER_LOGOUT|EVENT_AFTER_LOGOUT]]: вызывается после успешного выхода.
Вы можете использовать эти события для реализации функции аудита входа, сбора статистики онлайн пользователей. Например,

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

@ -51,7 +51,7 @@ class SiteController extends Controller
Параметр `rules` задаёт [[yii\filters\AccessRule|правила доступа]], которые означают следующее:
- Разрешить всем гостям (ещё не прошедшим авторизацию) доступ к действиям `login` и `signup`.
Опция `roles` содержит знак вопроса `?`, это специальный токен обозначающий "гостя".
Опция `roles` содержит знак вопроса `?`, это специальный токен обозначающий "гостя".
- Разрешить аутентифицированным пользователям доступ к действию `logout`. Символ `@` — это другой специальный токен,
обозначающий аутентифицированного пользователя.
@ -182,7 +182,7 @@ Yii реализует общую иерархическую RBAC, следуя
### Настройка RBAC Manager
Перед определением авторизационных данных и проверкой прав доступа, мы должны настроить компонент приложения
[[yii\base\Application::authManager|authManager]]. Yii предоставляет два типа менеджеров авторизации:
[[yii\base\Application::authManager|authManager]]. Yii предоставляет два типа менеджеров авторизации:
[[yii\rbac\PhpManager]] и [[yii\rbac\DbManager]]. Первый использует файл с PHP скриптом для хранения данных авторизации,
второй сохраняет данные в базе данных. Вы можете использовать первый, если ваше приложение не требует слишком динамичного
управления ролями и разрешениями.
@ -224,7 +224,7 @@ return [
];
```
`DbManager` использует четыре таблицы для хранения данных:
`DbManager` использует четыре таблицы для хранения данных:
- [[yii\rbac\DbManager::$itemTable|itemTable]]: таблица для хранения авторизационных элементов. По умолчанию "auth_item".
- [[yii\rbac\DbManager::$itemChildTable|itemChildTable]]: таблица для хранения иерархии элементов. По умолчанию "auth_item_child".
@ -334,7 +334,7 @@ public function signup()
```
Для приложений, требующих комплексного контроля доступа с динамически обновляемыми данными авторизации, существуют
специальные пользовательские интерфейсы (так называемые админ-панели), которые могут быть разработаны с
специальные пользовательские интерфейсы (так называемые админ-панели), которые могут быть разработаны с
использованием API, предлагаемого `authManager`.
@ -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)
{
@ -541,7 +541,7 @@ $auth->addChild($admin, $author);
Обратите внимание, так как "author" добавлен как дочерняя роль к "admin", следовательно в реализации метода `execute()`
класса правила вы должны учитывать эту иерархию. Именно поэтому для роли "author" метод `execute()` вернёт истину,
если пользователь принадлежит к группам 1 или 2 (это означает, что пользователь находится в группе
если пользователь принадлежит к группам 1 или 2 (это означает, что пользователь находится в группе
администраторов или авторов)
Далее настроим `authManager` с помощью перечисления ролей в свойстве [[yii\rbac\BaseManager::$defaultRoles]]:

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)
```

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

@ -1040,10 +1040,10 @@ In the code example above, we are modifying the relational query by appending an
### Joining with Relations <span id="joining-with-relations"></span>
> Note: The content described in this subsection is only applicable to relational databases, such as
> Note: The content described in this subsection is only applicable to relational databases, such as
MySQL, PostgreSQL, etc.
The relational queries that we have described so far only reference the primary table columns when
The relational queries that we have described so far only reference the primary table columns when
querying for the primary data. In reality we often need to reference columns in the related tables. For example,
we may want to bring back the customers who have at least one active order. To solve this problem, we can
build a join query like the following:
@ -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", [

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

@ -24,13 +24,15 @@ A typical usage of DetailView is as follows:
echo DetailView::widget([
'model' => $model,
'attributes' => [
'title', // title attribute (in plain text)
'description:html', // description attribute formatted as HTML
[ // the owner name of the model
'title', // title attribute (in plain text)
'description:html', // description attribute formatted as HTML
[ // the owner name of the model
'label' => 'Owner',
'value' => $model->owner->name,
'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
'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:
@ -360,7 +362,7 @@ use yii\data\ActiveDataProvider;
class PostSearch extends Post
{
public function rules()
{
{
// only fields in rules() are searchable
return [
[['id'], 'integer'],

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()`

40
docs/guide/security-authentication.md

@ -1,25 +1,25 @@
Authentication
==============
Authentication is the process of verifying the identity of a user. It usually uses an identifier
(e.g. a username or an email address) and a secret token (e.g. a password or an access token) to judge
Authentication is the process of verifying the identity of a user. It usually uses an identifier
(e.g. a username or an email address) and a secret token (e.g. a password or an access token) to judge
if the user is the one whom he claims as. Authentication is the basis of the login feature.
Yii provides an authentication framework which wires up various components to support login. To use this framework,
Yii provides an authentication framework which wires up various components to support login. To use this framework,
you mainly need to do the following work:
* Configure the [[yii\web\User|user]] application component;
* Create a class that implements the [[yii\web\IdentityInterface]] interface.
## Configuring [[yii\web\User]] <span id="configuring-user"></span>
The [[yii\web\User|user]] application component manages the user authentication status. It requires you to
The [[yii\web\User|user]] application component manages the user authentication status. It requires you to
specify an [[yii\web\User::identityClass|identity class]] which contains the actual authentication logic.
In the following application configuration, the [[yii\web\User::identityClass|identity class]] for
[[yii\web\User|user]] is configured to be `app\models\User` whose implementation is explained in
[[yii\web\User|user]] is configured to be `app\models\User` whose implementation is explained in
the next subsection:
```php
return [
'components' => [
@ -48,11 +48,11 @@ the following methods:
* [[yii\web\IdentityInterface::validateAuthKey()|validateAuthKey()]]: it implements the logic for verifying
the cookie-based login key.
If a particular method is not needed, you may implement it with an empty body. For example, if your application
If a particular method is not needed, you may implement it with an empty body. For example, if your application
is a pure stateless RESTful application, you would only need to implement [[yii\web\IdentityInterface::findIdentityByAccessToken()|findIdentityByAccessToken()]]
and [[yii\web\IdentityInterface::getId()|getId()]] while leaving all other methods with an empty body.
In the following example, an [[yii\web\User::identityClass|identity class]] is implemented as
In the following example, an [[yii\web\User::identityClass|identity class]] is implemented as
an [Active Record](db-active-record.md) class associated with the `user` database table.
```php
@ -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)
{
@ -125,7 +125,7 @@ user and store it in the `user` table:
class User extends ActiveRecord implements IdentityInterface
{
......
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
@ -147,7 +147,7 @@ class User extends ActiveRecord implements IdentityInterface
## Using [[yii\web\User]] <span id="using-user"></span>
You mainly use [[yii\web\User]] in terms of the `user` application component.
You mainly use [[yii\web\User]] in terms of the `user` application component.
You can detect the identity of the current user using the expression `Yii::$app->user->identity`. It returns
an instance of the [[yii\web\User::identityClass|identity class]] representing the currently logged-in user,
@ -172,19 +172,19 @@ To login a user, you may use the following code:
// note that you may want to check the password if needed
$identity = User::findOne(['username' => $username]);
// logs in the user
// logs in the user
Yii::$app->user->login($identity);
```
The [[yii\web\User::login()]] method sets the identity of the current user to the [[yii\web\User]]. If session is
The [[yii\web\User::login()]] method sets the identity of the current user to the [[yii\web\User]]. If session is
[[yii\web\User::enableSession|enabled]], it will keep the identity in the session so that the user
authentication status is maintained throughout the whole session. If cookie-based login (i.e. "remember me" login)
is [[yii\web\User::enableAutoLogin|enabled]], it will also save the identity in a cookie so that
the user authentication status can be recovered from the cookie as long as the cookie remains valid.
In order to enable cookie-based login, you need to configure [[yii\web\User::enableAutoLogin]] to be
`true` in the application configuration. You also need to provide a duration time parameter when calling
the [[yii\web\User::login()]] method.
`true` in the application configuration. You also need to provide a duration time parameter when calling
the [[yii\web\User::login()]] method.
To logout a user, simply call
@ -199,15 +199,15 @@ user session data. If you want to keep the session data, you should call `Yii::$
## Authentication Events <span id="auth-events"></span>
The [[yii\web\User]] class raises a few events during the login and logout processes.
The [[yii\web\User]] class raises a few events during the login and logout processes.
* [[yii\web\User::EVENT_BEFORE_LOGIN|EVENT_BEFORE_LOGIN]]: raised at the beginning of [[yii\web\User::login()]].
If the event handler sets the [[yii\web\UserEvent::isValid|isValid]] property of the event object to be `false`,
the login process will be cancelled.
the login process will be cancelled.
* [[yii\web\User::EVENT_AFTER_LOGIN|EVENT_AFTER_LOGIN]]: raised after a successful login.
* [[yii\web\User::EVENT_BEFORE_LOGOUT|EVENT_BEFORE_LOGOUT]]: raised at the beginning of [[yii\web\User::logout()]].
If the event handler sets the [[yii\web\UserEvent::isValid|isValid]] property of the event object to be `false`,
the logout process will be cancelled.
the logout process will be cancelled.
* [[yii\web\User::EVENT_AFTER_LOGOUT|EVENT_AFTER_LOGOUT]]: raised after a successful logout.
You may respond to these events to implement features such as login audit, online user statistics. For example,

18
docs/guide/security-authorization.md

@ -8,9 +8,9 @@ methods: Access Control Filter (ACF) and Role-Based Access Control (RBAC).
## Access Control Filter <span id="access-control-filter"></span>
Access Control Filter (ACF) is a simple authorization method implemented as [[yii\filters\AccessControl]] which
is best used by applications that only need some simple access control. As its name indicates, ACF is
is best used by applications that only need some simple access control. As its name indicates, ACF is
an action [filter](structure-filters.md) that can be used in a controller or a module. While a user is requesting
to execute an action, ACF will check a list of [[yii\filters\AccessControl::rules|access rules]]
to execute an action, ACF will check a list of [[yii\filters\AccessControl::rules|access rules]]
to determine if the user is allowed to access the requested action.
The code below shows how to use ACF in the `site` controller:
@ -48,7 +48,7 @@ class SiteController extends Controller
In the code above ACF is attached to the `site` controller as a behavior. This is the typical way of using an action
filter. The `only` option specifies that the ACF should only be applied to the `login`, `logout` and `signup` actions.
All other actions in the `site` controller are not subject to the access control. The `rules` option lists
All other actions in the `site` controller are not subject to the access control. The `rules` option lists
the [[yii\filters\AccessRule|access rules]], which reads as follows:
- Allow all guest (not yet authenticated) users to access the `login` and `signup` actions. The `roles` option
@ -57,7 +57,7 @@ the [[yii\filters\AccessRule|access rules]], which reads as follows:
"authenticated users".
ACF performs the authorization check by examining the access rules one by one from top to bottom until it finds
a rule that matches the current execution context. The `allow` value of the matching rule will then be used to
a rule that matches the current execution context. The `allow` value of the matching rule will then be used to
judge if the user is authorized or not. If none of the rules matches, it means the user is NOT authorized,
and ACF will stop further action execution.
@ -97,7 +97,7 @@ The comparison is case-sensitive. If this option is empty or not set, it means t
- `?`: matches a guest user (not authenticated yet)
- `@`: matches an authenticated user
Using other role names will trigger the invocation of [[yii\web\User::can()]], which requires enabling RBAC
Using other role names will trigger the invocation of [[yii\web\User::can()]], which requires enabling RBAC
(to be described in the next subsection). If this option is empty or not set, it means this rule applies to all roles.
* [[yii\filters\AccessRule::ips|ips]]: specifies which [[yii\web\Request::userIP|client IP addresses]] this rule matches.
@ -231,7 +231,7 @@ return [
`authManager` needs to be declared additionally to `config/web.php`.
> In case of yii2-advanced-app the `authManager` should be declared only once in `common/config/main.php`.
`DbManager` uses four database tables to store its data:
`DbManager` uses four database tables to store its data:
- [[yii\rbac\DbManager::$itemTable|itemTable]]: the table for storing authorization items. Defaults to "auth_item".
- [[yii\rbac\DbManager::$itemChildTable|itemChildTable]]: the table for storing authorization item hierarchy. Defaults to "auth_item_child".
@ -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)
{
@ -431,7 +431,7 @@ Here is what happens if the current user is John:
![Access check](images/rbac-access-check-2.png "Access check")
We are starting with the `updatePost` and going through `updateOwnPost`. In order to pass the access check, `AuthorRule`
We are starting with the `updatePost` and going through `updateOwnPost`. In order to pass the access check, `AuthorRule`
should return `true` from its `execute()` method. The method receives its `$params` from the `can()` method call so the value is
`['post' => $post]`. If everything is fine, we will get to `author` which is assigned to John.

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'],
]
```
@ -143,6 +153,9 @@ specified via [[yii\validators\DateValidator::timestampAttribute|timestampAttrib
Since version 2.0.4, a format and timezone can be specified for this attribute using
[[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.

8
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[]` を使います。
@ -297,14 +297,14 @@ switch には下記の書式を使用します。
```php
switch ($this->phpType) {
case 'string':
$a = (string)$value;
$a = (string) $value;
break;
case 'integer':
case 'int':
$a = (integer)$value;
$a = (int) $value;
break;
case 'boolean':
$a = (boolean)$value;
$a = (bool) $value;
break;
default:
$a = null;

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

@ -1,8 +1,8 @@
Styl kodowania bazowych plików frameworka Yii 2
===============================================
Poniższy styl kodowania jest stosowany w kodzie frameworka Yii 2.x i oficjalnych rozszerzeniach. Jeśli planujesz wysłać prośbę
o dołączenie kodu do bazowego frameworka, powinieneś rozważyć stosowanie takiego samego stylu. Nie zmuszamy jednak nikogo do
Poniższy styl kodowania jest stosowany w kodzie frameworka Yii 2.x i oficjalnych rozszerzeniach. Jeśli planujesz wysłać prośbę
o dołączenie kodu do bazowego frameworka, powinieneś rozważyć stosowanie takiego samego stylu. Nie zmuszamy jednak nikogo do
stosowania go we własnych aplikacjach. Wybierz styl, który najbardziej odpowiada Twoim potrzebom.
Możesz pobrać gotową konfigurację dla CodeSniffera pod adresem: https://github.com/yiisoft/yii2-coding-standards
@ -10,9 +10,9 @@ Możesz pobrać gotową konfigurację dla CodeSniffera pod adresem: https://gith
1. Omówienie
------------
Używamy przede wszystkim standardu kodowania
[PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md), zatem wszystko, co dotyczy
[PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) dotyczy również naszego stylu
Używamy przede wszystkim standardu kodowania
[PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md), zatem wszystko, co dotyczy
[PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) dotyczy również naszego stylu
kodowania.
- Pliki MUSZĄ używać tagów `<?php` albo `<?=`.
@ -85,12 +85,12 @@ class Foo
- Deklarując publiczne elementy klasy należy używać wprost słowa kluczowego `public`.
- Publiczne i chronione zmienne powinny być zadeklarowane na początku klasy, przed deklaracjami metod.
Prywatne zmienne również powinny być zadeklarowane na początku klasy, ale mogą być również dodane zaraz przed metodami,
Prywatne zmienne również powinny być zadeklarowane na początku klasy, ale mogą być również dodane zaraz przed metodami,
które ich używają w przypadku, gdy są stosowane tylko w kilku z nich.
- Kolejność deklaracji właściwości w klasie powinna być rosnąca według ich widoczności: od publicznych, przez chronione, do prywatnych.
- Nie ma ścisłych zasad dotyczących kolejności właściwości o tej samej widoczności.
- Dla zapewnienia lepszej czytelności kodu, nie powinno być żadnych pustych linii pomiędzy deklaracjami właściwości, a sekcje
deklaracji właściwości i metod klasy powinny być rozdzielona dwoma pustymi liniami. Pojedyncza pusta linia powinna być dodana
- Dla zapewnienia lepszej czytelności kodu, nie powinno być żadnych pustych linii pomiędzy deklaracjami właściwości, a sekcje
deklaracji właściwości i metod klasy powinny być rozdzielona dwoma pustymi liniami. Pojedyncza pusta linia powinna być dodana
pomiędzy grupami o różnej widoczności.
- Prywatne zmienne powinny być nazwane w formacie `$_varName`.
- Publiczne elementy klasy i niezależne zmienne powinny być nazwane w formacie `$camelCase` z pierwszą literą małą.
@ -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
@ -275,7 +275,7 @@ if (empty($result)) {
}
```
wygląda lepiej w postaci
wygląda lepiej w postaci
```php
$result = $this->getResult();
@ -347,14 +347,14 @@ Dokumentacja
- Należy stosować dokumentację zgodnie ze składnią [phpDoc](http://phpdoc.org/).
- Kod bez dokumentacji jest niedozwolony.
- Każdy plik klasy musi zawierać blok dokumentacji "poziomu pliku" na początku pliku i blok dokumentacji "poziomu klasy"
- Każdy plik klasy musi zawierać blok dokumentacji "poziomu pliku" na początku pliku i blok dokumentacji "poziomu klasy"
zaraz nad klasą.
- Nie ma konieczności używania `@return`, jeśli metoda niczego nie zwraca.
- Wszystkie wirtualne właściwości w klasach, które rozszerzają `yii\base\Object` są udokumentowane za pomocą tagu `@property`
- Wszystkie wirtualne właściwości w klasach, które rozszerzają `yii\base\Object` są udokumentowane za pomocą tagu `@property`
w bloku dokumentacji klasy.
Adnotacje te są automatycznie generowane z tagów `@return` lub `@param` w odpowiednich getterach lub setterach przez
Adnotacje te są automatycznie generowane z tagów `@return` lub `@param` w odpowiednich getterach lub setterach przez
uruchomienie `./build php-doc` w folderze build.
Można dodać tag `@property` do gettera lub settera, aby wprost określić informację dla dokumentacji właściwości zadeklarowanej
Można dodać tag `@property` do gettera lub settera, aby wprost określić informację dla dokumentacji właściwości zadeklarowanej
w tych metodach, kiedy opis różni się od tego, co znajduje się w `@return`. Poniżej znajduje się przykład:
```php

4
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 Конструкторы
@ -199,7 +199,7 @@ $sql = "SELECT *"
. "WHERE `id` = 121 ";
```
### 5.3 Массивы
### 5.3 Массивы
Для массивов мы используем краткий синтаксис, появившийся в PHP 5.4.

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

33
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 {
$form.submit();
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)
{

69
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,43 +118,56 @@ abstract class ErrorHandler extends Component
}
} catch (\Exception $e) {
// an other exception could be thrown while displaying the exception
$msg = "An Error occurred while handling another error:\n";
$msg .= (string) $e;
$msg .= "\nPrevious exception:\n";
$msg .= (string) $exception;
if (YII_DEBUG) {
if (PHP_SAPI === 'cli') {
echo $msg . "\n";
} else {
echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, Yii::$app->charset) . '</pre>';
}
} else {
echo 'An internal server error occurred.';
}
$msg .= "\n\$_SERVER = " . VarDumper::export($_SERVER);
error_log($msg);
if (defined('HHVM_VERSION')) {
flush();
}
exit(1);
$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) $exception;
$msg .= "\nPrevious exception:\n";
$msg .= (string) $previousException;
if (YII_DEBUG) {
if (PHP_SAPI === 'cli') {
echo $msg . "\n";
} else {
echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, Yii::$app->charset) . '</pre>';
}
} else {
echo 'An internal server error occurred.';
}
$msg .= "\n\$_SERVER = " . VarDumper::export($_SERVER);
error_log($msg);
if (defined('HHVM_VERSION')) {
flush();
}
exit(1);
}
/**
* 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;

86
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);
Yii::$app->controller = $oldController;
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