Browse Source

Fixes #12055: Changed `boolean` to `bool` and `integer` to `int` in phpdoc

tags/2.0.11
Robert Korulczyk 8 years ago committed by Alexander Makarov
parent
commit
4aa935e69e
  1. 2
      build/controllers/PhpDocController.php
  2. 2
      docs/guide-es/caching-http.md
  3. 4
      docs/guide-es/input-validation.md
  4. 16
      docs/guide-es/security-authorization.md
  5. 54
      docs/guide-fr/input-validation.md
  6. 42
      docs/guide-fr/security-authentication.md
  7. 56
      docs/guide-fr/security-authorization.md
  8. 2
      docs/guide-ja/caching-http.md
  9. 2
      docs/guide-ja/input-validation.md
  10. 8
      docs/guide-ja/security-authentication.md
  11. 4
      docs/guide-ja/security-authorization.md
  12. 56
      docs/guide-pl/caching-http.md
  13. 96
      docs/guide-pl/input-validation.md
  14. 18
      docs/guide-pt-BR/caching-http.md
  15. 22
      docs/guide-pt-BR/security-authentication.md
  16. 6
      docs/guide-pt-BR/security-authorization.md
  17. 10
      docs/guide-ru/caching-http.md
  18. 88
      docs/guide-ru/input-validation.md
  19. 20
      docs/guide-ru/security-authentication.md
  20. 14
      docs/guide-ru/security-authorization.md
  21. 2
      docs/guide-zh-CN/caching-http.md
  22. 2
      docs/guide-zh-CN/input-validation.md
  23. 2
      docs/guide/caching-http.md
  24. 2
      docs/guide/input-validation.md
  25. 40
      docs/guide/security-authentication.md
  26. 18
      docs/guide/security-authorization.md
  27. 8
      docs/internals-ja/core-code-style.md
  28. 28
      docs/internals-pl/core-code-style.md
  29. 4
      docs/internals-ru/core-code-style.md
  30. 2
      docs/internals-uk/core-code-style.md
  31. 14
      docs/internals/core-code-style.md
  32. 6
      framework/BaseYii.php
  33. 2
      framework/base/Action.php
  34. 2
      framework/base/ActionEvent.php
  35. 4
      framework/base/ActionFilter.php
  36. 8
      framework/base/Application.php
  37. 8
      framework/base/ArrayAccessTrait.php
  38. 2
      framework/base/Arrayable.php
  39. 2
      framework/base/ArrayableTrait.php
  40. 32
      framework/base/Component.php
  41. 4
      framework/base/Controller.php
  42. 2
      framework/base/ErrorException.php
  43. 16
      framework/base/ErrorHandler.php
  44. 8
      framework/base/Event.php
  45. 6
      framework/base/ExitException.php
  46. 26
      framework/base/Model.php
  47. 2
      framework/base/ModelEvent.php
  48. 14
      framework/base/Module.php
  49. 16
      framework/base/Object.php
  50. 6
      framework/base/Request.php
  51. 2
      framework/base/Response.php
  52. 36
      framework/base/Security.php
  53. 10
      framework/base/View.php
  54. 2
      framework/base/ViewEvent.php
  55. 4
      framework/base/Widget.php
  56. 2
      framework/behaviors/AttributeBehavior.php
  57. 18
      framework/behaviors/AttributeTypecastBehavior.php
  58. 10
      framework/behaviors/SluggableBehavior.php
  59. 20
      framework/caching/ApcCache.php
  60. 48
      framework/caching/Cache.php
  61. 4
      framework/caching/ChainedDependency.php
  62. 18
      framework/caching/DbCache.php
  63. 4
      framework/caching/Dependency.php
  64. 12
      framework/caching/DummyCache.php
  65. 28
      framework/caching/FileCache.php
  66. 16
      framework/caching/MemCache.php
  67. 12
      framework/caching/MemCacheServer.php
  68. 2
      framework/caching/TagDependency.php
  69. 20
      framework/caching/WinCache.php
  70. 14
      framework/caching/XCache.php
  71. 12
      framework/caching/ZendDataCache.php
  72. 26
      framework/captcha/CaptchaAction.php
  73. 4
      framework/captcha/CaptchaValidator.php
  74. 4
      framework/console/Application.php
  75. 18
      framework/console/Controller.php
  76. 6
      framework/console/controllers/AssetController.php
  77. 30
      framework/console/controllers/BaseMigrateController.php
  78. 6
      framework/console/controllers/CacheController.php
  79. 6
      framework/console/controllers/FixtureController.php
  80. 6
      framework/console/controllers/HelpController.php
  81. 46
      framework/console/controllers/MessageController.php
  82. 4
      framework/console/controllers/MigrateController.php
  83. 4
      framework/console/controllers/ServeController.php
  84. 22
      framework/data/BaseDataProvider.php
  85. 6
      framework/data/DataProviderInterface.php
  86. 48
      framework/data/Pagination.php
  87. 14
      framework/data/Sort.php
  88. 4
      framework/db/ActiveQuery.php
  89. 2
      framework/db/ActiveQueryInterface.php
  90. 4
      framework/db/ActiveQueryTrait.php
  91. 28
      framework/db/ActiveRecord.php
  92. 34
      framework/db/ActiveRecordInterface.php
  93. 4
      framework/db/ActiveRelationTrait.php
  94. 64
      framework/db/BaseActiveRecord.php
  95. 10
      framework/db/BatchQueryResult.php
  96. 14
      framework/db/ColumnSchema.php
  97. 12
      framework/db/ColumnSchemaBuilder.php
  98. 30
      framework/db/Command.php
  99. 30
      framework/db/Connection.php
  100. 30
      framework/db/DataReader.php
  101. Some files were not shown because too many files have changed in this diff Show More

2
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;

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

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

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 :

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

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

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.

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.

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

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

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 валидации.

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

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

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

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.

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 Конструктори

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

@ -144,23 +144,23 @@ class Foo
### 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`.
- `@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 integer $cidr the CIDR lendth
* @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 boolean whether the IP is in subnet range
* @return bool whether the IP is in subnet range
*/
private function inRange($ip, $cidr, $range)
private function inRange($ip, $cidr, $range)
{
// ...
}

6
framework/BaseYii.php

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

2
framework/base/Action.php

@ -105,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.
*/

4
framework/base/ActionFilter.php

@ -95,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)
{
@ -138,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)
{

8
framework/base/Application.php

@ -118,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';
@ -174,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;
@ -360,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()
{
@ -629,7 +629,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)

32
framework/base/Component.php

@ -211,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)
@ -307,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()
*/
@ -328,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)
@ -358,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)
@ -386,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)
{
@ -437,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)
{
@ -470,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()
@ -491,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)
@ -652,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

4
framework/base/Controller.php

@ -263,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)
{
@ -475,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.
*/

2
framework/base/ErrorException.php

@ -78,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)
{

16
framework/base/ErrorHandler.php

@ -27,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.
@ -161,13 +161,13 @@ abstract class ErrorHandler extends Component
* 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
@ -192,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
*/

8
framework/base/Event.php

@ -39,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.
*/
@ -80,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()
@ -104,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)
@ -149,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)
{

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)

26
framework/base/Model.php

@ -330,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)
@ -367,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()
@ -465,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)
{
@ -480,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)
@ -491,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)
@ -528,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)
{
@ -686,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()
@ -816,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)
{
@ -847,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)
{
@ -885,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)
@ -967,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)
{
@ -990,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;

14
framework/base/Module.php

@ -63,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.
*/
@ -133,7 +133,7 @@ class Module extends ServiceLocator
*
* ```php
* function (Module $module) {
* //return string|integer
* //return string|int
* }
* ```
*
@ -381,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)
@ -401,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()
*/
@ -451,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).
@ -551,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.
*/
@ -670,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

@ -170,7 +170,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)
@ -229,8 +229,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()
*/
@ -248,8 +248,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)
@ -266,8 +266,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)
@ -281,7 +281,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)
{

6
framework/base/Request.php

@ -14,7 +14,7 @@ use Yii;
*
* For more details and usage information on Request, see the [guide article on requests](guide:runtime-requests).
*
* @property boolean $isConsoleRequest The value indicating whether the current request is made via console.
* @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>
@ -34,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()
{
@ -43,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)
{

2
framework/base/Response.php

@ -18,7 +18,7 @@ namespace yii\base;
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;

36
framework/base/Security.php

@ -69,7 +69,7 @@ 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;
@ -84,7 +84,7 @@ class Security extends Component
*/
public $passwordHashStrategy;
/**
* @var integer Default cost used for password hashing.
* @var int Default cost used for password hashing.
* Allowed value is between 4 and 31.
* @see generatePasswordHash()
* @since 2.0.6
@ -136,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)
@ -149,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)
@ -161,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.
@ -212,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()
@ -266,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
@ -311,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.
@ -372,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.
@ -397,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.
@ -433,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.
@ -544,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.
*/
@ -585,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,
@ -622,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()
*/
@ -660,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.
*/
@ -686,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)
{

10
framework/base/View.php

@ -20,7 +20,7 @@ use yii\widgets\FragmentCache;
*
* For more details and usage information on View, see the [guide article on views](guide:structure-views).
*
* @property string|boolean $viewFile The view file currently being rendered. False if no view file is being
* @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>
@ -259,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()
{
@ -272,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)
{
@ -381,7 +381,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
*/
@ -452,7 +452,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.
*/

4
framework/base/Widget.php

@ -27,7 +27,7 @@ use ReflectionClass;
class Widget extends Component implements ViewContextInterface
{
/**
* @var integer a counter used to generate [[id]] for widgets.
* @var int a counter used to generate [[id]] for widgets.
* @internal
*/
public static $counter = 0;
@ -117,7 +117,7 @@ class Widget extends Component implements ViewContextInterface
/**
* Returns the ID of the widget.
* @param boolean $autoGenerate whether to generate an ID if it is not set previously
* @param bool $autoGenerate whether to generate an ID if it is not set previously
* @return string ID of the widget.
*/
public function getId($autoGenerate = true)

2
framework/behaviors/AttributeBehavior.php

@ -81,7 +81,7 @@ class AttributeBehavior extends Behavior
*/
public $value;
/**
* @var boolean whether to skip this behavior when the `$owner` has not been
* @var bool whether to skip this behavior when the `$owner` has not been
* modified
* @since 2.0.8
*/

18
framework/behaviors/AttributeTypecastBehavior.php

@ -140,20 +140,20 @@ class AttributeTypecastBehavior extends Behavior
*/
public $attributeTypes;
/**
* @var boolean whether to skip typecasting of `null` values.
* @var bool whether to skip typecasting of `null` values.
* If enabled attribute value which equals to `null` will not be type-casted (e.g. `null` remains `null`),
* otherwise it will be converted according to the type configured at [[attributeTypes]].
*/
public $skipOnNull = true;
/**
* @var boolean whether to perform typecasting after owner model validation.
* @var bool whether to perform typecasting after owner model validation.
* Note that typecasting will be performed only if validation was successful, e.g.
* owner model has no errors.
* Note that changing this option value will have no effect after this behavior has been attached to the model.
*/
public $typecastAfterValidate = true;
/**
* @var boolean whether to perform typecasting before saving owner model (insert or update).
* @var bool whether to perform typecasting before saving owner model (insert or update).
* This option may be disabled in order to achieve better performance.
* For example, in case of [[\yii\db\ActiveRecord]] usage, typecasting before save
* will grant no benefit an thus can be disabled.
@ -161,7 +161,7 @@ class AttributeTypecastBehavior extends Behavior
*/
public $typecastBeforeSave = false;
/**
* @var boolean whether to perform typecasting after retrieving owner model data from
* @var bool whether to perform typecasting after retrieving owner model data from
* the database (after find or refresh).
* This option may be disabled in order to achieve better performance.
* For example, in case of [[\yii\db\ActiveRecord]] usage, typecasting after find
@ -247,13 +247,13 @@ class AttributeTypecastBehavior extends Behavior
switch ($type) {
case self::TYPE_INTEGER:
return (int)$value;
return (int) $value;
case self::TYPE_FLOAT:
return (float)$value;
return (float) $value;
case self::TYPE_BOOLEAN:
return (boolean)$value;
return (bool) $value;
case self::TYPE_STRING:
return (string)$value;
return (string) $value;
default:
throw new InvalidParamException("Unsupported type '{$type}'");
}
@ -337,4 +337,4 @@ class AttributeTypecastBehavior extends Behavior
{
$this->typecastAttributes();
}
}
}

10
framework/behaviors/SluggableBehavior.php

@ -81,13 +81,13 @@ class SluggableBehavior extends AttributeBehavior
*/
public $value;
/**
* @var boolean whether to generate a new slug if it has already been generated before.
* @var bool whether to generate a new slug if it has already been generated before.
* If true, the behavior will not generate a new slug even if [[attribute]] is changed.
* @since 2.0.2
*/
public $immutable = false;
/**
* @var boolean whether to ensure generated slug value to be unique among owner class records.
* @var bool whether to ensure generated slug value to be unique among owner class records.
* If enabled behavior will validate slug uniqueness automatically. If validation fails it will attempt
* generating unique slug value from based one until success.
*/
@ -157,7 +157,7 @@ class SluggableBehavior extends AttributeBehavior
* Checks whether the new slug generation is needed
* This method is called by [[getValue]] to check whether the new slug generation is needed.
* You may override it to customize checking.
* @return boolean
* @return bool
* @since 2.0.7
*/
protected function isNewSlugNeeded()
@ -215,7 +215,7 @@ class SluggableBehavior extends AttributeBehavior
/**
* Checks if given slug value is unique.
* @param string $slug slug value
* @return boolean whether slug is unique.
* @return bool whether slug is unique.
*/
protected function validateSlug($slug)
{
@ -239,7 +239,7 @@ class SluggableBehavior extends AttributeBehavior
/**
* Generates slug using configured callback or increment of iteration.
* @param string $baseSlug base slug value
* @param integer $iteration iteration number
* @param int $iteration iteration number
* @return string new slug value
* @throws \yii\base\InvalidConfigException
*/

20
framework/caching/ApcCache.php

@ -26,7 +26,7 @@ use yii\base\InvalidConfigException;
class ApcCache extends Cache
{
/**
* @var boolean whether to use apcu or apc as the underlying caching extension.
* @var bool whether to use apcu or apc as the underlying caching extension.
* If true, [apcu](http://pecl.php.net/package/apcu) will be used.
* If false, [apc](http://pecl.php.net/package/apc) will be used.
* Defaults to false.
@ -56,7 +56,7 @@ class ApcCache extends Cache
* may return false while exists returns true.
* @param mixed $key a key identifying the cached value. This can be a simple string or
* a complex data structure consisting of factors representing the key.
* @return boolean true if a value exists in cache, false if the value is not in the cache or expired.
* @return bool true if a value exists in cache, false if the value is not in the cache or expired.
*/
public function exists($key)
{
@ -94,8 +94,8 @@ class ApcCache extends Cache
* @param string $key the key identifying the value to be cached
* @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
* it could be something else.
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise.
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return bool true if the value is successfully stored into cache, false otherwise.
*/
protected function setValue($key, $value, $duration)
{
@ -105,7 +105,7 @@ class ApcCache extends Cache
/**
* Stores multiple key-value pairs in cache.
* @param array $data array where key corresponds to cache key while value
* @param integer $duration the number of seconds in which the cached values will expire. 0 means never expire.
* @param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
* @return array array of failed keys
*/
protected function setValues($data, $duration)
@ -120,8 +120,8 @@ class ApcCache extends Cache
* @param string $key the key identifying the value to be cached
* @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
* it could be something else.
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return bool true if the value is successfully stored into cache, false otherwise
*/
protected function addValue($key, $value, $duration)
{
@ -131,7 +131,7 @@ class ApcCache extends Cache
/**
* Adds multiple key-value pairs to cache.
* @param array $data array where key corresponds to cache key while value is the value stored
* @param integer $duration the number of seconds in which the cached values will expire. 0 means never expire.
* @param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
* @return array array of failed keys
*/
protected function addValues($data, $duration)
@ -144,7 +144,7 @@ class ApcCache extends Cache
* Deletes a value with the specified key from cache
* This is the implementation of the method declared in the parent class.
* @param string $key the key of the value to be deleted
* @return boolean if no error happens during deletion
* @return bool if no error happens during deletion
*/
protected function deleteValue($key)
{
@ -154,7 +154,7 @@ class ApcCache extends Cache
/**
* Deletes all values from cache.
* This is the implementation of the method declared in the parent class.
* @return boolean whether the flush operation was successful.
* @return bool whether the flush operation was successful.
*/
protected function flushValues()
{

48
framework/caching/Cache.php

@ -129,7 +129,7 @@ abstract class Cache extends Component implements \ArrayAccess
* may return false while exists returns true.
* @param mixed $key a key identifying the cached value. This can be a simple string or
* a complex data structure consisting of factors representing the key.
* @return boolean true if a value exists in cache, false if the value is not in the cache or expired.
* @return bool true if a value exists in cache, false if the value is not in the cache or expired.
*/
public function exists($key)
{
@ -202,11 +202,11 @@ abstract class Cache extends Component implements \ArrayAccess
* @param mixed $key a key identifying the value to be cached. This can be a simple string or
* a complex data structure consisting of factors representing the key.
* @param mixed $value the value to be cached
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @param Dependency $dependency dependency of the cached item. If the dependency changes,
* the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
* This parameter is ignored if [[serializer]] is false.
* @return boolean whether the value is successfully stored into cache
* @return bool whether the value is successfully stored into cache
*/
public function set($key, $value, $duration = 0, $dependency = null)
{
@ -229,11 +229,11 @@ abstract class Cache extends Component implements \ArrayAccess
* expiration time will be replaced with the new ones, respectively.
*
* @param array $items the items to be cached, as key-value pairs.
* @param integer $duration default number of seconds in which the cached values will expire. 0 means never expire.
* @param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
* @param Dependency $dependency dependency of the cached items. If the dependency changes,
* the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
* This parameter is ignored if [[serializer]] is false.
* @return boolean whether the items are successfully stored into cache
* @return bool whether the items are successfully stored into cache
* @deprecated This method is an alias for [[multiSet()]] and will be removed in 2.1.0.
*/
public function mset($items, $duration = 0, $dependency = null)
@ -247,11 +247,11 @@ abstract class Cache extends Component implements \ArrayAccess
* expiration time will be replaced with the new ones, respectively.
*
* @param array $items the items to be cached, as key-value pairs.
* @param integer $duration default number of seconds in which the cached values will expire. 0 means never expire.
* @param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
* @param Dependency $dependency dependency of the cached items. If the dependency changes,
* the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
* This parameter is ignored if [[serializer]] is false.
* @return boolean whether the items are successfully stored into cache
* @return bool whether the items are successfully stored into cache
* @since 2.0.7
*/
public function multiSet($items, $duration = 0, $dependency = null)
@ -280,11 +280,11 @@ abstract class Cache extends Component implements \ArrayAccess
* If the cache already contains such a key, the existing value and expiration time will be preserved.
*
* @param array $items the items to be cached, as key-value pairs.
* @param integer $duration default number of seconds in which the cached values will expire. 0 means never expire.
* @param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
* @param Dependency $dependency dependency of the cached items. If the dependency changes,
* the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
* This parameter is ignored if [[serializer]] is false.
* @return boolean whether the items are successfully stored into cache
* @return bool whether the items are successfully stored into cache
* @deprecated This method is an alias for [[multiAdd()]] and will be removed in 2.1.0.
*/
public function madd($items, $duration = 0, $dependency = null)
@ -297,11 +297,11 @@ abstract class Cache extends Component implements \ArrayAccess
* If the cache already contains such a key, the existing value and expiration time will be preserved.
*
* @param array $items the items to be cached, as key-value pairs.
* @param integer $duration default number of seconds in which the cached values will expire. 0 means never expire.
* @param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
* @param Dependency $dependency dependency of the cached items. If the dependency changes,
* the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
* This parameter is ignored if [[serializer]] is false.
* @return boolean whether the items are successfully stored into cache
* @return bool whether the items are successfully stored into cache
* @since 2.0.7
*/
public function multiAdd($items, $duration = 0, $dependency = null)
@ -331,11 +331,11 @@ abstract class Cache extends Component implements \ArrayAccess
* @param mixed $key a key identifying the value to be cached. This can be a simple string or
* a complex data structure consisting of factors representing the key.
* @param mixed $value the value to be cached
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @param Dependency $dependency dependency of the cached item. If the dependency changes,
* the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
* This parameter is ignored if [[serializer]] is false.
* @return boolean whether the value is successfully stored into cache
* @return bool whether the value is successfully stored into cache
*/
public function add($key, $value, $duration = 0, $dependency = null)
{
@ -356,7 +356,7 @@ abstract class Cache extends Component implements \ArrayAccess
* Deletes a value with the specified key from cache
* @param mixed $key a key identifying the value to be deleted from cache. This can be a simple string or
* a complex data structure consisting of factors representing the key.
* @return boolean if no error happens during deletion
* @return bool if no error happens during deletion
*/
public function delete($key)
{
@ -368,7 +368,7 @@ abstract class Cache extends Component implements \ArrayAccess
/**
* Deletes all values from cache.
* Be careful of performing this operation if the cache is shared among multiple applications.
* @return boolean whether the flush operation was successful.
* @return bool whether the flush operation was successful.
*/
public function flush()
{
@ -392,8 +392,8 @@ abstract class Cache extends Component implements \ArrayAccess
* @param string $key the key identifying the value to be cached
* @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
* it could be something else.
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return bool true if the value is successfully stored into cache, false otherwise
*/
abstract protected function setValue($key, $value, $duration);
@ -404,8 +404,8 @@ abstract class Cache extends Component implements \ArrayAccess
* @param string $key the key identifying the value to be cached
* @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
* it could be something else.
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return bool true if the value is successfully stored into cache, false otherwise
*/
abstract protected function addValue($key, $value, $duration);
@ -413,14 +413,14 @@ abstract class Cache extends Component implements \ArrayAccess
* Deletes a value with the specified key from cache
* This method should be implemented by child classes to delete the data from actual cache storage.
* @param string $key the key of the value to be deleted
* @return boolean if no error happens during deletion
* @return bool if no error happens during deletion
*/
abstract protected function deleteValue($key);
/**
* Deletes all values from cache.
* Child classes may implement this method to realize the flush operation.
* @return boolean whether the flush operation was successful.
* @return bool whether the flush operation was successful.
*/
abstract protected function flushValues();
@ -447,7 +447,7 @@ abstract class Cache extends Component implements \ArrayAccess
* The default implementation calls [[setValue()]] multiple times store values one by one. If the underlying cache
* storage supports multi-set, this method should be overridden to exploit that feature.
* @param array $data array where key corresponds to cache key while value is the value stored
* @param integer $duration the number of seconds in which the cached values will expire. 0 means never expire.
* @param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
* @return array array of failed keys
*/
protected function setValues($data, $duration)
@ -467,7 +467,7 @@ abstract class Cache extends Component implements \ArrayAccess
* The default implementation calls [[addValue()]] multiple times add values one by one. If the underlying cache
* storage supports multi-add, this method should be overridden to exploit that feature.
* @param array $data array where key corresponds to cache key while value is the value stored.
* @param integer $duration the number of seconds in which the cached values will expire. 0 means never expire.
* @param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
* @return array array of failed keys
*/
protected function addValues($data, $duration)
@ -486,7 +486,7 @@ abstract class Cache extends Component implements \ArrayAccess
* Returns whether there is a cache entry with a specified key.
* This method is required by the interface [[\ArrayAccess]].
* @param string $key a key identifying the cached value
* @return boolean
* @return bool
*/
public function offsetExists($key)
{

4
framework/caching/ChainedDependency.php

@ -27,7 +27,7 @@ class ChainedDependency extends Dependency
*/
public $dependencies = [];
/**
* @var boolean whether this dependency is depending on every dependency in [[dependencies]].
* @var bool whether this dependency is depending on every dependency in [[dependencies]].
* Defaults to true, meaning if any of the dependencies has changed, this dependency is considered changed.
* When it is set false, it means if one of the dependencies has NOT changed, this dependency
* is considered NOT changed.
@ -62,7 +62,7 @@ class ChainedDependency extends Dependency
* This method returns true if any of the dependency objects
* reports a dependency change.
* @param Cache $cache the cache component that is currently evaluating this dependency
* @return boolean whether the dependency is changed or not.
* @return bool whether the dependency is changed or not.
*/
public function getHasChanged($cache)
{

18
framework/caching/DbCache.php

@ -69,7 +69,7 @@ class DbCache extends Cache
*/
public $cacheTable = '{{%cache}}';
/**
* @var integer the probability (parts per million) that garbage collection (GC) should be performed
* @var int the probability (parts per million) that garbage collection (GC) should be performed
* when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
* This number should be between 0 and 1000000. A value 0 meaning no GC will be performed at all.
*/
@ -95,7 +95,7 @@ class DbCache extends Cache
* may return false while exists returns true.
* @param mixed $key a key identifying the cached value. This can be a simple string or
* a complex data structure consisting of factors representing the key.
* @return boolean true if a value exists in cache, false if the value is not in the cache or expired.
* @return bool true if a value exists in cache, false if the value is not in the cache or expired.
*/
public function exists($key)
{
@ -182,8 +182,8 @@ class DbCache extends Cache
*
* @param string $key the key identifying the value to be cached
* @param string $value the value to be cached. Other types (if you have disabled [[serializer]]) cannot be saved.
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return bool true if the value is successfully stored into cache, false otherwise
*/
protected function setValue($key, $value, $duration)
{
@ -208,8 +208,8 @@ class DbCache extends Cache
*
* @param string $key the key identifying the value to be cached
* @param string $value the value to be cached. Other types (if you have disabled [[serializer]]) cannot be saved.
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return bool true if the value is successfully stored into cache, false otherwise
*/
protected function addValue($key, $value, $duration)
{
@ -233,7 +233,7 @@ class DbCache extends Cache
* Deletes a value with the specified key from cache
* This is the implementation of the method declared in the parent class.
* @param string $key the key of the value to be deleted
* @return boolean if no error happens during deletion
* @return bool if no error happens during deletion
*/
protected function deleteValue($key)
{
@ -246,7 +246,7 @@ class DbCache extends Cache
/**
* Removes the expired data values.
* @param boolean $force whether to enforce the garbage collection regardless of [[gcProbability]].
* @param bool $force whether to enforce the garbage collection regardless of [[gcProbability]].
* Defaults to false, meaning the actual deletion happens with the probability as specified by [[gcProbability]].
*/
public function gc($force = false)
@ -261,7 +261,7 @@ class DbCache extends Cache
/**
* Deletes all values from cache.
* This is the implementation of the method declared in the parent class.
* @return boolean whether the flush operation was successful.
* @return bool whether the flush operation was successful.
*/
protected function flushValues()
{

4
framework/caching/Dependency.php

@ -26,7 +26,7 @@ abstract class Dependency extends \yii\base\Object
*/
public $data;
/**
* @var boolean whether this dependency is reusable or not. True value means that dependent
* @var bool whether this dependency is reusable or not. True value means that dependent
* data for this cache dependency will be generated only once per request. This allows you
* to use the same cache dependency for multiple separate cache calls while generating the same
* page without an overhead of re-evaluating dependency data each time. Defaults to false.
@ -60,7 +60,7 @@ abstract class Dependency extends \yii\base\Object
/**
* Returns a value indicating whether the dependency has changed.
* @param Cache $cache the cache component that is currently evaluating this dependency
* @return boolean whether the dependency has changed.
* @return bool whether the dependency has changed.
*/
public function getHasChanged($cache)
{

12
framework/caching/DummyCache.php

@ -39,8 +39,8 @@ class DummyCache extends Cache
*
* @param string $key the key identifying the value to be cached
* @param mixed $value the value to be cached
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return bool true if the value is successfully stored into cache, false otherwise
*/
protected function setValue($key, $value, $duration)
{
@ -52,8 +52,8 @@ class DummyCache extends Cache
* This is the implementation of the method declared in the parent class.
* @param string $key the key identifying the value to be cached
* @param mixed $value the value to be cached
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return bool true if the value is successfully stored into cache, false otherwise
*/
protected function addValue($key, $value, $duration)
{
@ -64,7 +64,7 @@ class DummyCache extends Cache
* Deletes a value with the specified key from cache
* This is the implementation of the method declared in the parent class.
* @param string $key the key of the value to be deleted
* @return boolean if no error happens during deletion
* @return bool if no error happens during deletion
*/
protected function deleteValue($key)
{
@ -74,7 +74,7 @@ class DummyCache extends Cache
/**
* Deletes all values from cache.
* This is the implementation of the method declared in the parent class.
* @return boolean whether the flush operation was successful.
* @return bool whether the flush operation was successful.
*/
protected function flushValues()
{

28
framework/caching/FileCache.php

@ -44,26 +44,26 @@ class FileCache extends Cache
*/
public $cacheFileSuffix = '.bin';
/**
* @var integer the level of sub-directories to store cache files. Defaults to 1.
* @var int the level of sub-directories to store cache files. Defaults to 1.
* If the system has huge number of cache files (e.g. one million), you may use a bigger value
* (usually no bigger than 3). Using sub-directories is mainly to ensure the file system
* is not over burdened with a single directory having too many files.
*/
public $directoryLevel = 1;
/**
* @var integer the probability (parts per million) that garbage collection (GC) should be performed
* @var int the probability (parts per million) that garbage collection (GC) should be performed
* when storing a piece of data in the cache. Defaults to 10, meaning 0.001% chance.
* This number should be between 0 and 1000000. A value 0 means no GC will be performed at all.
*/
public $gcProbability = 10;
/**
* @var integer the permission to be set for newly created cache files.
* @var int the permission to be set for newly created cache files.
* This value will be used by PHP chmod() function. No umask will be applied.
* If not set, the permission will be determined by the current environment.
*/
public $fileMode;
/**
* @var integer the permission to be set for newly created directories.
* @var int the permission to be set for newly created directories.
* This value will be used by PHP chmod() function. No umask will be applied.
* Defaults to 0775, meaning the directory is read-writable by owner and group,
* but read-only for other users.
@ -91,7 +91,7 @@ class FileCache extends Cache
* may return false while exists returns true.
* @param mixed $key a key identifying the cached value. This can be a simple string or
* a complex data structure consisting of factors representing the key.
* @return boolean true if a value exists in cache, false if the value is not in the cache or expired.
* @return bool true if a value exists in cache, false if the value is not in the cache or expired.
*/
public function exists($key)
{
@ -131,8 +131,8 @@ class FileCache extends Cache
* @param string $key the key identifying the value to be cached
* @param string $value the value to be cached. Other types (If you have disabled [[serializer]]) unable to get is
* correct in [[getValue()]].
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return bool true if the value is successfully stored into cache, false otherwise
*/
protected function setValue($key, $value, $duration)
{
@ -164,8 +164,8 @@ class FileCache extends Cache
* @param string $key the key identifying the value to be cached
* @param string $value the value to be cached. Other types (if you have disabled [[serializer]]) unable to get is
* correct in [[getValue()]].
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return bool true if the value is successfully stored into cache, false otherwise
*/
protected function addValue($key, $value, $duration)
{
@ -181,7 +181,7 @@ class FileCache extends Cache
* Deletes a value with the specified key from cache
* This is the implementation of the method declared in the parent class.
* @param string $key the key of the value to be deleted
* @return boolean if no error happens during deletion
* @return bool if no error happens during deletion
*/
protected function deleteValue($key)
{
@ -214,7 +214,7 @@ class FileCache extends Cache
/**
* Deletes all values from cache.
* This is the implementation of the method declared in the parent class.
* @return boolean whether the flush operation was successful.
* @return bool whether the flush operation was successful.
*/
protected function flushValues()
{
@ -225,9 +225,9 @@ class FileCache extends Cache
/**
* Removes expired cache files.
* @param boolean $force whether to enforce the garbage collection regardless of [[gcProbability]].
* @param bool $force whether to enforce the garbage collection regardless of [[gcProbability]].
* Defaults to false, meaning the actual deletion happens with the probability as specified by [[gcProbability]].
* @param boolean $expiredOnly whether to removed expired cache files only.
* @param bool $expiredOnly whether to removed expired cache files only.
* If false, all cache files under [[cachePath]] will be removed.
*/
public function gc($force = false, $expiredOnly = true)
@ -241,7 +241,7 @@ class FileCache extends Cache
* Recursively removing expired cache files under a directory.
* This method is mainly used by [[gc()]].
* @param string $path the directory under which expired cache files are removed.
* @param boolean $expiredOnly whether to only remove expired cache files. If false, all files
* @param bool $expiredOnly whether to only remove expired cache files. If false, all files
* under `$path` will be removed.
*/
protected function gcRecursive($path, $expiredOnly)

16
framework/caching/MemCache.php

@ -66,7 +66,7 @@ use yii\base\InvalidConfigException;
class MemCache extends Cache
{
/**
* @var boolean whether to use memcached or memcache as the underlying caching extension.
* @var bool whether to use memcached or memcache as the underlying caching extension.
* If true, [memcached](http://pecl.php.net/package/memcached) will be used.
* If false, [memcache](http://pecl.php.net/package/memcache) will be used.
* Defaults to false.
@ -287,8 +287,8 @@ class MemCache extends Cache
* @param string $key the key identifying the value to be cached
* @param mixed $value the value to be cached.
* @see \MemcachePool::set()
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return bool true if the value is successfully stored into cache, false otherwise
*/
protected function setValue($key, $value, $duration)
{
@ -303,7 +303,7 @@ class MemCache extends Cache
/**
* Stores multiple key-value pairs in cache.
* @param array $data array where key corresponds to cache key while value is the value stored
* @param integer $duration the number of seconds in which the cached values will expire. 0 means never expire.
* @param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
* @return array array of failed keys. Always empty in case of using memcached.
*/
protected function setValues($data, $duration)
@ -328,8 +328,8 @@ class MemCache extends Cache
* @param string $key the key identifying the value to be cached
* @param mixed $value the value to be cached
* @see \MemcachePool::set()
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return bool true if the value is successfully stored into cache, false otherwise
*/
protected function addValue($key, $value, $duration)
{
@ -345,7 +345,7 @@ class MemCache extends Cache
* Deletes a value with the specified key from cache
* This is the implementation of the method declared in the parent class.
* @param string $key the key of the value to be deleted
* @return boolean if no error happens during deletion
* @return bool if no error happens during deletion
*/
protected function deleteValue($key)
{
@ -355,7 +355,7 @@ class MemCache extends Cache
/**
* Deletes all values from cache.
* This is the implementation of the method declared in the parent class.
* @return boolean whether the flush operation was successful.
* @return bool whether the flush operation was successful.
*/
protected function flushValues()
{

12
framework/caching/MemCacheServer.php

@ -25,29 +25,29 @@ class MemCacheServer extends \yii\base\Object
*/
public $host;
/**
* @var integer memcache server port
* @var int memcache server port
*/
public $port = 11211;
/**
* @var integer probability of using this server among all servers.
* @var int probability of using this server among all servers.
*/
public $weight = 1;
/**
* @var boolean whether to use a persistent connection. This is used by memcache only.
* @var bool whether to use a persistent connection. This is used by memcache only.
*/
public $persistent = true;
/**
* @var integer timeout in milliseconds which will be used for connecting to the server.
* @var int timeout in milliseconds which will be used for connecting to the server.
* This is used by memcache only. For old versions of memcache that only support specifying
* timeout in seconds this will be rounded up to full seconds.
*/
public $timeout = 1000;
/**
* @var integer how often a failed server will be retried (in seconds). This is used by memcache only.
* @var int how often a failed server will be retried (in seconds). This is used by memcache only.
*/
public $retryInterval = 15;
/**
* @var boolean if the server should be flagged as online upon a failure. This is used by memcache only.
* @var bool if the server should be flagged as online upon a failure. This is used by memcache only.
*/
public $status = true;
/**

2
framework/caching/TagDependency.php

@ -60,7 +60,7 @@ class TagDependency extends Dependency
/**
* Performs the actual dependency checking.
* @param Cache $cache the cache component that is currently evaluating this dependency
* @return boolean whether the dependency is changed or not.
* @return bool whether the dependency is changed or not.
*/
public function getHasChanged($cache)
{

20
framework/caching/WinCache.php

@ -30,7 +30,7 @@ class WinCache extends Cache
* may return false while exists returns true.
* @param mixed $key a key identifying the cached value. This can be a simple string or
* a complex data structure consisting of factors representing the key.
* @return boolean true if a value exists in cache, false if the value is not in the cache or expired.
* @return bool true if a value exists in cache, false if the value is not in the cache or expired.
*/
public function exists($key)
{
@ -43,7 +43,7 @@ class WinCache extends Cache
* Retrieves a value from cache with a specified key.
* This is the implementation of the method declared in the parent class.
* @param string $key a unique key identifying the cached value
* @return string|boolean the value stored in cache, false if the value is not in the cache or expired.
* @return string|bool the value stored in cache, false if the value is not in the cache or expired.
*/
protected function getValue($key)
{
@ -67,8 +67,8 @@ class WinCache extends Cache
* @param string $key the key identifying the value to be cached
* @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
* it could be something else.
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return bool true if the value is successfully stored into cache, false otherwise
*/
protected function setValue($key, $value, $duration)
{
@ -78,7 +78,7 @@ class WinCache extends Cache
/**
* Stores multiple key-value pairs in cache.
* @param array $data array where key corresponds to cache key while value is the value stored
* @param integer $duration the number of seconds in which the cached values will expire. 0 means never expire.
* @param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
* @return array array of failed keys
*/
protected function setValues($data, $duration)
@ -93,8 +93,8 @@ class WinCache extends Cache
* @param string $key the key identifying the value to be cached
* @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
* it could be something else.
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return bool true if the value is successfully stored into cache, false otherwise
*/
protected function addValue($key, $value, $duration)
{
@ -106,7 +106,7 @@ class WinCache extends Cache
* The default implementation calls [[addValue()]] multiple times add values one by one. If the underlying cache
* storage supports multiadd, this method should be overridden to exploit that feature.
* @param array $data array where key corresponds to cache key while value is the value stored
* @param integer $duration the number of seconds in which the cached values will expire. 0 means never expire.
* @param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
* @return array array of failed keys
*/
protected function addValues($data, $duration)
@ -118,7 +118,7 @@ class WinCache extends Cache
* Deletes a value with the specified key from cache
* This is the implementation of the method declared in the parent class.
* @param string $key the key of the value to be deleted
* @return boolean if no error happens during deletion
* @return bool if no error happens during deletion
*/
protected function deleteValue($key)
{
@ -128,7 +128,7 @@ class WinCache extends Cache
/**
* Deletes all values from cache.
* This is the implementation of the method declared in the parent class.
* @return boolean whether the flush operation was successful.
* @return bool whether the flush operation was successful.
*/
protected function flushValues()
{

14
framework/caching/XCache.php

@ -31,7 +31,7 @@ class XCache extends Cache
* may return false while exists returns true.
* @param mixed $key a key identifying the cached value. This can be a simple string or
* a complex data structure consisting of factors representing the key.
* @return boolean true if a value exists in cache, false if the value is not in the cache or expired.
* @return bool true if a value exists in cache, false if the value is not in the cache or expired.
*/
public function exists($key)
{
@ -58,8 +58,8 @@ class XCache extends Cache
* @param string $key the key identifying the value to be cached
* @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
* it could be something else.
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return bool true if the value is successfully stored into cache, false otherwise
*/
protected function setValue($key, $value, $duration)
{
@ -73,8 +73,8 @@ class XCache extends Cache
* @param string $key the key identifying the value to be cached
* @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
* it could be something else.
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return bool true if the value is successfully stored into cache, false otherwise
*/
protected function addValue($key, $value, $duration)
{
@ -85,7 +85,7 @@ class XCache extends Cache
* Deletes a value with the specified key from cache
* This is the implementation of the method declared in the parent class.
* @param string $key the key of the value to be deleted
* @return boolean if no error happens during deletion
* @return bool if no error happens during deletion
*/
protected function deleteValue($key)
{
@ -95,7 +95,7 @@ class XCache extends Cache
/**
* Deletes all values from cache.
* This is the implementation of the method declared in the parent class.
* @return boolean whether the flush operation was successful.
* @return bool whether the flush operation was successful.
*/
protected function flushValues()
{

12
framework/caching/ZendDataCache.php

@ -42,8 +42,8 @@ class ZendDataCache extends Cache
* @param string $key the key identifying the value to be cached
* @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
* it could be something else.
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return bool true if the value is successfully stored into cache, false otherwise
*/
protected function setValue($key, $value, $duration)
{
@ -57,8 +57,8 @@ class ZendDataCache extends Cache
* @param string $key the key identifying the value to be cached
* @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
* it could be something else.
* @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return boolean true if the value is successfully stored into cache, false otherwise
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @return bool true if the value is successfully stored into cache, false otherwise
*/
protected function addValue($key, $value, $duration)
{
@ -69,7 +69,7 @@ class ZendDataCache extends Cache
* Deletes a value with the specified key from cache
* This is the implementation of the method declared in the parent class.
* @param string $key the key of the value to be deleted
* @return boolean if no error happens during deletion
* @return bool if no error happens during deletion
*/
protected function deleteValue($key)
{
@ -79,7 +79,7 @@ class ZendDataCache extends Cache
/**
* Deletes all values from cache.
* This is the implementation of the method declared in the parent class.
* @return boolean whether the flush operation was successful.
* @return bool whether the flush operation was successful.
*/
protected function flushValues()
{

26
framework/captcha/CaptchaAction.php

@ -44,45 +44,45 @@ class CaptchaAction extends Action
const REFRESH_GET_VAR = 'refresh';
/**
* @var integer how many times should the same CAPTCHA be displayed. Defaults to 3.
* @var int how many times should the same CAPTCHA be displayed. Defaults to 3.
* A value less than or equal to 0 means the test is unlimited (available since version 1.1.2).
*/
public $testLimit = 3;
/**
* @var integer the width of the generated CAPTCHA image. Defaults to 120.
* @var int the width of the generated CAPTCHA image. Defaults to 120.
*/
public $width = 120;
/**
* @var integer the height of the generated CAPTCHA image. Defaults to 50.
* @var int the height of the generated CAPTCHA image. Defaults to 50.
*/
public $height = 50;
/**
* @var integer padding around the text. Defaults to 2.
* @var int padding around the text. Defaults to 2.
*/
public $padding = 2;
/**
* @var integer the background color. For example, 0x55FF00.
* @var int the background color. For example, 0x55FF00.
* Defaults to 0xFFFFFF, meaning white color.
*/
public $backColor = 0xFFFFFF;
/**
* @var integer the font color. For example, 0x55FF00. Defaults to 0x2040A0 (blue color).
* @var int the font color. For example, 0x55FF00. Defaults to 0x2040A0 (blue color).
*/
public $foreColor = 0x2040A0;
/**
* @var boolean whether to use transparent background. Defaults to false.
* @var bool whether to use transparent background. Defaults to false.
*/
public $transparent = false;
/**
* @var integer the minimum length for randomly generated word. Defaults to 6.
* @var int the minimum length for randomly generated word. Defaults to 6.
*/
public $minLength = 6;
/**
* @var integer the maximum length for randomly generated word. Defaults to 7.
* @var int the maximum length for randomly generated word. Defaults to 7.
*/
public $maxLength = 7;
/**
* @var integer the offset between characters. Defaults to -2. You can adjust this property
* @var int the offset between characters. Defaults to -2. You can adjust this property
* in order to decrease or increase the readability of the captcha.
*/
public $offset = -2;
@ -157,7 +157,7 @@ class CaptchaAction extends Action
/**
* Gets the verification code.
* @param boolean $regenerate whether the verification code should be regenerated.
* @param bool $regenerate whether the verification code should be regenerated.
* @return string the verification code.
*/
public function getVerifyCode($regenerate = false)
@ -180,8 +180,8 @@ class CaptchaAction extends Action
/**
* Validates the input to see if it matches the generated code.
* @param string $input user input
* @param boolean $caseSensitive whether the comparison should be case-sensitive
* @return boolean whether the input is valid
* @param bool $caseSensitive whether the comparison should be case-sensitive
* @return bool whether the input is valid
*/
public function validate($input, $caseSensitive)
{

4
framework/captcha/CaptchaValidator.php

@ -27,11 +27,11 @@ use yii\validators\Validator;
class CaptchaValidator extends Validator
{
/**
* @var boolean whether to skip this validator if the input is empty.
* @var bool whether to skip this validator if the input is empty.
*/
public $skipOnEmpty = false;
/**
* @var boolean whether the comparison is case sensitive. Defaults to false.
* @var bool whether the comparison is case sensitive. Defaults to false.
*/
public $caseSensitive = false;
/**

4
framework/console/Application.php

@ -70,7 +70,7 @@ class Application extends \yii\base\Application
*/
public $defaultRoute = 'help';
/**
* @var boolean whether to enable the commands provided by the core framework.
* @var bool whether to enable the commands provided by the core framework.
* Defaults to true.
*/
public $enableCoreCommands = true;
@ -170,7 +170,7 @@ class Application extends \yii\base\Application
*
* @param string $route the route that specifies the action.
* @param array $params the parameters to be passed to the action
* @return integer|Response the result of the action. This can be either an exit code or Response object.
* @return int|Response the result of the action. This can be either an exit code or Response object.
* Exit code 0 means normal, and other values mean abnormal. Exit code of `null` is treaded as `0` as well.
* @throws Exception if the route is invalid
*/

18
framework/console/Controller.php

@ -43,16 +43,16 @@ class Controller extends \yii\base\Controller
const EXIT_CODE_ERROR = 1;
/**
* @var boolean whether to run the command interactively.
* @var bool whether to run the command interactively.
*/
public $interactive = true;
/**
* @var boolean whether to enable ANSI color in the output.
* @var bool whether to enable ANSI color in the output.
* If not set, ANSI color will only be enabled for terminals that support it.
*/
public $color;
/**
* @var boolean whether to display help information about current command.
* @var bool whether to display help information about current command.
* @since 2.0.10
*/
public $help;
@ -70,7 +70,7 @@ class Controller extends \yii\base\Controller
* and the terminal supports ANSI color.
*
* @param resource $stream the stream to check.
* @return boolean Whether to enable ANSI style in output.
* @return bool Whether to enable ANSI style in output.
*/
public function isColorEnabled($stream = \STDOUT)
{
@ -82,7 +82,7 @@ class Controller extends \yii\base\Controller
* If the action ID is empty, the method will use [[defaultAction]].
* @param string $id the ID of the action to be executed.
* @param array $params the parameters (name-value pairs) to be passed to the action.
* @return integer the status of the action execution. 0 means normal, other values mean abnormal.
* @return int the status of the action execution. 0 means normal, other values mean abnormal.
* @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully.
* @throws Exception if there are unknown options or missing arguments
* @see createAction
@ -206,7 +206,7 @@ class Controller extends \yii\base\Controller
* ```
*
* @param string $string the string to print
* @return integer|boolean Number of bytes printed or false on error
* @return int|bool Number of bytes printed or false on error
*/
public function stdout($string)
{
@ -231,7 +231,7 @@ class Controller extends \yii\base\Controller
* ```
*
* @param string $string the string to print
* @return integer|boolean Number of bytes printed or false on error
* @return int|bool Number of bytes printed or false on error
*/
public function stderr($string)
{
@ -283,8 +283,8 @@ class Controller extends \yii\base\Controller
* Asks user to confirm by typing y or n.
*
* @param string $message to echo out before waiting for user input
* @param boolean $default this value is returned if no selection is made.
* @return boolean whether user confirmed.
* @param bool $default this value is returned if no selection is made.
* @return bool whether user confirmed.
* Will return true if [[interactive]] is false.
*/
public function confirm($message, $default = false)

6
framework/console/controllers/AssetController.php

@ -122,7 +122,7 @@ class AssetController extends Controller
*/
public $cssCompressor = 'java -jar yuicompressor.jar --type css {from} -o {to}';
/**
* @var boolean whether to delete asset source files after compression.
* @var bool whether to delete asset source files after compression.
* This option affects only those bundles, which have [[\yii\web\AssetBundle::sourcePath]] is set.
* @since 2.0.10
*/
@ -677,7 +677,7 @@ EOD;
/**
* Creates template of configuration file for [[actionCompress]].
* @param string $configFile output file name.
* @return integer CLI exit code
* @return int CLI exit code
* @throws \yii\console\Exception on failure.
*/
public function actionTemplate($configFile)
@ -762,7 +762,7 @@ EOD;
/**
* @param AssetBundle $bundle
* @return boolean whether asset bundle external or not.
* @return bool whether asset bundle external or not.
*/
private function isBundleExternal($bundle)
{

30
framework/console/controllers/BaseMigrateController.php

@ -83,7 +83,7 @@ abstract class BaseMigrateController extends Controller
* It checks the existence of the [[migrationPath]].
* @param \yii\base\Action $action the action to be executed.
* @throws InvalidConfigException if directory specified in migrationPath doesn't exist and action isn't "create".
* @return boolean whether the action should continue to be executed.
* @return bool whether the action should continue to be executed.
*/
public function beforeAction($action)
{
@ -125,10 +125,10 @@ abstract class BaseMigrateController extends Controller
* yii migrate 3 # apply the first 3 new migrations
* ```
*
* @param integer $limit the number of new migrations to be applied. If 0, it means
* @param int $limit the number of new migrations to be applied. If 0, it means
* applying all available new migrations.
*
* @return integer the status of the action execution. 0 means normal, other values mean abnormal.
* @return int the status of the action execution. 0 means normal, other values mean abnormal.
*/
public function actionUp($limit = 0)
{
@ -184,11 +184,11 @@ abstract class BaseMigrateController extends Controller
* yii migrate/down all # revert all migrations
* ```
*
* @param integer $limit the number of migrations to be reverted. Defaults to 1,
* @param int $limit the number of migrations to be reverted. Defaults to 1,
* meaning the last applied migration will be reverted.
* @throws Exception if the number of the steps specified is less than 1.
*
* @return integer the status of the action execution. 0 means normal, other values mean abnormal.
* @return int the status of the action execution. 0 means normal, other values mean abnormal.
*/
public function actionDown($limit = 1)
{
@ -246,11 +246,11 @@ abstract class BaseMigrateController extends Controller
* yii migrate/redo all # redo all migrations
* ```
*
* @param integer $limit the number of migrations to be redone. Defaults to 1,
* @param int $limit the number of migrations to be redone. Defaults to 1,
* meaning the last applied migration will be redone.
* @throws Exception if the number of the steps specified is less than 1.
*
* @return integer the status of the action execution. 0 means normal, other values mean abnormal.
* @return int the status of the action execution. 0 means normal, other values mean abnormal.
*/
public function actionRedo($limit = 1)
{
@ -352,7 +352,7 @@ abstract class BaseMigrateController extends Controller
*
* @param string $version the version at which the migration history should be marked.
* This can be either the timestamp or the full name of the migration.
* @return integer CLI exit code
* @return int CLI exit code
* @throws Exception if the version argument is invalid or the version cannot be found.
*/
public function actionMark($version)
@ -443,7 +443,7 @@ abstract class BaseMigrateController extends Controller
* yii migrate/history all # showing the whole history
* ```
*
* @param integer $limit the maximum number of migrations to be displayed.
* @param int $limit the maximum number of migrations to be displayed.
* If it is "all", the whole migration history will be displayed.
* @throws \yii\console\Exception if invalid limit value passed
*/
@ -487,7 +487,7 @@ abstract class BaseMigrateController extends Controller
* yii migrate/new all # showing all new migrations
* ```
*
* @param integer $limit the maximum number of new migrations to be displayed.
* @param int $limit the maximum number of new migrations to be displayed.
* If it is `all`, all available new migrations will be displayed.
* @throws \yii\console\Exception if invalid limit value passed
*/
@ -637,7 +637,7 @@ abstract class BaseMigrateController extends Controller
/**
* Upgrades with the specified migration class.
* @param string $class the migration class name
* @return boolean whether the migration is successful
* @return bool whether the migration is successful
*/
protected function migrateUp($class)
{
@ -665,7 +665,7 @@ abstract class BaseMigrateController extends Controller
/**
* Downgrades with the specified migration class.
* @param string $class the migration class name
* @return boolean whether the migration is successful
* @return bool whether the migration is successful
*/
protected function migrateDown($class)
{
@ -708,7 +708,7 @@ abstract class BaseMigrateController extends Controller
/**
* Migrates to the specified apply time in the past.
* @param integer $time UNIX timestamp value.
* @param int $time UNIX timestamp value.
*/
protected function migrateToTime($time)
{
@ -727,7 +727,7 @@ abstract class BaseMigrateController extends Controller
/**
* Migrates to the certain version.
* @param string $version name in the full format.
* @return integer CLI exit code
* @return int CLI exit code
* @throws Exception if the provided version cannot be found.
*/
protected function migrateToVersion($version)
@ -827,7 +827,7 @@ abstract class BaseMigrateController extends Controller
/**
* Returns the migration history.
* @param integer $limit the maximum number of records in the history to be returned. `null` for "no limit".
* @param int $limit the maximum number of records in the history to be returned. `null` for "no limit".
* @return array the migration history
*/
abstract protected function getMigrationHistory($limit);

6
framework/console/controllers/CacheController.php

@ -139,7 +139,7 @@ class CacheController extends Controller
* ```
*
* @param string $db id connection component
* @return integer exit code
* @return int exit code
* @throws Exception
* @throws \yii\base\InvalidConfigException
*
@ -231,7 +231,7 @@ class CacheController extends Controller
/**
* Prompts user with confirmation if caches should be flushed.
* @param array $cachesNames
* @return boolean
* @return bool
*/
private function confirmFlush($cachesNames)
{
@ -275,7 +275,7 @@ class CacheController extends Controller
/**
* Checks if given class is a Cache class.
* @param string $className class name.
* @return boolean
* @return bool
*/
private function isCacheClass($className)
{

6
framework/console/controllers/FixtureController.php

@ -310,7 +310,7 @@ class FixtureController extends Controller
* Prompts user with confirmation if fixtures should be loaded.
* @param array $fixtures
* @param array $except
* @return boolean
* @return bool
*/
private function confirmLoad($fixtures, $except)
{
@ -342,7 +342,7 @@ class FixtureController extends Controller
* Prompts user with confirmation for fixtures that should be unloaded.
* @param array $fixtures
* @param array $except
* @return boolean
* @return bool
*/
private function confirmUnload($fixtures, $except)
{
@ -381,7 +381,7 @@ class FixtureController extends Controller
/**
* Checks if needed to apply all fixtures.
* @param string $fixture
* @return boolean
* @return bool
*/
public function needToApplyAll($fixture)
{

6
framework/console/controllers/HelpController.php

@ -43,7 +43,7 @@ class HelpController extends Controller
*
* @param string $command The name of the command to show help about.
* If not provided, all available commands will be displayed.
* @return integer the exit status
* @return int the exit status
* @throws Exception if the command for help is unknown
*/
public function actionIndex($command = null)
@ -164,7 +164,7 @@ class HelpController extends Controller
/**
* Validates if the given class is a valid console controller class.
* @param string $controllerClass
* @return boolean
* @return bool
*/
protected function validateControllerClass($controllerClass)
{
@ -370,7 +370,7 @@ class HelpController extends Controller
/**
* Generates a well-formed string for an argument or option.
* @param string $name the name of the argument or option
* @param boolean $required whether the argument is required
* @param bool $required whether the argument is required
* @param string $type the type of the option or argument
* @param mixed $defaultValue the default value of the option or argument
* @param string $comment comment about the option or argument

46
framework/console/controllers/MessageController.php

@ -62,22 +62,22 @@ class MessageController extends Controller
*/
public $translator = 'Yii::t';
/**
* @var boolean whether to sort messages by keys when merging new messages
* @var bool whether to sort messages by keys when merging new messages
* with the existing ones. Defaults to false, which means the new (untranslated)
* messages will be separated from the old (translated) ones.
*/
public $sort = false;
/**
* @var boolean whether the message file should be overwritten with the merged messages
* @var bool whether the message file should be overwritten with the merged messages
*/
public $overwrite = true;
/**
* @var boolean whether to remove messages that no longer appear in the source code.
* @var bool whether to remove messages that no longer appear in the source code.
* Defaults to false, which means these messages will NOT be removed.
*/
public $removeUnused = false;
/**
* @var boolean whether to mark messages that no longer appear in the source code.
* @var bool whether to mark messages that no longer appear in the source code.
* Defaults to true, which means each of these messages will be enclosed with a pair of '@@' marks.
*/
public $markUnused = true;
@ -188,7 +188,7 @@ class MessageController extends Controller
* You may use this configuration file with the "extract" command.
*
* @param string $filePath output file name or alias.
* @return integer CLI exit code
* @return int CLI exit code
* @throws Exception on failure.
*/
public function actionConfig($filePath)
@ -234,7 +234,7 @@ EOD;
* you may use this configuration file with the "extract" command.
*
* @param string $filePath output file name or alias.
* @return integer CLI exit code
* @return int CLI exit code
* @throws Exception on failure.
*/
public function actionConfigTemplate($filePath)
@ -353,9 +353,9 @@ EOD;
* @param \yii\db\Connection $db
* @param string $sourceMessageTable
* @param string $messageTable
* @param boolean $removeUnused
* @param bool $removeUnused
* @param array $languages
* @param boolean $markUnused
* @param bool $markUnused
*/
protected function saveMessagesToDb($messages, $db, $sourceMessageTable, $messageTable, $removeUnused, $languages, $markUnused)
{
@ -549,7 +549,7 @@ EOD;
*
* @param string $category category that is checked
* @param array $ignoreCategories message categories to ignore.
* @return boolean
* @return bool
* @since 2.0.7
*/
protected function isCategoryIgnored($category, array $ignoreCategories)
@ -577,7 +577,7 @@ EOD;
*
* @param array|string $a
* @param array|string $b
* @return boolean
* @return bool
* @since 2.0.1
*/
protected function tokensEqual($a, $b)
@ -594,7 +594,7 @@ EOD;
* Finds out a line of the first non-char PHP token found
*
* @param array $tokens
* @return integer|string
* @return int|string
* @since 2.0.1
*/
protected function getLine($tokens)
@ -612,10 +612,10 @@ EOD;
*
* @param array $messages
* @param string $dirName name of the directory to write to
* @param boolean $overwrite if existing file should be overwritten without backup
* @param boolean $removeUnused if obsolete translations should be removed
* @param boolean $sort if translations should be sorted
* @param boolean $markUnused if obsolete translations should be marked
* @param bool $overwrite if existing file should be overwritten without backup
* @param bool $removeUnused if obsolete translations should be removed
* @param bool $sort if translations should be sorted
* @param bool $markUnused if obsolete translations should be marked
*/
protected function saveMessagesToPHP($messages, $dirName, $overwrite, $removeUnused, $sort, $markUnused)
{
@ -635,11 +635,11 @@ EOD;
*
* @param array $messages
* @param string $fileName name of the file to write to
* @param boolean $overwrite if existing file should be overwritten without backup
* @param boolean $removeUnused if obsolete translations should be removed
* @param boolean $sort if translations should be sorted
* @param bool $overwrite if existing file should be overwritten without backup
* @param bool $removeUnused if obsolete translations should be removed
* @param bool $sort if translations should be sorted
* @param string $category message category
* @param boolean $markUnused if obsolete translations should be marked
* @param bool $markUnused if obsolete translations should be marked
* @return int exit code
*/
protected function saveMessagesCategoryToPHP($messages, $fileName, $overwrite, $removeUnused, $sort, $category, $markUnused)
@ -734,11 +734,11 @@ EOD;
*
* @param array $messages
* @param string $dirName name of the directory to write to
* @param boolean $overwrite if existing file should be overwritten without backup
* @param boolean $removeUnused if obsolete translations should be removed
* @param boolean $sort if translations should be sorted
* @param bool $overwrite if existing file should be overwritten without backup
* @param bool $removeUnused if obsolete translations should be removed
* @param bool $sort if translations should be sorted
* @param string $catalog message catalog
* @param boolean $markUnused if obsolete translations should be marked
* @param bool $markUnused if obsolete translations should be marked
*/
protected function saveMessagesToPO($messages, $dirName, $overwrite, $removeUnused, $sort, $catalog, $markUnused)
{

4
framework/console/controllers/MigrateController.php

@ -101,7 +101,7 @@ class MigrateController extends BaseMigrateController
'create_junction' => '@yii/views/createTableMigration.php',
];
/**
* @var boolean indicates whether the table names generated should consider
* @var bool indicates whether the table names generated should consider
* the `tablePrefix` setting of the DB connection. For example, if the table
* name is `post` the generator wil return `{{%post}}`.
* @since 2.0.8
@ -161,7 +161,7 @@ class MigrateController extends BaseMigrateController
* This method is invoked right before an action is to be executed (after all possible filters.)
* It checks the existence of the [[migrationPath]].
* @param \yii\base\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)
{

4
framework/console/controllers/ServeController.php

@ -47,7 +47,7 @@ class ServeController extends Controller
*
* @param string $address address to serve on. Either "host" or "host:port".
*
* @return integer
* @return int
*/
public function actionIndex($address = 'localhost')
{
@ -109,7 +109,7 @@ class ServeController extends Controller
/**
* @param string $address server address
* @return boolean if address is already in use
* @return bool if address is already in use
*/
protected function isAddressTaken($address)
{

22
framework/data/BaseDataProvider.php

@ -16,16 +16,16 @@ use yii\base\InvalidParamException;
*
* For more details and usage information on BaseDataProvider, see the [guide article on data providers](guide:output-data-providers).
*
* @property integer $count The number of data models in the current page. This property is read-only.
* @property int $count The number of data models in the current page. This property is read-only.
* @property array $keys The list of key values corresponding to [[models]]. Each data model in [[models]] is
* uniquely identified by the corresponding key value in this array.
* @property array $models The list of data models in the current page.
* @property Pagination|false $pagination The pagination object. If this is false, it means the pagination is
* disabled. Note that the type of this property differs in getter and setter. See [[getPagination()]] and
* [[setPagination()]] for details.
* @property Sort|boolean $sort The sorting object. If this is false, it means the sorting is disabled. Note
* @property Sort|bool $sort The sorting object. If this is false, it means the sorting is disabled. Note
* that the type of this property differs in getter and setter. See [[getSort()]] and [[setSort()]] for details.
* @property integer $totalCount Total number of possible data models.
* @property int $totalCount Total number of possible data models.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
@ -61,7 +61,7 @@ abstract class BaseDataProvider extends Component implements DataProviderInterfa
/**
* Returns a value indicating the total number of data models in this data provider.
* @return integer total number of data models in this data provider.
* @return int total number of data models in this data provider.
*/
abstract protected function prepareTotalCount();
@ -73,7 +73,7 @@ abstract class BaseDataProvider extends Component implements DataProviderInterfa
*
* This method will be implicitly called by [[getModels()]] and [[getKeys()]] if it has not been called before.
*
* @param boolean $forcePrepare whether to force data preparation even if it has been done before.
* @param bool $forcePrepare whether to force data preparation even if it has been done before.
*/
public function prepare($forcePrepare = false)
{
@ -128,7 +128,7 @@ abstract class BaseDataProvider extends Component implements DataProviderInterfa
/**
* Returns the number of data models in the current page.
* @return integer the number of data models in the current page.
* @return int the number of data models in the current page.
*/
public function getCount()
{
@ -139,7 +139,7 @@ abstract class BaseDataProvider extends Component implements DataProviderInterfa
* Returns the total number of data models.
* When [[pagination]] is false, this returns the same value as [[count]].
* Otherwise, it will call [[prepareTotalCount()]] to get the count.
* @return integer total number of possible data models.
* @return int total number of possible data models.
*/
public function getTotalCount()
{
@ -154,7 +154,7 @@ abstract class BaseDataProvider extends Component implements DataProviderInterfa
/**
* Sets the total number of data models.
* @param integer $value the total number of data models.
* @param int $value the total number of data models.
*/
public function setTotalCount($value)
{
@ -178,7 +178,7 @@ abstract class BaseDataProvider extends Component implements DataProviderInterfa
/**
* Sets the pagination for this data provider.
* @param array|Pagination|boolean $value the pagination to be used by this data provider.
* @param array|Pagination|bool $value the pagination to be used by this data provider.
* This can be one of the following:
*
* - a configuration array for creating the pagination object. The "class" element defaults
@ -206,7 +206,7 @@ abstract class BaseDataProvider extends Component implements DataProviderInterfa
/**
* Returns the sorting object used by this data provider.
* @return Sort|boolean the sorting object. If this is false, it means the sorting is disabled.
* @return Sort|bool the sorting object. If this is false, it means the sorting is disabled.
*/
public function getSort()
{
@ -219,7 +219,7 @@ abstract class BaseDataProvider extends Component implements DataProviderInterfa
/**
* Sets the sort definition for this data provider.
* @param array|Sort|boolean $value the sort definition to be used by this data provider.
* @param array|Sort|bool $value the sort definition to be used by this data provider.
* This can be one of the following:
*
* - a configuration array for creating the sort definition object. The "class" element defaults

6
framework/data/DataProviderInterface.php

@ -28,7 +28,7 @@ interface DataProviderInterface
*
* This method will be implicitly called by [[getModels()]] and [[getKeys()]] if it has not been called before.
*
* @param boolean $forcePrepare whether to force data preparation even if it has been done before.
* @param bool $forcePrepare whether to force data preparation even if it has been done before.
*/
public function prepare($forcePrepare = false);
@ -36,14 +36,14 @@ interface DataProviderInterface
* Returns the number of data models in the current page.
* This is equivalent to `count($provider->getModels())`.
* When [[getPagination|pagination]] is false, this is the same as [[getTotalCount|totalCount]].
* @return integer the number of data models in the current page.
* @return int the number of data models in the current page.
*/
public function getCount();
/**
* Returns the total number of data models.
* When [[getPagination|pagination]] is false, this is the same as [[getCount|count]].
* @return integer total number of possible data models.
* @return int total number of possible data models.
*/
public function getTotalCount();

48
framework/data/Pagination.php

@ -58,16 +58,16 @@ use yii\web\Request;
*
* For more details and usage information on Pagination, see the [guide article on pagination](guide:output-pagination).
*
* @property integer $limit The limit of the data. This may be used to set the LIMIT value for a SQL statement
* @property int $limit The limit of the data. This may be used to set the LIMIT value for a SQL statement
* for fetching the current page of data. Note that if the page size is infinite, a value -1 will be returned.
* This property is read-only.
* @property array $links The links for navigational purpose. The array keys specify the purpose of the links
* (e.g. [[LINK_FIRST]]), and the array values are the corresponding URLs. This property is read-only.
* @property integer $offset The offset of the data. This may be used to set the OFFSET value for a SQL
* @property int $offset The offset of the data. This may be used to set the OFFSET value for a SQL
* statement for fetching the current page of data. This property is read-only.
* @property integer $page The zero-based current page number.
* @property integer $pageCount Number of pages. This property is read-only.
* @property integer $pageSize The number of items per page. If it is less than 1, it means the page size is
* @property int $page The zero-based current page number.
* @property int $pageCount Number of pages. This property is read-only.
* @property int $pageSize The number of items per page. If it is less than 1, it means the page size is
* infinite, and thus a single page contains all items.
*
* @author Qiang Xue <qiang.xue@gmail.com>
@ -91,7 +91,7 @@ class Pagination extends Object implements Linkable
*/
public $pageSizeParam = 'per-page';
/**
* @var boolean whether to always have the page parameter in the URL created by [[createUrl()]].
* @var bool whether to always have the page parameter in the URL created by [[createUrl()]].
* If false and [[page]] is 0, the page parameter will not be put in the URL.
*/
public $forcePageParam = true;
@ -116,7 +116,7 @@ class Pagination extends Object implements Linkable
*/
public $urlManager;
/**
* @var boolean whether to check if [[page]] is within valid range.
* @var bool whether to check if [[page]] is within valid range.
* When this property is true, the value of [[page]] will always be between 0 and ([[pageCount]]-1).
* Because [[pageCount]] relies on the correct value of [[totalCount]] which may not be available
* in some cases (e.g. MongoDB), you may want to set this property to be false to disable the page
@ -124,11 +124,11 @@ class Pagination extends Object implements Linkable
*/
public $validatePage = true;
/**
* @var integer total number of items.
* @var int total number of items.
*/
public $totalCount = 0;
/**
* @var integer the default page size. This property will be returned by [[pageSize]] when page size
* @var int the default page size. This property will be returned by [[pageSize]] when page size
* cannot be determined by [[pageSizeParam]] from [[params]].
*/
public $defaultPageSize = 20;
@ -139,14 +139,14 @@ class Pagination extends Object implements Linkable
public $pageSizeLimit = [1, 50];
/**
* @var integer number of items on each page.
* @var int number of items on each page.
* If it is less than 1, it means the page size is infinite, and thus a single page contains all items.
*/
private $_pageSize;
/**
* @return integer number of pages
* @return int number of pages
*/
public function getPageCount()
{
@ -164,8 +164,8 @@ class Pagination extends Object implements Linkable
/**
* Returns the zero-based current page number.
* @param boolean $recalculate whether to recalculate the current page based on the page size and item count.
* @return integer the zero-based current page number.
* @param bool $recalculate whether to recalculate the current page based on the page size and item count.
* @return int the zero-based current page number.
*/
public function getPage($recalculate = false)
{
@ -179,8 +179,8 @@ class Pagination extends Object implements Linkable
/**
* Sets the current page number.
* @param integer $value the zero-based index of the current page.
* @param boolean $validatePage whether to validate the page number. Note that in order
* @param int $value the zero-based index of the current page.
* @param bool $validatePage whether to validate the page number. Note that in order
* to validate the page number, both [[validatePage]] and this parameter must be true.
*/
public function setPage($value, $validatePage = false)
@ -206,7 +206,7 @@ class Pagination extends Object implements Linkable
* Returns the number of items per page.
* By default, this method will try to determine the page size by [[pageSizeParam]] in [[params]].
* If the page size cannot be determined this way, [[defaultPageSize]] will be returned.
* @return integer the number of items per page. If it is less than 1, it means the page size is infinite,
* @return int the number of items per page. If it is less than 1, it means the page size is infinite,
* and thus a single page contains all items.
* @see pageSizeLimit
*/
@ -226,8 +226,8 @@ class Pagination extends Object implements Linkable
}
/**
* @param integer $value the number of items per page.
* @param boolean $validatePageSize whether to validate page size.
* @param int $value the number of items per page.
* @param bool $validatePageSize whether to validate page size.
*/
public function setPageSize($value, $validatePageSize = false)
{
@ -249,9 +249,9 @@ class Pagination extends Object implements Linkable
/**
* Creates the URL suitable for pagination with the specified page number.
* This method is mainly called by pagers when creating URLs used to perform pagination.
* @param integer $page the zero-based page number that the URL should point to.
* @param integer $pageSize the number of items on each page. If not set, the value of [[pageSize]] will be used.
* @param boolean $absolute whether to create an absolute URL. Defaults to `false`.
* @param int $page the zero-based page number that the URL should point to.
* @param int $pageSize the number of items on each page. If not set, the value of [[pageSize]] will be used.
* @param bool $absolute whether to create an absolute URL. Defaults to `false`.
* @return string the created URL
* @see params
* @see forcePageParam
@ -287,7 +287,7 @@ class Pagination extends Object implements Linkable
}
/**
* @return integer the offset of the data. This may be used to set the
* @return int the offset of the data. This may be used to set the
* OFFSET value for a SQL statement for fetching the current page of data.
*/
public function getOffset()
@ -298,7 +298,7 @@ class Pagination extends Object implements Linkable
}
/**
* @return integer the limit of the data. This may be used to set the
* @return int the limit of the data. This may be used to set the
* LIMIT value for a SQL statement for fetching the current page of data.
* Note that if the page size is infinite, a value -1 will be returned.
*/
@ -311,7 +311,7 @@ class Pagination extends Object implements Linkable
/**
* Returns a whole set of links for navigating to the first, last, next and previous pages.
* @param boolean $absolute whether the generated URLs should be absolute.
* @param bool $absolute whether the generated URLs should be absolute.
* @return array the links for navigational purpose. The array keys specify the purpose of the links (e.g. [[LINK_FIRST]]),
* and the array values are the corresponding URLs.
*/

14
framework/data/Sort.php

@ -80,7 +80,7 @@ use yii\web\Request;
class Sort extends Object
{
/**
* @var boolean whether the sorting can be applied to multiple attributes simultaneously.
* @var bool whether the sorting can be applied to multiple attributes simultaneously.
* Defaults to `false`, which means each time the data can only be sorted by one attribute.
*/
public $enableMultiSort = false;
@ -204,7 +204,7 @@ class Sort extends Object
/**
* Returns the columns and their corresponding sort directions.
* @param boolean $recalculate whether to recalculate the sort directions
* @param bool $recalculate whether to recalculate the sort directions
* @return array the columns (keys) and their corresponding sort directions (values).
* This can be passed to [[\yii\db\Query::orderBy()]] to construct a DB query.
*/
@ -230,7 +230,7 @@ class Sort extends Object
/**
* Returns the currently requested sort information.
* @param boolean $recalculate whether to recalculate the sort directions
* @param bool $recalculate whether to recalculate the sort directions
* @return array sort directions indexed by attribute names.
* Sort direction can be either `SORT_ASC` for ascending order or
* `SORT_DESC` for descending order.
@ -273,7 +273,7 @@ class Sort extends Object
* @param array|null $attributeOrders sort directions indexed by attribute names.
* Sort direction can be either `SORT_ASC` for ascending order or
* `SORT_DESC` for descending order.
* @param boolean $validate whether to validate given attribute orders against [[attributes]] and [[enableMultiSort]].
* @param bool $validate whether to validate given attribute orders against [[attributes]] and [[enableMultiSort]].
* If validation is enabled incorrect entries will be removed.
* @since 2.0.10
*/
@ -297,7 +297,7 @@ class Sort extends Object
/**
* Returns the sort direction of the specified attribute in the current request.
* @param string $attribute the attribute name
* @return boolean|null Sort direction of the attribute. Can be either `SORT_ASC`
* @return bool|null Sort direction of the attribute. Can be either `SORT_ASC`
* for ascending order or `SORT_DESC` for descending order. Null is returned
* if the attribute is invalid or does not need to be sorted.
*/
@ -355,7 +355,7 @@ class Sort extends Object
* For example, if the current page already sorts the data by the specified attribute in ascending order,
* then the URL created will lead to a page that sorts the data by the specified attribute in descending order.
* @param string $attribute the attribute name
* @param boolean $absolute whether to create an absolute URL. Defaults to `false`.
* @param bool $absolute whether to create an absolute URL. Defaults to `false`.
* @return string the URL for sorting. False if the attribute is invalid.
* @throws InvalidConfigException if the attribute is unknown
* @see attributeOrders
@ -416,7 +416,7 @@ class Sort extends Object
/**
* Returns a value indicating whether the sort definition supports sorting by the named attribute.
* @param string $name the attribute name
* @return boolean whether the sort definition supports sorting by the named attribute.
* @return bool whether the sort definition supports sorting by the named attribute.
*/
public function hasAttribute($name)
{

4
framework/db/ActiveQuery.php

@ -389,7 +389,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface
*
* The alias syntax is available since version 2.0.7.
*
* @param boolean|array $eagerLoading whether to eager load the relations specified in `$with`.
* @param bool|array $eagerLoading whether to eager load the relations specified in `$with`.
* When this is a boolean, it applies to all relations specified in `$with`. Use an array
* to explicitly list which relations in `$with` need to be eagerly loaded. Defaults to `true`.
* @param string|array $joinType the join type of the relations specified in `$with`.
@ -476,7 +476,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface
* This is a shortcut method to [[joinWith()]] with the join type set as "INNER JOIN".
* Please refer to [[joinWith()]] for detailed usage of this method.
* @param string|array $with the relations to be joined with.
* @param boolean|array $eagerLoading whether to eager loading the relations.
* @param bool|array $eagerLoading whether to eager loading the relations.
* @return $this the query object itself
* @see joinWith()
*/

2
framework/db/ActiveQueryInterface.php

@ -24,7 +24,7 @@ interface ActiveQueryInterface extends QueryInterface
{
/**
* Sets the [[asArray]] property.
* @param boolean $value whether to return the query results in terms of arrays instead of Active Records.
* @param bool $value whether to return the query results in terms of arrays instead of Active Records.
* @return $this the query object itself
*/
public function asArray($value = true);

4
framework/db/ActiveQueryTrait.php

@ -25,7 +25,7 @@ trait ActiveQueryTrait
*/
public $with;
/**
* @var boolean whether to return each record as an array. If false (default), an object
* @var bool whether to return each record as an array. If false (default), an object
* of [[modelClass]] will be created to represent each record.
*/
public $asArray;
@ -33,7 +33,7 @@ trait ActiveQueryTrait
/**
* Sets the [[asArray]] property.
* @param boolean $value whether to return the query results in terms of arrays instead of Active Records.
* @param bool $value whether to return the query results in terms of arrays instead of Active Records.
* @return $this the query object itself
*/
public function asArray($value = true)

28
framework/db/ActiveRecord.php

@ -108,7 +108,7 @@ class ActiveRecord extends BaseActiveRecord
* $customer->loadDefaultValues();
* ```
*
* @param boolean $skipIfSet whether existing value should be preserved.
* @param bool $skipIfSet whether existing value should be preserved.
* This will only set defaults for attributes that are `null`.
* @return $this the model instance itself.
*/
@ -200,7 +200,7 @@ class ActiveRecord extends BaseActiveRecord
* @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
* Please refer to [[Query::where()]] on how to specify this parameter.
* @param array $params the parameters (name => value) to be bound to the query.
* @return integer the number of rows updated
* @return int the number of rows updated
*/
public static function updateAll($attributes, $condition = '', $params = [])
{
@ -224,7 +224,7 @@ class ActiveRecord extends BaseActiveRecord
* Please refer to [[Query::where()]] on how to specify this parameter.
* @param array $params the parameters (name => value) to be bound to the query.
* Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method.
* @return integer the number of rows updated
* @return int the number of rows updated
*/
public static function updateAllCounters($counters, $condition = '', $params = [])
{
@ -252,7 +252,7 @@ class ActiveRecord extends BaseActiveRecord
* @param string|array $condition the conditions that will be put in the WHERE part of the DELETE SQL.
* Please refer to [[Query::where()]] on how to specify this parameter.
* @param array $params the parameters (name => value) to be bound to the query.
* @return integer the number of rows deleted
* @return int the number of rows deleted
*/
public static function deleteAll($condition = '', $params = [])
{
@ -408,12 +408,12 @@ class ActiveRecord extends BaseActiveRecord
* $customer->insert();
* ```
*
* @param boolean $runValidation whether to perform validation (calling [[validate()]])
* @param bool $runValidation whether to perform validation (calling [[validate()]])
* before saving the record. Defaults to `true`. If the validation fails, the record
* will not be saved to the database and this method will return `false`.
* @param array $attributes list of attributes that need to be saved. Defaults to `null`,
* meaning all attributes that are loaded from DB will be saved.
* @return boolean whether the attributes are valid and the record is inserted successfully.
* @return bool whether the attributes are valid and the record is inserted successfully.
* @throws \Exception in case insert failed.
*/
public function insert($runValidation = true, $attributes = null)
@ -446,7 +446,7 @@ class ActiveRecord extends BaseActiveRecord
* Inserts an ActiveRecord into DB without considering transaction.
* @param array $attributes list of attributes that need to be saved. Defaults to `null`,
* meaning all attributes that are loaded from DB will be saved.
* @return boolean whether the record is inserted successfully.
* @return bool whether the record is inserted successfully.
*/
protected function insertInternal($attributes = null)
{
@ -511,12 +511,12 @@ class ActiveRecord extends BaseActiveRecord
* }
* ```
*
* @param boolean $runValidation whether to perform validation (calling [[validate()]])
* @param bool $runValidation whether to perform validation (calling [[validate()]])
* before saving the record. Defaults to `true`. If the validation fails, the record
* will not be saved to the database and this method will return `false`.
* @param array $attributeNames list of attributes that need to be saved. Defaults to `null`,
* meaning all attributes that are loaded from DB will be saved.
* @return integer|false the number of rows affected, or false if validation fails
* @return int|false the number of rows affected, or false if validation fails
* or [[beforeSave()]] stops the updating process.
* @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
* being updated is outdated.
@ -561,7 +561,7 @@ class ActiveRecord extends BaseActiveRecord
* In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
* will be raised by the corresponding methods.
*
* @return integer|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
* @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
* Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
* @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
* being deleted is outdated.
@ -590,7 +590,7 @@ class ActiveRecord extends BaseActiveRecord
/**
* Deletes an ActiveRecord without considering transaction.
* @return integer|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
* @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
* Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
* @throws StaleObjectException
*/
@ -622,7 +622,7 @@ class ActiveRecord extends BaseActiveRecord
* The comparison is made by comparing the table names and the primary key values of the two active records.
* If one of the records [[isNewRecord|is new]] they are also considered not equal.
* @param ActiveRecord $record record to compare to
* @return boolean whether the two active records refer to the same row in the same database table.
* @return bool whether the two active records refer to the same row in the same database table.
*/
public function equals($record)
{
@ -635,8 +635,8 @@ class ActiveRecord extends BaseActiveRecord
/**
* Returns a value indicating whether the specified operation is transactional in the current [[scenario]].
* @param integer $operation the operation to check. Possible values are [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]].
* @return boolean whether the specified operation is transactional in the current [[scenario]].
* @param int $operation the operation to check. Possible values are [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]].
* @return bool whether the specified operation is transactional in the current [[scenario]].
*/
public function isTransactional($operation)
{

34
framework/db/ActiveRecordInterface.php

@ -54,13 +54,13 @@ interface ActiveRecordInterface
/**
* Returns a value indicating whether the record has an attribute with the specified name.
* @param string $name the name of the attribute
* @return boolean whether the record has an attribute with the specified name.
* @return bool whether the record has an attribute with the specified name.
*/
public function hasAttribute($name);
/**
* Returns the primary key value(s).
* @param boolean $asArray whether to return the primary key value as an array. If true,
* @param bool $asArray whether to return the primary key value as an array. If true,
* the return value will be an array with attribute names as keys and attribute values as values.
* Note that for composite primary keys, an array will always be returned regardless of this parameter value.
* @return mixed the primary key value. An array (attribute name => attribute value) is returned if the primary key
@ -74,7 +74,7 @@ interface ActiveRecordInterface
* This refers to the primary key value that is populated into the record
* after executing a find method (e.g. find(), findOne()).
* The value remains unchanged even if the primary key attribute is manually assigned with a different value.
* @param boolean $asArray whether to return the primary key value as an array. If true,
* @param bool $asArray whether to return the primary key value as an array. If true,
* the return value will be an array with column name as key and column value as value.
* If this is `false` (default), a scalar value will be returned for non-composite primary key.
* @property mixed The old primary key value. An array (column name => column value) is
@ -89,7 +89,7 @@ interface ActiveRecordInterface
/**
* Returns a value indicating whether the given set of attributes represents the primary key for this model
* @param array $keys the set of attributes to check
* @return boolean whether the given set of attributes represents the primary key for this model
* @return bool whether the given set of attributes represents the primary key for this model
*/
public static function isPrimaryKey($keys);
@ -240,7 +240,7 @@ interface ActiveRecordInterface
* @param array $condition the condition that matches the records that should get updated.
* Please refer to [[QueryInterface::where()]] on how to specify this parameter.
* An empty condition will match all records.
* @return integer the number of rows updated
* @return int the number of rows updated
*/
public static function updateAll($attributes, $condition = null);
@ -257,7 +257,7 @@ interface ActiveRecordInterface
* @param array $condition the condition that matches the records that should get deleted.
* Please refer to [[QueryInterface::where()]] on how to specify this parameter.
* An empty condition will match all records.
* @return integer the number of rows deleted
* @return int the number of rows deleted
*/
public static function deleteAll($condition = null);
@ -276,12 +276,12 @@ interface ActiveRecordInterface
* $customer->save();
* ```
*
* @param boolean $runValidation whether to perform validation (calling [[Model::validate()|validate()]])
* @param bool $runValidation whether to perform validation (calling [[Model::validate()|validate()]])
* before saving the record. Defaults to `true`. If the validation fails, the record
* will not be saved to the database and this method will return `false`.
* @param array $attributeNames list of attribute names that need to be saved. Defaults to `null`,
* meaning all attributes that are loaded from DB will be saved.
* @return boolean whether the saving succeeded (i.e. no validation errors occurred).
* @return bool whether the saving succeeded (i.e. no validation errors occurred).
*/
public function save($runValidation = true, $attributeNames = null);
@ -297,12 +297,12 @@ interface ActiveRecordInterface
* $customer->insert();
* ```
*
* @param boolean $runValidation whether to perform validation (calling [[Model::validate()|validate()]])
* @param bool $runValidation whether to perform validation (calling [[Model::validate()|validate()]])
* before saving the record. Defaults to `true`. If the validation fails, the record
* will not be saved to the database and this method will return `false`.
* @param array $attributes list of attributes that need to be saved. Defaults to `null`,
* meaning all attributes that are loaded from DB will be saved.
* @return boolean whether the attributes are valid and the record is inserted successfully.
* @return bool whether the attributes are valid and the record is inserted successfully.
*/
public function insert($runValidation = true, $attributes = null);
@ -318,12 +318,12 @@ interface ActiveRecordInterface
* $customer->update();
* ```
*
* @param boolean $runValidation whether to perform validation (calling [[Model::validate()|validate()]])
* @param bool $runValidation whether to perform validation (calling [[Model::validate()|validate()]])
* before saving the record. Defaults to `true`. If the validation fails, the record
* will not be saved to the database and this method will return `false`.
* @param array $attributeNames list of attributes that need to be saved. Defaults to `null`,
* meaning all attributes that are loaded from DB will be saved.
* @return integer|boolean the number of rows affected, or `false` if validation fails
* @return int|bool the number of rows affected, or `false` if validation fails
* or updating process is stopped for other reasons.
* Note that it is possible that the number of rows affected is 0, even though the
* update execution is successful.
@ -333,14 +333,14 @@ interface ActiveRecordInterface
/**
* Deletes the record from the database.
*
* @return integer|boolean the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
* @return int|bool the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
* Note that it is possible that the number of rows deleted is 0, even though the deletion execution is successful.
*/
public function delete();
/**
* Returns a value indicating whether the current record is new (not saved in the database).
* @return boolean whether the record is new and should be inserted when calling [[save()]].
* @return bool whether the record is new and should be inserted when calling [[save()]].
*/
public function getIsNewRecord();
@ -348,7 +348,7 @@ interface ActiveRecordInterface
* Returns a value indicating whether the given active record is the same as the current one.
* Two [[getIsNewRecord()|new]] records are considered to be not equal.
* @param static $record record to compare to
* @return boolean whether the two active records refer to the same row in the same database table.
* @return bool whether the two active records refer to the same row in the same database table.
*/
public function equals($record);
@ -358,7 +358,7 @@ interface ActiveRecordInterface
* (normally this would be a relational [[ActiveQuery]] object).
* It can be declared in either the ActiveRecord class itself or one of its behaviors.
* @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
* @param boolean $throwException whether to throw exception if the relation does not exist.
* @param bool $throwException whether to throw exception if the relation does not exist.
* @return ActiveQueryInterface the relational query object
*/
public function getRelation($name, $throwException = true);
@ -400,7 +400,7 @@ interface ActiveRecordInterface
*
* @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
* @param static $model the model to be unlinked from the current one.
* @param boolean $delete whether to delete the model that contains the foreign key.
* @param bool $delete whether to delete the model that contains the foreign key.
* If false, the model's foreign key will be set `null` and saved.
* If true, the model containing the foreign key will be deleted.
*/

4
framework/db/ActiveRelationTrait.php

@ -24,7 +24,7 @@ use yii\base\InvalidParamException;
trait ActiveRelationTrait
{
/**
* @var boolean whether this query represents a relation to more than one record.
* @var bool whether this query represents a relation to more than one record.
* This property is only used in relational context. If true, this relation will
* populate all query results into AR instances using [[Query::all()|all()]].
* If false, only the first row of the results will be retrieved using [[Query::one()|one()]].
@ -347,7 +347,7 @@ trait ActiveRelationTrait
* @param array $link
* @param array $viaModels
* @param array $viaLink
* @param boolean $checkMultiple
* @param bool $checkMultiple
* @return array
*/
private function buildBuckets($models, $link, $viaModels = null, $viaLink = null, $checkMultiple = true)

64
framework/db/BaseActiveRecord.php

@ -24,7 +24,7 @@ use yii\helpers\ArrayHelper;
*
* @property array $dirtyAttributes The changed attribute values (name-value pairs). This property is
* read-only.
* @property boolean $isNewRecord Whether the record is new and should be inserted when calling [[save()]].
* @property bool $isNewRecord Whether the record is new and should be inserted when calling [[save()]].
* @property array $oldAttributes The old attribute values (name-value pairs). Note that the type of this
* property differs in getter and setter. See [[getOldAttributes()]] and [[setOldAttributes()]] for details.
* @property mixed $oldPrimaryKey The old primary key value. An array (column name => column value) is
@ -152,7 +152,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* @param array $attributes attribute values (name-value pairs) to be saved into the table
* @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
* Please refer to [[Query::where()]] on how to specify this parameter.
* @return integer the number of rows updated
* @return int the number of rows updated
* @throws NotSupportedException if not overridden
*/
public static function updateAll($attributes, $condition = '')
@ -172,7 +172,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* Use negative values if you want to decrement the counters.
* @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
* Please refer to [[Query::where()]] on how to specify this parameter.
* @return integer the number of rows updated
* @return int the number of rows updated
* @throws NotSupportedException if not overrided
*/
public static function updateAllCounters($counters, $condition = '')
@ -193,7 +193,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* @param string|array $condition the conditions that will be put in the WHERE part of the DELETE SQL.
* Please refer to [[Query::where()]] on how to specify this parameter.
* @param array $params the parameters (name => value) to be bound to the query.
* @return integer the number of rows deleted
* @return int the number of rows deleted
* @throws NotSupportedException if not overrided
*/
public static function deleteAll($condition = '', $params = [])
@ -311,7 +311,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* Checks if a property value is null.
* This method overrides the parent implementation by checking if the named attribute is `null` or not.
* @param string $name the property name or the event name
* @return boolean whether the property value is null
* @return bool whether the property value is null
*/
public function __isset($name)
{
@ -436,7 +436,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
/**
* Check whether the named relation has been populated with records.
* @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
* @return boolean whether relation has been populated with records.
* @return bool whether relation has been populated with records.
* @see getRelation()
*/
public function isRelationPopulated($name)
@ -457,7 +457,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
/**
* Returns a value indicating whether the model has an attribute with the specified name.
* @param string $name the name of the attribute
* @return boolean whether the model has an attribute with the specified name.
* @return bool whether the model has an attribute with the specified name.
*/
public function hasAttribute($name)
{
@ -557,10 +557,10 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
/**
* Returns a value indicating whether the named attribute has been changed.
* @param string $name the name of the attribute.
* @param boolean $identical whether the comparison of new and old value is made for
* @param bool $identical whether the comparison of new and old value is made for
* identical values using `===`, defaults to `true`. Otherwise `==` is used for comparison.
* This parameter is available since version 2.0.4.
* @return boolean whether the attribute has been changed
* @return bool whether the attribute has been changed
*/
public function isAttributeChanged($name, $identical = true)
{
@ -622,12 +622,12 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* $customer->save();
* ```
*
* @param boolean $runValidation whether to perform validation (calling [[validate()]])
* @param bool $runValidation whether to perform validation (calling [[validate()]])
* before saving the record. Defaults to `true`. If the validation fails, the record
* will not be saved to the database and this method will return `false`.
* @param array $attributeNames list of attribute names that need to be saved. Defaults to null,
* meaning all attributes that are loaded from DB will be saved.
* @return boolean whether the saving succeeded (i.e. no validation errors occurred).
* @return bool whether the saving succeeded (i.e. no validation errors occurred).
*/
public function save($runValidation = true, $attributeNames = null)
{
@ -679,12 +679,12 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* }
* ```
*
* @param boolean $runValidation whether to perform validation (calling [[validate()]])
* @param bool $runValidation whether to perform validation (calling [[validate()]])
* before saving the record. Defaults to `true`. If the validation fails, the record
* will not be saved to the database and this method will return `false`.
* @param array $attributeNames list of attribute names that need to be saved. Defaults to null,
* meaning all attributes that are loaded from DB will be saved.
* @return integer|false the number of rows affected, or `false` if validation fails
* @return int|false the number of rows affected, or `false` if validation fails
* or [[beforeSave()]] stops the updating process.
* @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
* being updated is outdated.
@ -711,7 +711,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* Note that this method will **not** perform data validation and will **not** trigger events.
*
* @param array $attributes the attributes (names or name-value pairs) to be updated
* @return integer the number of rows affected.
* @return int the number of rows affected.
*/
public function updateAttributes($attributes)
{
@ -742,7 +742,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
/**
* @see update()
* @param array $attributes attributes to update
* @return integer|false the number of rows affected, or false if [[beforeSave()]] stops the updating process.
* @return int|false the number of rows affected, or false if [[beforeSave()]] stops the updating process.
* @throws StaleObjectException
*/
protected function updateInternal($attributes = null)
@ -797,7 +797,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
*
* @param array $counters the counters to be updated (attribute name => increment value)
* Use negative values if you want to decrement the counters.
* @return boolean whether the saving is successful
* @return bool whether the saving is successful
* @see updateAllCounters()
*/
public function updateCounters($counters)
@ -830,7 +830,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
* will be raised by the corresponding methods.
*
* @return integer|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
* @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
* Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
* @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
* being deleted is outdated.
@ -860,7 +860,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
/**
* Returns a value indicating whether the current record is new.
* @return boolean whether the record is new and should be inserted when calling [[save()]].
* @return bool whether the record is new and should be inserted when calling [[save()]].
*/
public function getIsNewRecord()
{
@ -869,7 +869,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
/**
* Sets the value indicating whether the record is new.
* @param boolean $value whether the record is new and should be inserted when calling [[save()]].
* @param bool $value whether the record is new and should be inserted when calling [[save()]].
* @see getIsNewRecord()
*/
public function setIsNewRecord($value)
@ -919,9 +919,9 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* }
* ```
*
* @param boolean $insert whether this method called while inserting a record.
* @param bool $insert whether this method called while inserting a record.
* If `false`, it means the method is called while updating a record.
* @return boolean whether the insertion or updating should continue.
* @return bool whether the insertion or updating should continue.
* If `false`, the insertion or updating will be cancelled.
*/
public function beforeSave($insert)
@ -938,7 +938,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* or an [[EVENT_AFTER_UPDATE]] event if `$insert` is `false`. The event class used is [[AfterSaveEvent]].
* When overriding this method, make sure you call the parent implementation so that
* the event is triggered.
* @param boolean $insert whether this method called while inserting a record.
* @param bool $insert whether this method called while inserting a record.
* If `false`, it means the method is called while updating a record.
* @param array $changedAttributes The old values of attributes that had changed and were saved.
* You can use this parameter to take action based on the changes made for example send an email
@ -970,7 +970,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* }
* ```
*
* @return boolean whether the record should be deleted. Defaults to `true`.
* @return bool whether the record should be deleted. Defaults to `true`.
*/
public function beforeDelete()
{
@ -997,7 +997,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* If the refresh is successful, an [[EVENT_AFTER_REFRESH]] event will be triggered.
* This event is available since version 2.0.8.
*
* @return boolean whether the row still exists in the database. If `true`, the latest data
* @return bool whether the row still exists in the database. If `true`, the latest data
* will be populated to this active record. Otherwise, this record will remain unchanged.
*/
public function refresh()
@ -1034,7 +1034,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* The comparison is made by comparing the table names and the primary key values of the two active records.
* If one of the records [[isNewRecord|is new]] they are also considered not equal.
* @param ActiveRecordInterface $record record to compare to
* @return boolean whether the two active records refer to the same row in the same database table.
* @return bool whether the two active records refer to the same row in the same database table.
*/
public function equals($record)
{
@ -1047,7 +1047,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
/**
* Returns the primary key value(s).
* @param boolean $asArray whether to return the primary key value as an array. If `true`,
* @param bool $asArray whether to return the primary key value as an array. If `true`,
* the return value will be an array with column names as keys and column values as values.
* Note that for composite primary keys, an array will always be returned regardless of this parameter value.
* @property mixed The primary key value. An array (column name => column value) is returned if
@ -1077,7 +1077,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* This refers to the primary key value that is populated into the record
* after executing a find method (e.g. find(), findOne()).
* The value remains unchanged even if the primary key attribute is manually assigned with a different value.
* @param boolean $asArray whether to return the primary key value as an array. If `true`,
* @param bool $asArray whether to return the primary key value as an array. If `true`,
* the return value will be an array with column name as key and column value as value.
* If this is `false` (default), a scalar value will be returned for non-composite primary key.
* @property mixed The old primary key value. An array (column name => column value) is
@ -1155,7 +1155,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* Returns whether there is an element at the specified offset.
* This method is required by the interface [[\ArrayAccess]].
* @param mixed $offset the offset to check on
* @return boolean whether there is an element at the specified offset.
* @return bool whether there is an element at the specified offset.
*/
public function offsetExists($offset)
{
@ -1167,7 +1167,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* A relation is defined by a getter method which returns an [[ActiveQueryInterface]] object.
* It can be declared in either the Active Record class itself or one of its behaviors.
* @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
* @param boolean $throwException whether to throw exception if the relation does not exist.
* @param bool $throwException whether to throw exception if the relation does not exist.
* @return ActiveQueryInterface|ActiveQuery the relational query object. If the relation does not exist
* and `$throwException` is `false`, `null` will be returned.
* @throws InvalidParamException if the named relation does not exist.
@ -1316,7 +1316,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* @param ActiveRecordInterface $model the model to be unlinked from the current one.
* You have to make sure that the model is really related with the current model as this method
* does not check this.
* @param boolean $delete whether to delete the model that contains the foreign key.
* @param bool $delete whether to delete the model that contains the foreign key.
* If `false`, the model's foreign key will be set `null` and saved.
* If `true`, the model containing the foreign key will be deleted.
* @throws InvalidCallException if the models cannot be unlinked
@ -1414,7 +1414,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* Note that to destroy the relationship without removing records make sure your keys can be set to null
*
* @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
* @param boolean $delete whether to delete the model that contains the foreign key.
* @param bool $delete whether to delete the model that contains the foreign key.
*/
public function unlinkAll($name, $delete = false)
{
@ -1509,7 +1509,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
/**
* Returns a value indicating whether the given set of attributes represents the primary key for this model
* @param array $keys the set of attributes to check
* @return boolean whether the given set of attributes represents the primary key for this model
* @return bool whether the given set of attributes represents the primary key for this model
*/
public static function isPrimaryKey($keys)
{

10
framework/db/BatchQueryResult.php

@ -41,11 +41,11 @@ class BatchQueryResult extends Object implements \Iterator
*/
public $query;
/**
* @var integer the number of rows to be returned in each batch.
* @var int the number of rows to be returned in each batch.
*/
public $batchSize = 100;
/**
* @var boolean whether to return a single row during each iteration.
* @var bool whether to return a single row during each iteration.
* If false, a whole batch of rows will be returned in each iteration.
*/
public $each = false;
@ -63,7 +63,7 @@ class BatchQueryResult extends Object implements \Iterator
*/
private $_value;
/**
* @var string|integer the key for the current iteration
* @var string|int the key for the current iteration
*/
private $_key;
@ -150,7 +150,7 @@ class BatchQueryResult extends Object implements \Iterator
/**
* Returns the index of the current dataset.
* This method is required by the interface [[\Iterator]].
* @return integer the index of the current row.
* @return int the index of the current row.
*/
public function key()
{
@ -170,7 +170,7 @@ class BatchQueryResult extends Object implements \Iterator
/**
* Returns whether there is a valid dataset at the current position.
* This method is required by the interface [[\Iterator]].
* @return boolean whether there is a valid dataset at the current position.
* @return bool whether there is a valid dataset at the current position.
*/
public function valid()
{

14
framework/db/ColumnSchema.php

@ -22,7 +22,7 @@ class ColumnSchema extends Object
*/
public $name;
/**
* @var boolean whether this column can be null.
* @var bool whether this column can be null.
*/
public $allowNull;
/**
@ -49,27 +49,27 @@ class ColumnSchema extends Object
*/
public $enumValues;
/**
* @var integer display size of the column.
* @var int display size of the column.
*/
public $size;
/**
* @var integer precision of the column data, if it is numeric.
* @var int precision of the column data, if it is numeric.
*/
public $precision;
/**
* @var integer scale of the column data, if it is numeric.
* @var int scale of the column data, if it is numeric.
*/
public $scale;
/**
* @var boolean whether this column is a primary key
* @var bool whether this column is a primary key
*/
public $isPrimaryKey;
/**
* @var boolean whether this column is auto-incremental
* @var bool whether this column is auto-incremental
*/
public $autoIncrement = false;
/**
* @var boolean whether this column is unsigned. This is only meaningful
* @var bool whether this column is unsigned. This is only meaningful
* when [[type]] is `smallint`, `integer` or `bigint`.
*/
public $unsigned;

12
framework/db/ColumnSchemaBuilder.php

@ -34,18 +34,18 @@ class ColumnSchemaBuilder extends Object
*/
protected $type;
/**
* @var integer|string|array column size or precision definition. This is what goes into the parenthesis after
* @var int|string|array column size or precision definition. This is what goes into the parenthesis after
* the column type. This can be either a string, an integer or an array. If it is an array, the array values will
* be joined into a string separated by comma.
*/
protected $length;
/**
* @var boolean|null whether the column is or not nullable. If this is `true`, a `NOT NULL` constraint will be added.
* @var bool|null whether the column is or not nullable. If this is `true`, a `NOT NULL` constraint will be added.
* If this is `false`, a `NULL` constraint will be added.
*/
protected $isNotNull;
/**
* @var boolean whether the column values should be unique. If this is `true`, a `UNIQUE` constraint will be added.
* @var bool whether the column values should be unique. If this is `true`, a `UNIQUE` constraint will be added.
*/
protected $isUnique = false;
/**
@ -62,7 +62,7 @@ class ColumnSchemaBuilder extends Object
*/
protected $append;
/**
* @var boolean whether the column values should be unsigned. If this is `true`, an `UNSIGNED` keyword will be added.
* @var bool whether the column values should be unsigned. If this is `true`, an `UNSIGNED` keyword will be added.
* @since 2.0.7
*/
protected $isUnsigned = false;
@ -72,7 +72,7 @@ class ColumnSchemaBuilder extends Object
*/
protected $after;
/**
* @var boolean whether this column is to be inserted at the beginning of the table.
* @var bool whether this column is to be inserted at the beginning of the table.
* @since 2.0.8
*/
protected $isFirst;
@ -120,7 +120,7 @@ class ColumnSchemaBuilder extends Object
* Create a column schema builder instance giving the type and value precision.
*
* @param string $type type of the column. See [[$type]].
* @param integer|string|array $length length or precision of the column. See [[$length]].
* @param int|string|array $length length or precision of the column. See [[$length]].
* @param \yii\db\Connection $db the current database connection. See [[$db]].
* @param array $config name-value pairs that will be used to initialize the object properties
*/

30
framework/db/Command.php

@ -65,7 +65,7 @@ class Command extends Component
*/
public $pdoStatement;
/**
* @var integer the default fetch mode for this command.
* @var int the default fetch mode for this command.
* @see http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php
*/
public $fetchMode = \PDO::FETCH_ASSOC;
@ -76,7 +76,7 @@ class Command extends Component
*/
public $params = [];
/**
* @var integer the default number of seconds that query results can remain valid in cache.
* @var int the default number of seconds that query results can remain valid in cache.
* Use 0 to indicate that the cached data will never expire. And use a negative number to indicate
* query cache should not be used.
* @see cache()
@ -104,7 +104,7 @@ class Command extends Component
/**
* Enables query cache for this command.
* @param integer $duration the number of seconds that query result of this command can remain valid in the cache.
* @param int $duration the number of seconds that query result of this command can remain valid in the cache.
* If this is not set, the value of [[Connection::queryCacheDuration]] will be used instead.
* Use 0 to indicate that the cached data will never expire.
* @param \yii\caching\Dependency $dependency the cache dependency associated with the cached query result.
@ -198,7 +198,7 @@ class Command extends Component
* this may improve performance.
* For SQL statement with binding parameters, this method is invoked
* automatically.
* @param boolean $forRead whether this method is called for a read query. If null, it means
* @param bool $forRead whether this method is called for a read query. If null, it means
* the SQL statement should be used to determine whether it is for read or write.
* @throws Exception if there is any DB error
*/
@ -242,13 +242,13 @@ class Command extends Component
/**
* Binds a parameter to the SQL statement to be executed.
* @param string|integer $name parameter identifier. For a prepared statement
* @param string|int $name parameter identifier. For a prepared statement
* using named placeholders, this will be a parameter name of
* the form `:name`. For a prepared statement using question mark
* placeholders, this will be the 1-indexed position of the parameter.
* @param mixed $value the PHP variable to bind to the SQL statement parameter (passed by reference)
* @param integer $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
* @param integer $length length of the data type
* @param int $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
* @param int $length length of the data type
* @param mixed $driverOptions the driver-specific options
* @return $this the current command being executed
* @see http://www.php.net/manual/en/function.PDOStatement-bindParam.php
@ -286,12 +286,12 @@ class Command extends Component
/**
* Binds a value to a parameter.
* @param string|integer $name Parameter identifier. For a prepared statement
* @param string|int $name Parameter identifier. For a prepared statement
* using named placeholders, this will be a parameter name of
* the form `:name`. For a prepared statement using question mark
* placeholders, this will be the 1-indexed position of the parameter.
* @param mixed $value The value to bind to the parameter
* @param integer $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
* @param int $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
* @return $this the current command being executed
* @see http://www.php.net/manual/en/function.PDOStatement-bindValue.php
*/
@ -351,7 +351,7 @@ class Command extends Component
/**
* Executes the SQL statement and returns ALL rows at once.
* @param integer $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
* @param int $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
* for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
* @return array all rows of the query result. Each array element is an array representing a row of data.
* An empty array is returned if the query results in nothing.
@ -365,7 +365,7 @@ class Command extends Component
/**
* Executes the SQL statement and returns the first row of the result.
* This method is best used when only the first row of result is needed for a query.
* @param integer $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
* @param int $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
* for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
* @return array|false the first row (in terms of an array) of the query result. False is returned if the query
* results in nothing.
@ -700,7 +700,7 @@ class Command extends Component
* @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
* @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, please separate them
* by commas. The column names will be properly quoted by the method.
* @param boolean $unique whether to add UNIQUE constraint on the created index.
* @param bool $unique whether to add UNIQUE constraint on the created index.
* @return $this the command object itself
*/
public function createIndex($name, $table, $columns, $unique = false)
@ -742,7 +742,7 @@ class Command extends Component
/**
* Builds a SQL command for enabling or disabling integrity check.
* @param boolean $check whether to turn on or off the integrity check.
* @param bool $check whether to turn on or off the integrity check.
* @param string $schema the schema name of the tables. Defaults to empty string, meaning the current
* or default schema.
* @param string $table the table name.
@ -820,7 +820,7 @@ class Command extends Component
* Executes the SQL statement.
* This method should only be used for executing non-query SQL statement, such as `INSERT`, `DELETE`, `UPDATE` SQLs.
* No result set will be returned.
* @return integer number of rows affected by the execution.
* @return int number of rows affected by the execution.
* @throws Exception execution failed
*/
public function execute()
@ -858,7 +858,7 @@ class Command extends Component
/**
* Performs the actual DB query of a SQL statement.
* @param string $method method of PDOStatement to be called
* @param integer $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
* @param int $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
* for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
* @return mixed the method execution result
* @throws Exception if the query causes any problem

30
framework/db/Connection.php

@ -111,7 +111,7 @@ use yii\caching\Cache;
* ```
*
* @property string $driverName Name of the DB driver.
* @property boolean $isActive Whether the DB connection is established. This property is read-only.
* @property bool $isActive Whether the DB connection is established. This property is read-only.
* @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the
* sequence object. This property is read-only.
* @property PDO $masterPdo The PDO instance for the currently active master connection. This property is
@ -184,7 +184,7 @@ class Connection extends Component
*/
public $pdo;
/**
* @var boolean whether to enable schema caching.
* @var bool whether to enable schema caching.
* Note that in order to enable truly schema caching, a valid cache component as specified
* by [[schemaCache]] must be enabled and [[enableSchemaCache]] must be set true.
* @see schemaCacheDuration
@ -193,7 +193,7 @@ class Connection extends Component
*/
public $enableSchemaCache = false;
/**
* @var integer number of seconds that table metadata can remain valid in cache.
* @var int number of seconds that table metadata can remain valid in cache.
* Use 0 to indicate that the cached data will never expire.
* @see enableSchemaCache
*/
@ -211,7 +211,7 @@ class Connection extends Component
*/
public $schemaCache = 'cache';
/**
* @var boolean whether to enable query caching.
* @var bool whether to enable query caching.
* Note that in order to enable query caching, a valid cache component as specified
* by [[queryCache]] must be enabled and [[enableQueryCache]] must be set true.
* Also, only the results of the queries enclosed within [[cache()]] will be cached.
@ -221,7 +221,7 @@ class Connection extends Component
*/
public $enableQueryCache = true;
/**
* @var integer the default number of seconds that query results can remain valid in cache.
* @var int the default number of seconds that query results can remain valid in cache.
* Defaults to 3600, meaning 3600 seconds, or one hour. Use 0 to indicate that the cached data will never expire.
* The value of this property will be used when [[cache()]] is called without a cache duration.
* @see enableQueryCache
@ -247,7 +247,7 @@ class Connection extends Component
*/
public $charset;
/**
* @var boolean whether to turn on prepare emulation. Defaults to false, meaning PDO
* @var bool whether to turn on prepare emulation. Defaults to false, meaning PDO
* will use the native prepare support if available. For some databases (such as MySQL),
* this may need to be set true so that PDO can emulate the prepare support to bypass
* the buggy native prepare support.
@ -295,7 +295,7 @@ class Connection extends Component
*/
public $commandClass = 'yii\db\Command';
/**
* @var boolean whether to enable [savepoint](http://en.wikipedia.org/wiki/Savepoint).
* @var bool whether to enable [savepoint](http://en.wikipedia.org/wiki/Savepoint).
* Note that if the underlying DBMS does not support savepoint, setting this property to be true will have no effect.
*/
public $enableSavepoint = true;
@ -306,12 +306,12 @@ class Connection extends Component
*/
public $serverStatusCache = 'cache';
/**
* @var integer the retry interval in seconds for dead servers listed in [[masters]] and [[slaves]].
* @var int the retry interval in seconds for dead servers listed in [[masters]] and [[slaves]].
* This is used together with [[serverStatusCache]].
*/
public $serverRetryInterval = 600;
/**
* @var boolean whether to enable read/write splitting by using [[slaves]] to read data.
* @var bool whether to enable read/write splitting by using [[slaves]] to read data.
* Note that if [[slaves]] is empty, read/write splitting will NOT be enabled no matter what value this property takes.
*/
public $enableSlaves = true;
@ -389,7 +389,7 @@ class Connection extends Component
/**
* Returns a value indicating whether the DB connection is established.
* @return boolean whether the DB connection is established
* @return bool whether the DB connection is established
*/
public function getIsActive()
{
@ -415,7 +415,7 @@ class Connection extends Component
*
* @param callable $callable a PHP callable that contains DB queries which will make use of query cache.
* The signature of the callable is `function (Connection $db)`.
* @param integer $duration the number of seconds that query results can remain valid in the cache. If this is
* @param int $duration the number of seconds that query results can remain valid in the cache. If this is
* not set, the value of [[queryCacheDuration]] will be used instead.
* Use 0 to indicate that the cached data will never expire.
* @param \yii\caching\Dependency $dependency the cache dependency associated with the cached query results.
@ -478,7 +478,7 @@ class Connection extends Component
/**
* Returns the current query cache information.
* This method is used internally by [[Command]].
* @param integer $duration the preferred caching duration. If null, it will be ignored.
* @param int $duration the preferred caching duration. If null, it will be ignored.
* @param \yii\caching\Dependency $dependency the preferred caching dependency. If null, it will be ignored.
* @return array the current query cache information, or null if query cache is not enabled.
* @internal
@ -728,7 +728,7 @@ class Connection extends Component
/**
* Obtains the schema information for the named table.
* @param string $name table name.
* @param boolean $refresh whether to reload the table schema even if it is found in the cache.
* @param bool $refresh whether to reload the table schema even if it is found in the cache.
* @return TableSchema table schema information. Null if the named table does not exist.
*/
public function getTableSchema($name, $refresh = false)
@ -839,7 +839,7 @@ class Connection extends Component
* Returns the PDO instance for the currently active slave connection.
* When [[enableSlaves]] is true, one of the slaves will be used for read queries, and its PDO instance
* will be returned by this method.
* @param boolean $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
* @param bool $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
* @return PDO the PDO instance for the currently active slave connection. Null is returned if no slave connection
* is available and `$fallbackToMaster` is false.
*/
@ -867,7 +867,7 @@ class Connection extends Component
/**
* Returns the currently active slave connection.
* If this method is called the first time, it will try to open a slave connection when [[enableSlaves]] is true.
* @param boolean $fallbackToMaster whether to return a master connection in case there is no slave connection available.
* @param bool $fallbackToMaster whether to return a master connection in case there is no slave connection available.
* @return Connection the currently active slave connection. Null is returned if there is slave available and
* `$fallbackToMaster` is false.
*/

30
framework/db/DataReader.php

@ -40,10 +40,10 @@ use yii\base\InvalidCallException;
* [[fetchMode]]. See the [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
* for more details about possible fetch mode.
*
* @property integer $columnCount The number of columns in the result set. This property is read-only.
* @property integer $fetchMode Fetch mode. This property is write-only.
* @property boolean $isClosed Whether the reader is closed or not. This property is read-only.
* @property integer $rowCount Number of rows contained in the result. This property is read-only.
* @property int $columnCount The number of columns in the result set. This property is read-only.
* @property int $fetchMode Fetch mode. This property is write-only.
* @property bool $isClosed Whether the reader is closed or not. This property is read-only.
* @property int $rowCount Number of rows contained in the result. This property is read-only.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
@ -75,11 +75,11 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable
* Binds a column to a PHP variable.
* When rows of data are being fetched, the corresponding column value
* will be set in the variable. Note, the fetch mode must include PDO::FETCH_BOUND.
* @param integer|string $column Number of the column (1-indexed) or name of the column
* @param int|string $column Number of the column (1-indexed) or name of the column
* in the result set. If using the column name, be aware that the name
* should match the case of the column, as returned by the driver.
* @param mixed $value Name of the PHP variable to which the column will be bound.
* @param integer $dataType Data type of the parameter
* @param int $dataType Data type of the parameter
* @see http://www.php.net/manual/en/function.PDOStatement-bindColumn.php
*/
public function bindColumn($column, &$value, $dataType = null)
@ -93,7 +93,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable
/**
* Set the default fetch mode for this statement
* @param integer $mode fetch mode
* @param int $mode fetch mode
* @see http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php
*/
public function setFetchMode($mode)
@ -113,7 +113,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable
/**
* Returns a single column from the next row of a result set.
* @param integer $columnIndex zero-based column index
* @param int $columnIndex zero-based column index
* @return mixed the column of the current row, false if no more rows available
*/
public function readColumn($columnIndex)
@ -146,7 +146,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable
* Advances the reader to the next result when reading the results of a batch of statements.
* This method is only useful when there are multiple result sets
* returned by the query. Not all DBMS support this feature.
* @return boolean Returns true on success or false on failure.
* @return bool Returns true on success or false on failure.
*/
public function nextResult()
{
@ -170,7 +170,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable
/**
* whether the reader is closed or not.
* @return boolean whether the reader is closed or not.
* @return bool whether the reader is closed or not.
*/
public function getIsClosed()
{
@ -181,7 +181,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable
* Returns the number of rows in the result set.
* Note, most DBMS may not give a meaningful count.
* In this case, use "SELECT COUNT(*) FROM tableName" to obtain the number of rows.
* @return integer number of rows contained in the result.
* @return int number of rows contained in the result.
*/
public function getRowCount()
{
@ -193,7 +193,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable
* This method is required by the Countable interface.
* Note, most DBMS may not give a meaningful count.
* In this case, use "SELECT COUNT(*) FROM tableName" to obtain the number of rows.
* @return integer number of rows contained in the result.
* @return int number of rows contained in the result.
*/
public function count()
{
@ -203,7 +203,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable
/**
* Returns the number of columns in the result set.
* Note, even there's no row in the reader, this still gives correct column number.
* @return integer the number of columns in the result set.
* @return int the number of columns in the result set.
*/
public function getColumnCount()
{
@ -228,7 +228,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable
/**
* Returns the index of the current row.
* This method is required by the interface [[\Iterator]].
* @return integer the index of the current row.
* @return int the index of the current row.
*/
public function key()
{
@ -258,7 +258,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable
/**
* Returns whether there is a row of data at current position.
* This method is required by the interface [[\Iterator]].
* @return boolean whether there is a row of data at current position.
* @return bool whether there is a row of data at current position.
*/
public function valid()
{

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

Loading…
Cancel
Save