diff --git a/build/controllers/PhpDocController.php b/build/controllers/PhpDocController.php index 5e9628250ca..9aedda1a47d 100644 --- a/build/controllers/PhpDocController.php +++ b/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; diff --git a/docs/guide-es/caching-http.md b/docs/guide-es/caching-http.md index 7ea1bfbbfc2..92806124668 100644 --- a/docs/guide-es/caching-http.md +++ b/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) ``` diff --git a/docs/guide-es/input-validation.md b/docs/guide-es/input-validation.md index 2862d2c7c92..a64abefa88f 100644 --- a/docs/guide-es/input-validation.md +++ b/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()`. diff --git a/docs/guide-es/security-authorization.md b/docs/guide-es/security-authorization.md index c80aa5bc9f8..669912fc300 100644 --- a/docs/guide-es/security-authorization.md +++ b/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 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) { diff --git a/docs/guide-fr/input-validation.md b/docs/guide-fr/input-validation.md index f04d986333f..6e59fbfedeb 100644 --- a/docs/guide-fr/input-validation.md +++ b/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 -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 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 -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 @@ -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 -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 -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 @@ -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 -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 @@ -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 : diff --git a/docs/guide-fr/security-authentication.md b/docs/guide-fr/security-authentication.md index 7f02cc35276..964f947e7be 100644 --- a/docs/guide-fr/security-authentication.md +++ b/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]] -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 -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`. diff --git a/docs/guide-fr/security-authorization.md b/docs/guide-fr/security-authorization.md index 8c02a9d1c51..609ebe7183b 100644 --- a/docs/guide-fr/security-authorization.md +++ b/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 @@ -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 -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 -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 -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` @@ -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` @@ -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 -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. diff --git a/docs/guide-ja/caching-http.md b/docs/guide-ja/caching-http.md index bba0d1472d1..47f6415f856 100644 --- a/docs/guide-ja/caching-http.md +++ b/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) ``` diff --git a/docs/guide-ja/input-validation.md b/docs/guide-ja/input-validation.md index fafdc57ed04..017281bb0f4 100644 --- a/docs/guide-ja/input-validation.md +++ b/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) ``` diff --git a/docs/guide-ja/security-authentication.md b/docs/guide-ja/security-authentication.md index 713531e3724..0693b1807ce 100644 --- a/docs/guide-ja/security-authentication.md +++ b/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)) { diff --git a/docs/guide-ja/security-authorization.md b/docs/guide-ja/security-authorization.md index 12953e76de0..340e4536e36 100644 --- a/docs/guide-ja/security-authorization.md +++ b/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) { diff --git a/docs/guide-pl/caching-http.md b/docs/guide-pl/caching-http.md index 2c6fc7007f6..0e5440192b0 100644 --- a/docs/guide-pl/caching-http.md +++ b/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` -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` -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` -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 -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 -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ć. diff --git a/docs/guide-pl/input-validation.md b/docs/guide-pl/input-validation.md index a3e8ccb2b19..f1514d73422 100644 --- a/docs/guide-pl/input-validation.md +++ b/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 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 -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" -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 -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 -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 -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 ``` -"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 -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. diff --git a/docs/guide-pt-BR/caching-http.md b/docs/guide-pt-BR/caching-http.md index 9b7314a2eb5..365883a9792 100644 --- a/docs/guide-pt-BR/caching-http.md +++ b/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 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 -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. diff --git a/docs/guide-pt-BR/security-authentication.md b/docs/guide-pt-BR/security-authentication.md index e55d987efe2..3a8fdb95857 100644 --- a/docs/guide-pt-BR/security-authentication.md +++ b/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]] -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`. diff --git a/docs/guide-pt-BR/security-authorization.md b/docs/guide-pt-BR/security-authorization.md index 00f29619da9..721aaf4552e 100644 --- a/docs/guide-pt-BR/security-authorization.md +++ b/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) { diff --git a/docs/guide-ru/caching-http.md b/docs/guide-ru/caching-http.md index 0c124b7c3b5..26277d17be0 100644 --- a/docs/guide-ru/caching-http.md +++ b/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), diff --git a/docs/guide-ru/input-validation.md b/docs/guide-ru/input-validation.md index 206f96c53ae..675b451f289 100644 --- a/docs/guide-ru/input-validation.md +++ b/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) ### Фильтрация данных Пользователь часто вводит данные которые нужно предварительно отфильтровать или предварительно обработать(очистить). -Например, вы хотите обрезать пробелы вокруг `username`. Вы можете использовать правила валидации для +Например, вы хотите обрезать пробелы вокруг `username`. Вы можете использовать правила валидации для достижения этой цели. В следующих примерах показано, как обрезать пробелы в входных данных и превратить пустые входные данные в `NULL` @@ -206,8 +206,8 @@ return [ ### Обработка пустых входных данных -Если входные данные представлены из 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) ## Создание Валидаторов -Кроме того, используя [основные валидаторы](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()`. ## Валидация на стороне клиента -Проверка на стороне клиента на основе JavaScript целесообразна, когда конечные пользователи вводят -входные данные через HTML-формы, так как эта проверка позволяет пользователям узнать, ошибки ввода -быстрее, и таким образом улучшает ваш пользовательский интерфейс. Вы можете использовать или +Проверка на стороне клиента на основе JavaScript целесообразна, когда конечные пользователи вводят +входные данные через HTML-формы, так как эта проверка позволяет пользователям узнать, ошибки ввода +быстрее, и таким образом улучшает ваш пользовательский интерфейс. Вы можете использовать или реализовать валидатор, который поддерживает валидацию на стороне клиента *в дополнение* к проверке на стороне сервера. > Info: Проверка на стороне клиента желательна, но необязательна. Её основная цель заключается в -предоставлении пользователям более удобного интерфейса. Так как входные данные, поступают от конечных -пользователей, вы никогда не должны доверять верификации на стороне клиента. По этой причине, вы всегда -должны выполнять верификацию на стороне сервера путем вызова [[yii\base\Model::validate()]], +предоставлении пользователям более удобного интерфейса. Так как входные данные, поступают от конечных +пользователей, вы никогда не должны доверять верификации на стороне клиента. По этой причине, вы всегда +должны выполнять верификацию на стороне сервера путем вызова [[yii\base\Model::validate()]], как описано в предыдущих пунктах. @@ -477,21 +477,21 @@ HTML-форма построена с помощью следующего код ``` -Класс [[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`. ### Реализация проверки на стороне клиента -Чтобы создать валидатор, который поддерживает проверку на стороне клиента, вы должны реализовать метод -[[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; ### Отложенная валидация -Если Вам необходимо выполнить асинхронную проверку на стороне клиента, вы можете создавать -[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 валидация Некоторые проверки можно сделать только на стороне сервера, потому что только сервер имеет необходимую информацию. -Например, чтобы проверить логин пользователя на уникальность, необходимо проверить логин в +Например, чтобы проверить логин пользователя на уникальность, необходимо проверить логин в базе данных на стороне сервера. Вы можете использовать проверку на основе 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 валидации. diff --git a/docs/guide-ru/security-authentication.md b/docs/guide-ru/security-authentication.md index db060ee0654..a78cf9b8dcc 100644 --- a/docs/guide-ru/security-authentication.md +++ b/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]] Компонент [[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]]: вызывается после успешного выхода. Вы можете использовать эти события для реализации функции аудита входа, сбора статистики онлайн пользователей. Например, diff --git a/docs/guide-ru/security-authorization.md b/docs/guide-ru/security-authorization.md index f4994ac4ed1..51a2ae13389 100644 --- a/docs/guide-ru/security-authorization.md +++ b/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]]: diff --git a/docs/guide-zh-CN/caching-http.md b/docs/guide-zh-CN/caching-http.md index 29b64978065..c2114548fa0 100644 --- a/docs/guide-zh-CN/caching-http.md +++ b/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) ``` diff --git a/docs/guide-zh-CN/input-validation.md b/docs/guide-zh-CN/input-validation.md index 46d7c8fae9e..db96ec7a8b4 100644 --- a/docs/guide-zh-CN/input-validation.md +++ b/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) ``` diff --git a/docs/guide/caching-http.md b/docs/guide/caching-http.md index 31c6b57915a..41137e64df2 100644 --- a/docs/guide/caching-http.md +++ b/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) ``` diff --git a/docs/guide/input-validation.md b/docs/guide/input-validation.md index 8eb984e197f..33569a63d35 100644 --- a/docs/guide/input-validation.md +++ b/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) ``` diff --git a/docs/guide/security-authentication.md b/docs/guide/security-authentication.md index afc9b275ed9..4c7790b919b 100644 --- a/docs/guide/security-authentication.md +++ b/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]] -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]] -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 -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, diff --git a/docs/guide/security-authorization.md b/docs/guide/security-authorization.md index e088156981c..c37576df041 100644 --- a/docs/guide/security-authorization.md +++ b/docs/guide/security-authorization.md @@ -8,9 +8,9 @@ methods: Access Control Filter (ACF) and Role-Based Access Control (RBAC). ## Access Control Filter 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. diff --git a/docs/internals-ja/core-code-style.md b/docs/internals-ja/core-code-style.md index ba1dc835056..45cd5531493 100644 --- a/docs/internals-ja/core-code-style.md +++ b/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; diff --git a/docs/internals-pl/core-code-style.md b/docs/internals-pl/core-code-style.md index a5dd07c1dc7..a4d60404fa3 100644 --- a/docs/internals-pl/core-code-style.md +++ b/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 `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 diff --git a/docs/internals-ru/core-code-style.md b/docs/internals-ru/core-code-style.md index c0646711de1..02b4bdf9f80 100644 --- a/docs/internals-ru/core-code-style.md +++ b/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. diff --git a/docs/internals-uk/core-code-style.md b/docs/internals-uk/core-code-style.md index 6f3a696614c..6899339b992 100644 --- a/docs/internals-uk/core-code-style.md +++ b/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 Конструктори diff --git a/docs/internals/core-code-style.md b/docs/internals/core-code-style.md index 0d449a3226a..c0b80147365 100644 --- a/docs/internals/core-code-style.md +++ b/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) { // ... } diff --git a/framework/BaseYii.php b/framework/BaseYii.php index 21dcaef11a5..1f199908109 100644 --- a/framework/BaseYii.php +++ b/framework/BaseYii.php @@ -120,9 +120,9 @@ public static function getVersion() * 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 @@ public static function getAlias($alias, $throwException = true) * 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) { diff --git a/framework/base/Action.php b/framework/base/Action.php index ea9d1742efb..9dc7063cc33 100644 --- a/framework/base/Action.php +++ b/framework/base/Action.php @@ -105,7 +105,7 @@ public function runWithParams($params) * 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() { diff --git a/framework/base/ActionEvent.php b/framework/base/ActionEvent.php index 897572b18a0..54a9f6ef640 100644 --- a/framework/base/ActionEvent.php +++ b/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. */ diff --git a/framework/base/ActionFilter.php b/framework/base/ActionFilter.php index d3ba46ef6a2..f66dd9fe842 100644 --- a/framework/base/ActionFilter.php +++ b/framework/base/ActionFilter.php @@ -95,7 +95,7 @@ public function afterFilter($event) * 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 @@ protected function getActionId($action) /** * 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) { diff --git a/framework/base/Application.php b/framework/base/Application.php index 70546819333..f31bfd1d27a 100644 --- a/framework/base/Application.php +++ b/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 @@ public function setBasePath($path) /** * 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 @@ public function coreComponents() * 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 */ diff --git a/framework/base/ArrayAccessTrait.php b/framework/base/ArrayAccessTrait.php index 43a229ab8bd..87a1db1d61c 100644 --- a/framework/base/ArrayAccessTrait.php +++ b/framework/base/ArrayAccessTrait.php @@ -34,7 +34,7 @@ public function getIterator() /** * 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 @@ public function count() /** * 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 @@ public function offsetExists($offset) /** * 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 @@ public function offsetGet($offset) /** * 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) diff --git a/framework/base/Arrayable.php b/framework/base/Arrayable.php index 92572a0c2f3..97dabf4ad88 100644 --- a/framework/base/Arrayable.php +++ b/framework/base/Arrayable.php @@ -85,7 +85,7 @@ public function extraFields(); * @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); diff --git a/framework/base/ArrayableTrait.php b/framework/base/ArrayableTrait.php index 308feeea1be..7b41328da05 100644 --- a/framework/base/ArrayableTrait.php +++ b/framework/base/ArrayableTrait.php @@ -110,7 +110,7 @@ public function extraFields() * @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) diff --git a/framework/base/Component.php b/framework/base/Component.php index f44a8dbef89..9a4630954db 100644 --- a/framework/base/Component.php +++ b/framework/base/Component.php @@ -211,7 +211,7 @@ public function __set($name, $value) * 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 @@ public function __clone() * - 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 @@ public function hasProperty($name, $checkVars = true, $checkBehaviors = true) * - 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 @@ public function canGetProperty($name, $checkVars = true, $checkBehaviors = true) * - 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 @@ public function canSetProperty($name, $checkVars = true, $checkBehaviors = true) * - 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 @@ public function behaviors() /** * 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 @@ public function hasEventHandlers($name) * @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 @@ public function on($name, $handler, $data = null, $append = true) * @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 @@ public function ensureBehaviors() /** * 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 diff --git a/framework/base/Controller.php b/framework/base/Controller.php index 60924b02297..690c3cd3688 100644 --- a/framework/base/Controller.php +++ b/framework/base/Controller.php @@ -263,7 +263,7 @@ public function createAction($id) * ``` * * @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 @@ public function setViewPath($path) /** * 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. */ diff --git a/framework/base/ErrorException.php b/framework/base/ErrorException.php index c595b1fab05..acae4754c9e 100644 --- a/framework/base/ErrorException.php +++ b/framework/base/ErrorException.php @@ -78,7 +78,7 @@ public function __construct($message = '', $code = 0, $severity = 1, $filename = * 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) { diff --git a/framework/base/ErrorHandler.php b/framework/base/ErrorHandler.php index ab9a65b5ab8..ae6a0bfd53b 100644 --- a/framework/base/ErrorHandler.php +++ b/framework/base/ErrorHandler.php @@ -27,11 +27,11 @@ 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 @@ protected function handleFallbackExceptionMessage($exception, $previousException * 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 @@ public function handleHhvmError($code, $message, $file, $line, $context, $backtr * * 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 */ diff --git a/framework/base/Event.php b/framework/base/Event.php index 9f05acb71d9..498607abff9 100644 --- a/framework/base/Event.php +++ b/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 @@ public static function on($class, $name, $handler, $data = null, $append = true) * @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 @@ public static function offAll() * 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) { diff --git a/framework/base/ExitException.php b/framework/base/ExitException.php index e62f8dff7ca..9197b0f9aac 100644 --- a/framework/base/ExitException.php +++ b/framework/base/ExitException.php @@ -18,16 +18,16 @@ 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) diff --git a/framework/base/Model.php b/framework/base/Model.php index 8aecd7c4792..05fecdda7de 100644 --- a/framework/base/Model.php +++ b/framework/base/Model.php @@ -330,8 +330,8 @@ public function attributeHints() * @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 @@ public function validate($attributeNames = null, $clearErrors = true) * 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 @@ public function createValidators() * 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 @@ public function isAttributeRequired($attribute) /** * 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 @@ public function isAttributeSafe($attribute) /** * 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 @@ public function getAttributeHint($attribute) /** * 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 @@ public function getAttributes($names = null, $except = []) /** * 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 @@ public function activeAttributes() * @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 @@ public function load($data, $formName = null) * @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 @@ public static function loadMultiple($models, $data, $formName = null) * @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 @@ public function getIterator() * 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 @@ public function offsetGet($offset) * 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) diff --git a/framework/base/ModelEvent.php b/framework/base/ModelEvent.php index 421b9142185..fffcfe19994 100644 --- a/framework/base/ModelEvent.php +++ b/framework/base/ModelEvent.php @@ -16,7 +16,7 @@ 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; diff --git a/framework/base/Module.php b/framework/base/Module.php index 146dab4ddf7..bd347eaac24 100644 --- a/framework/base/Module.php +++ b/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 @@ public function setAliases($aliases) * 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 @@ public function hasModule($id) * 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 @@ public function setModule($id, $module) /** * 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 @@ public function runAction($route, $params = []) * 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 @@ public function createControllerByID($id) * ``` * * @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) { diff --git a/framework/base/Object.php b/framework/base/Object.php index 220ab3e1e3e..ff674b50465 100644 --- a/framework/base/Object.php +++ b/framework/base/Object.php @@ -170,7 +170,7 @@ public function __set($name, $value) * * 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 @@ public function __call($name, $params) * - 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 @@ public function hasProperty($name, $checkVars = true) * - 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 @@ public function canGetProperty($name, $checkVars = true) * - 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 @@ public function canSetProperty($name, $checkVars = true) * 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) { diff --git a/framework/base/Request.php b/framework/base/Request.php index 060dd46be16..eaae73b6b21 100644 --- a/framework/base/Request.php +++ b/framework/base/Request.php @@ -14,7 +14,7 @@ * * 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 @@ -34,7 +34,7 @@ abstract public function resolve(); /** * 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 @@ public function getIsConsoleRequest() /** * 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) { diff --git a/framework/base/Response.php b/framework/base/Response.php index 5ed4228474c..2508319835c 100644 --- a/framework/base/Response.php +++ b/framework/base/Response.php @@ -18,7 +18,7 @@ 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; diff --git a/framework/base/Security.php b/framework/base/Security.php index c1eb2afa0ec..086f18164fe 100644 --- a/framework/base/Security.php +++ b/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 @@ public function encryptByKey($data, $inputKey, $info = null) * 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 @@ public function decryptByPassword($data, $password) * @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 @@ public function decryptByKey($data, $inputKey, $info = null) * 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 @@ protected function encrypt($data, $passwordBased, $secret, $info) * 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 @@ protected function decrypt($data, $passwordBased, $secret, $info) * @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 @@ public function hkdf($algo, $inputKey, $salt = null, $info = null, $length = 0) * @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 @@ public function pbkdf2($algo, $password, $salt, $iterations, $length = 0) * @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 @@ public function hashData($data, $key, $rawHash = false) * @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 @@ public function validateData($data, $key, $rawHash = false) * 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 @@ public function generateRandomKey($length = 32) * 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 @@ public function generateRandomString($length = 32) * ``` * * @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 @@ public function generatePasswordHash($password, $cost = null) * 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 @@ public function validatePassword($password, $hash) * "$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 @@ protected function generateSalt($cost = 13) * @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) { diff --git a/framework/base/View.php b/framework/base/View.php index d779be7677f..4d3ff524fbe 100644 --- a/framework/base/View.php +++ b/framework/base/View.php @@ -20,7 +20,7 @@ * * 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 @@ -259,7 +259,7 @@ public function renderFile($viewFile, $params = [], $context = null) } /** - * @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 @@ public function getViewFile() * 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 @@ public function evaluateDynamicContent($statements) * 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 @@ public function endContent() * * @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 = []) diff --git a/framework/base/ViewEvent.php b/framework/base/ViewEvent.php index 38e2f8a0e04..a06fa0770d6 100644 --- a/framework/base/ViewEvent.php +++ b/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. */ diff --git a/framework/base/Widget.php b/framework/base/Widget.php index 2b68c3885f8..cb162b882f1 100644 --- a/framework/base/Widget.php +++ b/framework/base/Widget.php @@ -27,7 +27,7 @@ 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 @@ public static function widget($config = []) /** * 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) diff --git a/framework/behaviors/AttributeBehavior.php b/framework/behaviors/AttributeBehavior.php index aad6f829760..5a2cd94ddd6 100644 --- a/framework/behaviors/AttributeBehavior.php +++ b/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 */ diff --git a/framework/behaviors/AttributeTypecastBehavior.php b/framework/behaviors/AttributeTypecastBehavior.php index 4543664cf33..0090e74833f 100644 --- a/framework/behaviors/AttributeTypecastBehavior.php +++ b/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 @@ protected function typecastValue($value, $type) 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 @@ public function afterFind($event) { $this->typecastAttributes(); } -} \ No newline at end of file +} diff --git a/framework/behaviors/SluggableBehavior.php b/framework/behaviors/SluggableBehavior.php index b1f722ec3f8..453f4ce923b 100644 --- a/framework/behaviors/SluggableBehavior.php +++ b/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 @@ protected function getValue($event) * 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 @@ protected function makeUnique($slug) /** * 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 @@ protected function validateSlug($slug) /** * 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 */ diff --git a/framework/caching/ApcCache.php b/framework/caching/ApcCache.php index af9615fbb8e..7d1cc7b3135 100644 --- a/framework/caching/ApcCache.php +++ b/framework/caching/ApcCache.php @@ -26,7 +26,7 @@ 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 @@ public function init() * 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 @@ protected function getValues($keys) * @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 @@ protected function setValue($key, $value, $duration) /** * 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 @@ protected function setValues($data, $duration) * @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 @@ protected function addValue($key, $value, $duration) /** * 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 @@ protected function addValues($data, $duration) * 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 @@ protected function deleteValue($key) /** * 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() { diff --git a/framework/caching/Cache.php b/framework/caching/Cache.php index d4812d74a74..be069c6cec6 100644 --- a/framework/caching/Cache.php +++ b/framework/caching/Cache.php @@ -129,7 +129,7 @@ public function get($key) * 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 @@ public function multiGet($keys) * @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 @@ public function set($key, $value, $duration = 0, $dependency = null) * 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 @@ public function mset($items, $duration = 0, $dependency = null) * 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 @@ public function multiSet($items, $duration = 0, $dependency = null) * 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 @@ public function madd($items, $duration = 0, $dependency = null) * 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 @@ public function multiAdd($items, $duration = 0, $dependency = null) * @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 @@ public function add($key, $value, $duration = 0, $dependency = null) * 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 @@ public function delete($key) /** * 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 protected function getValue($key); * @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 protected function setValue($key, $value, $duration); * @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 protected function addValue($key, $value, $duration); * 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 @@ protected function getValues($keys) * 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 @@ protected function setValues($data, $duration) * 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 @@ protected function addValues($data, $duration) * 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) { diff --git a/framework/caching/ChainedDependency.php b/framework/caching/ChainedDependency.php index 4f7fcb810aa..28df4356919 100644 --- a/framework/caching/ChainedDependency.php +++ b/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 @@ protected function generateDependencyData($cache) * 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) { diff --git a/framework/caching/DbCache.php b/framework/caching/DbCache.php index 1af172c4f9d..cecc8d63600 100644 --- a/framework/caching/DbCache.php +++ b/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 @@ public function init() * 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 @@ protected function getValues($keys) * * @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 @@ protected function setValue($key, $value, $duration) * * @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 @@ protected function addValue($key, $value, $duration) * 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 @@ protected function deleteValue($key) /** * 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 @@ public function gc($force = false) /** * 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() { diff --git a/framework/caching/Dependency.php b/framework/caching/Dependency.php index 368e2bc1906..b9f653abc01 100644 --- a/framework/caching/Dependency.php +++ b/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 @@ public function evaluateDependency($cache) /** * 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) { diff --git a/framework/caching/DummyCache.php b/framework/caching/DummyCache.php index 802843c30c8..b8db22bc389 100644 --- a/framework/caching/DummyCache.php +++ b/framework/caching/DummyCache.php @@ -39,8 +39,8 @@ protected function getValue($key) * * @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 @@ protected function setValue($key, $value, $duration) * 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 @@ protected function addValue($key, $value, $duration) * 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 @@ protected function deleteValue($key) /** * 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() { diff --git a/framework/caching/FileCache.php b/framework/caching/FileCache.php index c25b6983f5e..7069fe40201 100644 --- a/framework/caching/FileCache.php +++ b/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 @@ public function init() * 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 @@ protected function getValue($key) * @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 @@ protected function setValue($key, $value, $duration) * @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 @@ protected function addValue($key, $value, $duration) * 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 @@ protected function getCacheFile($key) /** * 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 @@ protected function flushValues() /** * 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 @@ public function gc($force = false, $expiredOnly = true) * 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) diff --git a/framework/caching/MemCache.php b/framework/caching/MemCache.php index 42bc3de6e49..9521aaacb5e 100644 --- a/framework/caching/MemCache.php +++ b/framework/caching/MemCache.php @@ -66,7 +66,7 @@ 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 @@ protected function getValues($keys) * @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 @@ protected function setValue($key, $value, $duration) /** * 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 @@ protected function setValues($data, $duration) * @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 @@ protected function addValue($key, $value, $duration) * 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 @@ protected function deleteValue($key) /** * 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() { diff --git a/framework/caching/MemCacheServer.php b/framework/caching/MemCacheServer.php index 1cdbe4f3fe7..df8a3263ab3 100644 --- a/framework/caching/MemCacheServer.php +++ b/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; /** diff --git a/framework/caching/TagDependency.php b/framework/caching/TagDependency.php index c55b2492de9..7e9d79c46ac 100644 --- a/framework/caching/TagDependency.php +++ b/framework/caching/TagDependency.php @@ -60,7 +60,7 @@ protected function generateDependencyData($cache) /** * 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) { diff --git a/framework/caching/WinCache.php b/framework/caching/WinCache.php index e2ec265c658..4ac4deab61b 100644 --- a/framework/caching/WinCache.php +++ b/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 @@ public function exists($key) * 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 @@ protected function getValues($keys) * @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 @@ protected function setValue($key, $value, $duration) /** * 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 @@ protected function setValues($data, $duration) * @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 @@ protected function addValue($key, $value, $duration) * 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 @@ protected function addValues($data, $duration) * 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 @@ protected function deleteValue($key) /** * 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() { diff --git a/framework/caching/XCache.php b/framework/caching/XCache.php index f81d2e25b89..63c296d425e 100644 --- a/framework/caching/XCache.php +++ b/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 @@ protected function getValue($key) * @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 @@ protected function setValue($key, $value, $duration) * @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 @@ protected function addValue($key, $value, $duration) * 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 @@ protected function deleteValue($key) /** * 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() { diff --git a/framework/caching/ZendDataCache.php b/framework/caching/ZendDataCache.php index a372880e295..4c5ae9061ca 100644 --- a/framework/caching/ZendDataCache.php +++ b/framework/caching/ZendDataCache.php @@ -42,8 +42,8 @@ protected function getValue($key) * @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 @@ protected function setValue($key, $value, $duration) * @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 @@ protected function addValue($key, $value, $duration) * 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 @@ protected function deleteValue($key) /** * 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() { diff --git a/framework/captcha/CaptchaAction.php b/framework/captcha/CaptchaAction.php index 95a66e79b0e..483cdd10edc 100644 --- a/framework/captcha/CaptchaAction.php +++ b/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 @@ public function generateValidationHash($code) /** * 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 @@ public function getVerifyCode($regenerate = false) /** * 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) { diff --git a/framework/captcha/CaptchaValidator.php b/framework/captcha/CaptchaValidator.php index 068ae0505f4..81fbc3fb181 100644 --- a/framework/captcha/CaptchaValidator.php +++ b/framework/captcha/CaptchaValidator.php @@ -27,11 +27,11 @@ 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; /** diff --git a/framework/console/Application.php b/framework/console/Application.php index 7a086625edc..e550bfc6f7f 100644 --- a/framework/console/Application.php +++ b/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 @@ public function handleRequest($request) * * @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 */ diff --git a/framework/console/Controller.php b/framework/console/Controller.php index 344dba4336f..7c17549a980 100644 --- a/framework/console/Controller.php +++ b/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 @@ public function isColorEnabled($stream = \STDOUT) * 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 @@ public function ansiFormat($string) * ``` * * @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 @@ public function stdout($string) * ``` * * @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 @@ public function prompt($text, $options = []) * 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) diff --git a/framework/console/controllers/AssetController.php b/framework/console/controllers/AssetController.php index bd98555eccf..d0f8fbfe9c0 100644 --- a/framework/console/controllers/AssetController.php +++ b/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 @@ protected function adjustCssUrl($cssContent, $inputFilePath, $outputFilePath) /** * 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 @@ private function findRealPath($path) /** * @param AssetBundle $bundle - * @return boolean whether asset bundle external or not. + * @return bool whether asset bundle external or not. */ private function isBundleExternal($bundle) { diff --git a/framework/console/controllers/BaseMigrateController.php b/framework/console/controllers/BaseMigrateController.php index 06936a3042a..e4d1bfc9569 100644 --- a/framework/console/controllers/BaseMigrateController.php +++ b/framework/console/controllers/BaseMigrateController.php @@ -83,7 +83,7 @@ public function options($actionID) * 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 @@ public function beforeAction($action) * 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 @@ public function actionUp($limit = 0) * 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 @@ public function actionDown($limit = 1) * 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 @@ public function actionTo($version) * * @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 @@ private function extractMigrationVersion($rawVersion) * 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 @@ public function actionHistory($limit = 10) * 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 @@ private function getNamespacePath($namespace) /** * 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 @@ protected function migrateUp($class) /** * 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 @@ protected function createMigration($class) /** * 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 @@ protected function migrateToTime($time) /** * 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 @@ protected function generateMigrationSourceCode($params) /** * 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); diff --git a/framework/console/controllers/CacheController.php b/framework/console/controllers/CacheController.php index a7faa6155fc..ba791ea3d29 100644 --- a/framework/console/controllers/CacheController.php +++ b/framework/console/controllers/CacheController.php @@ -139,7 +139,7 @@ public function actionFlushAll() * ``` * * @param string $db id connection component - * @return integer exit code + * @return int exit code * @throws Exception * @throws \yii\base\InvalidConfigException * @@ -231,7 +231,7 @@ private function notifyFlushed($caches) /** * Prompts user with confirmation if caches should be flushed. * @param array $cachesNames - * @return boolean + * @return bool */ private function confirmFlush($cachesNames) { @@ -275,7 +275,7 @@ private function findCaches(array $cachesNames = []) /** * Checks if given class is a Cache class. * @param string $className class name. - * @return boolean + * @return bool */ private function isCacheClass($className) { diff --git a/framework/console/controllers/FixtureController.php b/framework/console/controllers/FixtureController.php index 16540d6fbb3..0771512608e 100644 --- a/framework/console/controllers/FixtureController.php +++ b/framework/console/controllers/FixtureController.php @@ -310,7 +310,7 @@ private function notifyNotFound($fixtures) * 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 @@ private function confirmLoad($fixtures, $except) * 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 @@ private function outputList($data) /** * Checks if needed to apply all fixtures. * @param string $fixture - * @return boolean + * @return bool */ public function needToApplyAll($fixture) { diff --git a/framework/console/controllers/HelpController.php b/framework/console/controllers/HelpController.php index de791dbb36b..22f1e7bed84 100644 --- a/framework/console/controllers/HelpController.php +++ b/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 @@ protected function getModuleCommands($module) /** * 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 @@ protected function getSubCommandHelp($controller, $actionID) /** * 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 diff --git a/framework/console/controllers/MessageController.php b/framework/console/controllers/MessageController.php index e41e70befbd..bd47cc00ba2 100644 --- a/framework/console/controllers/MessageController.php +++ b/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 @@ public function optionAliases() * 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 @@ public function actionConfig($filePath) * 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 @@ public function actionExtract($configFile = null) * @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 @@ private function extractMessagesFromTokens(array $tokens, array $translatorToken * * @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 @@ protected function isCategoryIgnored($category, array $ignoreCategories) * * @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 @@ protected function tokensEqual($a, $b) * 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 @@ protected function getLine($tokens) * * @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 @@ protected function saveMessagesToPHP($messages, $dirName, $overwrite, $removeUnu * * @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 @@ protected function saveMessagesCategoryToPHP($messages, $fileName, $overwrite, $ * * @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) { diff --git a/framework/console/controllers/MigrateController.php b/framework/console/controllers/MigrateController.php index b271818ff61..77a8cf84cc3 100644 --- a/framework/console/controllers/MigrateController.php +++ b/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 @@ public function optionAliases() * 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) { diff --git a/framework/console/controllers/ServeController.php b/framework/console/controllers/ServeController.php index 65ca37cf27b..db8523c71ed 100644 --- a/framework/console/controllers/ServeController.php +++ b/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 @@ public function optionAliases() /** * @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) { diff --git a/framework/data/BaseDataProvider.php b/framework/data/BaseDataProvider.php index 2ee40ccf548..fafd9fcc3e6 100644 --- a/framework/data/BaseDataProvider.php +++ b/framework/data/BaseDataProvider.php @@ -16,16 +16,16 @@ * * 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 * @since 2.0 @@ -61,7 +61,7 @@ abstract protected function prepareKeys($models); /** * 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 protected function prepareTotalCount(); * * 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 @@ public function setKeys($keys) /** * 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 @@ public function getCount() * 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 @@ public function getTotalCount() /** * 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 @@ public function getPagination() /** * 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 @@ public function setPagination($value) /** * 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 @@ public function getSort() /** * 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 diff --git a/framework/data/DataProviderInterface.php b/framework/data/DataProviderInterface.php index 068bfa0ae22..1eed8824c23 100644 --- a/framework/data/DataProviderInterface.php +++ b/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 @@ public function prepare($forcePrepare = false); * 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(); diff --git a/framework/data/Pagination.php b/framework/data/Pagination.php index 153ff98caff..408b5cba4ea 100644 --- a/framework/data/Pagination.php +++ b/framework/data/Pagination.php @@ -58,16 +58,16 @@ * * 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 @@ -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 @@ public function getPageCount() /** * 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 @@ public function getPage($recalculate = false) /** * 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 @@ public function setPage($value, $validatePage = false) * 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 @@ public function getPageSize() } /** - * @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 @@ public function setPageSize($value, $validatePageSize = false) /** * 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 @@ public function createUrl($page, $pageSize = null, $absolute = false) } /** - * @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 @@ public function getOffset() } /** - * @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 @@ public function getLimit() /** * 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. */ diff --git a/framework/data/Sort.php b/framework/data/Sort.php index 831f2c66093..6049af4ea48 100644 --- a/framework/data/Sort.php +++ b/framework/data/Sort.php @@ -80,7 +80,7 @@ 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 @@ public function init() /** * 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 @@ public function getOrders($recalculate = false) /** * 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 @@ public function getAttributeOrders($recalculate = false) * @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 @@ public function setAttributeOrders($attributeOrders, $validate = true) /** * 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 @@ public function link($attribute, $options = []) * 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 @@ public function createSortParam($attribute) /** * 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) { diff --git a/framework/db/ActiveQuery.php b/framework/db/ActiveQuery.php index a79e15be0d1..16b6aeeaacf 100644 --- a/framework/db/ActiveQuery.php +++ b/framework/db/ActiveQuery.php @@ -389,7 +389,7 @@ protected function queryScalar($selectExpression, $db) * * 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 @@ private function buildJoinWith() * 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() */ diff --git a/framework/db/ActiveQueryInterface.php b/framework/db/ActiveQueryInterface.php index 4f8341a6d0b..1b06d9f682f 100644 --- a/framework/db/ActiveQueryInterface.php +++ b/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); diff --git a/framework/db/ActiveQueryTrait.php b/framework/db/ActiveQueryTrait.php index 66c90066339..c7c0e05df5e 100644 --- a/framework/db/ActiveQueryTrait.php +++ b/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) diff --git a/framework/db/ActiveRecord.php b/framework/db/ActiveRecord.php index b8feb6616a5..d403914bc4f 100644 --- a/framework/db/ActiveRecord.php +++ b/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 @@ protected static function findByCondition($condition) * @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 @@ public static function updateAll($attributes, $condition = '', $params = []) * 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 @@ public static function updateAllCounters($counters, $condition = '', $params = [ * @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 @@ public static function populateRecord($record, $row) * $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 @@ public function insert($runValidation = true, $attributes = null) * 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 @@ protected function insertInternal($attributes = null) * } * ``` * - * @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 @@ public function update($runValidation = true, $attributeNames = null) * 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 @@ public function delete() /** * 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 @@ protected function deleteInternal() * 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 @@ public function equals($record) /** * 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) { diff --git a/framework/db/ActiveRecordInterface.php b/framework/db/ActiveRecordInterface.php index e16356ef3ca..22f09d18efc 100644 --- a/framework/db/ActiveRecordInterface.php +++ b/framework/db/ActiveRecordInterface.php @@ -54,13 +54,13 @@ public function setAttribute($name, $value); /** * 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 @@ public function getPrimaryKey($asArray = false); * 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 @@ public function getOldPrimaryKey($asArray = false); /** * 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 @@ public static function findAll($condition); * @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 @@ public static function updateAll($attributes, $condition = null); * @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 @@ public static function deleteAll($condition = null); * $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 @@ public function save($runValidation = true, $attributeNames = null); * $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 @@ public function insert($runValidation = true, $attributes = null); * $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 @@ public function update($runValidation = true, $attributeNames = null); /** * 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 @@ public function getIsNewRecord(); * 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 @@ public function equals($record); * (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 @@ public function link($name, $model, $extraColumns = []); * * @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. */ diff --git a/framework/db/ActiveRelationTrait.php b/framework/db/ActiveRelationTrait.php index e5bfdfe1468..1801b99208d 100644 --- a/framework/db/ActiveRelationTrait.php +++ b/framework/db/ActiveRelationTrait.php @@ -24,7 +24,7 @@ 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 @@ private function populateInverseRelation(&$primaryModels, $models, $primaryName, * @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) diff --git a/framework/db/BaseActiveRecord.php b/framework/db/BaseActiveRecord.php index af3b3292b85..639964dec6c 100644 --- a/framework/db/BaseActiveRecord.php +++ b/framework/db/BaseActiveRecord.php @@ -24,7 +24,7 @@ * * @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 @@ protected static function findByCondition($condition) * @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 @@ public static function updateAll($attributes, $condition = '') * 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 @@ public static function updateAllCounters($counters, $condition = '') * @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 @@ public function __set($name, $value) * 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 @@ public function populateRelation($name, $records) /** * 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 @@ public function getRelatedRecords() /** * 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 @@ public function markAttributeDirty($name) /** * 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 @@ public function getDirtyAttributes($names = null) * $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 @@ public function save($runValidation = true, $attributeNames = null) * } * ``` * - * @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 @@ public function update($runValidation = true, $attributeNames = null) * 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 @@ public function updateAttributes($attributes) /** * @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 @@ protected function updateInternal($attributes = null) * * @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 @@ public function updateCounters($counters) * 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 @@ public function delete() /** * 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 @@ public function getIsNewRecord() /** * 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 @@ public function afterFind() * } * ``` * - * @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 @@ public function beforeSave($insert) * 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 @@ public function afterSave($insert, $changedAttributes) * } * ``` * - * @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 @@ public function afterDelete() * 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 @@ public function afterRefresh() * 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 @@ public function equals($record) /** * 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 @@ public function getPrimaryKey($asArray = false) * 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 @@ public static function instantiate($row) * 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 @@ public function offsetExists($offset) * 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 @@ public function link($name, $model, $extraColumns = []) * @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 @@ public function unlink($name, $model, $delete = false) * 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 @@ private function bindModels($link, $foreignModel, $primaryModel) /** * 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) { diff --git a/framework/db/BatchQueryResult.php b/framework/db/BatchQueryResult.php index e2f679f9546..1e6dcf38c3c 100644 --- a/framework/db/BatchQueryResult.php +++ b/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 @@ protected function fetchData() /** * 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 @@ public function current() /** * 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() { diff --git a/framework/db/ColumnSchema.php b/framework/db/ColumnSchema.php index 64d007f3e5d..9e5d093e83f 100644 --- a/framework/db/ColumnSchema.php +++ b/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; diff --git a/framework/db/ColumnSchemaBuilder.php b/framework/db/ColumnSchemaBuilder.php index c5d09c78e65..024a9e829ff 100644 --- a/framework/db/ColumnSchemaBuilder.php +++ b/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 */ diff --git a/framework/db/Command.php b/framework/db/Command.php index 31a0dbd4d20..3b6fc2f3bbd 100644 --- a/framework/db/Command.php +++ b/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 @@ public function getRawSql() * 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 @@ public function cancel() /** * 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 @@ protected function bindPendingParams() /** * 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 @@ public function query() /** * 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 @@ public function queryAll($fetchMode = null) /** * 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 @@ public function dropForeignKey($name, $table) * @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 @@ public function resetSequence($table, $value = null) /** * 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 @@ public function dropCommentFromTable($table) * 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 @@ public function execute() /** * 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 diff --git a/framework/db/Connection.php b/framework/db/Connection.php index 4d7d100194c..49f1e383ad7 100644 --- a/framework/db/Connection.php +++ b/framework/db/Connection.php @@ -111,7 +111,7 @@ * ``` * * @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 @@ public function getIsActive() * * @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 @@ public function noCache(callable $callable) /** * 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 @@ public function getQueryBuilder() /** * 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 @@ public function setDriverName($driverName) * 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 @@ public function getMasterPdo() /** * 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. */ diff --git a/framework/db/DataReader.php b/framework/db/DataReader.php index 35d57a9e9ec..1173cfaeb32 100644 --- a/framework/db/DataReader.php +++ b/framework/db/DataReader.php @@ -40,10 +40,10 @@ * [[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 * @since 2.0 @@ -75,11 +75,11 @@ public function __construct(Command $command, $config = []) * 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 @@ public function bindColumn($column, &$value, $dataType = null) /** * 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 @@ public function read() /** * 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 @@ public function readAll() * 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 @@ public function close() /** * 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 @@ public function getIsClosed() * 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 @@ public function getRowCount() * 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 @@ public function count() /** * 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 @@ public function rewind() /** * 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 @@ public function next() /** * 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() { diff --git a/framework/db/Exception.php b/framework/db/Exception.php index 2c04f829440..15466cd736e 100644 --- a/framework/db/Exception.php +++ b/framework/db/Exception.php @@ -26,7 +26,7 @@ class Exception extends \yii\base\Exception * Constructor. * @param string $message PDO error message * @param array $errorInfo PDO error info - * @param integer $code PDO error code + * @param int $code PDO error code * @param \Exception $previous The previous exception used for the exception chaining. */ public function __construct($message, $errorInfo = [], $code = 0, \Exception $previous = null) diff --git a/framework/db/Migration.php b/framework/db/Migration.php index c42533196b0..7b5a4e16782 100644 --- a/framework/db/Migration.php +++ b/framework/db/Migration.php @@ -86,7 +86,7 @@ protected function getDb() /** * This method contains the logic to be executed when applying this migration. * Child classes may override this method to provide actual migration logic. - * @return boolean return a false value to indicate the migration fails + * @return bool return a false value to indicate the migration fails * and should not proceed further. All other return values mean the migration succeeds. */ public function up() @@ -114,7 +114,7 @@ public function up() * This method contains the logic to be executed when removing this migration. * The default implementation throws an exception indicating the migration cannot be removed. * Child classes may override this method if the corresponding migrations can be removed. - * @return boolean return a false value to indicate the migration fails + * @return bool return a false value to indicate the migration fails * and should not proceed further. All other return values mean the migration succeeds. */ public function down() @@ -144,7 +144,7 @@ public function down() * be enclosed within a DB transaction. * Child classes may implement this method instead of [[up()]] if the DB logic * needs to be within a transaction. - * @return boolean return a false value to indicate the migration fails + * @return bool return a false value to indicate the migration fails * and should not proceed further. All other return values mean the migration succeeds. */ public function safeUp() @@ -157,7 +157,7 @@ public function safeUp() * be enclosed within a DB transaction. * Child classes may implement this method instead of [[down()]] if the DB logic * needs to be within a transaction. - * @return boolean return a false value to indicate the migration fails + * @return bool return a false value to indicate the migration fails * and should not proceed further. All other return values mean the migration succeeds. */ public function safeDown() @@ -438,7 +438,7 @@ public function dropForeignKey($name, $table) * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, please separate them * by commas or use an array. Each column name will be properly quoted by the method. Quoting will be skipped for column names that * include a left parenthesis "(". - * @param boolean $unique whether to add UNIQUE constraint on the created index. + * @param bool $unique whether to add UNIQUE constraint on the created index. */ public function createIndex($name, $table, $columns, $unique = false) { diff --git a/framework/db/MigrationInterface.php b/framework/db/MigrationInterface.php index 8f9d1573695..e86c79b8f38 100644 --- a/framework/db/MigrationInterface.php +++ b/framework/db/MigrationInterface.php @@ -20,7 +20,7 @@ interface MigrationInterface { /** * This method contains the logic to be executed when applying this migration. - * @return boolean return a false value to indicate the migration fails + * @return bool return a false value to indicate the migration fails * and should not proceed further. All other return values mean the migration succeeds. */ public function up(); @@ -28,7 +28,7 @@ public function up(); /** * This method contains the logic to be executed when removing this migration. * The default implementation throws an exception indicating the migration cannot be removed. - * @return boolean return a false value to indicate the migration fails + * @return bool return a false value to indicate the migration fails * and should not proceed further. All other return values mean the migration succeeds. */ public function down(); diff --git a/framework/db/Query.php b/framework/db/Query.php index 9b50e87ee6d..6fe9bfc9f90 100644 --- a/framework/db/Query.php +++ b/framework/db/Query.php @@ -59,7 +59,7 @@ class Query extends Component implements QueryInterface */ public $selectOption; /** - * @var boolean whether to select distinct rows of data only. If this is set true, + * @var bool whether to select distinct rows of data only. If this is set true, * the SELECT clause would be changed to SELECT DISTINCT. */ public $distinct; @@ -156,7 +156,7 @@ public function prepare($builder) * } * ``` * - * @param integer $batchSize the number of records to be fetched in each batch. + * @param int $batchSize the number of records to be fetched in each batch. * @param Connection $db the database connection. If not set, the "db" application component will be used. * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface * and can be traversed to retrieve the data in batches. @@ -183,7 +183,7 @@ public function batch($batchSize = 100, $db = null) * } * ``` * - * @param integer $batchSize the number of records to be fetched in each batch. + * @param int $batchSize the number of records to be fetched in each batch. * @param Connection $db the database connection. If not set, the "db" application component will be used. * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface * and can be traversed to retrieve the data in batches. @@ -239,7 +239,7 @@ public function populate($rows) * Executes the query and returns a single row of result. * @param Connection $db the database connection used to generate the SQL statement. * If this parameter is not given, the `db` application component will be used. - * @return array|boolean the first row (in terms of an array) of the query result. False is returned if the query + * @return array|bool the first row (in terms of an array) of the query result. False is returned if the query * results in nothing. */ public function one($db = null) @@ -295,7 +295,7 @@ public function column($db = null) * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression. * @param Connection $db the database connection used to generate the SQL statement. * If this parameter is not given (or null), the `db` application component will be used. - * @return integer|string number of records. The result may be a string depending on the + * @return int|string number of records. The result may be a string depending on the * underlying database engine and to support integer values higher than a 32bit PHP integer can handle. */ public function count($q = '*', $db = null) @@ -359,7 +359,7 @@ public function max($q, $db = null) * Returns a value indicating whether the query result contains any row of data. * @param Connection $db the database connection used to generate the SQL statement. * If this parameter is not given, the `db` application component will be used. - * @return boolean whether the query result contains any row of data. + * @return bool whether the query result contains any row of data. */ public function exists($db = null) { @@ -367,7 +367,7 @@ public function exists($db = null) $params = $command->params; $command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql())); $command->bindValues($params); - return (boolean)$command->queryScalar(); + return (bool) $command->queryScalar(); } /** @@ -375,7 +375,7 @@ public function exists($db = null) * Restores the value of select to make this query reusable. * @param string|Expression $selectExpression * @param Connection|null $db - * @return boolean|string + * @return bool|string */ protected function queryScalar($selectExpression, $db) { @@ -468,7 +468,7 @@ public function addSelect($columns) /** * Sets the value indicating whether to SELECT DISTINCT or not. - * @param boolean $value whether to SELECT DISTINCT or not. + * @param bool $value whether to SELECT DISTINCT or not. * @return $this the query object itself */ public function distinct($value = true) @@ -846,7 +846,7 @@ public function orHaving($condition, $params = []) /** * Appends a SQL statement using UNION operator. * @param string|Query $sql the SQL statement to be appended using UNION - * @param boolean $all TRUE if using UNION ALL and FALSE if using UNION + * @param bool $all TRUE if using UNION ALL and FALSE if using UNION * @return $this the query object itself */ public function union($sql, $all = false) diff --git a/framework/db/QueryBuilder.php b/framework/db/QueryBuilder.php index ba325af2e26..85f9666e6be 100644 --- a/framework/db/QueryBuilder.php +++ b/framework/db/QueryBuilder.php @@ -525,7 +525,7 @@ public function dropForeignKey($name, $table) * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, * separate them with commas or use an array to represent them. Each column name will be properly quoted * by the method, unless a parenthesis is found in the name. - * @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 string the SQL statement for creating a new index. */ public function createIndex($name, $table, $columns, $unique = false) @@ -564,7 +564,7 @@ public function resetSequence($table, $value = null) /** * Builds a SQL statement 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 of the tables. Defaults to empty string, meaning the current or default schema. * @param string $table the table name. Defaults to empty string, meaning that no table will be changed. * @return string the SQL statement for checking integrity @@ -691,7 +691,7 @@ public function getColumnType($type) /** * @param array $columns * @param array $params the binding parameters to be populated - * @param boolean $distinct + * @param bool $distinct * @param string $selectOption * @return string the SELECT clause built from [[Query::$select]]. */ @@ -858,8 +858,8 @@ public function buildHaving($condition, &$params) * Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL. * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET) * @param array $orderBy the order by columns. See [[Query::orderBy]] for more details on how to specify this parameter. - * @param integer $limit the limit number. See [[Query::limit]] for more details. - * @param integer $offset the offset number. See [[Query::offset]] for more details. + * @param int $limit the limit number. See [[Query::limit]] for more details. + * @param int $offset the offset number. See [[Query::offset]] for more details. * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any) */ public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset) @@ -897,8 +897,8 @@ public function buildOrderBy($columns) } /** - * @param integer $limit - * @param integer $offset + * @param int $limit + * @param int $offset * @return string the LIMIT and OFFSET clauses */ public function buildLimit($limit, $offset) @@ -917,7 +917,7 @@ public function buildLimit($limit, $offset) /** * Checks to see if the given limit is effective. * @param mixed $limit the given limit - * @return boolean whether the limit is effective + * @return bool whether the limit is effective */ protected function hasLimit($limit) { @@ -927,7 +927,7 @@ protected function hasLimit($limit) /** * Checks to see if the given offset is effective. * @param mixed $offset the given offset - * @return boolean whether the offset is effective + * @return bool whether the offset is effective */ protected function hasOffset($offset) { diff --git a/framework/db/QueryInterface.php b/framework/db/QueryInterface.php index c3a0991c3eb..28d16c9e1cc 100644 --- a/framework/db/QueryInterface.php +++ b/framework/db/QueryInterface.php @@ -34,7 +34,7 @@ public function all($db = null); * Executes the query and returns a single row of result. * @param Connection $db the database connection used to execute the query. * If this parameter is not given, the `db` application component will be used. - * @return array|boolean the first row (in terms of an array) of the query result. False is returned if the query + * @return array|bool the first row (in terms of an array) of the query result. False is returned if the query * results in nothing. */ public function one($db = null); @@ -44,7 +44,7 @@ public function one($db = null); * @param string $q the COUNT expression. Defaults to '*'. * @param Connection $db the database connection used to execute the query. * If this parameter is not given, the `db` application component will be used. - * @return integer number of records. + * @return int number of records. */ public function count($q = '*', $db = null); @@ -52,7 +52,7 @@ public function count($q = '*', $db = null); * Returns a value indicating whether the query result contains any row of data. * @param Connection $db the database connection used to execute the query. * If this parameter is not given, the `db` application component will be used. - * @return boolean whether the query result contains any row of data. + * @return bool whether the query result contains any row of data. */ public function exists($db = null); @@ -241,14 +241,14 @@ public function addOrderBy($columns); /** * Sets the LIMIT part of the query. - * @param integer $limit the limit. Use null or negative value to disable limit. + * @param int $limit the limit. Use null or negative value to disable limit. * @return $this the query object itself */ public function limit($limit); /** * Sets the OFFSET part of the query. - * @param integer $offset the offset. Use null or negative value to disable offset. + * @param int $offset the offset. Use null or negative value to disable offset. * @return $this the query object itself */ public function offset($offset); diff --git a/framework/db/QueryTrait.php b/framework/db/QueryTrait.php index 85d0108b5f1..4a64903d0b7 100644 --- a/framework/db/QueryTrait.php +++ b/framework/db/QueryTrait.php @@ -27,11 +27,11 @@ trait QueryTrait */ public $where; /** - * @var integer maximum number of records to be returned. If not set or less than 0, it means no limit. + * @var int maximum number of records to be returned. If not set or less than 0, it means no limit. */ public $limit; /** - * @var integer zero-based offset from where the records are to be returned. If not set or + * @var int zero-based offset from where the records are to be returned. If not set or * less than 0, it means starting from the beginning. */ public $offset; @@ -283,7 +283,7 @@ protected function filterCondition($condition) * - or an empty array. * * @param mixed $value - * @return boolean if the value is empty + * @return bool if the value is empty */ protected function isEmpty($value) { @@ -369,7 +369,7 @@ protected function normalizeOrderBy($columns) /** * Sets the LIMIT part of the query. - * @param integer $limit the limit. Use null or negative value to disable limit. + * @param int $limit the limit. Use null or negative value to disable limit. * @return $this the query object itself */ public function limit($limit) @@ -380,7 +380,7 @@ public function limit($limit) /** * Sets the OFFSET part of the query. - * @param integer $offset the offset. Use null or negative value to disable offset. + * @param int $offset the offset. Use null or negative value to disable offset. * @return $this the query object itself */ public function offset($offset) diff --git a/framework/db/Schema.php b/framework/db/Schema.php index 79fa74f29e4..2d67008be11 100644 --- a/framework/db/Schema.php +++ b/framework/db/Schema.php @@ -118,7 +118,7 @@ abstract protected function loadTableSchema($name); /** * Obtains the metadata for the named table. * @param string $name table name. The table name may contain schema name if any. Do not quote the 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 null|TableSchema table metadata. Null if the named table does not exist. */ public function getTableSchema($name, $refresh = false) @@ -185,7 +185,7 @@ protected function getCacheTag() /** * Returns the metadata for all tables in the database. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name. - * @param boolean $refresh whether to fetch the latest available table schemas. If this is false, + * @param bool $refresh whether to fetch the latest available table schemas. If this is false, * cached data may be returned if available. * @return TableSchema[] the metadata for all tables in the database. * Each array element is an instance of [[TableSchema]] or its child class. @@ -207,7 +207,7 @@ public function getTableSchemas($schema = '', $refresh = false) /** * Returns all schema names in the database, except system schemas. - * @param boolean $refresh whether to fetch the latest available schema names. If this is false, + * @param bool $refresh whether to fetch the latest available schema names. If this is false, * schema names fetched previously (if available) will be returned. * @return string[] all schema names in the database, except system schemas. * @since 2.0.4 @@ -225,7 +225,7 @@ public function getSchemaNames($refresh = false) * Returns all table names in the database. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name. * If not empty, the returned table names will be prefixed with the schema name. - * @param boolean $refresh whether to fetch the latest available table names. If this is false, + * @param bool $refresh whether to fetch the latest available table names. If this is false, * table names fetched previously (if available) will be returned. * @return string[] all table names in the database. */ @@ -253,7 +253,7 @@ public function getQueryBuilder() /** * Determines the PDO type for the given PHP data value. * @param mixed $data the data whose PDO type is to be determined - * @return integer the PDO type + * @return int the PDO type * @see http://www.php.net/manual/en/pdo.constants.php */ public function getPdoType($data) @@ -321,7 +321,7 @@ public function createQueryBuilder() * This method may be overridden by child classes to create a DBMS-specific column schema builder. * * @param string $type type of the column. See [[ColumnSchemaBuilder::$type]]. - * @param integer|string|array $length length or precision of the column. See [[ColumnSchemaBuilder::$length]]. + * @param int|string|array $length length or precision of the column. See [[ColumnSchemaBuilder::$length]]. * @return ColumnSchemaBuilder column schema builder instance * @since 2.0.6 */ @@ -395,7 +395,7 @@ public function getLastInsertID($sequenceName = '') } /** - * @return boolean whether this DBMS supports [savepoint](http://en.wikipedia.org/wiki/Savepoint). + * @return bool whether this DBMS supports [savepoint](http://en.wikipedia.org/wiki/Savepoint). */ public function supportsSavepoint() { @@ -640,7 +640,7 @@ public function convertException(\Exception $e, $rawSql) /** * Returns a value indicating whether a SQL statement is for read purpose. * @param string $sql the SQL statement - * @return boolean whether a SQL statement is for read purpose. + * @return bool whether a SQL statement is for read purpose. */ public function isReadQuery($sql) { diff --git a/framework/db/SchemaBuilderTrait.php b/framework/db/SchemaBuilderTrait.php index 89e587f7df0..5b03c326660 100644 --- a/framework/db/SchemaBuilderTrait.php +++ b/framework/db/SchemaBuilderTrait.php @@ -41,7 +41,7 @@ protected abstract function getDb(); /** * Creates a primary key column. - * @param integer $length column size or precision definition. + * @param int $length column size or precision definition. * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 @@ -53,7 +53,7 @@ public function primaryKey($length = null) /** * Creates a big primary key column. - * @param integer $length column size or precision definition. + * @param int $length column size or precision definition. * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 @@ -65,7 +65,7 @@ public function bigPrimaryKey($length = null) /** * Creates a char column. - * @param integer $length column size definition i.e. the maximum string length. + * @param int $length column size definition i.e. the maximum string length. * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.8 @@ -77,7 +77,7 @@ public function char($length = null) /** * Creates a string column. - * @param integer $length column size definition i.e. the maximum string length. + * @param int $length column size definition i.e. the maximum string length. * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 @@ -99,7 +99,7 @@ public function text() /** * Creates a smallint column. - * @param integer $length column size or precision definition. + * @param int $length column size or precision definition. * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 @@ -111,7 +111,7 @@ public function smallInteger($length = null) /** * Creates an integer column. - * @param integer $length column size or precision definition. + * @param int $length column size or precision definition. * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 @@ -123,7 +123,7 @@ public function integer($length = null) /** * Creates a bigint column. - * @param integer $length column size or precision definition. + * @param int $length column size or precision definition. * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 @@ -135,7 +135,7 @@ public function bigInteger($length = null) /** * Creates a float column. - * @param integer $precision column value precision. First parameter passed to the column type, e.g. FLOAT(precision). + * @param int $precision column value precision. First parameter passed to the column type, e.g. FLOAT(precision). * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 @@ -147,7 +147,7 @@ public function float($precision = null) /** * Creates a double column. - * @param integer $precision column value precision. First parameter passed to the column type, e.g. DOUBLE(precision). + * @param int $precision column value precision. First parameter passed to the column type, e.g. DOUBLE(precision). * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 @@ -159,10 +159,10 @@ public function double($precision = null) /** * Creates a decimal column. - * @param integer $precision column value precision, which is usually the total number of digits. + * @param int $precision column value precision, which is usually the total number of digits. * First parameter passed to the column type, e.g. DECIMAL(precision, scale). * This parameter will be ignored if not supported by the DBMS. - * @param integer $scale column value scale, which is usually the number of digits after the decimal point. + * @param int $scale column value scale, which is usually the number of digits after the decimal point. * Second parameter passed to the column type, e.g. DECIMAL(precision, scale). * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. @@ -182,7 +182,7 @@ public function decimal($precision = null, $scale = null) /** * Creates a datetime column. - * @param integer $precision column value precision. First parameter passed to the column type, e.g. DATETIME(precision). + * @param int $precision column value precision. First parameter passed to the column type, e.g. DATETIME(precision). * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 @@ -194,7 +194,7 @@ public function dateTime($precision = null) /** * Creates a timestamp column. - * @param integer $precision column value precision. First parameter passed to the column type, e.g. TIMESTAMP(precision). + * @param int $precision column value precision. First parameter passed to the column type, e.g. TIMESTAMP(precision). * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 @@ -206,7 +206,7 @@ public function timestamp($precision = null) /** * Creates a time column. - * @param integer $precision column value precision. First parameter passed to the column type, e.g. TIME(precision). + * @param int $precision column value precision. First parameter passed to the column type, e.g. TIME(precision). * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 @@ -228,7 +228,7 @@ public function date() /** * Creates a binary column. - * @param integer $length column size or precision definition. + * @param int $length column size or precision definition. * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. * @since 2.0.6 @@ -250,10 +250,10 @@ public function boolean() /** * Creates a money column. - * @param integer $precision column value precision, which is usually the total number of digits. + * @param int $precision column value precision, which is usually the total number of digits. * First parameter passed to the column type, e.g. DECIMAL(precision, scale). * This parameter will be ignored if not supported by the DBMS. - * @param integer $scale column value scale, which is usually the number of digits after the decimal point. + * @param int $scale column value scale, which is usually the number of digits after the decimal point. * Second parameter passed to the column type, e.g. DECIMAL(precision, scale). * This parameter will be ignored if not supported by the DBMS. * @return ColumnSchemaBuilder the column instance which can be further customized. diff --git a/framework/db/Transaction.php b/framework/db/Transaction.php index 63595ed42ac..d2877163bb6 100644 --- a/framework/db/Transaction.php +++ b/framework/db/Transaction.php @@ -31,13 +31,13 @@ * } * ``` * - * @property boolean $isActive Whether this transaction is active. Only an active transaction can [[commit()]] + * @property bool $isActive Whether this transaction is active. Only an active transaction can [[commit()]] * or [[rollBack()]]. This property is read-only. * @property string $isolationLevel The transaction isolation level to use for this transaction. This can be * one of [[READ_UNCOMMITTED]], [[READ_COMMITTED]], [[REPEATABLE_READ]] and [[SERIALIZABLE]] but also a string * containing DBMS specific syntax to be used after `SET TRANSACTION ISOLATION LEVEL`. This property is * write-only. - * @property integer $level The current nesting level of the transaction. This property is read-only. + * @property int $level The current nesting level of the transaction. This property is read-only. * * @author Qiang Xue * @since 2.0 @@ -71,14 +71,14 @@ class Transaction extends \yii\base\Object public $db; /** - * @var integer the nesting level of the transaction. 0 means the outermost level. + * @var int the nesting level of the transaction. 0 means the outermost level. */ private $_level = 0; /** * Returns a value indicating whether this transaction is active. - * @return boolean whether this transaction is active. Only an active transaction + * @return bool whether this transaction is active. Only an active transaction * can [[commit()]] or [[rollBack()]]. */ public function getIsActive() @@ -214,7 +214,7 @@ public function setIsolationLevel($level) } /** - * @return integer The current nesting level of the transaction. + * @return int The current nesting level of the transaction. * @since 2.0.8 */ public function getLevel() diff --git a/framework/db/cubrid/Schema.php b/framework/db/cubrid/Schema.php index f70063c2290..95b9ff22c60 100644 --- a/framework/db/cubrid/Schema.php +++ b/framework/db/cubrid/Schema.php @@ -258,7 +258,7 @@ protected function findTableNames($schema = '') /** * Determines the PDO type for the given PHP data value. * @param mixed $data the data whose PDO type is to be determined - * @return integer the PDO type + * @return int the PDO type * @see http://www.php.net/manual/en/pdo.constants.php */ public function getPdoType($data) diff --git a/framework/db/mssql/PDO.php b/framework/db/mssql/PDO.php index ebecd39c7a0..6a776b227a5 100644 --- a/framework/db/mssql/PDO.php +++ b/framework/db/mssql/PDO.php @@ -19,7 +19,7 @@ class PDO extends \PDO /** * Returns value of the last inserted ID. * @param string|null $sequence the sequence name. Defaults to null. - * @return integer last inserted ID value. + * @return int last inserted ID value. */ public function lastInsertId($sequence = null) { @@ -29,7 +29,7 @@ public function lastInsertId($sequence = null) /** * Starts a transaction. It is necessary to override PDO's method as MSSQL PDO driver does not * natively support transactions. - * @return boolean the result of a transaction start. + * @return bool the result of a transaction start. */ public function beginTransaction() { @@ -41,7 +41,7 @@ public function beginTransaction() /** * Commits a transaction. It is necessary to override PDO's method as MSSQL PDO driver does not * natively support transactions. - * @return boolean the result of a transaction commit. + * @return bool the result of a transaction commit. */ public function commit() { @@ -53,7 +53,7 @@ public function commit() /** * Rollbacks a transaction. It is necessary to override PDO's method as MSSQL PDO driver does not * natively support transactions. - * @return boolean the result of a transaction roll back. + * @return bool the result of a transaction roll back. */ public function rollBack() { @@ -66,7 +66,7 @@ public function rollBack() * Retrieve a database connection attribute. * It is necessary to override PDO's method as some MSSQL PDO driver (e.g. dblib) does not * support getting attributes - * @param integer $attribute One of the PDO::ATTR_* constants. + * @param int $attribute One of the PDO::ATTR_* constants. * @return mixed A successful call returns the value of the requested PDO attribute. * An unsuccessful call returns null. */ diff --git a/framework/db/mssql/QueryBuilder.php b/framework/db/mssql/QueryBuilder.php index a3308ba55f5..dc91814d46f 100644 --- a/framework/db/mssql/QueryBuilder.php +++ b/framework/db/mssql/QueryBuilder.php @@ -66,8 +66,8 @@ public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset) * Builds the ORDER BY/LIMIT/OFFSET clauses for SQL SERVER 2012 or newer. * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET) * @param array $orderBy the order by columns. See [[Query::orderBy]] for more details on how to specify this parameter. - * @param integer $limit the limit number. See [[Query::limit]] for more details. - * @param integer $offset the offset number. See [[Query::offset]] for more details. + * @param int $limit the limit number. See [[Query::limit]] for more details. + * @param int $offset the offset number. See [[Query::offset]] for more details. * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any) */ protected function newBuildOrderByAndLimit($sql, $orderBy, $limit, $offset) @@ -93,8 +93,8 @@ protected function newBuildOrderByAndLimit($sql, $orderBy, $limit, $offset) * Builds the ORDER BY/LIMIT/OFFSET clauses for SQL SERVER 2005 to 2008. * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET) * @param array $orderBy the order by columns. See [[Query::orderBy]] for more details on how to specify this parameter. - * @param integer $limit the limit number. See [[Query::limit]] for more details. - * @param integer $offset the offset number. See [[Query::offset]] for more details. + * @param int $limit the limit number. See [[Query::limit]] for more details. + * @param int $offset the offset number. See [[Query::offset]] for more details. * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any) */ protected function oldBuildOrderByAndLimit($sql, $orderBy, $limit, $offset) @@ -166,7 +166,7 @@ public function alterColumn($table, $column, $type) /** * Builds a SQL statement 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 of the tables. Defaults to empty string, meaning the current or default schema. * @param string $table the table name. Defaults to empty string, meaning that no table will be changed. * @return string the SQL statement for checking integrity @@ -240,12 +240,12 @@ protected function getAllColumnNames($modelClass = null) } /** - * @var boolean whether MSSQL used is old. + * @var bool whether MSSQL used is old. */ private $_oldMssql; /** - * @return boolean whether the version of the MSSQL being used is older than 2012. + * @return bool whether the version of the MSSQL being used is older than 2012. * @throws \yii\base\InvalidConfigException * @throws \yii\db\Exception */ diff --git a/framework/db/mssql/Schema.php b/framework/db/mssql/Schema.php index 333acd2a2fa..6352502f261 100644 --- a/framework/db/mssql/Schema.php +++ b/framework/db/mssql/Schema.php @@ -233,7 +233,7 @@ protected function loadColumnSchema($info) /** * Collects the metadata of table columns. * @param TableSchema $table the table metadata - * @return boolean whether the table exists in the database + * @return bool whether the table exists in the database */ protected function findColumns($table) { diff --git a/framework/db/mssql/SqlsrvPDO.php b/framework/db/mssql/SqlsrvPDO.php index ade96c01c1f..e248b1cc6ca 100644 --- a/framework/db/mssql/SqlsrvPDO.php +++ b/framework/db/mssql/SqlsrvPDO.php @@ -24,7 +24,7 @@ class SqlsrvPDO extends \PDO * But when parameter is not specified it works as expected and returns actual * last inserted ID (like the other PDO drivers). * @param string|null $sequence the sequence name. Defaults to null. - * @return integer last inserted ID value. + * @return int last inserted ID value. */ public function lastInsertId($sequence = null) { diff --git a/framework/db/mysql/QueryBuilder.php b/framework/db/mysql/QueryBuilder.php index 72ce174c8d0..dd52adc96d8 100644 --- a/framework/db/mysql/QueryBuilder.php +++ b/framework/db/mysql/QueryBuilder.php @@ -151,7 +151,7 @@ public function resetSequence($tableName, $value = null) /** * Builds a SQL statement 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 of the tables. Meaningless for MySQL. * @param string $table the table name. Meaningless for MySQL. * @return string the SQL statement for checking integrity diff --git a/framework/db/mysql/Schema.php b/framework/db/mysql/Schema.php index 7c94ba13dfd..19f408e0097 100644 --- a/framework/db/mysql/Schema.php +++ b/framework/db/mysql/Schema.php @@ -188,7 +188,7 @@ protected function loadColumnSchema($info) /** * Collects the metadata of table columns. * @param TableSchema $table the table metadata - * @return boolean whether the table exists in the database + * @return bool whether the table exists in the database * @throws \Exception if DB query fails */ protected function findColumns($table) diff --git a/framework/db/oci/Schema.php b/framework/db/oci/Schema.php index f65e608e3b4..1f472070534 100644 --- a/framework/db/oci/Schema.php +++ b/framework/db/oci/Schema.php @@ -116,7 +116,7 @@ protected function resolveTableNames($table, $name) /** * Collects the table column metadata. * @param TableSchema $table the table schema - * @return boolean whether the table exists + * @return bool whether the table exists */ protected function findColumns($table) { diff --git a/framework/db/pgsql/QueryBuilder.php b/framework/db/pgsql/QueryBuilder.php index 68289a6277b..1ede10a1a9a 100644 --- a/framework/db/pgsql/QueryBuilder.php +++ b/framework/db/pgsql/QueryBuilder.php @@ -101,7 +101,7 @@ class QueryBuilder extends \yii\db\QueryBuilder * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, * separate them with commas or use an array to represent them. Each column name will be properly quoted * by the method, unless a parenthesis is found in the name. - * @param boolean|string $unique whether to make this a UNIQUE index constraint. You can pass `true` or [[INDEX_UNIQUE]] to create + * @param bool|string $unique whether to make this a UNIQUE index constraint. You can pass `true` or [[INDEX_UNIQUE]] to create * a unique index, `false` to make a non-unique index using the default index type, or one of the following constants to specify * the index method to use: [[INDEX_B_TREE]], [[INDEX_HASH]], [[INDEX_GIST]], [[INDEX_GIN]]. * @return string the SQL statement for creating a new index. @@ -180,7 +180,7 @@ public function resetSequence($tableName, $value = null) /** * Builds a SQL statement 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 of the tables. * @param string $table the table name. * @return string the SQL statement for checking integrity diff --git a/framework/db/pgsql/Schema.php b/framework/db/pgsql/Schema.php index b1df0f94361..8506e37bbe6 100644 --- a/framework/db/pgsql/Schema.php +++ b/framework/db/pgsql/Schema.php @@ -251,7 +251,7 @@ protected function findViewNames($schema = '') * Returns all view names in the database. * @param string $schema the schema of the views. Defaults to empty string, meaning the current or default schema name. * If not empty, the returned view names will be prefixed with the schema name. - * @param boolean $refresh whether to fetch the latest available view names. If this is false, + * @param bool $refresh whether to fetch the latest available view names. If this is false, * view names fetched previously (if available) will be returned. * @return string[] all view names in the database. * @since 2.0.9 @@ -388,7 +388,7 @@ public function findUniqueIndexes($table) /** * Collects the metadata of table columns. * @param TableSchema $table the table metadata - * @return boolean whether the table exists in the database + * @return bool whether the table exists in the database */ protected function findColumns($table) { diff --git a/framework/db/sqlite/QueryBuilder.php b/framework/db/sqlite/QueryBuilder.php index 3852e757ec6..0e361ca7f8f 100644 --- a/framework/db/sqlite/QueryBuilder.php +++ b/framework/db/sqlite/QueryBuilder.php @@ -153,7 +153,7 @@ public function resetSequence($tableName, $value = null) /** * Enables or disables 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 of the tables. Meaningless for SQLite. * @param string $table the table name. Meaningless for SQLite. * @return string the SQL statement for checking integrity diff --git a/framework/db/sqlite/Schema.php b/framework/db/sqlite/Schema.php index 21af58de2ae..1b58c339fe6 100644 --- a/framework/db/sqlite/Schema.php +++ b/framework/db/sqlite/Schema.php @@ -135,7 +135,7 @@ protected function loadTableSchema($name) /** * Collects the table column metadata. * @param TableSchema $table the table metadata - * @return boolean whether the table exists in the database + * @return bool whether the table exists in the database */ protected function findColumns($table) { diff --git a/framework/di/Container.php b/framework/di/Container.php index 4a4464c988c..3649d6fe9c4 100644 --- a/framework/di/Container.php +++ b/framework/di/Container.php @@ -281,7 +281,7 @@ public function setSingleton($class, $definition = [], array $params = []) /** * Returns a value indicating whether the container has the definition of the specified name. * @param string $class class name, interface name or alias name - * @return boolean whether the container has the definition of the specified name.. + * @return bool whether the container has the definition of the specified name.. * @see set() */ public function has($class) @@ -292,8 +292,8 @@ public function has($class) /** * Returns a value indicating whether the given name corresponds to a registered singleton. * @param string $class class name, interface name or alias name - * @param boolean $checkInstance whether to check if the singleton has been instantiated. - * @return boolean whether the given name corresponds to a registered singleton. If `$checkInstance` is true, + * @param bool $checkInstance whether to check if the singleton has been instantiated. + * @return bool whether the given name corresponds to a registered singleton. If `$checkInstance` is true, * the method should return a value indicating whether the singleton has been instantiated. */ public function hasSingleton($class, $checkInstance = false) diff --git a/framework/di/ServiceLocator.php b/framework/di/ServiceLocator.php index f729304ae44..09485fa4bdf 100644 --- a/framework/di/ServiceLocator.php +++ b/framework/di/ServiceLocator.php @@ -80,7 +80,7 @@ public function __get($name) * Checks if a property value is null. * This method overrides the parent implementation by checking if the named component is loaded. * @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) { @@ -101,8 +101,8 @@ public function __isset($name) * instantiated the specified component. * * @param string $id component ID (e.g. `db`). - * @param boolean $checkInstance whether the method should check if the component is shared and instantiated. - * @return boolean whether the locator has the specified component definition or has instantiated the component. + * @param bool $checkInstance whether the method should check if the component is shared and instantiated. + * @return bool whether the locator has the specified component definition or has instantiated the component. * @see set() */ public function has($id, $checkInstance = false) @@ -114,7 +114,7 @@ public function has($id, $checkInstance = false) * Returns the component instance with the specified ID. * * @param string $id component ID (e.g. `db`). - * @param boolean $throwException whether to throw an exception if `$id` is not registered with the locator before. + * @param bool $throwException whether to throw an exception if `$id` is not registered with the locator before. * @return object|null the component of the specified ID. If `$throwException` is false and `$id` * is not registered before, null will be returned. * @throws InvalidConfigException if `$id` refers to a nonexistent component ID @@ -219,7 +219,7 @@ public function clear($id) /** * Returns the list of the component definitions or the loaded component instances. - * @param boolean $returnDefinitions whether to return component definitions instead of the loaded component instances. + * @param bool $returnDefinitions whether to return component definitions instead of the loaded component instances. * @return array the list of the component definitions or the loaded component instances (ID => definition or instance). */ public function getComponents($returnDefinitions = true) diff --git a/framework/filters/AccessControl.php b/framework/filters/AccessControl.php index 5c1ce9ad30f..7b39adc6561 100644 --- a/framework/filters/AccessControl.php +++ b/framework/filters/AccessControl.php @@ -107,7 +107,7 @@ public function init() * 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) { diff --git a/framework/filters/AccessRule.php b/framework/filters/AccessRule.php index 6cbf485b90e..2af5adc2074 100644 --- a/framework/filters/AccessRule.php +++ b/framework/filters/AccessRule.php @@ -22,7 +22,7 @@ class AccessRule extends Component { /** - * @var boolean whether this is an 'allow' rule or 'deny' rule. + * @var bool whether this is an 'allow' rule or 'deny' rule. */ public $allow; /** @@ -95,7 +95,7 @@ class AccessRule extends Component * @param Action $action the action to be performed * @param User $user the user object * @param Request $request - * @return boolean|null true if the user is allowed, false if the user is denied, null if the rule does not apply to the user + * @return bool|null true if the user is allowed, false if the user is denied, null if the rule does not apply to the user */ public function allows($action, $user, $request) { @@ -114,7 +114,7 @@ public function allows($action, $user, $request) /** * @param Action $action the action - * @return boolean whether the rule applies to the action + * @return bool whether the rule applies to the action */ protected function matchAction($action) { @@ -123,7 +123,7 @@ protected function matchAction($action) /** * @param Controller $controller the controller - * @return boolean whether the rule applies to the controller + * @return bool whether the rule applies to the controller */ protected function matchController($controller) { @@ -132,7 +132,7 @@ protected function matchController($controller) /** * @param User $user the user object - * @return boolean whether the rule applies to the role + * @return bool whether the rule applies to the role */ protected function matchRole($user) { @@ -158,7 +158,7 @@ protected function matchRole($user) /** * @param string $ip the IP address - * @return boolean whether the rule applies to the IP address + * @return bool whether the rule applies to the IP address */ protected function matchIP($ip) { @@ -176,7 +176,7 @@ protected function matchIP($ip) /** * @param string $verb the request method. - * @return boolean whether the rule applies to the request + * @return bool whether the rule applies to the request */ protected function matchVerb($verb) { @@ -185,7 +185,7 @@ protected function matchVerb($verb) /** * @param Action $action the action to be performed - * @return boolean whether the rule should be applied + * @return bool whether the rule should be applied */ protected function matchCustom($action) { diff --git a/framework/filters/ContentNegotiator.php b/framework/filters/ContentNegotiator.php index 7d2bfc5d211..86140bc149c 100644 --- a/framework/filters/ContentNegotiator.php +++ b/framework/filters/ContentNegotiator.php @@ -245,7 +245,7 @@ protected function negotiateLanguage($request) * Returns a value indicating whether the requested language matches the supported language. * @param string $requested the requested language code * @param string $supported the supported language code - * @return boolean whether the requested language is supported + * @return bool whether the requested language is supported */ protected function isLanguageSupported($requested, $supported) { diff --git a/framework/filters/HttpCache.php b/framework/filters/HttpCache.php index 590611c146b..7732b204bed 100644 --- a/framework/filters/HttpCache.php +++ b/framework/filters/HttpCache.php @@ -102,7 +102,7 @@ class HttpCache extends ActionFilter */ public $sessionCacheLimiter = ''; /** - * @var boolean a value indicating whether this filter should be enabled. + * @var bool a value indicating whether this filter should be enabled. */ public $enabled = true; @@ -111,7 +111,7 @@ class HttpCache extends ActionFilter * 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) { @@ -158,10 +158,10 @@ public function beforeAction($action) /** * Validates if the HTTP cache contains valid content. * If both Last-Modified and ETag are null, returns false. - * @param integer $lastModified the calculated Last-Modified value in terms of a UNIX timestamp. + * @param int $lastModified the calculated Last-Modified value in terms of a UNIX timestamp. * If null, the Last-Modified header will not be validated. * @param string $etag the calculated ETag value. If null, the ETag header will not be validated. - * @return boolean whether the HTTP cache is still valid. + * @return bool whether the HTTP cache is still valid. */ protected function validateCache($lastModified, $etag) { diff --git a/framework/filters/PageCache.php b/framework/filters/PageCache.php index 516c33bbda8..9b9495e2859 100644 --- a/framework/filters/PageCache.php +++ b/framework/filters/PageCache.php @@ -51,7 +51,7 @@ class PageCache extends ActionFilter { /** - * @var boolean whether the content being cached should be differentiated according to the route. + * @var bool whether the content being cached should be differentiated according to the route. * A route consists of the requested controller ID and action ID. Defaults to true. */ public $varyByRoute = true; @@ -63,7 +63,7 @@ class PageCache extends ActionFilter */ public $cache = 'cache'; /** - * @var integer number of seconds that the data can remain valid in cache. + * @var int number of seconds that the data can remain valid in cache. * Use 0 to indicate that the cached data will never expire. */ public $duration = 60; @@ -100,7 +100,7 @@ class PageCache extends ActionFilter */ public $variations; /** - * @var boolean whether to enable the page cache. You may use this property to turn on and off + * @var bool whether to enable the page cache. You may use this property to turn on and off * the page cache according to specific setting (e.g. enable page cache only for GET requests). */ public $enabled = true; @@ -110,14 +110,14 @@ class PageCache extends ActionFilter */ public $view; /** - * @var boolean|array a boolean value indicating whether to cache all cookies, or an array of + * @var bool|array a boolean value indicating whether to cache all cookies, or an array of * cookie names indicating which cookies can be cached. Be very careful with caching cookies, because * it may leak sensitive or private data stored in cookies to unwanted users. * @since 2.0.4 */ public $cacheCookies = false; /** - * @var boolean|array a boolean value indicating whether to cache all HTTP headers, or an array of + * @var bool|array a boolean value indicating whether to cache all HTTP headers, or an array of * HTTP header names (case-insensitive) indicating which HTTP headers can be cached. * Note if your HTTP headers contain sensitive information, you should white-list which headers can be cached. * @since 2.0.4 @@ -140,7 +140,7 @@ public function init() * 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) { diff --git a/framework/filters/RateLimitInterface.php b/framework/filters/RateLimitInterface.php index ebcce73086e..7a3ee3f73f2 100644 --- a/framework/filters/RateLimitInterface.php +++ b/framework/filters/RateLimitInterface.php @@ -37,8 +37,8 @@ public function loadAllowance($request, $action); * Saves the number of allowed requests and the corresponding timestamp to a persistent storage. * @param \yii\web\Request $request the current request * @param \yii\base\Action $action the action to be executed - * @param integer $allowance the number of allowed requests remaining. - * @param integer $timestamp the current timestamp. + * @param int $allowance the number of allowed requests remaining. + * @param int $timestamp the current timestamp. */ public function saveAllowance($request, $action, $allowance, $timestamp); } diff --git a/framework/filters/RateLimiter.php b/framework/filters/RateLimiter.php index d55ca787676..798706171e4 100644 --- a/framework/filters/RateLimiter.php +++ b/framework/filters/RateLimiter.php @@ -40,7 +40,7 @@ class RateLimiter extends ActionFilter { /** - * @var boolean whether to include rate limit headers in the response + * @var bool whether to include rate limit headers in the response */ public $enableRateLimitHeaders = true; /** @@ -117,9 +117,9 @@ public function checkRateLimit($user, $request, $response, $action) /** * Adds the rate limit headers to the response * @param Response $response - * @param integer $limit the maximum number of allowed requests during a period - * @param integer $remaining the remaining number of allowed requests within the current period - * @param integer $reset the number of seconds to wait before having maximum number of allowed requests again + * @param int $limit the maximum number of allowed requests during a period + * @param int $remaining the remaining number of allowed requests within the current period + * @param int $reset the number of seconds to wait before having maximum number of allowed requests again */ public function addRateLimitHeaders($response, $limit, $remaining, $reset) { diff --git a/framework/filters/VerbFilter.php b/framework/filters/VerbFilter.php index 4acda1e970b..510330ea569 100644 --- a/framework/filters/VerbFilter.php +++ b/framework/filters/VerbFilter.php @@ -82,7 +82,7 @@ public function events() /** * @param ActionEvent $event - * @return boolean + * @return bool * @throws MethodNotAllowedHttpException when the request method is not allowed. */ public function beforeAction($event) diff --git a/framework/filters/auth/AuthMethod.php b/framework/filters/auth/AuthMethod.php index f2662122a27..b13f02ef046 100644 --- a/framework/filters/auth/AuthMethod.php +++ b/framework/filters/auth/AuthMethod.php @@ -95,7 +95,7 @@ public function handleFailure($response) * Checks, whether authentication is optional for the given action. * * @param Action $action action to be checked. - * @return boolean whether authentication is optional or not. + * @return bool whether authentication is optional or not. * @see optional * @since 2.0.7 */ diff --git a/framework/grid/ActionColumn.php b/framework/grid/ActionColumn.php index 36f73fba1af..67c6210da0e 100644 --- a/framework/grid/ActionColumn.php +++ b/framework/grid/ActionColumn.php @@ -179,7 +179,7 @@ protected function initDefaultButton($name, $iconName, $additionalOptions = []) * @param string $action the button name (or action ID) * @param \yii\db\ActiveRecord $model the data model * @param mixed $key the key associated with the data model - * @param integer $index the current row index + * @param int $index the current row index * @return string the created URL */ public function createUrl($action, $model, $key, $index) diff --git a/framework/grid/CheckboxColumn.php b/framework/grid/CheckboxColumn.php index ccf547b22f9..b1afdc656aa 100644 --- a/framework/grid/CheckboxColumn.php +++ b/framework/grid/CheckboxColumn.php @@ -66,7 +66,7 @@ class CheckboxColumn extends Column */ public $checkboxOptions = []; /** - * @var boolean whether it is possible to select multiple rows. Defaults to `true`. + * @var bool whether it is possible to select multiple rows. Defaults to `true`. */ public $multiple = true; /** diff --git a/framework/grid/Column.php b/framework/grid/Column.php index 162deb85b2e..96d83fd924d 100644 --- a/framework/grid/Column.php +++ b/framework/grid/Column.php @@ -41,7 +41,7 @@ class Column extends Object */ public $content; /** - * @var boolean whether this column is visible. Defaults to true. + * @var bool whether this column is visible. Defaults to true. */ public $visible = true; /** @@ -97,7 +97,7 @@ public function renderFooterCell() * Renders a data cell. * @param mixed $model the data model being rendered * @param mixed $key the key associated with the data model - * @param integer $index the zero-based index of the data item among the item array returned by [[GridView::dataProvider]]. + * @param int $index the zero-based index of the data item among the item array returned by [[GridView::dataProvider]]. * @return string the rendering result */ public function renderDataCell($model, $key, $index) @@ -155,7 +155,7 @@ protected function renderFooterCellContent() * Renders the data cell content. * @param mixed $model the data model * @param mixed $key the key associated with the data model - * @param integer $index the zero-based index of the data model among the models array returned by [[GridView::dataProvider]]. + * @param int $index the zero-based index of the data model among the models array returned by [[GridView::dataProvider]]. * @return string the rendering result */ protected function renderDataCellContent($model, $key, $index) diff --git a/framework/grid/DataColumn.php b/framework/grid/DataColumn.php index f9c6346c3f5..246271d4409 100644 --- a/framework/grid/DataColumn.php +++ b/framework/grid/DataColumn.php @@ -53,7 +53,7 @@ class DataColumn extends Column */ public $label; /** - * @var boolean whether the header label should be HTML-encoded. + * @var bool whether the header label should be HTML-encoded. * @see label * @since 2.0.1 */ @@ -81,7 +81,7 @@ class DataColumn extends Column */ public $format = 'text'; /** - * @var boolean whether to allow sorting by this column. If true and [[attribute]] is found in + * @var bool whether to allow sorting by this column. If true and [[attribute]] is found in * the sort definition of [[GridView::dataProvider]], then the header cell of this column * will contain a link that may trigger the sorting when being clicked. */ @@ -201,7 +201,7 @@ protected function renderFilterCellContent() * Returns the data cell value. * @param mixed $model the data model * @param mixed $key the key associated with the data model - * @param integer $index the zero-based index of the data model among the models array returned by [[GridView::dataProvider]]. + * @param int $index the zero-based index of the data model among the models array returned by [[GridView::dataProvider]]. * @return string the data cell value */ public function getDataCellValue($model, $key, $index) diff --git a/framework/grid/GridView.php b/framework/grid/GridView.php index 87d7e08c60a..0798ae385dd 100644 --- a/framework/grid/GridView.php +++ b/framework/grid/GridView.php @@ -120,15 +120,15 @@ class GridView extends BaseListView */ public $afterRow; /** - * @var boolean whether to show the header section of the grid table. + * @var bool whether to show the header section of the grid table. */ public $showHeader = true; /** - * @var boolean whether to show the footer section of the grid table. + * @var bool whether to show the footer section of the grid table. */ public $showFooter = false; /** - * @var boolean whether to show the grid view if [[dataProvider]] returns no data. + * @var bool whether to show the grid view if [[dataProvider]] returns no data. */ public $showOnEmpty = true; /** @@ -359,7 +359,7 @@ public function renderItems() /** * Renders the caption element. - * @return boolean|string the rendered caption element or `false` if no caption element should be rendered. + * @return bool|string the rendered caption element or `false` if no caption element should be rendered. */ public function renderCaption() { @@ -372,7 +372,7 @@ public function renderCaption() /** * Renders the column group HTML. - * @return boolean|string the column group HTML or `false` if no column group should be rendered. + * @return bool|string the column group HTML or `false` if no column group should be rendered. */ public function renderColumnGroup() { @@ -496,7 +496,7 @@ public function renderTableBody() * Renders a table row with the given data model and key. * @param mixed $model the data model to be rendered * @param mixed $key the key associated with the data model - * @param integer $index the zero-based index of the data model among the model array returned by [[dataProvider]]. + * @param int $index the zero-based index of the data model among the model array returned by [[dataProvider]]. * @return string the rendering result */ public function renderTableRow($model, $key, $index) diff --git a/framework/helpers/BaseArrayHelper.php b/framework/helpers/BaseArrayHelper.php index 9918b1f6d8d..a395f6fb16e 100644 --- a/framework/helpers/BaseArrayHelper.php +++ b/framework/helpers/BaseArrayHelper.php @@ -53,7 +53,7 @@ class BaseArrayHelper * ] * ``` * - * @param boolean $recursive whether to recursively converts properties which are objects into arrays. + * @param bool $recursive whether to recursively converts properties which are objects into arrays. * @return array the array representation of the object */ public static function toArray($object, $properties = [], $recursive = true) @@ -434,7 +434,7 @@ public static function index($array, $key, $groups = []) * * @param array $array * @param string|\Closure $name - * @param boolean $keepKeys whether to maintain the array keys. If false, the resulting array + * @param bool $keepKeys whether to maintain the array keys. If false, the resulting array * will be re-indexed with integers. * @return array the list of column values */ @@ -517,8 +517,8 @@ public static function map($array, $from, $to, $group = null) * key comparison. * @param string $key the key to check * @param array $array the array with keys to check - * @param boolean $caseSensitive whether the key comparison should be case-sensitive - * @return boolean whether the array contains the specified key + * @param bool $caseSensitive whether the key comparison should be case-sensitive + * @return bool whether the array contains the specified key */ public static function keyExists($key, $array, $caseSensitive = true) { @@ -544,9 +544,9 @@ public static function keyExists($key, $array, $caseSensitive = true) * elements, a property name of the objects, or an anonymous function returning the values for comparison * purpose. The anonymous function signature should be: `function($item)`. * To sort by multiple keys, provide an array of keys here. - * @param integer|array $direction the sorting direction. It can be either `SORT_ASC` or `SORT_DESC`. + * @param int|array $direction the sorting direction. It can be either `SORT_ASC` or `SORT_DESC`. * When sorting by multiple keys with different sorting directions, use an array of sorting directions. - * @param integer|array $sortFlag the PHP sort flag. Valid values include + * @param int|array $sortFlag the PHP sort flag. Valid values include * `SORT_REGULAR`, `SORT_NUMERIC`, `SORT_STRING`, `SORT_LOCALE_STRING`, `SORT_NATURAL` and `SORT_FLAG_CASE`. * Please refer to [PHP manual](http://php.net/manual/en/function.sort.php) * for more details. When sorting by multiple keys with different sort flags, use an array of sort flags. @@ -594,7 +594,7 @@ public static function multisort(&$array, $key, $direction = SORT_ASC, $sortFlag * If a value is an array, this method will also encode it recursively. * Only string values will be encoded. * @param array $data data to be encoded - * @param boolean $valuesOnly whether to encode array values only. If false, + * @param bool $valuesOnly whether to encode array values only. If false, * both the array keys and array values will be encoded. * @param string $charset the charset that the data is using. If not set, * [[\yii\base\Application::charset]] will be used. @@ -629,7 +629,7 @@ public static function htmlEncode($data, $valuesOnly = true, $charset = null) * If a value is an array, this method will also decode it recursively. * Only string values will be decoded. * @param array $data data to be decoded - * @param boolean $valuesOnly whether to decode array values only. If false, + * @param bool $valuesOnly whether to decode array values only. If false, * both the array keys and array values will be decoded. * @return array the decoded data * @see http://www.php.net/manual/en/function.htmlspecialchars-decode.php @@ -662,9 +662,9 @@ public static function htmlDecode($data, $valuesOnly = true) * Note that an empty array will NOT be considered associative. * * @param array $array the array being checked - * @param boolean $allStrings whether the array keys must be all strings in order for + * @param bool $allStrings whether the array keys must be all strings in order for * the array to be treated as associative. - * @return boolean whether the array is associative + * @return bool whether the array is associative */ public static function isAssociative($array, $allStrings = true) { @@ -698,9 +698,9 @@ public static function isAssociative($array, $allStrings = true) * Note that an empty array will be considered indexed. * * @param array $array the array being checked - * @param boolean $consecutive whether the array keys must be a consecutive sequence + * @param bool $consecutive whether the array keys must be a consecutive sequence * in order for the array to be treated as indexed. - * @return boolean whether the array is associative + * @return bool whether the array is associative */ public static function isIndexed($array, $consecutive = false) { @@ -731,8 +731,8 @@ public static function isIndexed($array, $consecutive = false) * but additionally works for objects that implement the [[\Traversable]] interface. * @param mixed $needle The value to look for. * @param array|\Traversable $haystack The set of values to search. - * @param boolean $strict Whether to enable strict (`===`) comparison. - * @return boolean `true` if `$needle` was found in `$haystack`, `false` otherwise. + * @param bool $strict Whether to enable strict (`===`) comparison. + * @return bool `true` if `$needle` was found in `$haystack`, `false` otherwise. * @throws InvalidParamException if `$haystack` is neither traversable nor an array. * @see http://php.net/manual/en/function.in-array.php * @since 2.0.7 @@ -760,7 +760,7 @@ public static function isIn($needle, $haystack, $strict = false) * This method does the same as the PHP function [is_array()](http://php.net/manual/en/function.is-array.php) * but additionally works on objects that implement the [[\Traversable]] interface. * @param mixed $var The variable being evaluated. - * @return boolean whether $var is array-like + * @return bool whether $var is array-like * @see http://php.net/manual/en/function.is_array.php * @since 2.0.8 */ @@ -776,9 +776,9 @@ public static function isTraversable($var) * `$haystack`. If at least one element is missing, `false` will be returned. * @param array|\Traversable $needles The values that must **all** be in `$haystack`. * @param array|\Traversable $haystack The set of value to search. - * @param boolean $strict Whether to enable strict (`===`) comparison. + * @param bool $strict Whether to enable strict (`===`) comparison. * @throws InvalidParamException if `$haystack` or `$needles` is neither traversable nor an array. - * @return boolean `true` if `$needles` is a subset of `$haystack`, `false` otherwise. + * @return bool `true` if `$needles` is a subset of `$haystack`, `false` otherwise. * @since 2.0.7 */ public static function isSubset($needles, $haystack, $strict = false) diff --git a/framework/helpers/BaseConsole.php b/framework/helpers/BaseConsole.php index f826b453073..70323c2d241 100644 --- a/framework/helpers/BaseConsole.php +++ b/framework/helpers/BaseConsole.php @@ -55,7 +55,7 @@ class BaseConsole /** * Moves the terminal cursor up by sending ANSI control code CUU to the terminal. * If the cursor is already at the edge of the screen, this has no effect. - * @param integer $rows number of rows the cursor should be moved up + * @param int $rows number of rows the cursor should be moved up */ public static function moveCursorUp($rows = 1) { @@ -65,7 +65,7 @@ public static function moveCursorUp($rows = 1) /** * Moves the terminal cursor down by sending ANSI control code CUD to the terminal. * If the cursor is already at the edge of the screen, this has no effect. - * @param integer $rows number of rows the cursor should be moved down + * @param int $rows number of rows the cursor should be moved down */ public static function moveCursorDown($rows = 1) { @@ -75,7 +75,7 @@ public static function moveCursorDown($rows = 1) /** * Moves the terminal cursor forward by sending ANSI control code CUF to the terminal. * If the cursor is already at the edge of the screen, this has no effect. - * @param integer $steps number of steps the cursor should be moved forward + * @param int $steps number of steps the cursor should be moved forward */ public static function moveCursorForward($steps = 1) { @@ -85,7 +85,7 @@ public static function moveCursorForward($steps = 1) /** * Moves the terminal cursor backward by sending ANSI control code CUB to the terminal. * If the cursor is already at the edge of the screen, this has no effect. - * @param integer $steps number of steps the cursor should be moved backward + * @param int $steps number of steps the cursor should be moved backward */ public static function moveCursorBackward($steps = 1) { @@ -94,7 +94,7 @@ public static function moveCursorBackward($steps = 1) /** * Moves the terminal cursor to the beginning of the next line by sending ANSI control code CNL to the terminal. - * @param integer $lines number of lines the cursor should be moved down + * @param int $lines number of lines the cursor should be moved down */ public static function moveCursorNextLine($lines = 1) { @@ -103,7 +103,7 @@ public static function moveCursorNextLine($lines = 1) /** * Moves the terminal cursor to the beginning of the previous line by sending ANSI control code CPL to the terminal. - * @param integer $lines number of lines the cursor should be moved up + * @param int $lines number of lines the cursor should be moved up */ public static function moveCursorPrevLine($lines = 1) { @@ -112,8 +112,8 @@ public static function moveCursorPrevLine($lines = 1) /** * Moves the cursor to an absolute position given as column and row by sending ANSI control code CUP or CHA to the terminal. - * @param integer $column 1-based column number, 1 is the left edge of the screen. - * @param integer|null $row 1-based row number, 1 is the top edge of the screen. if not set, will move cursor only in current line. + * @param int $column 1-based column number, 1 is the left edge of the screen. + * @param int|null $row 1-based row number, 1 is the top edge of the screen. if not set, will move cursor only in current line. */ public static function moveCursorTo($column, $row = null) { @@ -127,7 +127,7 @@ public static function moveCursorTo($column, $row = null) /** * Scrolls whole page up by sending ANSI control code SU to the terminal. * New lines are added at the bottom. This is not supported by ANSI.SYS used in windows. - * @param integer $lines number of lines to scroll up + * @param int $lines number of lines to scroll up */ public static function scrollUp($lines = 1) { @@ -137,7 +137,7 @@ public static function scrollUp($lines = 1) /** * Scrolls whole page down by sending ANSI control code SD to the terminal. * New lines are added at the top. This is not supported by ANSI.SYS used in windows. - * @param integer $lines number of lines to scroll down + * @param int $lines number of lines to scroll down */ public static function scrollDown($lines = 1) { @@ -296,7 +296,7 @@ public static function ansiFormat($string, $format = []) * You can pass the return value of this to one of the formatting methods: * [[ansiFormat]], [[ansiFormatCode]], [[beginAnsiFormat]] * - * @param integer $colorCode xterm color code + * @param int $colorCode xterm color code * @return string * @see http://en.wikipedia.org/wiki/Talk:ANSI_escape_code#xterm-256colors */ @@ -310,7 +310,7 @@ public static function xtermFgColor($colorCode) * You can pass the return value of this to one of the formatting methods: * [[ansiFormat]], [[ansiFormatCode]], [[beginAnsiFormat]] * - * @param integer $colorCode xterm color code + * @param int $colorCode xterm color code * @return string * @see http://en.wikipedia.org/wiki/Talk:ANSI_escape_code#xterm-256colors */ @@ -333,7 +333,7 @@ public static function stripAnsiFormat($string) /** * Returns the length of the string without ANSI color codes. * @param string $string the string to measure - * @return integer the length of the string not counting ANSI format characters + * @return int the length of the string not counting ANSI format characters */ public static function ansiStrlen($string) { @@ -496,7 +496,7 @@ public static function markdownToAnsi($markdown) * color codes will just be removed (And %% will be transformed into %) * * @param string $string String to convert - * @param boolean $colored Should the string be colored? + * @param bool $colored Should the string be colored? * @return string */ public static function renderColoredString($string, $colored = true) @@ -577,7 +577,7 @@ public static function escape($string) * - not tty consoles * * @param mixed $stream - * @return boolean true if the stream supports ANSI colors, otherwise false. + * @return bool true if the stream supports ANSI colors, otherwise false. */ public static function streamSupportsAnsiColors($stream) { @@ -588,7 +588,7 @@ public static function streamSupportsAnsiColors($stream) /** * Returns true if the console is running on windows - * @return boolean + * @return bool */ public static function isRunningOnWindows() { @@ -598,10 +598,10 @@ public static function isRunningOnWindows() /** * Usage: list($width, $height) = ConsoleHelper::getScreenSize(); * - * @param boolean $refresh whether to force checking and not re-use cached size value. + * @param bool $refresh whether to force checking and not re-use cached size value. * This is useful to detect changing window size while the application is running but may * not get up to date values on every terminal. - * @return array|boolean An array of ($width, $height) or false when it was not able to determine size. + * @return array|bool An array of ($width, $height) or false when it was not able to determine size. */ public static function getScreenSize($refresh = false) { @@ -652,8 +652,8 @@ public static function getScreenSize($refresh = false) * ``` * * @param string $text the text to be wrapped - * @param integer $indent number of spaces to use for indentation. - * @param boolean $refresh whether to force refresh of screen size. + * @param int $indent number of spaces to use for indentation. + * @param bool $refresh whether to force refresh of screen size. * This will be passed to [[getScreenSize()]]. * @return string the wrapped text. * @since 2.0.4 @@ -680,7 +680,7 @@ public static function wrapText($text, $indent = 0, $refresh = false) /** * Gets input from STDIN and returns a string right-trimmed for EOLs. * - * @param boolean $raw If set to true, returns the raw string without trimming + * @param bool $raw If set to true, returns the raw string without trimming * @return string the string read from stdin */ public static function stdin($raw = false) @@ -692,7 +692,7 @@ public static function stdin($raw = false) * Prints a string to STDOUT. * * @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 static function stdout($string) { @@ -703,7 +703,7 @@ public static function stdout($string) * Prints a string to STDERR. * * @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 static function stderr($string) { @@ -730,7 +730,7 @@ public static function input($prompt = null) * Prints text to STDOUT appended with a carriage return (PHP_EOL). * * @param string $string the text 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 static function output($string = null) { @@ -741,7 +741,7 @@ public static function output($string = null) * Prints text to STDERR appended with a carriage return (PHP_EOL). * * @param string $string the text 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 static function error($string = null) { @@ -806,8 +806,8 @@ public static function prompt($text, $options = []) * Asks user to confirm by typing y or n. * * @param string $message to print 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 */ public static function confirm($message, $default = false) { @@ -889,11 +889,11 @@ public static function select($prompt, $options = []) * Console::endProgress("done." . PHP_EOL); * ``` * - * @param integer $done the number of items that are completed. - * @param integer $total the total value of items that are to be done. + * @param int $done the number of items that are completed. + * @param int $total the total value of items that are to be done. * @param string $prefix an optional string to display before the progress bar. * Default to empty string which results in no prefix to be displayed. - * @param integer|boolean $width optional width of the progressbar. This can be an integer representing + * @param int|bool $width optional width of the progressbar. This can be an integer representing * the number of characters to display for the progress bar or a float between 0 and 1 representing the * percentage of screen with the progress bar may take. It can also be set to false to disable the * bar and only show progress information like percent, number of items and ETA. @@ -917,8 +917,8 @@ public static function startProgress($done, $total, $prefix = '', $width = null) /** * Updates a progress bar that has been started by [[startProgress()]]. * - * @param integer $done the number of items that are completed. - * @param integer $total the total value of items that are to be done. + * @param int $done the number of items that are completed. + * @param int $total the total value of items that are to be done. * @param string $prefix an optional string to display before the progress bar. * Defaults to null meaning the prefix specified by [[startProgress()]] will be used. * If prefix is specified it will update the prefix that will be used by later calls. @@ -995,10 +995,10 @@ public static function updateProgress($done, $total, $prefix = null) /** * Ends a progress bar that has been started by [[startProgress()]]. * - * @param string|boolean $remove This can be `false` to leave the progress bar on screen and just print a newline. + * @param string|bool $remove This can be `false` to leave the progress bar on screen and just print a newline. * If set to `true`, the line of the progress bar will be cleared. This may also be a string to be displayed instead * of the progress bar. - * @param boolean $keepPrefix whether to keep the prefix that has been specified for the progressbar when progressbar + * @param bool $keepPrefix whether to keep the prefix that has been specified for the progressbar when progressbar * gets removed. Defaults to true. * @see startProgress * @see updateProgress diff --git a/framework/helpers/BaseFileHelper.php b/framework/helpers/BaseFileHelper.php index 734330ad511..d4a373705f1 100644 --- a/framework/helpers/BaseFileHelper.php +++ b/framework/helpers/BaseFileHelper.php @@ -125,7 +125,7 @@ public static function localize($file, $language = null, $sourceLanguage = null) * This will be passed as the second parameter to [finfo_open()](http://php.net/manual/en/function.finfo-open.php) * when the `fileinfo` extension is installed. If the MIME type is being determined based via [[getMimeTypeByExtension()]] * and this is null, it will use the file specified by [[mimeMagicFile]]. - * @param boolean $checkExtension whether to use the file extension to determine the MIME type in case + * @param bool $checkExtension whether to use the file extension to determine the MIME type in case * `finfo_open()` cannot determine it. * @return string the MIME type (e.g. `text/plain`). Null is returned if the MIME type cannot be determined. * @throws InvalidConfigException when the `fileinfo` PHP extension is not installed and `$checkExtension` is `false`. @@ -426,7 +426,7 @@ public static function findFiles($dir, $options = []) * @param string $path the path of the file or directory to be checked * @param array $options the filtering options. See [[findFiles()]] for explanations of * the supported options. - * @return boolean whether the file or directory satisfies the filtering options. + * @return bool whether the file or directory satisfies the filtering options. */ public static function filterPath($path, $options) { @@ -469,9 +469,9 @@ public static function filterPath($path, $options) * in order to avoid the impact of the `umask` setting. * * @param string $path path of the directory to be created. - * @param integer $mode the permission to be set for the created directory. - * @param boolean $recursive whether to create parent directories if they do not exist. - * @return boolean whether the directory is created successfully + * @param int $mode the permission to be set for the created directory. + * @param bool $recursive whether to create parent directories if they do not exist. + * @return bool whether the directory is created successfully * @throws \yii\base\Exception if the directory could not be created (i.e. php error due to parallel changes) */ public static function createDirectory($path, $mode = 0775, $recursive = true) @@ -507,9 +507,9 @@ public static function createDirectory($path, $mode = 0775, $recursive = true) * * @param string $baseName file or directory name to compare with the pattern * @param string $pattern the pattern that $baseName will be compared against - * @param integer|boolean $firstWildcard location of first wildcard character in the $pattern - * @param integer $flags pattern flags - * @return boolean whether the name matches against pattern + * @param int|bool $firstWildcard location of first wildcard character in the $pattern + * @param int $flags pattern flags + * @return bool whether the name matches against pattern */ private static function matchBasename($baseName, $pattern, $firstWildcard, $flags) { @@ -541,9 +541,9 @@ private static function matchBasename($baseName, $pattern, $firstWildcard, $flag * @param string $path full path to compare * @param string $basePath base of path that will not be compared * @param string $pattern the pattern that path part will be compared against - * @param integer|boolean $firstWildcard location of first wildcard character in the $pattern - * @param integer $flags pattern flags - * @return boolean whether the path part matches against pattern + * @param int|bool $firstWildcard location of first wildcard character in the $pattern + * @param int $flags pattern flags + * @return bool whether the path part matches against pattern */ private static function matchPathname($path, $basePath, $pattern, $firstWildcard, $flags) { @@ -632,9 +632,9 @@ private static function lastExcludeMatchingFromList($basePath, $path, $excludes) /** * Processes the pattern, stripping special characters like / and ! from the beginning and settings flags instead. * @param string $pattern - * @param boolean $caseSensitive + * @param bool $caseSensitive * @throws \yii\base\InvalidParamException - * @return array with keys: (string) pattern, (int) flags, (int|boolean) firstWildcard + * @return array with keys: (string) pattern, (int) flags, (int|bool) firstWildcard */ private static function parseExcludePattern($pattern, $caseSensitive) { @@ -679,7 +679,7 @@ private static function parseExcludePattern($pattern, $caseSensitive) /** * Searches for the first wildcard character in the pattern. * @param string $pattern the pattern to search in - * @return integer|boolean position of first wildcard character or false if not found + * @return int|bool position of first wildcard character or false if not found */ private static function firstWildcardInPattern($pattern) { diff --git a/framework/helpers/BaseHtml.php b/framework/helpers/BaseHtml.php index 13d2609379c..edd2406f480 100644 --- a/framework/helpers/BaseHtml.php +++ b/framework/helpers/BaseHtml.php @@ -93,7 +93,7 @@ class BaseHtml * Encodes special characters into HTML entities. * The [[\yii\base\Application::charset|application charset]] will be used for encoding. * @param string $content the content to be encoded - * @param boolean $doubleEncode whether to encode HTML entities in `$content`. If false, + * @param bool $doubleEncode whether to encode HTML entities in `$content`. If false, * HTML entities in `$content` will not be further encoded. * @return string the encoded content * @see decode() @@ -119,7 +119,7 @@ public static function decode($content) /** * Generates a complete HTML tag. - * @param string|boolean|null $name the tag name. If $name is `null` or `false`, the corresponding content will be rendered without any tag. + * @param string|bool|null $name the tag name. If $name is `null` or `false`, the corresponding content will be rendered without any tag. * @param string $content the content to be enclosed between the start and end tags. It will not be HTML-encoded. * If this is coming from end users, you should consider [[encode()]] it to prevent XSS attacks. * @param array $options the HTML tag attributes (HTML options) in terms of name-value pairs. @@ -146,7 +146,7 @@ public static function tag($name, $content = '', $options = []) /** * Generates a start tag. - * @param string|boolean|null $name the tag name. If $name is `null` or `false`, the corresponding content will be rendered without any tag. + * @param string|bool|null $name the tag name. If $name is `null` or `false`, the corresponding content will be rendered without any tag. * @param array $options the tag options in terms of name-value pairs. These will be rendered as * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. @@ -165,7 +165,7 @@ public static function beginTag($name, $options = []) /** * Generates an end tag. - * @param string|boolean|null $name the tag name. If $name is `null` or `false`, the corresponding content will be rendered without any tag. + * @param string|bool|null $name the tag name. If $name is `null` or `false`, the corresponding content will be rendered without any tag. * @return string the generated end tag * @see beginTag() * @see tag() @@ -671,7 +671,7 @@ public static function textarea($name, $value = '', $options = []) /** * Generates a radio button input. * @param string $name the name attribute. - * @param boolean $checked whether the radio button should be checked. + * @param bool $checked whether the radio button should be checked. * @param array $options the tag options in terms of name-value pairs. * See [[booleanInput()]] for details about accepted attributes. * @@ -685,7 +685,7 @@ public static function radio($name, $checked = false, $options = []) /** * Generates a checkbox input. * @param string $name the name attribute. - * @param boolean $checked whether the checkbox should be checked. + * @param bool $checked whether the checkbox should be checked. * @param array $options the tag options in terms of name-value pairs. * See [[booleanInput()]] for details about accepted attributes. * @@ -700,7 +700,7 @@ public static function checkbox($name, $checked = false, $options = []) * Generates a boolean input. * @param string $type the input type. This can be either `radio` or `checkbox`. * @param string $name the name attribute. - * @param boolean $checked whether the checkbox should be checked. + * @param bool $checked whether the checkbox should be checked. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled: * * - uncheck: string, the value associated with the uncheck state of the checkbox. When this attribute @@ -1895,7 +1895,7 @@ public static function removeCssClass(&$options, $class) * @param array $options the HTML options to be modified. * @param string|array $style the new style string (e.g. `'width: 100px; height: 200px'`) or * array (e.g. `['width' => '100px', 'height' => '200px']`). - * @param boolean $overwrite whether to overwrite existing CSS properties if the new style + * @param bool $overwrite whether to overwrite existing CSS properties if the new style * contain them too. * @see removeCssStyle() * @see cssStyleFromArray() diff --git a/framework/helpers/BaseInflector.php b/framework/helpers/BaseInflector.php index 1e19d38b2a3..c7085f81d3b 100644 --- a/framework/helpers/BaseInflector.php +++ b/framework/helpers/BaseInflector.php @@ -326,7 +326,7 @@ public static function singularize($word) * Converts an underscored or CamelCase word into a English * sentence. * @param string $words - * @param boolean $ucAll whether to set all words to uppercase + * @param bool $ucAll whether to set all words to uppercase * @return string */ public static function titleize($words, $ucAll = false) @@ -354,7 +354,7 @@ public static function camelize($word) * Converts a CamelCase name into space-separated words. * For example, 'PostTag' will be converted to 'Post Tag'. * @param string $name the string to be converted - * @param boolean $ucwords whether to capitalize the first letter in each word + * @param bool $ucwords whether to capitalize the first letter in each word * @return string the resulting words */ public static function camel2words($name, $ucwords = true) @@ -374,7 +374,7 @@ public static function camel2words($name, $ucwords = true) * For example, 'PostTag' will be converted to 'post-tag'. * @param string $name the string to be converted * @param string $separator the character used to concatenate the words in the ID - * @param boolean|string $strict whether to insert a separator between two consecutive uppercase chars, defaults to false + * @param bool|string $strict whether to insert a separator between two consecutive uppercase chars, defaults to false * @return string the resulting ID */ public static function camel2id($name, $separator = '-', $strict = false) @@ -413,7 +413,7 @@ public static function underscore($words) /** * Returns a human-readable string from $word * @param string $word the string to humanize - * @param boolean $ucAll whether to set all words to uppercase or not + * @param bool $ucAll whether to set all words to uppercase or not * @return string */ public static function humanize($word, $ucAll = false) @@ -459,7 +459,7 @@ public static function tableize($className) * * @param string $string An arbitrary string to convert * @param string $replacement The replacement to use for spaces - * @param boolean $lowercase whether to return the string in lowercase or not. Defaults to `true`. + * @param bool $lowercase whether to return the string in lowercase or not. Defaults to `true`. * @return string The converted string. */ public static function slug($string, $replacement = '-', $lowercase = true) @@ -499,7 +499,7 @@ public static function transliterate($string, $transliterator = null) } /** - * @return boolean if intl extension is loaded + * @return bool if intl extension is loaded */ protected static function hasIntl() { @@ -518,7 +518,7 @@ public static function classify($tableName) /** * Converts number to its ordinal English form. For example, converts 13 to 13th, 2 to 2nd ... - * @param integer $number the number to get its ordinal value + * @param int $number the number to get its ordinal value * @return string */ public static function ordinalize($number) diff --git a/framework/helpers/BaseJson.php b/framework/helpers/BaseJson.php index 9e3b8796e9d..faf6bc8ce9d 100644 --- a/framework/helpers/BaseJson.php +++ b/framework/helpers/BaseJson.php @@ -44,7 +44,7 @@ class BaseJson * In particular, the method will not encode a JavaScript expression that is * represented in terms of a [[JsExpression]] object. * @param mixed $value the data to be encoded. - * @param integer $options the encoding options. For more details please refer to + * @param int $options the encoding options. For more details please refer to * . Default is `JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE`. * @return string the encoding result. * @throws InvalidParamException if there is any encoding error. @@ -82,7 +82,7 @@ public static function htmlEncode($value) /** * Decodes the given JSON string into a PHP data structure. * @param string $json the JSON string to be decoded - * @param boolean $asArray whether to return objects in terms of associative arrays. + * @param bool $asArray whether to return objects in terms of associative arrays. * @return mixed the PHP data * @throws InvalidParamException if there is any decoding error */ @@ -102,7 +102,7 @@ public static function decode($json, $asArray = true) /** * Handles [[encode()]] and [[decode()]] errors by throwing exceptions with the respective error message. * - * @param integer $lastError error code from [json_last_error()](http://php.net/manual/en/function.json-last-error.php). + * @param int $lastError error code from [json_last_error()](http://php.net/manual/en/function.json-last-error.php). * @throws \yii\base\InvalidParamException if there is any encoding/decoding error. * @since 2.0.6 */ diff --git a/framework/helpers/BaseStringHelper.php b/framework/helpers/BaseStringHelper.php index e16b74f494e..4fd0d2edd55 100644 --- a/framework/helpers/BaseStringHelper.php +++ b/framework/helpers/BaseStringHelper.php @@ -24,7 +24,7 @@ class BaseStringHelper * Returns the number of bytes in the given string. * This method ensures the string is treated as a byte array by using `mb_strlen()`. * @param string $string the string being measured for length - * @return integer the number of bytes in the given string. + * @return int the number of bytes in the given string. */ public static function byteLength($string) { @@ -35,8 +35,8 @@ public static function byteLength($string) * Returns the portion of string specified by the start and length parameters. * This method ensures the string is treated as a byte array by using `mb_substr()`. * @param string $string the input string. Must be one character or longer. - * @param integer $start the starting position - * @param integer $length the desired portion length. If not specified or `null`, there will be + * @param int $start the starting position + * @param int $length the desired portion length. If not specified or `null`, there will be * no limit on length i.e. the output will be until the end of the string. * @return string the extracted part of string, or FALSE on failure or an empty string. * @see http://www.php.net/manual/en/function.substr.php @@ -95,10 +95,10 @@ public static function dirname($path) * Truncates a string to the number of characters specified. * * @param string $string The string to truncate. - * @param integer $length How many characters from original string to include into truncated string. + * @param int $length How many characters from original string to include into truncated string. * @param string $suffix String to append to the end of truncated string. * @param string $encoding The charset to use, defaults to charset currently used by application. - * @param boolean $asHtml Whether to treat the string being truncated as HTML and preserve proper HTML tags. + * @param bool $asHtml Whether to treat the string being truncated as HTML and preserve proper HTML tags. * This parameter is available since version 2.0.1. * @return string the truncated string. */ @@ -119,9 +119,9 @@ public static function truncate($string, $length, $suffix = '...', $encoding = n * Truncates a string to the number of words specified. * * @param string $string The string to truncate. - * @param integer $count How many words from original string to include into truncated string. + * @param int $count How many words from original string to include into truncated string. * @param string $suffix String to append to the end of truncated string. - * @param boolean $asHtml Whether to treat the string being truncated as HTML and preserve proper HTML tags. + * @param bool $asHtml Whether to treat the string being truncated as HTML and preserve proper HTML tags. * This parameter is available since version 2.0.1. * @return string the truncated string. */ @@ -143,9 +143,9 @@ public static function truncateWords($string, $count, $suffix = '...', $asHtml = * Truncate a string while preserving the HTML. * * @param string $string The string to truncate - * @param integer $count + * @param int $count * @param string $suffix String to append to the end of the truncated string. - * @param string|boolean $encoding + * @param string|bool $encoding * @return string * @since 2.0.1 */ @@ -194,8 +194,8 @@ protected static function truncateHtml($string, $count, $suffix, $encoding = fal * * @param string $string Input string * @param string $with Part to search inside the $string - * @param boolean $caseSensitive Case sensitive search. Default is true. When case sensitive is enabled, $with must exactly match the starting of the string in order to get a true value. - * @return boolean Returns true if first input starts with second input, false otherwise + * @param bool $caseSensitive Case sensitive search. Default is true. When case sensitive is enabled, $with must exactly match the starting of the string in order to get a true value. + * @return bool Returns true if first input starts with second input, false otherwise */ public static function startsWith($string, $with, $caseSensitive = true) { @@ -215,8 +215,8 @@ public static function startsWith($string, $with, $caseSensitive = true) * * @param string $string Input string to check * @param string $with Part to search inside of the $string. - * @param boolean $caseSensitive Case sensitive search. Default is true. When case sensitive is enabled, $with must exactly match the ending of the string in order to get a true value. - * @return boolean Returns true if first input ends with second input, false otherwise + * @param bool $caseSensitive Case sensitive search. Default is true. When case sensitive is enabled, $with must exactly match the ending of the string in order to get a true value. + * @return bool Returns true if first input ends with second input, false otherwise */ public static function endsWith($string, $with, $caseSensitive = true) { @@ -243,7 +243,7 @@ public static function endsWith($string, $with, $caseSensitive = true) * - boolean - to trim normally; * - string - custom characters to trim. Will be passed as a second argument to `trim()` function. * - callable - will be called for each value instead of trim. Takes the only argument - value. - * @param boolean $skipEmpty Whether to skip empty strings between delimiters. Default is false. + * @param bool $skipEmpty Whether to skip empty strings between delimiters. Default is false. * @return array * @since 2.0.4 */ @@ -274,7 +274,7 @@ public static function explode($string, $delimiter = ',', $trim = true, $skipEmp * @since 2.0.8 * * @param string $string - * @return integer + * @return int */ public static function countWords($string) { diff --git a/framework/helpers/BaseUrl.php b/framework/helpers/BaseUrl.php index 7ebf62ae5f0..0134ec961da 100644 --- a/framework/helpers/BaseUrl.php +++ b/framework/helpers/BaseUrl.php @@ -83,7 +83,7 @@ class BaseUrl * * @param string|array $route use a string to represent a route (e.g. `index`, `site/index`), * or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`). - * @param boolean|string $scheme the URI scheme to use in the generated URL: + * @param bool|string $scheme the URI scheme to use in the generated URL: * * - `false` (default): generating a relative URL. * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::hostInfo]]. @@ -194,7 +194,7 @@ protected static function normalizeRoute($route) * * * @param array|string $url the parameter to be used to generate a valid URL - * @param boolean|string $scheme the URI scheme to use in the generated URL: + * @param bool|string $scheme the URI scheme to use in the generated URL: * * - `false` (default): generating a relative URL. * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::hostInfo]]. @@ -238,7 +238,7 @@ public static function to($url = '', $scheme = false) /** * Returns the base URL of the current request. - * @param boolean|string $scheme the URI scheme to use in the returned base URL: + * @param bool|string $scheme the URI scheme to use in the returned base URL: * * - `false` (default): returning the base URL without host info. * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::hostInfo]]. @@ -317,7 +317,7 @@ public static function canonical() /** * Returns the home URL. * - * @param boolean|string $scheme the URI scheme to use for the returned URL: + * @param bool|string $scheme the URI scheme to use for the returned URL: * * - `false` (default): returning a relative URL. * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::hostInfo]]. @@ -343,7 +343,7 @@ public static function home($scheme = false) * Returns a value indicating whether a URL is relative. * A relative URL does not have host info part. * @param string $url the URL to be checked - * @return boolean whether the URL is relative + * @return bool whether the URL is relative */ public static function isRelative($url) { @@ -384,7 +384,7 @@ public static function isRelative($url) * * @param array $params an associative array of parameters that will be merged with the current GET parameters. * If a parameter value is null, the corresponding GET parameter will be removed. - * @param boolean|string $scheme the URI scheme to use in the generated URL: + * @param bool|string $scheme the URI scheme to use in the generated URL: * * - `false` (default): generating a relative URL. * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::hostInfo]]. diff --git a/framework/helpers/BaseVarDumper.php b/framework/helpers/BaseVarDumper.php index ce4847d5e04..5354e269cb1 100644 --- a/framework/helpers/BaseVarDumper.php +++ b/framework/helpers/BaseVarDumper.php @@ -30,8 +30,8 @@ class BaseVarDumper * This method achieves the similar functionality as var_dump and print_r * but is more robust when handling complex objects such as Yii controllers. * @param mixed $var variable to be dumped - * @param integer $depth maximum depth that the dumper should go into the variable. Defaults to 10. - * @param boolean $highlight whether the result should be syntax-highlighted + * @param int $depth maximum depth that the dumper should go into the variable. Defaults to 10. + * @param bool $highlight whether the result should be syntax-highlighted */ public static function dump($var, $depth = 10, $highlight = false) { @@ -43,8 +43,8 @@ public static function dump($var, $depth = 10, $highlight = false) * This method achieves the similar functionality as var_dump and print_r * but is more robust when handling complex objects such as Yii controllers. * @param mixed $var variable to be dumped - * @param integer $depth maximum depth that the dumper should go into the variable. Defaults to 10. - * @param boolean $highlight whether the result should be syntax-highlighted + * @param int $depth maximum depth that the dumper should go into the variable. Defaults to 10. + * @param bool $highlight whether the result should be syntax-highlighted * @return string the string representation of the variable */ public static function dumpAsString($var, $depth = 10, $highlight = false) @@ -63,7 +63,7 @@ public static function dumpAsString($var, $depth = 10, $highlight = false) /** * @param mixed $var variable to be dumped - * @param integer $level depth level + * @param int $level depth level */ private static function dumpInternal($var, $level) { @@ -161,7 +161,7 @@ public static function export($var) /** * @param mixed $var variable to be exported - * @param integer $level depth level + * @param int $level depth level */ private static function exportInternal($var, $level) { diff --git a/framework/i18n/DbMessageSource.php b/framework/i18n/DbMessageSource.php index 3ad1b4bcddf..92d32a68bc8 100644 --- a/framework/i18n/DbMessageSource.php +++ b/framework/i18n/DbMessageSource.php @@ -76,13 +76,13 @@ class DbMessageSource extends MessageSource */ public $messageTable = '{{%message}}'; /** - * @var integer the time in seconds that the messages can remain valid in cache. + * @var int the time in seconds that the messages can remain valid in cache. * Use 0 to indicate that the cached data will never expire. * @see enableCaching */ public $cachingDuration = 0; /** - * @var boolean whether to enable caching translated messages + * @var bool whether to enable caching translated messages */ public $enableCaching = false; diff --git a/framework/i18n/Formatter.php b/framework/i18n/Formatter.php index a2b3e86c19f..fdd83f73620 100644 --- a/framework/i18n/Formatter.php +++ b/framework/i18n/Formatter.php @@ -246,13 +246,13 @@ class Formatter extends Component */ public $currencyCode; /** - * @var integer the base at which a kilobyte is calculated (1000 or 1024 bytes per kilobyte), used by [[asSize]] and [[asShortSize]]. + * @var int the base at which a kilobyte is calculated (1000 or 1024 bytes per kilobyte), used by [[asSize]] and [[asShortSize]]. * Defaults to 1024. */ public $sizeFormatBase = 1024; /** - * @var boolean whether the [PHP intl extension](http://php.net/manual/en/book.intl.php) is loaded. + * @var bool whether the [PHP intl extension](http://php.net/manual/en/book.intl.php) is loaded. */ private $_intlLoaded = false; @@ -463,7 +463,7 @@ public function asBoolean($value) /** * Formats the value as a date. - * @param integer|string|DateTime $value the value to be formatted. The following + * @param int|string|DateTime $value the value to be formatted. The following * types of value are supported: * * - an integer representing a UNIX timestamp @@ -495,7 +495,7 @@ public function asDate($value, $format = null) /** * Formats the value as a time. - * @param integer|string|DateTime $value the value to be formatted. The following + * @param int|string|DateTime $value the value to be formatted. The following * types of value are supported: * * - an integer representing a UNIX timestamp @@ -527,7 +527,7 @@ public function asTime($value, $format = null) /** * Formats the value as a datetime. - * @param integer|string|DateTime $value the value to be formatted. The following + * @param int|string|DateTime $value the value to be formatted. The following * types of value are supported: * * - an integer representing a UNIX timestamp @@ -568,7 +568,7 @@ public function asDatetime($value, $format = null) ]; /** - * @param integer|string|DateTime $value the value to be formatted. The following + * @param int|string|DateTime $value the value to be formatted. The following * types of value are supported: * * - an integer representing a UNIX timestamp @@ -642,7 +642,7 @@ private function formatDateTimeValue($value, $format, $type) /** * Normalizes the given datetime value as a DateTime object that can be taken by various date/time formatting methods. * - * @param integer|string|DateTime $value the datetime value to be normalized. The following + * @param int|string|DateTime $value the datetime value to be normalized. The following * types of value are supported: * * - an integer representing a UNIX timestamp @@ -650,7 +650,7 @@ private function formatDateTimeValue($value, $format, $type) * The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given. * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object * - * @param boolean $checkTimeInfo whether to also check if the date/time value has some time information attached. + * @param bool $checkTimeInfo whether to also check if the date/time value has some time information attached. * Defaults to `false`. If `true`, the method will then return an array with the first element being the normalized * timestamp and the second a boolean indicating whether the timestamp has time information or it is just a date value. * This parameter is available since version 2.0.1. @@ -695,7 +695,7 @@ protected function normalizeDatetimeValue($value, $checkTimeInfo = false) /** * Formats a date, time or datetime in a float number as UNIX timestamp (seconds since 01-01-1970). - * @param integer|string|DateTime $value the value to be formatted. The following + * @param int|string|DateTime $value the value to be formatted. The following * types of value are supported: * * - an integer representing a UNIX timestamp @@ -723,7 +723,7 @@ public function asTimestamp($value) * 2. Using a timestamp that is relative to the `$referenceTime`. * 3. Using a `DateInterval` object. * - * @param integer|string|DateTime|DateInterval $value the value to be formatted. The following + * @param int|string|DateTime|DateInterval $value the value to be formatted. The following * types of value are supported: * * - an integer representing a UNIX timestamp @@ -732,7 +732,7 @@ public function asTimestamp($value) * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object * - a PHP DateInterval object (a positive time interval will refer to the past, a negative one to the future) * - * @param integer|string|DateTime $referenceTime if specified the value is used as a reference time instead of `now` + * @param int|string|DateTime $referenceTime if specified the value is used as a reference time instead of `now` * when `$value` is not a `DateInterval` object. * @return string the formatted result. * @throws InvalidParamException if the input value can not be evaluated as a date value. @@ -819,7 +819,7 @@ public function asRelativeTime($value, $referenceTime = null) /** * Represents the value as duration in human readable format. * - * @param DateInterval|string|integer $value the value to be formatted. Acceptable formats: + * @param DateInterval|string|int $value the value to be formatted. Acceptable formats: * - [DateInterval object](http://php.net/manual/ru/class.dateinterval.php) * - integer - number of seconds. For example: value `131` represents `2 minutes, 11 seconds` * - ISO8601 duration format. For example, all of these values represent `1 day, 2 hours, 30 minutes` duration: @@ -920,7 +920,7 @@ public function asInteger($value, $options = [], $textOptions = []) * value is rounded automatically to the defined decimal digits. * * @param mixed $value the value to be formatted. - * @param integer $decimals the number of digits after the decimal point. If not given the number of digits is determined from the + * @param int $decimals the number of digits after the decimal point. If not given the number of digits is determined from the * [[locale]] and if the [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available defaults to `2`. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]]. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]]. @@ -955,7 +955,7 @@ public function asDecimal($value, $decimals = null, $options = [], $textOptions * Formats the value as a percent number with "%" sign. * * @param mixed $value the value to be formatted. It must be a factor e.g. `0.75` will result in `75%`. - * @param integer $decimals the number of digits after the decimal point. + * @param int $decimals the number of digits after the decimal point. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]]. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]]. * @return string the formatted result. @@ -987,7 +987,7 @@ public function asPercent($value, $decimals = null, $options = [], $textOptions * Formats the value as a scientific number. * * @param mixed $value the value to be formatted. - * @param integer $decimals the number of digits after the decimal point. + * @param int $decimals the number of digits after the decimal point. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]]. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]]. * @return string the formatted result. @@ -1125,8 +1125,8 @@ public function asOrdinal($value) * If [[sizeFormatBase]] is 1024, [binary prefixes](http://en.wikipedia.org/wiki/Binary_prefix) (e.g. kibibyte/KiB, mebibyte/MiB, ...) * are used in the formatting result. * - * @param string|integer|float $value value in bytes to be formatted. - * @param integer $decimals the number of digits after the decimal point. + * @param string|int|float $value value in bytes to be formatted. + * @param int $decimals the number of digits after the decimal point. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]]. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]]. * @return string the formatted result. @@ -1181,8 +1181,8 @@ public function asShortSize($value, $decimals = null, $options = [], $textOption * If [[sizeFormatBase]] is 1024, [binary prefixes](http://en.wikipedia.org/wiki/Binary_prefix) (e.g. kibibyte/KiB, mebibyte/MiB, ...) * are used in the formatting result. * - * @param string|integer|float $value value in bytes to be formatted. - * @param integer $decimals the number of digits after the decimal point. + * @param string|int|float $value value in bytes to be formatted. + * @param int $decimals the number of digits after the decimal point. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]]. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]]. * @return string the formatted result. @@ -1235,8 +1235,8 @@ public function asSize($value, $decimals = null, $options = [], $textOptions = [ /** * Given the value in bytes formats number part of the human readable form. * - * @param string|integer|float $value value in bytes to be formatted. - * @param integer $decimals the number of digits after the decimal point + * @param string|int|float $value value in bytes to be formatted. + * @param int $decimals the number of digits after the decimal point * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]]. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]]. * @return array [parameters for Yii::t containing formatted number, internal position of size unit] @@ -1290,7 +1290,7 @@ private function formatSizeNumber($value, $decimals, $options, $textOptions) * otherwise an exception is thrown. * * @param mixed $value the input value - * @return float|integer the normalized number value + * @return float|int the normalized number value * @throws InvalidParamException if the input value is not numeric. */ protected function normalizeNumericValue($value) @@ -1312,10 +1312,10 @@ protected function normalizeNumericValue($value) * * You may override this method to create a number formatter based on patterns. * - * @param integer $style the type of the number formatter. + * @param int $style the type of the number formatter. * Values: NumberFormatter::DECIMAL, ::CURRENCY, ::PERCENT, ::SCIENTIFIC, ::SPELLOUT, ::ORDINAL * ::DURATION, ::PATTERN_RULEBASED, ::DEFAULT_STYLE, ::IGNORE - * @param integer $decimals the number of digits after the decimal point. + * @param int $decimals the number of digits after the decimal point. * @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]]. * @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]]. * @return NumberFormatter the created formatter instance diff --git a/framework/i18n/GettextMessageSource.php b/framework/i18n/GettextMessageSource.php index 16ddf81a1b6..60e993412ef 100644 --- a/framework/i18n/GettextMessageSource.php +++ b/framework/i18n/GettextMessageSource.php @@ -40,11 +40,11 @@ class GettextMessageSource extends MessageSource */ public $catalog = 'messages'; /** - * @var boolean + * @var bool */ public $useMoFile = true; /** - * @var boolean + * @var bool */ public $useBigEndian = false; diff --git a/framework/i18n/GettextMoFile.php b/framework/i18n/GettextMoFile.php index 27d958b6d6d..4692bda6e1c 100644 --- a/framework/i18n/GettextMoFile.php +++ b/framework/i18n/GettextMoFile.php @@ -44,7 +44,7 @@ class GettextMoFile extends GettextFile { /** - * @var boolean whether to use big-endian when reading and writing an integer. + * @var bool whether to use big-endian when reading and writing an integer. */ public $useBigEndian = false; @@ -200,7 +200,7 @@ public function save($filePath, $messages) /** * Reads one or several bytes. * @param resource $fileHandle to read from - * @param integer $byteCount to be read + * @param int $byteCount to be read * @return string bytes */ protected function readBytes($fileHandle, $byteCount = 1) @@ -216,7 +216,7 @@ protected function readBytes($fileHandle, $byteCount = 1) * Write bytes. * @param resource $fileHandle to write to * @param string $bytes to be written - * @return integer how many bytes are written + * @return int how many bytes are written */ protected function writeBytes($fileHandle, $bytes) { @@ -226,7 +226,7 @@ protected function writeBytes($fileHandle, $bytes) /** * Reads a 4-byte integer. * @param resource $fileHandle to read from - * @return integer the result + * @return int the result */ protected function readInteger($fileHandle) { @@ -238,8 +238,8 @@ protected function readInteger($fileHandle) /** * Writes a 4-byte integer. * @param resource $fileHandle to write to - * @param integer $integer to be written - * @return integer how many bytes are written + * @param int $integer to be written + * @return int how many bytes are written */ protected function writeInteger($fileHandle, $integer) { @@ -249,8 +249,8 @@ protected function writeInteger($fileHandle, $integer) /** * Reads a string. * @param resource $fileHandle file handle - * @param integer $length of the string - * @param integer $offset of the string in the file. If null, it reads from the current position. + * @param int $length of the string + * @param int $offset of the string in the file. If null, it reads from the current position. * @return string the result */ protected function readString($fileHandle, $length, $offset = null) @@ -266,7 +266,7 @@ protected function readString($fileHandle, $length, $offset = null) * Writes a string. * @param resource $fileHandle to write to * @param string $string to be written - * @return integer how many bytes are written + * @return int how many bytes are written */ protected function writeString($fileHandle, $string) { diff --git a/framework/i18n/MessageFormatter.php b/framework/i18n/MessageFormatter.php index 5476a827737..425ea82dbdc 100644 --- a/framework/i18n/MessageFormatter.php +++ b/framework/i18n/MessageFormatter.php @@ -79,7 +79,7 @@ public function getErrorMessage() * @param string $pattern The pattern string to insert parameters into. * @param array $params The array of name value pairs to insert into the format string. * @param string $language The locale to use for formatting locale-dependent parts - * @return string|boolean The formatted pattern string or `FALSE` if an error occurred + * @return string|bool The formatted pattern string or `FALSE` if an error occurred */ public function format($pattern, $params, $language) { @@ -141,7 +141,7 @@ public function format($pattern, $params, $language) * @param string $pattern The pattern to use for parsing the message. * @param string $message The message to parse, conforming to the pattern. * @param string $language The locale to use for formatting locale-dependent parts - * @return array|boolean An array containing items extracted, or `FALSE` on error. + * @return array|bool An array containing items extracted, or `FALSE` on error. * @throws \yii\base\NotSupportedException when PHP intl extension is not installed. */ public function parse($pattern, $message, $language) @@ -259,7 +259,7 @@ private function replaceNamedArguments($pattern, $givenParams, &$resultingParams * @param string $pattern The pattern string to insert things into. * @param array $args The array of values to insert into the format string * @param string $locale The locale to use for formatting locale-dependent parts - * @return string|boolean The formatted pattern string or `FALSE` if an error occurred + * @return string|bool The formatted pattern string or `FALSE` if an error occurred */ protected function fallbackFormat($pattern, $args, $locale) { @@ -286,7 +286,7 @@ protected function fallbackFormat($pattern, $args, $locale) /** * Tokenizes a pattern by separating normal text from replaceable patterns * @param string $pattern patter to tokenize - * @return array|boolean array of tokens or false on failure + * @return array|bool array of tokens or false on failure */ private static function tokenizePattern($pattern) { @@ -331,7 +331,7 @@ private static function tokenizePattern($pattern) * @param array $token the token to parse * @param array $args arguments to replace * @param string $locale the locale - * @return boolean|string parsed token or false on failure + * @return bool|string parsed token or false on failure * @throws \yii\base\NotSupportedException when unsupported formatting is used. */ private function parseToken($token, $args, $locale) diff --git a/framework/i18n/MessageSource.php b/framework/i18n/MessageSource.php index 34b5ce8946e..9d8ea1f49e7 100644 --- a/framework/i18n/MessageSource.php +++ b/framework/i18n/MessageSource.php @@ -28,7 +28,7 @@ class MessageSource extends Component const EVENT_MISSING_TRANSLATION = 'missingTranslation'; /** - * @var boolean whether to force message translation when the source and target languages are the same. + * @var bool whether to force message translation when the source and target languages are the same. * Defaults to false, meaning translation is only performed when source and target languages are different. */ public $forceTranslation = false; @@ -79,7 +79,7 @@ protected function loadMessages($category, $language) * @param string $category the message category * @param string $message the message to be translated * @param string $language the target language - * @return string|boolean the translated message or false if translation wasn't found or isn't required + * @return string|bool the translated message or false if translation wasn't found or isn't required */ public function translate($category, $message, $language) { @@ -98,7 +98,7 @@ public function translate($category, $message, $language) * @param string $category the category that the message belongs to. * @param string $message the message to be translated. * @param string $language the target language. - * @return string|boolean the translated message or false if translation wasn't found. + * @return string|bool the translated message or false if translation wasn't found. */ protected function translateMessage($category, $message, $language) { diff --git a/framework/log/Dispatcher.php b/framework/log/Dispatcher.php index 3caf8f570fb..472e4d7a940 100644 --- a/framework/log/Dispatcher.php +++ b/framework/log/Dispatcher.php @@ -50,11 +50,11 @@ * Yii::$app->log->targets['file']->enabled = false; * ``` * - * @property integer $flushInterval How many messages should be logged before they are sent to targets. This + * @property int $flushInterval How many messages should be logged before they are sent to targets. This * method returns the value of [[Logger::flushInterval]]. * @property Logger $logger The logger. If not set, [[\Yii::getLogger()]] will be used. Note that the type of * this property differs in getter and setter. See [[getLogger()]] and [[setLogger()]] for details. - * @property integer $traceLevel How many application call stacks should be logged together with each message. + * @property int $traceLevel How many application call stacks should be logged together with each message. * This method returns the value of [[Logger::traceLevel]]. Defaults to 0. * * @author Qiang Xue @@ -133,7 +133,7 @@ public function setLogger($value) } /** - * @return integer how many application call stacks should be logged together with each message. + * @return int how many application call stacks should be logged together with each message. * This method returns the value of [[Logger::traceLevel]]. Defaults to 0. */ public function getTraceLevel() @@ -142,7 +142,7 @@ public function getTraceLevel() } /** - * @param integer $value how many application call stacks should be logged together with each message. + * @param int $value how many application call stacks should be logged together with each message. * This method will set the value of [[Logger::traceLevel]]. If the value is greater than 0, * at most that number of call stacks will be logged. Note that only application call stacks are counted. * Defaults to 0. @@ -153,7 +153,7 @@ public function setTraceLevel($value) } /** - * @return integer how many messages should be logged before they are sent to targets. + * @return int how many messages should be logged before they are sent to targets. * This method returns the value of [[Logger::flushInterval]]. */ public function getFlushInterval() @@ -162,7 +162,7 @@ public function getFlushInterval() } /** - * @param integer $value how many messages should be logged before they are sent to targets. + * @param int $value how many messages should be logged before they are sent to targets. * This method will set the value of [[Logger::flushInterval]]. * Defaults to 1000, meaning the [[Logger::flush()]] method will be invoked once every 1000 messages logged. * Set this property to be 0 if you don't want to flush messages until the application terminates. @@ -177,7 +177,7 @@ public function setFlushInterval($value) /** * Dispatches the logged messages to [[targets]]. * @param array $messages the logged messages - * @param boolean $final whether this method is called at the end of the current application + * @param bool $final whether this method is called at the end of the current application */ public function dispatch($messages, $final) { diff --git a/framework/log/FileTarget.php b/framework/log/FileTarget.php index f4a1f288705..e4c895c0e35 100644 --- a/framework/log/FileTarget.php +++ b/framework/log/FileTarget.php @@ -38,28 +38,28 @@ class FileTarget extends Target */ public $enableRotation = true; /** - * @var integer maximum log file size, in kilo-bytes. Defaults to 10240, meaning 10MB. + * @var int maximum log file size, in kilo-bytes. Defaults to 10240, meaning 10MB. */ public $maxFileSize = 10240; // in KB /** - * @var integer number of log files used for rotation. Defaults to 5. + * @var int number of log files used for rotation. Defaults to 5. */ public $maxLogFiles = 5; /** - * @var integer the permission to be set for newly created log files. + * @var int the permission to be set for newly created log 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. */ public $dirMode = 0775; /** - * @var boolean Whether to rotate log files by copy and truncate in contrast to rotation by + * @var bool Whether to rotate log files by copy and truncate in contrast to rotation by * renaming files. Defaults to `true` to be more compatible with log tailers and is windows * systems which do not play well with rename on open files. Rotation by renaming however is * a bit faster. diff --git a/framework/log/Logger.php b/framework/log/Logger.php index 3e4a3cd996f..155ac391665 100644 --- a/framework/log/Logger.php +++ b/framework/log/Logger.php @@ -92,7 +92,7 @@ class Logger extends Component */ public $messages = []; /** - * @var integer how many messages should be logged before they are flushed from memory and sent to targets. + * @var int how many messages should be logged before they are flushed from memory and sent to targets. * Defaults to 1000, meaning the [[flush]] method will be invoked once every 1000 messages logged. * Set this property to be 0 if you don't want to flush messages until the application terminates. * This property mainly affects how much memory will be taken by the logged messages. @@ -100,7 +100,7 @@ class Logger extends Component */ public $flushInterval = 1000; /** - * @var integer how much call stack information (file name and line number) should be logged for each message. + * @var int how much call stack information (file name and line number) should be logged for each message. * If it is greater than 0, at most that number of call stacks will be logged. Note that only application * call stacks are counted. */ @@ -132,7 +132,7 @@ public function init() * the application code will be logged as well. * @param string|array $message the message to be logged. This can be a simple string or a more * complex data structure that will be handled by a [[Target|log target]]. - * @param integer $level the level of the message. This must be one of the following: + * @param int $level the level of the message. This must be one of the following: * `Logger::LEVEL_ERROR`, `Logger::LEVEL_WARNING`, `Logger::LEVEL_INFO`, `Logger::LEVEL_TRACE`, * `Logger::LEVEL_PROFILE_BEGIN`, `Logger::LEVEL_PROFILE_END`. * @param string $category the category of the message. @@ -163,7 +163,7 @@ public function log($message, $level, $category = 'application') /** * Flushes log messages from memory to targets. - * @param boolean $final whether this is a final call during a request. + * @param bool $final whether this is a final call during a request. */ public function flush($final = false) { @@ -297,7 +297,7 @@ public function calculateTimings($messages) /** * Returns the text display of the specified level. - * @param integer $level the message level, e.g. [[LEVEL_ERROR]], [[LEVEL_WARNING]]. + * @param int $level the message level, e.g. [[LEVEL_ERROR]], [[LEVEL_WARNING]]. * @return string the text display of the level */ public static function getLevelName($level) diff --git a/framework/log/SyslogTarget.php b/framework/log/SyslogTarget.php index 08d17f5cc1c..48d27fbba3c 100644 --- a/framework/log/SyslogTarget.php +++ b/framework/log/SyslogTarget.php @@ -23,7 +23,7 @@ class SyslogTarget extends Target */ public $identity; /** - * @var integer syslog facility. + * @var int syslog facility. */ public $facility = LOG_USER; diff --git a/framework/log/Target.php b/framework/log/Target.php index dc798797033..d7c0a38267f 100644 --- a/framework/log/Target.php +++ b/framework/log/Target.php @@ -25,7 +25,7 @@ * satisfying both filter conditions will be handled. Additionally, you * may specify [[except]] to exclude messages of certain categories. * - * @property integer $levels The message levels that this target is interested in. This is a bitmap of level + * @property int $levels The message levels that this target is interested in. This is a bitmap of level * values. Defaults to 0, meaning all available levels. Note that the type of this property differs in getter * and setter. See [[getLevels()]] and [[setLevels()]] for details. * @@ -37,7 +37,7 @@ abstract class Target extends Component { /** - * @var boolean whether to enable this log target. Defaults to true. + * @var bool whether to enable this log target. Defaults to true. */ public $enabled = true; /** @@ -82,7 +82,7 @@ abstract class Target extends Component */ public $prefix; /** - * @var integer how many messages should be accumulated before they are exported. + * @var int how many messages should be accumulated before they are exported. * Defaults to 1000. Note that messages will always be exported when the application terminates. * Set this property to be 0 if you don't want to export messages until the application terminates. */ @@ -108,7 +108,7 @@ abstract public function export(); * And if requested, it will also export the filtering result to specific medium (e.g. email). * @param array $messages log messages to be processed. See [[Logger::messages]] for the structure * of each message. - * @param boolean $final whether this method is called at the end of the current application + * @param bool $final whether this method is called at the end of the current application */ public function collect($messages, $final) { @@ -144,7 +144,7 @@ protected function getContextMessage() } /** - * @return integer the message levels that this target is interested in. This is a bitmap of + * @return int the message levels that this target is interested in. This is a bitmap of * level values. Defaults to 0, meaning all available levels. */ public function getLevels() @@ -169,7 +169,7 @@ public function getLevels() * Logger::LEVEL_ERROR | Logger::LEVEL_WARNING * ``` * - * @param array|integer $levels message levels that this target is interested in. + * @param array|int $levels message levels that this target is interested in. * @throws InvalidConfigException if $levels value is not correct. */ public function setLevels($levels) @@ -205,7 +205,7 @@ public function setLevels($levels) * Filters the given messages according to their categories and levels. * @param array $messages messages to be filtered. * The message structure follows that in [[Logger::messages]]. - * @param integer $levels the message levels to filter by. This is a bitmap of + * @param int $levels the message levels to filter by. This is a bitmap of * level values. Value 0 means allowing all levels. * @param array $categories the message categories to filter by. If empty, it means all categories are allowed. * @param array $except the message categories to exclude. If empty, it means all categories are allowed. diff --git a/framework/mail/BaseMailer.php b/framework/mail/BaseMailer.php index 9b80f8369b5..07ab9c17684 100644 --- a/framework/mail/BaseMailer.php +++ b/framework/mail/BaseMailer.php @@ -43,7 +43,7 @@ abstract class BaseMailer extends Component implements MailerInterface, ViewCont const EVENT_AFTER_SEND = 'afterSend'; /** - * @var string|boolean HTML layout view name. This is the layout used to render HTML mail body. + * @var string|bool HTML layout view name. This is the layout used to render HTML mail body. * The property can take the following values: * * - a relative view name: a view file relative to [[viewPath]], e.g., 'layouts/html'. @@ -52,7 +52,7 @@ abstract class BaseMailer extends Component implements MailerInterface, ViewCont */ public $htmlLayout = 'layouts/html'; /** - * @var string|boolean text layout view name. This is the layout used to render TEXT mail body. + * @var string|bool text layout view name. This is the layout used to render TEXT mail body. * Please refer to [[htmlLayout]] for possible values that this property can take. */ public $textLayout = 'layouts/text'; @@ -77,7 +77,7 @@ abstract class BaseMailer extends Component implements MailerInterface, ViewCont */ public $messageClass = 'yii\mail\BaseMessage'; /** - * @var boolean whether to save email messages as files under [[fileTransportPath]] instead of sending them + * @var bool whether to save email messages as files under [[fileTransportPath]] instead of sending them * to the actual recipients. This is usually used during development for debugging purpose. * @see fileTransportPath */ @@ -242,7 +242,7 @@ protected function createMessage() * Otherwise, it will call [[sendMessage()]] to send the email to its recipient(s). * Child classes should implement [[sendMessage()]] with the actual email sending logic. * @param MessageInterface $message email message instance to be sent - * @return boolean whether the message has been sent successfully + * @return bool whether the message has been sent successfully */ public function send($message) { @@ -274,7 +274,7 @@ public function send($message) * sending multiple messages. * * @param array $messages list of email messages, which should be sent. - * @return integer number of messages that are successfully sent. + * @return int number of messages that are successfully sent. */ public function sendMultiple(array $messages) { @@ -293,7 +293,7 @@ public function sendMultiple(array $messages) * The view will be rendered using the [[view]] component. * @param string $view the view name or the path alias of the view file. * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file. - * @param string|boolean $layout layout view name or path alias. If false, no layout will be applied. + * @param string|bool $layout layout view name or path alias. If false, no layout will be applied. * @return string the rendering result. */ public function render($view, $params = [], $layout = false) @@ -310,14 +310,14 @@ public function render($view, $params = [], $layout = false) * Sends the specified message. * This method should be implemented by child classes with the actual email sending logic. * @param MessageInterface $message the message to be sent - * @return boolean whether the message is sent successfully + * @return bool whether the message is sent successfully */ abstract protected function sendMessage($message); /** * Saves the message as a file under [[fileTransportPath]]. * @param MessageInterface $message - * @return boolean whether the message is saved successfully + * @return bool whether the message is saved successfully */ protected function saveMessage($message) { @@ -371,7 +371,7 @@ public function setViewPath($path) * You may override this method to do last-minute preparation for the message. * If you override this method, please make sure you call the parent implementation first. * @param MessageInterface $message - * @return boolean whether to continue sending an email. + * @return bool whether to continue sending an email. */ public function beforeSend($message) { @@ -386,7 +386,7 @@ public function beforeSend($message) * You may override this method to do some postprocessing or logging based on mail send status. * If you override this method, please make sure you call the parent implementation first. * @param MessageInterface $message - * @param boolean $isSuccessful + * @param bool $isSuccessful */ public function afterSend($message, $isSuccessful) { diff --git a/framework/mail/BaseMessage.php b/framework/mail/BaseMessage.php index 11c8ab215f1..1a0c73e582b 100644 --- a/framework/mail/BaseMessage.php +++ b/framework/mail/BaseMessage.php @@ -36,7 +36,7 @@ abstract class BaseMessage extends Object implements MessageInterface * @param MailerInterface $mailer the mailer that should be used to send this message. * If no mailer is given it will first check if [[mailer]] is set and if not, * the "mail" application component will be used instead. - * @return boolean whether this message is sent successfully. + * @return bool whether this message is sent successfully. */ public function send(MailerInterface $mailer = null) { diff --git a/framework/mail/MailEvent.php b/framework/mail/MailEvent.php index bb50e54b0bd..5562d8bcaf7 100644 --- a/framework/mail/MailEvent.php +++ b/framework/mail/MailEvent.php @@ -24,11 +24,11 @@ class MailEvent extends Event */ public $message; /** - * @var boolean if message was sent successfully. + * @var bool if message was sent successfully. */ public $isSuccessful; /** - * @var boolean whether to continue sending an email. Event handlers of + * @var bool whether to continue sending an email. Event handlers of * [[\yii\mail\BaseMailer::EVENT_BEFORE_SEND]] may set this property to decide whether * to continue send or not. */ diff --git a/framework/mail/MailerInterface.php b/framework/mail/MailerInterface.php index d730f8739c3..12542de0e17 100644 --- a/framework/mail/MailerInterface.php +++ b/framework/mail/MailerInterface.php @@ -48,7 +48,7 @@ public function compose($view = null, array $params = []); /** * Sends the given email message. * @param MessageInterface $message email message instance to be sent - * @return boolean whether the message has been sent successfully + * @return bool whether the message has been sent successfully */ public function send($message); @@ -58,7 +58,7 @@ public function send($message); * This method may be implemented by some mailers which support more efficient way of sending multiple messages in the same batch. * * @param array $messages list of email messages, which should be sent. - * @return integer number of messages that are successfully sent. + * @return int number of messages that are successfully sent. */ public function sendMultiple(array $messages); } diff --git a/framework/mail/MessageInterface.php b/framework/mail/MessageInterface.php index 57128fde7d4..3f1fae2c5f3 100644 --- a/framework/mail/MessageInterface.php +++ b/framework/mail/MessageInterface.php @@ -206,7 +206,7 @@ public function embedContent($content, array $options = []); * Sends this email message. * @param MailerInterface $mailer the mailer that should be used to send this message. * If null, the "mail" application component will be used instead. - * @return boolean whether this message is sent successfully. + * @return bool whether this message is sent successfully. */ public function send(MailerInterface $mailer = null); diff --git a/framework/mutex/FileMutex.php b/framework/mutex/FileMutex.php index 29a0258ab9c..d673785e1fa 100644 --- a/framework/mutex/FileMutex.php +++ b/framework/mutex/FileMutex.php @@ -46,13 +46,13 @@ class FileMutex extends Mutex */ public $mutexPath = '@runtime/mutex'; /** - * @var integer the permission to be set for newly created mutex files. + * @var int the permission to be set for newly created mutex 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. @@ -81,8 +81,8 @@ public function init() /** * Acquires lock by given name. * @param string $name of the lock to be acquired. - * @param integer $timeout to wait for lock to become released. - * @return boolean acquiring result. + * @param int $timeout to wait for lock to become released. + * @return bool acquiring result. */ protected function acquireLock($name, $timeout = 0) { @@ -111,7 +111,7 @@ protected function acquireLock($name, $timeout = 0) /** * Releases lock by given name. * @param string $name of the lock to be released. - * @return boolean release result. + * @return bool release result. */ protected function releaseLock($name) { diff --git a/framework/mutex/Mutex.php b/framework/mutex/Mutex.php index b868bd7e4b5..ae889b81f45 100644 --- a/framework/mutex/Mutex.php +++ b/framework/mutex/Mutex.php @@ -33,7 +33,7 @@ abstract class Mutex extends Component { /** - * @var boolean whether all locks acquired in this process (i.e. local locks) must be released automatically + * @var bool whether all locks acquired in this process (i.e. local locks) must be released automatically * before finishing script execution. Defaults to true. Setting this property to true means that all locks * acquired in this process must be released (regardless of errors or exceptions). */ @@ -63,9 +63,9 @@ public function init() /** * Acquires a lock by name. * @param string $name of the lock to be acquired. Must be unique. - * @param integer $timeout time to wait for lock to be released. Defaults to zero meaning that method will return + * @param int $timeout time to wait for lock to be released. Defaults to zero meaning that method will return * false immediately in case lock was already acquired. - * @return boolean lock acquiring result. + * @return bool lock acquiring result. */ public function acquire($name, $timeout = 0) { @@ -81,7 +81,7 @@ public function acquire($name, $timeout = 0) /** * Releases acquired lock. This method will return false in case the lock was not found. * @param string $name of the lock to be released. This lock must already exist. - * @return boolean lock release result: false in case named lock was not found.. + * @return bool lock release result: false in case named lock was not found.. */ public function release($name) { @@ -100,15 +100,15 @@ public function release($name) /** * This method should be extended by a concrete Mutex implementations. Acquires lock by name. * @param string $name of the lock to be acquired. - * @param integer $timeout time to wait for the lock to be released. - * @return boolean acquiring result. + * @param int $timeout time to wait for the lock to be released. + * @return bool acquiring result. */ abstract protected function acquireLock($name, $timeout = 0); /** * This method should be extended by a concrete Mutex implementations. Releases lock by given name. * @param string $name of the lock to be released. - * @return boolean release result. + * @return bool release result. */ abstract protected function releaseLock($name); } diff --git a/framework/mutex/MysqlMutex.php b/framework/mutex/MysqlMutex.php index e47a71b9dec..ecb986d86f7 100644 --- a/framework/mutex/MysqlMutex.php +++ b/framework/mutex/MysqlMutex.php @@ -51,8 +51,8 @@ public function init() /** * Acquires lock by given name. * @param string $name of the lock to be acquired. - * @param integer $timeout to wait for lock to become released. - * @return boolean acquiring result. + * @param int $timeout to wait for lock to become released. + * @return bool acquiring result. * @see http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_get-lock */ protected function acquireLock($name, $timeout = 0) @@ -65,7 +65,7 @@ protected function acquireLock($name, $timeout = 0) /** * Releases lock by given name. * @param string $name of the lock to be released. - * @return boolean release result. + * @return bool release result. * @see http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock */ protected function releaseLock($name) diff --git a/framework/mutex/OracleMutex.php b/framework/mutex/OracleMutex.php index d6cba79a488..bc527890bf6 100644 --- a/framework/mutex/OracleMutex.php +++ b/framework/mutex/OracleMutex.php @@ -56,7 +56,7 @@ class OracleMutex extends DbMutex */ public $lockMode = self::MODE_X; /** - * @var boolean whether to release lock on commit. + * @var bool whether to release lock on commit. */ public $releaseOnCommit = false; @@ -77,7 +77,7 @@ public function init() * Acquires lock by given name. * @see http://docs.oracle.com/cd/B19306_01/appdev.102/b14258/d_lock.htm * @param string $name of the lock to be acquired. - * @param integer $timeout to wait for lock to become released. + * @param int $timeout to wait for lock to become released. * @return bool acquiring result. */ protected function acquireLock($name, $timeout = 0) @@ -107,7 +107,7 @@ protected function acquireLock($name, $timeout = 0) /** * Releases lock by given name. * @param string $name of the lock to be released. - * @return boolean release result. + * @return bool release result. * @see http://docs.oracle.com/cd/B19306_01/appdev.102/b14258/d_lock.htm */ protected function releaseLock($name) diff --git a/framework/mutex/PgsqlMutex.php b/framework/mutex/PgsqlMutex.php index aa0d9be5722..311f8950625 100644 --- a/framework/mutex/PgsqlMutex.php +++ b/framework/mutex/PgsqlMutex.php @@ -62,8 +62,8 @@ private function getKeysFromName($name) /** * Acquires lock by given name. * @param string $name of the lock to be acquired. - * @param integer $timeout to wait for lock to become released. - * @return boolean acquiring result. + * @param int $timeout to wait for lock to become released. + * @return bool acquiring result. * @see http://www.postgresql.org/docs/9.0/static/functions-admin.html */ protected function acquireLock($name, $timeout = 0) @@ -80,7 +80,7 @@ protected function acquireLock($name, $timeout = 0) /** * Releases lock by given name. * @param string $name of the lock to be released. - * @return boolean release result. + * @return bool release result. * @see http://www.postgresql.org/docs/9.0/static/functions-admin.html */ protected function releaseLock($name) diff --git a/framework/rbac/Assignment.php b/framework/rbac/Assignment.php index 6c98a93544a..6f077293b59 100644 --- a/framework/rbac/Assignment.php +++ b/framework/rbac/Assignment.php @@ -22,7 +22,7 @@ class Assignment extends Object { /** - * @var string|integer user ID (see [[\yii\web\User::id]]) + * @var string|int user ID (see [[\yii\web\User::id]]) */ public $userId; /** @@ -30,7 +30,7 @@ class Assignment extends Object */ public $roleName; /** - * @var integer UNIX timestamp representing the assignment creation time + * @var int UNIX timestamp representing the assignment creation time */ public $createdAt; } diff --git a/framework/rbac/BaseManager.php b/framework/rbac/BaseManager.php index a68d6db7027..98460ff198d 100644 --- a/framework/rbac/BaseManager.php +++ b/framework/rbac/BaseManager.php @@ -36,7 +36,7 @@ abstract protected function getItem($name); /** * Returns the items of the specified type. - * @param integer $type the auth item type (either [[Item::TYPE_ROLE]] or [[Item::TYPE_PERMISSION]] + * @param int $type the auth item type (either [[Item::TYPE_ROLE]] or [[Item::TYPE_PERMISSION]] * @return Item[] the auth items of the specified type. */ abstract protected function getItems($type); @@ -44,7 +44,7 @@ abstract protected function getItems($type); /** * Adds an auth item to the RBAC system. * @param Item $item the item to add - * @return boolean whether the auth item is successfully added to the system + * @return bool whether the auth item is successfully added to the system * @throws \Exception if data validation or saving fails (such as the name of the role or permission is not unique) */ abstract protected function addItem($item); @@ -52,7 +52,7 @@ abstract protected function addItem($item); /** * Adds a rule to the RBAC system. * @param Rule $rule the rule to add - * @return boolean whether the rule is successfully added to the system + * @return bool whether the rule is successfully added to the system * @throws \Exception if data validation or saving fails (such as the name of the rule is not unique) */ abstract protected function addRule($rule); @@ -60,7 +60,7 @@ abstract protected function addRule($rule); /** * Removes an auth item from the RBAC system. * @param Item $item the item to remove - * @return boolean whether the role or permission is successfully removed + * @return bool whether the role or permission is successfully removed * @throws \Exception if data validation or saving fails (such as the name of the role or permission is not unique) */ abstract protected function removeItem($item); @@ -68,7 +68,7 @@ abstract protected function removeItem($item); /** * Removes a rule from the RBAC system. * @param Rule $rule the rule to remove - * @return boolean whether the rule is successfully removed + * @return bool whether the rule is successfully removed * @throws \Exception if data validation or saving fails (such as the name of the rule is not unique) */ abstract protected function removeRule($rule); @@ -77,7 +77,7 @@ abstract protected function removeRule($rule); * Updates an auth item in the RBAC system. * @param string $name the name of the item being updated * @param Item $item the updated item - * @return boolean whether the auth item is successfully updated + * @return bool whether the auth item is successfully updated * @throws \Exception if data validation or saving fails (such as the name of the role or permission is not unique) */ abstract protected function updateItem($name, $item); @@ -86,7 +86,7 @@ abstract protected function updateItem($name, $item); * Updates a rule to the RBAC system. * @param string $name the name of the rule being updated * @param Rule $rule the updated rule - * @return boolean whether the rule is successfully updated + * @return bool whether the rule is successfully updated * @throws \Exception if data validation or saving fails (such as the name of the rule is not unique) */ abstract protected function updateRule($name, $rule); @@ -203,11 +203,11 @@ public function getPermissions() * If the item does not specify a rule, this method will return true. Otherwise, it will * return the value of [[Rule::execute()]]. * - * @param string|integer $user the user ID. This should be either an integer or a string representing + * @param string|int $user the user ID. This should be either an integer or a string representing * the unique identifier of a user. See [[\yii\web\User::id]]. * @param Item $item the auth item that needs to execute its rule * @param array $params parameters passed to [[CheckAccessInterface::checkAccess()]] and will be passed to the rule - * @return boolean the return value of [[Rule::execute()]]. If the auth item does not specify a rule, true will be returned. + * @return bool the return value of [[Rule::execute()]]. If the auth item does not specify a rule, true will be returned. * @throws InvalidConfigException if the auth item has an invalid rule. */ protected function executeRule($user, $item, $params) diff --git a/framework/rbac/CheckAccessInterface.php b/framework/rbac/CheckAccessInterface.php index e80d065c207..366088a8f46 100644 --- a/framework/rbac/CheckAccessInterface.php +++ b/framework/rbac/CheckAccessInterface.php @@ -17,12 +17,12 @@ interface CheckAccessInterface { /** * Checks if the user has the specified permission. - * @param string|integer $userId the user ID. This should be either an integer or a string representing + * @param string|int $userId the user ID. This should be either an integer or a string representing * the unique identifier of a user. See [[\yii\web\User::id]]. * @param string $permissionName the name of the permission to be checked against * @param array $params name-value pairs that will be passed to the rules associated * with the roles and permissions assigned to the user. - * @return boolean whether the user has the specified permission. + * @return bool whether the user has the specified permission. * @throws \yii\base\InvalidParamException if $permissionName does not refer to an existing permission */ public function checkAccess($userId, $permissionName, $params = []); diff --git a/framework/rbac/DbManager.php b/framework/rbac/DbManager.php index 276bf15ba93..c412e9d697b 100644 --- a/framework/rbac/DbManager.php +++ b/framework/rbac/DbManager.php @@ -132,14 +132,14 @@ public function checkAccess($userId, $permissionName, $params = []) /** * Performs access check for the specified user based on the data loaded from cache. * This method is internally called by [[checkAccess()]] when [[cache]] is enabled. - * @param string|integer $user the user ID. This should can be either an integer or a string representing + * @param string|int $user the user ID. This should can be either an integer or a string representing * the unique identifier of a user. See [[\yii\web\User::id]]. * @param string $itemName the name of the operation that need access check * @param array $params name-value pairs that would be passed to rules associated * with the tasks and roles assigned to the user. A param with name 'user' is added to this array, * which holds the value of `$userId`. * @param Assignment[] $assignments the assignments to the specified user - * @return boolean whether the operations can be performed by the user. + * @return bool whether the operations can be performed by the user. * @since 2.0.3 */ protected function checkAccessFromCache($user, $itemName, $params, $assignments) @@ -174,14 +174,14 @@ protected function checkAccessFromCache($user, $itemName, $params, $assignments) /** * Performs access check for the specified user. * This method is internally called by [[checkAccess()]]. - * @param string|integer $user the user ID. This should can be either an integer or a string representing + * @param string|int $user the user ID. This should can be either an integer or a string representing * the unique identifier of a user. See [[\yii\web\User::id]]. * @param string $itemName the name of the operation that need access check * @param array $params name-value pairs that would be passed to rules associated * with the tasks and roles assigned to the user. A param with name 'user' is added to this array, * which holds the value of `$userId`. * @param Assignment[] $assignments the assignments to the specified user - * @return boolean whether the operations can be performed by the user. + * @return bool whether the operations can be performed by the user. */ protected function checkAccessRecursive($user, $itemName, $params, $assignments) { @@ -244,7 +244,7 @@ protected function getItem($name) /** * Returns a value indicating whether the database supports cascading update and delete. * The default implementation will return false for SQLite database and true for all other databases. - * @return boolean whether the database supports cascading update and delete. + * @return bool whether the database supports cascading update and delete. */ protected function supportsCascadeUpdate() { @@ -534,7 +534,7 @@ public function getPermissionsByUser($userId) /** * Returns all permissions that are directly assigned to user. - * @param string|integer $userId the user ID (see [[\yii\web\User::id]]) + * @param string|int $userId the user ID (see [[\yii\web\User::id]]) * @return Permission[] all direct permissions that the user has. The array is indexed by the permission names. * @since 2.0.7 */ @@ -555,7 +555,7 @@ protected function getDirectPermissionsByUser($userId) /** * Returns all permissions that the user inherits from the roles assigned to him. - * @param string|integer $userId the user ID (see [[\yii\web\User::id]]) + * @param string|int $userId the user ID (see [[\yii\web\User::id]]) * @return Permission[] all inherited permissions that the user has. The array is indexed by the permission names. * @since 2.0.7 */ @@ -797,7 +797,7 @@ public function getChildren($name) * Checks whether there is a loop in the authorization item hierarchy. * @param Item $parent the parent item * @param Item $child the child item to be added to the hierarchy - * @return boolean whether a loop exists + * @return bool whether a loop exists */ protected function detectLoop($parent, $child) { @@ -891,7 +891,7 @@ public function removeAllRoles() /** * Removes all auth items of the specified type. - * @param integer $type the auth item type (either Item::TYPE_PERMISSION or Item::TYPE_ROLE) + * @param int $type the auth item type (either Item::TYPE_PERMISSION or Item::TYPE_ROLE) */ protected function removeAllItems($type) { diff --git a/framework/rbac/Item.php b/framework/rbac/Item.php index b80984f5db2..156e58f8cd4 100644 --- a/framework/rbac/Item.php +++ b/framework/rbac/Item.php @@ -21,7 +21,7 @@ class Item extends Object const TYPE_PERMISSION = 2; /** - * @var integer the type of the item. This should be either [[TYPE_ROLE]] or [[TYPE_PERMISSION]]. + * @var int the type of the item. This should be either [[TYPE_ROLE]] or [[TYPE_PERMISSION]]. */ public $type; /** @@ -41,11 +41,11 @@ class Item extends Object */ public $data; /** - * @var integer UNIX timestamp representing the item creation time + * @var int UNIX timestamp representing the item creation time */ public $createdAt; /** - * @var integer UNIX timestamp representing the item updating time + * @var int UNIX timestamp representing the item updating time */ public $updatedAt; } diff --git a/framework/rbac/ManagerInterface.php b/framework/rbac/ManagerInterface.php index fde8a6cb234..7c7ed1895b7 100644 --- a/framework/rbac/ManagerInterface.php +++ b/framework/rbac/ManagerInterface.php @@ -36,7 +36,7 @@ public function createPermission($name); /** * Adds a role, permission or rule to the RBAC system. * @param Role|Permission|Rule $object - * @return boolean whether the role, permission or rule is successfully added to the system + * @return bool whether the role, permission or rule is successfully added to the system * @throws \Exception if data validation or saving fails (such as the name of the role or permission is not unique) */ public function add($object); @@ -44,7 +44,7 @@ public function add($object); /** * Removes a role, permission or rule from the RBAC system. * @param Role|Permission|Rule $object - * @return boolean whether the role, permission or rule is successfully removed + * @return bool whether the role, permission or rule is successfully removed */ public function remove($object); @@ -52,7 +52,7 @@ public function remove($object); * Updates the specified role, permission or rule in the system. * @param string $name the old name of the role, permission or rule * @param Role|Permission|Rule $object - * @return boolean whether the update is successful + * @return bool whether the update is successful * @throws \Exception if data validation or saving fails (such as the name of the role or permission is not unique) */ public function update($name, $object); @@ -73,7 +73,7 @@ public function getRoles(); /** * Returns the roles that are assigned to the user via [[assign()]]. * Note that child roles that are not assigned directly to the user will not be returned. - * @param string|integer $userId the user ID (see [[\yii\web\User::id]]) + * @param string|int $userId the user ID (see [[\yii\web\User::id]]) * @return Role[] all roles directly assigned to the user. The array is indexed by the role names. */ public function getRolesByUser($userId); @@ -110,7 +110,7 @@ public function getPermissionsByRole($roleName); /** * Returns all permissions that the user has. - * @param string|integer $userId the user ID (see [[\yii\web\User::id]]) + * @param string|int $userId the user ID (see [[\yii\web\User::id]]) * @return Permission[] all permissions that the user has. The array is indexed by the permission names. */ public function getPermissionsByUser($userId); @@ -132,7 +132,7 @@ public function getRules(); * Checks the possibility of adding a child to parent * @param Item $parent the parent item * @param Item $child the child item to be added to the hierarchy - * @return boolean possibility of adding + * @return bool possibility of adding * * @since 2.0.8 */ @@ -142,7 +142,7 @@ public function canAddChild($parent, $child); * Adds an item as a child of another item. * @param Item $parent * @param Item $child - * @return boolean whether the child successfully added + * @return bool whether the child successfully added * @throws \yii\base\Exception if the parent-child relationship already exists or if a loop has been detected. */ public function addChild($parent, $child); @@ -152,7 +152,7 @@ public function addChild($parent, $child); * Note, the child item is not deleted. Only the parent-child relationship is removed. * @param Item $parent * @param Item $child - * @return boolean whether the removal is successful + * @return bool whether the removal is successful */ public function removeChild($parent, $child); @@ -160,7 +160,7 @@ public function removeChild($parent, $child); * Removed all children form their parent. * Note, the children items are not deleted. Only the parent-child relationships are removed. * @param Item $parent - * @return boolean whether the removal is successful + * @return bool whether the removal is successful */ public function removeChildren($parent); @@ -168,7 +168,7 @@ public function removeChildren($parent); * Returns a value indicating whether the child already exists for the parent. * @param Item $parent * @param Item $child - * @return boolean whether `$child` is already a child of `$parent` + * @return bool whether `$child` is already a child of `$parent` */ public function hasChild($parent, $child); @@ -183,7 +183,7 @@ public function getChildren($name); * Assigns a role to a user. * * @param Role $role - * @param string|integer $userId the user ID (see [[\yii\web\User::id]]) + * @param string|int $userId the user ID (see [[\yii\web\User::id]]) * @return Assignment the role assignment information. * @throws \Exception if the role has already been assigned to the user */ @@ -192,22 +192,22 @@ public function assign($role, $userId); /** * Revokes a role from a user. * @param Role $role - * @param string|integer $userId the user ID (see [[\yii\web\User::id]]) - * @return boolean whether the revoking is successful + * @param string|int $userId the user ID (see [[\yii\web\User::id]]) + * @return bool whether the revoking is successful */ public function revoke($role, $userId); /** * Revokes all roles from a user. * @param mixed $userId the user ID (see [[\yii\web\User::id]]) - * @return boolean whether the revoking is successful + * @return bool whether the revoking is successful */ public function revokeAll($userId); /** * Returns the assignment information regarding a role and a user. * @param string $roleName the role name - * @param string|integer $userId the user ID (see [[\yii\web\User::id]]) + * @param string|int $userId the user ID (see [[\yii\web\User::id]]) * @return null|Assignment the assignment information. Null is returned if * the role is not assigned to the user. */ @@ -215,7 +215,7 @@ public function getAssignment($roleName, $userId); /** * Returns all role assignment information for the specified user. - * @param string|integer $userId the user ID (see [[\yii\web\User::id]]) + * @param string|int $userId the user ID (see [[\yii\web\User::id]]) * @return Assignment[] the assignments indexed by role names. An empty array will be * returned if there is no role assigned to the user. */ diff --git a/framework/rbac/PhpManager.php b/framework/rbac/PhpManager.php index 66459c410fe..432653d376f 100644 --- a/framework/rbac/PhpManager.php +++ b/framework/rbac/PhpManager.php @@ -114,14 +114,14 @@ public function getAssignments($userId) * Performs access check for the specified user. * This method is internally called by [[checkAccess()]]. * - * @param string|integer $user the user ID. This should can be either an integer or a string representing + * @param string|int $user the user ID. This should can be either an integer or a string representing * the unique identifier of a user. See [[\yii\web\User::id]]. * @param string $itemName the name of the operation that need access check * @param array $params name-value pairs that would be passed to rules associated * with the tasks and roles assigned to the user. A param with name 'user' is added to this array, * which holds the value of `$userId`. * @param Assignment[] $assignments the assignments to the specified user - * @return boolean whether the operations can be performed by the user. + * @return bool whether the operations can be performed by the user. */ protected function checkAccessRecursive($user, $itemName, $params, $assignments) { @@ -192,7 +192,7 @@ public function addChild($parent, $child) * * @param Item $parent parent item * @param Item $child the child item that is to be added to the hierarchy - * @return boolean whether a loop exists + * @return bool whether a loop exists */ protected function detectLoop($parent, $child) { @@ -469,7 +469,7 @@ public function getPermissionsByUser($userId) /** * Returns all permissions that are directly assigned to user. - * @param string|integer $userId the user ID (see [[\yii\web\User::id]]) + * @param string|int $userId the user ID (see [[\yii\web\User::id]]) * @return Permission[] all direct permissions that the user has. The array is indexed by the permission names. * @since 2.0.7 */ @@ -488,7 +488,7 @@ protected function getDirectPermissionsByUser($userId) /** * Returns all permissions that the user inherits from the roles assigned to him. - * @param string|integer $userId the user ID (see [[\yii\web\User::id]]) + * @param string|int $userId the user ID (see [[\yii\web\User::id]]) * @return Permission[] all inherited permissions that the user has. The array is indexed by the permission names. * @since 2.0.7 */ @@ -551,7 +551,7 @@ public function removeAllRoles() /** * Removes all auth items of the specified type. - * @param integer $type the auth item type (either Item::TYPE_PERMISSION or Item::TYPE_ROLE) + * @param int $type the auth item type (either Item::TYPE_PERMISSION or Item::TYPE_ROLE) */ protected function removeAllItems($type) { diff --git a/framework/rbac/Rule.php b/framework/rbac/Rule.php index b654e0d4411..0ea2469a1bc 100644 --- a/framework/rbac/Rule.php +++ b/framework/rbac/Rule.php @@ -24,11 +24,11 @@ abstract class Rule extends Object */ public $name; /** - * @var integer UNIX timestamp representing the rule creation time + * @var int UNIX timestamp representing the rule creation time */ public $createdAt; /** - * @var integer UNIX timestamp representing the rule updating time + * @var int UNIX timestamp representing the rule updating time */ public $updatedAt; @@ -36,11 +36,11 @@ abstract class Rule extends Object /** * Executes the rule. * - * @param string|integer $user the user ID. This should be either an integer or a string representing + * @param string|int $user the user ID. This should be either an integer or a string representing * the unique identifier of a user. See [[\yii\web\User::id]]. * @param Item $item the role or permission that this rule is associated with * @param array $params parameters passed to [[CheckAccessInterface::checkAccess()]]. - * @return boolean a value indicating whether the rule permits the auth item it is associated with. + * @return bool a value indicating whether the rule permits the auth item it is associated with. */ abstract public function execute($user, $item, $params); } diff --git a/framework/requirements/YiiRequirementChecker.php b/framework/requirements/YiiRequirementChecker.php index ee971b03ae5..9fe8608d382 100644 --- a/framework/requirements/YiiRequirementChecker.php +++ b/framework/requirements/YiiRequirementChecker.php @@ -169,7 +169,7 @@ function render() * @param string $extensionName PHP extension name. * @param string $version required PHP extension version. * @param string $compare comparison operator, by default '>=' - * @return boolean if PHP extension version matches. + * @return bool if PHP extension version matches. */ function checkPhpExtensionVersion($extensionName, $version, $compare = '>=') { @@ -190,7 +190,7 @@ function checkPhpExtensionVersion($extensionName, $version, $compare = '>=') /** * Checks if PHP configuration option (from php.ini) is on. * @param string $name configuration option name. - * @return boolean option is on. + * @return bool option is on. */ function checkPhpIniOn($name) { @@ -205,7 +205,7 @@ function checkPhpIniOn($name) /** * Checks if PHP configuration option (from php.ini) is off. * @param string $name configuration option name. - * @return boolean option is off. + * @return bool option is off. */ function checkPhpIniOff($name) { @@ -223,7 +223,7 @@ function checkPhpIniOff($name) * @param string $a first value. * @param string $b second value. * @param string $compare comparison operator, by default '>='. - * @return boolean comparison result. + * @return bool comparison result. */ function compareByteSize($a, $b, $compare = '>=') { @@ -236,7 +236,7 @@ function compareByteSize($a, $b, $compare = '>=') * Gets the size in bytes from verbose size representation. * For example: '5K' => 5*1024 * @param string $verboseSize verbose size representation. - * @return integer actual size in bytes. + * @return int actual size in bytes. */ function getByteSize($verboseSize) { @@ -271,7 +271,7 @@ function getByteSize($verboseSize) * Checks if upload max file size matches the given range. * @param string|null $min verbose file size minimum required value, pass null to skip minimum check. * @param string|null $max verbose file size maximum required value, pass null to skip maximum check. - * @return boolean success. + * @return bool success. */ function checkUploadMaxFileSize($min = null, $max = null) { @@ -297,7 +297,7 @@ function checkUploadMaxFileSize($min = null, $max = null) * and captures the display result if required. * @param string $_viewFile_ view file * @param array $_data_ data to be extracted and made available to the view file - * @param boolean $_return_ whether the rendering result should be returned as a string + * @param bool $_return_ whether the rendering result should be returned as a string * @return string the rendering result. Null if the rendering result is not required. */ function renderViewFile($_viewFile_, $_data_ = null, $_return_ = false) @@ -322,7 +322,7 @@ function renderViewFile($_viewFile_, $_data_ = null, $_return_ = false) /** * Normalizes requirement ensuring it has correct format. * @param array $requirement raw requirement. - * @param integer $requirementKey requirement key in the list. + * @param int $requirementKey requirement key in the list. * @return array normalized requirement. */ function normalizeRequirement($requirement, $requirementKey = 0) diff --git a/framework/rest/UrlRule.php b/framework/rest/UrlRule.php index 9c326e299d1..d83b062f81d 100644 --- a/framework/rest/UrlRule.php +++ b/framework/rest/UrlRule.php @@ -130,7 +130,7 @@ class UrlRule extends CompositeUrlRule 'class' => 'yii\web\UrlRule', ]; /** - * @var boolean whether to automatically pluralize the URL names for controllers. + * @var bool whether to automatically pluralize the URL names for controllers. * If true, a controller ID will appear in plural form in URLs. For example, `user` controller * will appear as `users` in URLs. * @see controller diff --git a/framework/test/ActiveFixture.php b/framework/test/ActiveFixture.php index 713176b9cb4..6bdea5f099e 100644 --- a/framework/test/ActiveFixture.php +++ b/framework/test/ActiveFixture.php @@ -40,7 +40,7 @@ class ActiveFixture extends BaseActiveFixture */ public $tableName; /** - * @var string|boolean the file path or path alias of the data file that contains the fixture data + * @var string|bool the file path or path alias of the data file that contains the fixture data * to be returned by [[getData()]]. If this is not set, it will default to `FixturePath/data/TableName.php`, * where `FixturePath` stands for the directory containing this fixture class, and `TableName` stands for the * name of the table associated with this fixture. You can set this property to be false to prevent loading any data. diff --git a/framework/test/ArrayFixture.php b/framework/test/ArrayFixture.php index 2697f674dcc..7262e16e44e 100644 --- a/framework/test/ArrayFixture.php +++ b/framework/test/ArrayFixture.php @@ -28,7 +28,7 @@ class ArrayFixture extends Fixture implements \IteratorAggregate, \ArrayAccess, */ public $data = []; /** - * @var string|boolean the file path or path alias of the data file that contains the fixture data + * @var string|bool the file path or path alias of the data file that contains the fixture data * to be returned by [[getData()]]. You can set this property to be false to prevent loading any data. */ public $dataFile; diff --git a/framework/test/BaseActiveFixture.php b/framework/test/BaseActiveFixture.php index 17fec0b39ca..72138762541 100644 --- a/framework/test/BaseActiveFixture.php +++ b/framework/test/BaseActiveFixture.php @@ -32,7 +32,7 @@ abstract class BaseActiveFixture extends DbFixture implements \IteratorAggregate */ public $data = []; /** - * @var string|boolean the file path or path alias of the data file that contains the fixture data + * @var string|bool the file path or path alias of the data file that contains the fixture data * to be returned by [[getData()]]. You can set this property to be false to prevent loading any data. */ public $dataFile; diff --git a/framework/test/InitDbFixture.php b/framework/test/InitDbFixture.php index 81145011e3f..285269edf3e 100644 --- a/framework/test/InitDbFixture.php +++ b/framework/test/InitDbFixture.php @@ -88,7 +88,7 @@ public function afterUnload() /** * Toggles the DB 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. */ public function checkIntegrity($check) { diff --git a/framework/validators/BooleanValidator.php b/framework/validators/BooleanValidator.php index 348d9dd58e9..52c6dfcb9d1 100644 --- a/framework/validators/BooleanValidator.php +++ b/framework/validators/BooleanValidator.php @@ -29,7 +29,7 @@ class BooleanValidator extends Validator */ public $falseValue = '0'; /** - * @var boolean whether the comparison to [[trueValue]] and [[falseValue]] is strict. + * @var bool whether the comparison to [[trueValue]] and [[falseValue]] is strict. * When this is true, the attribute value and type must both match those of [[trueValue]] or [[falseValue]]. * Defaults to false, meaning only the value needs to be matched. */ diff --git a/framework/validators/CompareValidator.php b/framework/validators/CompareValidator.php index f13aade3e8e..b2ee65cce91 100644 --- a/framework/validators/CompareValidator.php +++ b/framework/validators/CompareValidator.php @@ -187,7 +187,7 @@ protected function validateValue($value) * @param string $type the type of the values being compared * @param mixed $value the value being compared * @param mixed $compareValue another value being compared - * @return boolean whether the comparison using the specified operator is true. + * @return bool whether the comparison using the specified operator is true. */ protected function compareValues($operator, $type, $value, $compareValue) { diff --git a/framework/validators/DateValidator.php b/framework/validators/DateValidator.php index 3758dee9cf1..53e605fec73 100644 --- a/framework/validators/DateValidator.php +++ b/framework/validators/DateValidator.php @@ -157,7 +157,7 @@ class DateValidator extends Validator */ public $timestampAttributeTimeZone = 'UTC'; /** - * @var integer|string upper limit of the date. Defaults to null, meaning no upper limit. + * @var int|string upper limit of the date. Defaults to null, meaning no upper limit. * This can be a unix timestamp or a string representing a date time value. * If this property is a string, [[format]] will be used to parse it. * @see tooBig for the customized message used when the date is too big. @@ -165,7 +165,7 @@ class DateValidator extends Validator */ public $max; /** - * @var integer|string lower limit of the date. Defaults to null, meaning no lower limit. + * @var int|string lower limit of the date. Defaults to null, meaning no lower limit. * This can be a unix timestamp or a string representing a date time value. * If this property is a string, [[format]] will be used to parse it. * @see tooSmall for the customized message used when the date is too small. @@ -314,7 +314,7 @@ protected function validateValue($value) * Parses date string into UNIX timestamp * * @param string $value string representing date - * @return integer|false a UNIX timestamp or `false` on failure. + * @return int|false a UNIX timestamp or `false` on failure. */ protected function parseDateValue($value) { @@ -327,7 +327,7 @@ protected function parseDateValue($value) * * @param string $value string representing date * @param string $format expected date format - * @return integer|false a UNIX timestamp or `false` on failure. + * @return int|false a UNIX timestamp or `false` on failure. */ private function parseDateValueFormat($value, $format) { @@ -351,7 +351,7 @@ private function parseDateValueFormat($value, $format) * Parses a date value using the IntlDateFormatter::parse() * @param string $value string representing date * @param string $format the expected date format - * @return integer|boolean a UNIX timestamp or `false` on failure. + * @return int|bool a UNIX timestamp or `false` on failure. * @throws InvalidConfigException */ private function parseDateValueIntl($value, $format) @@ -389,7 +389,7 @@ private function parseDateValueIntl($value, $format) * Parses a date value using the DateTime::createFromFormat() * @param string $value string representing date * @param string $format the expected date format - * @return integer|boolean a UNIX timestamp or `false` on failure. + * @return int|bool a UNIX timestamp or `false` on failure. */ private function parseDateValuePHP($value, $format) { @@ -410,7 +410,7 @@ private function parseDateValuePHP($value, $format) /** * Formats a timestamp using the specified format - * @param integer $timestamp + * @param int $timestamp * @param string $format * @return string */ diff --git a/framework/validators/DefaultValueValidator.php b/framework/validators/DefaultValueValidator.php index e31ecf4010b..1b54e5a286c 100644 --- a/framework/validators/DefaultValueValidator.php +++ b/framework/validators/DefaultValueValidator.php @@ -32,7 +32,7 @@ class DefaultValueValidator extends Validator */ public $value; /** - * @var boolean this property is overwritten to be false so that this validator will + * @var bool this property is overwritten to be false so that this validator will * be applied when the value being validated is empty. */ public $skipOnEmpty = false; diff --git a/framework/validators/EachValidator.php b/framework/validators/EachValidator.php index 6773c88a626..e6f75102a59 100644 --- a/framework/validators/EachValidator.php +++ b/framework/validators/EachValidator.php @@ -55,7 +55,7 @@ class EachValidator extends Validator */ public $rule; /** - * @var boolean whether to use error message composed by validator declared via [[rule]] if its validation fails. + * @var bool whether to use error message composed by validator declared via [[rule]] if its validation fails. * If enabled, error message specified for this validator itself will appear only if attribute value is not an array. * If disabled, own error message value will be used always. */ diff --git a/framework/validators/EmailValidator.php b/framework/validators/EmailValidator.php index 42c96b0e165..33147f72deb 100644 --- a/framework/validators/EmailValidator.php +++ b/framework/validators/EmailValidator.php @@ -32,18 +32,18 @@ class EmailValidator extends Validator */ public $fullPattern = '/^[^@]*<[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?>$/'; /** - * @var boolean whether to allow name in the email address (e.g. "John Smith "). Defaults to false. + * @var bool whether to allow name in the email address (e.g. "John Smith "). Defaults to false. * @see fullPattern */ public $allowName = false; /** - * @var boolean whether to check whether the email's domain exists and has either an A or MX record. + * @var bool whether to check whether the email's domain exists and has either an A or MX record. * Be aware that this check can fail due to temporary DNS problems even if the email address is * valid and an email would be deliverable. Defaults to false. */ public $checkDNS = false; /** - * @var boolean whether validation process should take into account IDN (internationalized domain + * @var bool whether validation process should take into account IDN (internationalized domain * names). Defaults to false meaning that validation of emails containing IDN will always fail. * Note that in order to use IDN validation you have to install and enable `intl` PHP extension, * otherwise an exception would be thrown. diff --git a/framework/validators/ExistValidator.php b/framework/validators/ExistValidator.php index 51be2cb9c73..f3086a49656 100644 --- a/framework/validators/ExistValidator.php +++ b/framework/validators/ExistValidator.php @@ -62,7 +62,7 @@ class ExistValidator extends Validator */ public $filter; /** - * @var boolean whether to allow array type attribute. + * @var bool whether to allow array type attribute. */ public $allowArray = false; diff --git a/framework/validators/FileValidator.php b/framework/validators/FileValidator.php index f29af8543dc..aa5ed26431b 100644 --- a/framework/validators/FileValidator.php +++ b/framework/validators/FileValidator.php @@ -19,7 +19,7 @@ * * Note that you should enable `fileinfo` PHP extension. * - * @property integer $sizeLimit The size limit for uploaded files. This property is read-only. + * @property int $sizeLimit The size limit for uploaded files. This property is read-only. * * @author Qiang Xue * @since 2.0 @@ -36,7 +36,7 @@ class FileValidator extends Validator */ public $extensions; /** - * @var boolean whether to check file type (extension) with mime-type. If extension produced by + * @var bool whether to check file type (extension) with mime-type. If extension produced by * file mime-type check differs from uploaded file extension, the file will be considered as invalid. */ public $checkExtensionByMimeType = true; @@ -51,13 +51,13 @@ class FileValidator extends Validator */ public $mimeTypes; /** - * @var integer the minimum number of bytes required for the uploaded file. + * @var int the minimum number of bytes required for the uploaded file. * Defaults to null, meaning no limit. * @see tooSmall for the customized message for a file that is too small. */ public $minSize; /** - * @var integer the maximum number of bytes required for the uploaded file. + * @var int the maximum number of bytes required for the uploaded file. * Defaults to null, meaning no limit. * Note, the size limit is also affected by `upload_max_filesize` and `post_max_size` INI setting * and the 'MAX_FILE_SIZE' hidden field value. See [[getSizeLimit()]] for details. @@ -68,7 +68,7 @@ class FileValidator extends Validator */ public $maxSize; /** - * @var integer the maximum file count the given attribute can hold. + * @var int the maximum file count the given attribute can hold. * Defaults to 1, meaning single file upload. By defining a higher number, * multiple uploads become possible. Setting it to `0` means there is no limit on * the number of files that can be uploaded simultaneously. @@ -289,7 +289,7 @@ protected function validateValue($file) * - 'MAX_FILE_SIZE' hidden field * - [[maxSize]] * - * @return integer the size limit for uploaded files. + * @return int the size limit for uploaded files. */ public function getSizeLimit() { @@ -323,7 +323,7 @@ public function isEmpty($value, $trim = false) * Converts php.ini style size to bytes * * @param string $sizeStr $sizeStr - * @return integer + * @return int */ private function sizeToBytes($sizeStr) { @@ -345,7 +345,7 @@ private function sizeToBytes($sizeStr) /** * Checks if given uploaded file have correct type (extension) according current validator settings. * @param UploadedFile $file - * @return boolean + * @return bool */ protected function validateExtension($file) { @@ -472,7 +472,7 @@ private function buildMimeTypeRegexp($mask) * Checks the mimeType of the $file against the list in the [[mimeTypes]] property * * @param UploadedFile $file - * @return boolean whether the $file mimeType is allowed + * @return bool whether the $file mimeType is allowed * @throws \yii\base\InvalidConfigException * @see mimeTypes * @since 2.0.8 diff --git a/framework/validators/FilterValidator.php b/framework/validators/FilterValidator.php index c9208280fad..5b011029fd7 100644 --- a/framework/validators/FilterValidator.php +++ b/framework/validators/FilterValidator.php @@ -46,12 +46,12 @@ class FilterValidator extends Validator */ public $filter; /** - * @var boolean whether the filter should be skipped if an array input is given. + * @var bool whether the filter should be skipped if an array input is given. * If true and an array input is given, the filter will not be applied. */ public $skipOnArray = false; /** - * @var boolean this property is overwritten to be false so that this validator will + * @var bool this property is overwritten to be false so that this validator will * be applied when the value being validated is empty. */ public $skipOnEmpty = false; diff --git a/framework/validators/ImageValidator.php b/framework/validators/ImageValidator.php index 4e72f63a396..53cc1377287 100644 --- a/framework/validators/ImageValidator.php +++ b/framework/validators/ImageValidator.php @@ -27,25 +27,25 @@ class ImageValidator extends FileValidator */ public $notImage; /** - * @var integer the minimum width in pixels. + * @var int the minimum width in pixels. * Defaults to null, meaning no limit. * @see underWidth for the customized message used when image width is too small. */ public $minWidth; /** - * @var integer the maximum width in pixels. + * @var int the maximum width in pixels. * Defaults to null, meaning no limit. * @see overWidth for the customized message used when image width is too big. */ public $maxWidth; /** - * @var integer the minimum height in pixels. + * @var int the minimum height in pixels. * Defaults to null, meaning no limit. * @see underHeight for the customized message used when image height is too small. */ public $minHeight; /** - * @var integer the maximum width in pixels. + * @var int the maximum width in pixels. * Defaults to null, meaning no limit. * @see overWidth for the customized message used when image height is too big. */ diff --git a/framework/validators/IpValidator.php b/framework/validators/IpValidator.php index 455788a540d..3e9b97d25d5 100644 --- a/framework/validators/IpValidator.php +++ b/framework/validators/IpValidator.php @@ -84,15 +84,15 @@ class IpValidator extends Validator 'system' => ['multicast', 'linklocal', 'localhost', 'documentation'], ]; /** - * @var boolean whether the validating value can be an IPv6 address. Defaults to `true`. + * @var bool whether the validating value can be an IPv6 address. Defaults to `true`. */ public $ipv6 = true; /** - * @var boolean whether the validating value can be an IPv4 address. Defaults to `true`. + * @var bool whether the validating value can be an IPv4 address. Defaults to `true`. */ public $ipv4 = true; /** - * @var boolean whether the address can be an IP with CIDR subnet, like `192.168.10.0/24`. + * @var bool whether the address can be an IP with CIDR subnet, like `192.168.10.0/24`. * The following values are possible: * * - `false` - the address must not have a subnet (default). @@ -101,7 +101,7 @@ class IpValidator extends Validator */ public $subnet = false; /** - * @var boolean whether to add the CIDR prefix with the smallest length (32 for IPv4 and 128 for IPv6) to an + * @var bool whether to add the CIDR prefix with the smallest length (32 for IPv4 and 128 for IPv6) to an * address without it. Works only when `subnet` is not `false`. For example: * - `10.0.1.5` will normalized to `10.0.1.5/32` * - `2008:db0::1` will be normalized to `2008:db0::1/128` @@ -110,12 +110,12 @@ class IpValidator extends Validator */ public $normalize = false; /** - * @var boolean whether address may have a [[NEGATION_CHAR]] character at the beginning. + * @var bool whether address may have a [[NEGATION_CHAR]] character at the beginning. * Defaults to `false`. */ public $negation = false; /** - * @var boolean whether to expand an IPv6 address to the full notation format. + * @var bool whether to expand an IPv6 address to the full notation format. * Defaults to `false`. */ public $expandIPv6 = false; @@ -427,8 +427,8 @@ private function expandIPv6($ip) * The method checks whether the IP address with specified CIDR is allowed according to the [[ranges]] list. * * @param string $ip - * @param integer $cidr - * @return boolean + * @param int $cidr + * @return bool * @see ranges */ private function isAllowed($ip, $cidr) @@ -451,7 +451,7 @@ private function isAllowed($ip, $cidr) * Parses IP address/range for the negation with [[NEGATION_CHAR]]. * * @param $string - * @return array `[0 => boolean, 1 => string]` + * @return array `[0 => bool, 1 => string]` * - boolean: whether the string is negated * - string: the string without negation (when the negation were present) */ @@ -493,7 +493,7 @@ private function prepareRanges($ranges) * Validates IPv4 address * * @param string $value - * @return boolean + * @return bool */ protected function validateIPv4($value) { @@ -504,7 +504,7 @@ protected function validateIPv4($value) * Validates IPv6 address * * @param string $value - * @return boolean + * @return bool */ protected function validateIPv6($value) { @@ -515,7 +515,7 @@ protected function validateIPv6($value) * Gets the IP version * * @param string $ip - * @return integer + * @return int */ private function getIpVersion($ip) { @@ -535,9 +535,9 @@ private function getIpParsePattern() * Checks whether the IP is in subnet range * * @param string $ip an IPv4 or IPv6 address - * @param integer $cidr + * @param int $cidr * @param string $range subnet in CIDR format e.g. `10.0.0.0/8` or `2001:af::/64` - * @return boolean + * @return bool */ private function inRange($ip, $cidr, $range) { @@ -605,8 +605,8 @@ public function clientValidateAttribute($model, $attribute, $view) 'ipv4Pattern' => new JsExpression(Html::escapeJsRegularExpression($this->ipv4Pattern)), 'ipv6Pattern' => new JsExpression(Html::escapeJsRegularExpression($this->ipv6Pattern)), 'messages' => $messages, - 'ipv4' => (boolean)$this->ipv4, - 'ipv6' => (boolean)$this->ipv6, + 'ipv4' => (bool) $this->ipv4, + 'ipv6' => (bool) $this->ipv6, 'ipParsePattern' => new JsExpression(Html::escapeJsRegularExpression($this->getIpParsePattern())), 'negation' => $this->negation, 'subnet' => $this->subnet, diff --git a/framework/validators/NumberValidator.php b/framework/validators/NumberValidator.php index 32e6abb86a2..a3f27e8186f 100644 --- a/framework/validators/NumberValidator.php +++ b/framework/validators/NumberValidator.php @@ -24,16 +24,16 @@ class NumberValidator extends Validator { /** - * @var boolean whether the attribute value can only be an integer. Defaults to false. + * @var bool whether the attribute value can only be an integer. Defaults to false. */ public $integerOnly = false; /** - * @var integer|float upper limit of the number. Defaults to null, meaning no upper limit. + * @var int|float upper limit of the number. Defaults to null, meaning no upper limit. * @see tooBig for the customized message used when the number is too big. */ public $max; /** - * @var integer|float lower limit of the number. Defaults to null, meaning no lower limit. + * @var int|float lower limit of the number. Defaults to null, meaning no lower limit. * @see tooSmall for the customized message used when the number is too small. */ public $min; diff --git a/framework/validators/RangeValidator.php b/framework/validators/RangeValidator.php index 27e128f09a9..4e1c89aecff 100644 --- a/framework/validators/RangeValidator.php +++ b/framework/validators/RangeValidator.php @@ -36,16 +36,16 @@ class RangeValidator extends Validator */ public $range; /** - * @var boolean whether the comparison is strict (both type and value must be the same) + * @var bool whether the comparison is strict (both type and value must be the same) */ public $strict = false; /** - * @var boolean whether to invert the validation logic. Defaults to false. If set to true, + * @var bool whether to invert the validation logic. Defaults to false. If set to true, * the attribute value should NOT be among the list of values defined via [[range]]. */ public $not = false; /** - * @var boolean whether to allow array type attribute. + * @var bool whether to allow array type attribute. */ public $allowArray = false; diff --git a/framework/validators/RegularExpressionValidator.php b/framework/validators/RegularExpressionValidator.php index 62b7922e29b..2180519689d 100644 --- a/framework/validators/RegularExpressionValidator.php +++ b/framework/validators/RegularExpressionValidator.php @@ -28,7 +28,7 @@ class RegularExpressionValidator extends Validator */ public $pattern; /** - * @var boolean whether to invert the validation logic. Defaults to false. If set to true, + * @var bool whether to invert the validation logic. Defaults to false. If set to true, * the regular expression defined via [[pattern]] should NOT match the attribute value. */ public $not = false; diff --git a/framework/validators/RequiredValidator.php b/framework/validators/RequiredValidator.php index e416b108644..dd99b991018 100644 --- a/framework/validators/RequiredValidator.php +++ b/framework/validators/RequiredValidator.php @@ -18,7 +18,7 @@ class RequiredValidator extends Validator { /** - * @var boolean whether to skip this validator if the value being validated is empty. + * @var bool whether to skip this validator if the value being validated is empty. */ public $skipOnEmpty = false; /** @@ -31,7 +31,7 @@ class RequiredValidator extends Validator */ public $requiredValue; /** - * @var boolean whether the comparison between the attribute value and [[requiredValue]] is strict. + * @var bool whether the comparison between the attribute value and [[requiredValue]] is strict. * When this is true, both the values and types must match. * Defaults to false, meaning only the values need to match. * Note that when [[requiredValue]] is null, if this property is true, the validator will check diff --git a/framework/validators/StringValidator.php b/framework/validators/StringValidator.php index b9595cd1b1d..3c93b57c54f 100644 --- a/framework/validators/StringValidator.php +++ b/framework/validators/StringValidator.php @@ -20,7 +20,7 @@ class StringValidator extends Validator { /** - * @var integer|array specifies the length limit of the value to be validated. + * @var int|array specifies the length limit of the value to be validated. * This can be specified in one of the following forms: * * - an integer: the exact length that the value should be of; @@ -34,12 +34,12 @@ class StringValidator extends Validator */ public $length; /** - * @var integer maximum length. If not set, it means no maximum length limit. + * @var int maximum length. If not set, it means no maximum length limit. * @see tooLong for the customized message for a too long string. */ public $max; /** - * @var integer minimum length. If not set, it means no minimum length limit. + * @var int minimum length. If not set, it means no minimum length limit. * @see tooShort for the customized message for a too short string. */ public $min; diff --git a/framework/validators/UrlValidator.php b/framework/validators/UrlValidator.php index 12c8633a727..413736d22f5 100644 --- a/framework/validators/UrlValidator.php +++ b/framework/validators/UrlValidator.php @@ -41,7 +41,7 @@ class UrlValidator extends Validator */ public $defaultScheme; /** - * @var boolean whether validation process should take into account IDN (internationalized + * @var bool whether validation process should take into account IDN (internationalized * domain names). Defaults to false meaning that validation of URLs containing IDN will always * fail. Note that in order to use IDN validation you have to install and enable `intl` PHP * extension, otherwise an exception would be thrown. diff --git a/framework/validators/Validator.php b/framework/validators/Validator.php index 04eb10a8822..c162547c11b 100644 --- a/framework/validators/Validator.php +++ b/framework/validators/Validator.php @@ -125,17 +125,17 @@ class Validator extends Component */ public $except = []; /** - * @var boolean whether this validation rule should be skipped if the attribute being validated + * @var bool whether this validation rule should be skipped if the attribute being validated * already has some validation error according to some previous rules. Defaults to true. */ public $skipOnError = true; /** - * @var boolean whether this validation rule should be skipped if the attribute value + * @var bool whether this validation rule should be skipped if the attribute value * is null or an empty string. */ public $skipOnEmpty = true; /** - * @var boolean whether to enable client-side validation for this validator. + * @var bool whether to enable client-side validation for this validator. * The actual client-side validation is done via the JavaScript code returned * by [[clientValidateAttribute()]]. If that method returns null, even if this property * is true, no client-side validation will be done by this validator. @@ -289,7 +289,7 @@ public function validateAttribute($model, $attribute) * You may use this method to validate a value out of the context of a data model. * @param mixed $value the data value to be validated. * @param string $error the error message to be returned, if the validation fails. - * @return boolean whether the data is valid. + * @return bool whether the data is valid. */ public function validate($value, &$error = null) { @@ -369,7 +369,7 @@ public function clientValidateAttribute($model, $attribute, $view) * - the validator's `on` property contains the specified scenario * * @param string $scenario scenario name - * @return boolean whether the validator applies to the specified scenario. + * @return bool whether the validator applies to the specified scenario. */ public function isActive($scenario) { @@ -405,7 +405,7 @@ public function addError($model, $attribute, $message, $params = []) * A value is considered empty if it is null, an empty array, or an empty string. * Note that this method is different from PHP empty(). It will return false when the value is 0. * @param mixed $value the value to be checked - * @return boolean whether the value is empty + * @return bool whether the value is empty */ public function isEmpty($value) { diff --git a/framework/views/errorHandler/callStackItem.php b/framework/views/errorHandler/callStackItem.php index 7144965b20a..6701ee44db4 100644 --- a/framework/views/errorHandler/callStackItem.php +++ b/framework/views/errorHandler/callStackItem.php @@ -1,12 +1,12 @@ diff --git a/framework/web/AssetConverter.php b/framework/web/AssetConverter.php index d708f2ffcef..e1ab5dc30bb 100644 --- a/framework/web/AssetConverter.php +++ b/framework/web/AssetConverter.php @@ -43,7 +43,7 @@ class AssetConverter extends Component implements AssetConverterInterface 'ts' => ['js', 'tsc --out {to} {from}'], ]; /** - * @var boolean whether the source asset file should be converted even if its result already exists. + * @var bool whether the source asset file should be converted even if its result already exists. * You may want to set this to be `true` during the development stage to make sure the converted * assets are always up-to-date. Do not set this to true on production servers as it will * significantly degrade the performance. @@ -82,7 +82,7 @@ public function convert($asset, $basePath) * @param string $basePath asset base path and command working directory * @param string $asset the name of the asset file * @param string $result the name of the file to be generated by the converter command - * @return boolean true on success, false on failure. Failures will be logged. + * @return bool true on success, false on failure. Failures will be logged. * @throws \yii\base\Exception when the command fails and YII_DEBUG is true. * In production mode the error will be logged. */ diff --git a/framework/web/AssetManager.php b/framework/web/AssetManager.php index 7c51052680f..cc5088711b2 100644 --- a/framework/web/AssetManager.php +++ b/framework/web/AssetManager.php @@ -42,7 +42,7 @@ class AssetManager extends Component { /** - * @var array|boolean list of asset bundle configurations. This property is provided to customize asset bundles. + * @var array|bool list of asset bundle configurations. This property is provided to customize asset bundles. * When a bundle is being loaded by [[getBundle()]], if it has a corresponding configuration specified here, * the configuration will be applied to the bundle. * @@ -105,7 +105,7 @@ class AssetManager extends Component */ public $assetMap = []; /** - * @var boolean whether to use symbolic link to publish asset files. Defaults to false, meaning + * @var bool whether to use symbolic link to publish asset files. Defaults to false, meaning * asset files are copied to [[basePath]]. Using symbolic links has the benefit that the published * assets will always be consistent with the source assets and there is no copy operation required. * This is especially useful during development. @@ -123,13 +123,13 @@ class AssetManager extends Component */ public $linkAssets = false; /** - * @var integer the permission to be set for newly published asset files. + * @var int the permission to be set for newly published asset 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 generated asset directories. + * @var int the permission to be set for newly generated asset 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. @@ -154,7 +154,7 @@ class AssetManager extends Component */ public $afterCopy; /** - * @var boolean whether the directory being published should be copied even if + * @var bool whether the directory being published should be copied even if * it is found in the target directory. This option is used only when publishing a directory. * You may want to set this to be `true` during the development stage to make sure the published * directory is always up-to-date. Do not set this to true on production servers as it will @@ -162,7 +162,7 @@ class AssetManager extends Component */ public $forceCopy = false; /** - * @var boolean whether to append a timestamp to the URL of every published asset. When this is true, + * @var bool whether to append a timestamp to the URL of every published asset. When this is true, * the URL of a published asset may look like `/path/to/asset?v=timestamp`, where `timestamp` is the * last modification time of the published asset file. * You normally would want to set this property to true when you have enabled HTTP caching for assets, @@ -226,7 +226,7 @@ public function init() * it will treat `$name` as the class of the asset bundle and create a new instance of it. * * @param string $name the class name of the asset bundle (without the leading backslash) - * @param boolean $publish whether to publish the asset files in the asset bundle before it is returned. + * @param bool $publish whether to publish the asset files in the asset bundle before it is returned. * If you set this false, you must manually call `AssetBundle::publish()` to publish the asset files. * @return AssetBundle the asset bundle instance * @throws InvalidConfigException if $name does not refer to a valid asset bundle @@ -253,7 +253,7 @@ public function getBundle($name, $publish = true) * * @param string $name bundle name * @param array $config bundle object configuration - * @param boolean $publish if bundle should be published + * @param bool $publish if bundle should be published * @return AssetBundle * @throws InvalidConfigException if configuration isn't valid */ @@ -328,7 +328,7 @@ public function getAssetUrl($bundle, $asset) * Returns the actual file path for the specified asset. * @param AssetBundle $bundle the asset bundle which the asset file belongs to * @param string $asset the asset path. This should be one of the assets listed in [[js]] or [[css]]. - * @return string|boolean the actual file path, or false if the asset is specified as an absolute URL + * @return string|bool the actual file path, or false if the asset is specified as an absolute URL */ public function getAssetPath($bundle, $asset) { @@ -342,7 +342,7 @@ public function getAssetPath($bundle, $asset) /** * @param AssetBundle $bundle * @param string $asset - * @return string|boolean + * @return string|bool */ protected function resolveAsset($bundle, $asset) { diff --git a/framework/web/BadRequestHttpException.php b/framework/web/BadRequestHttpException.php index e510c442d1d..827aa8711cd 100644 --- a/framework/web/BadRequestHttpException.php +++ b/framework/web/BadRequestHttpException.php @@ -24,7 +24,7 @@ class BadRequestHttpException extends HttpException /** * Constructor. * @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($message = null, $code = 0, \Exception $previous = null) diff --git a/framework/web/CacheSession.php b/framework/web/CacheSession.php index acbf03e6c07..4f473226862 100644 --- a/framework/web/CacheSession.php +++ b/framework/web/CacheSession.php @@ -31,7 +31,7 @@ * ] * ``` * - * @property boolean $useCustomStorage Whether to use custom storage. This property is read-only. + * @property bool $useCustomStorage Whether to use custom storage. This property is read-only. * * @author Qiang Xue * @since 2.0 @@ -62,7 +62,7 @@ public function init() /** * Returns a value indicating whether to use custom session storage. * This method overrides the parent implementation and always returns true. - * @return boolean whether to use custom storage. + * @return bool whether to use custom storage. */ public function getUseCustomStorage() { @@ -87,7 +87,7 @@ public function readSession($id) * Do not call this method directly. * @param string $id session ID * @param string $data session data - * @return boolean whether session write is successful + * @return bool whether session write is successful */ public function writeSession($id, $data) { @@ -98,7 +98,7 @@ public function writeSession($id, $data) * Session destroy handler. * Do not call this method directly. * @param string $id session ID - * @return boolean whether session is destroyed successfully + * @return bool whether session is destroyed successfully */ public function destroySession($id) { diff --git a/framework/web/ConflictHttpException.php b/framework/web/ConflictHttpException.php index be3b7e59db7..51565ce8e2c 100644 --- a/framework/web/ConflictHttpException.php +++ b/framework/web/ConflictHttpException.php @@ -19,7 +19,7 @@ class ConflictHttpException extends HttpException /** * Constructor. * @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($message = null, $code = 0, \Exception $previous = null) diff --git a/framework/web/Controller.php b/framework/web/Controller.php index 2e08d9d8ca4..4b309a1f7c9 100644 --- a/framework/web/Controller.php +++ b/framework/web/Controller.php @@ -22,7 +22,7 @@ class Controller extends \yii\base\Controller { /** - * @var boolean whether to enable CSRF validation for the actions in this controller. + * @var bool whether to enable CSRF validation for the actions in this controller. * CSRF validation is enabled only when both this property and [[\yii\web\Request::enableCsrfValidation]] are true. */ public $enableCsrfValidation = true; @@ -138,7 +138,7 @@ public function beforeAction($action) * Any relative URL will be converted into an absolute one by prepending it with the host info * of the current request. * - * @param integer $statusCode the HTTP status code. Defaults to 302. + * @param int $statusCode the HTTP status code. Defaults to 302. * See * for details about HTTP status code * @return Response the current response object diff --git a/framework/web/Cookie.php b/framework/web/Cookie.php index 061772f1076..90bc751f77d 100644 --- a/framework/web/Cookie.php +++ b/framework/web/Cookie.php @@ -30,7 +30,7 @@ class Cookie extends \yii\base\Object */ public $domain = ''; /** - * @var integer the timestamp at which the cookie expires. This is the server timestamp. + * @var int the timestamp at which the cookie expires. This is the server timestamp. * Defaults to 0, meaning "until the browser is closed". */ public $expire = 0; @@ -39,11 +39,11 @@ class Cookie extends \yii\base\Object */ public $path = '/'; /** - * @var boolean whether cookie should be sent via secure connection + * @var bool whether cookie should be sent via secure connection */ public $secure = false; /** - * @var boolean whether the cookie should be accessible only through the HTTP protocol. + * @var bool whether the cookie should be accessible only through the HTTP protocol. * By setting this property to true, the cookie will not be accessible by scripting languages, * such as JavaScript, which can effectively help to reduce identity theft through XSS attacks. */ diff --git a/framework/web/CookieCollection.php b/framework/web/CookieCollection.php index cd9b758094d..05ebfa48738 100644 --- a/framework/web/CookieCollection.php +++ b/framework/web/CookieCollection.php @@ -17,7 +17,7 @@ * * For more details and usage information on CookieCollection, see the [guide article on handling cookies](guide:runtime-sessions-cookies). * - * @property integer $count The number of cookies in the collection. This property is read-only. + * @property int $count The number of cookies in the collection. This property is read-only. * @property ArrayIterator $iterator An iterator for traversing the cookies in the collection. This property * is read-only. * @@ -27,7 +27,7 @@ class CookieCollection extends Object implements \IteratorAggregate, \ArrayAccess, \Countable { /** - * @var boolean whether this collection is read only. + * @var bool whether this collection is read only. */ public $readOnly = false; @@ -64,7 +64,7 @@ public function getIterator() * Returns the number of cookies in the collection. * This method is required by the SPL `Countable` interface. * It will be implicitly called when you use `count($collection)`. - * @return integer the number of cookies in the collection. + * @return int the number of cookies in the collection. */ public function count() { @@ -73,7 +73,7 @@ public function count() /** * Returns the number of cookies in the collection. - * @return integer the number of cookies in the collection. + * @return int the number of cookies in the collection. */ public function getCount() { @@ -107,7 +107,7 @@ public function getValue($name, $defaultValue = null) * Returns whether there is a cookie with the specified name. * Note that if a cookie is marked for deletion from browser, this method will return false. * @param string $name the cookie name - * @return boolean whether the named cookie exists + * @return bool whether the named cookie exists * @see remove() */ public function has($name) @@ -135,7 +135,7 @@ public function add($cookie) * If `$removeFromBrowser` is true, the cookie will be removed from the browser. * In this case, a cookie with outdated expiry will be added to the collection. * @param Cookie|string $cookie the cookie object or the name of the cookie to be removed. - * @param boolean $removeFromBrowser whether to remove the cookie from browser + * @param bool $removeFromBrowser whether to remove the cookie from browser * @throws InvalidCallException if the cookie collection is read only */ public function remove($cookie, $removeFromBrowser = true) @@ -196,7 +196,7 @@ public function fromArray(array $array) * This method is required by the SPL interface [[\ArrayAccess]]. * It is implicitly called when you use something like `isset($collection[$name])`. * @param string $name the cookie name - * @return boolean whether the named cookie exists + * @return bool whether the named cookie exists */ public function offsetExists($name) { diff --git a/framework/web/DbSession.php b/framework/web/DbSession.php index 770016d84db..01938f9fac9 100644 --- a/framework/web/DbSession.php +++ b/framework/web/DbSession.php @@ -89,7 +89,7 @@ public function init() /** * Updates the current session ID with a newly generated one . * Please refer to for more details. - * @param boolean $deleteOldSession Whether to delete the old associated session file or not. + * @param bool $deleteOldSession Whether to delete the old associated session file or not. */ public function regenerateID($deleteOldSession = false) { @@ -153,7 +153,7 @@ public function readSession($id) * Do not call this method directly. * @param string $id session ID * @param string $data session data - * @return boolean whether session write is successful + * @return bool whether session write is successful */ public function writeSession($id, $data) { @@ -194,7 +194,7 @@ public function writeSession($id, $data) * Session destroy handler. * Do not call this method directly. * @param string $id session ID - * @return boolean whether session is destroyed successfully + * @return bool whether session is destroyed successfully */ public function destroySession($id) { @@ -208,8 +208,8 @@ public function destroySession($id) /** * Session GC (garbage collection) handler. * Do not call this method directly. - * @param integer $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up. - * @return boolean whether session is GCed successfully + * @param int $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up. + * @return bool whether session is GCed successfully */ public function gcSession($maxLifetime) { diff --git a/framework/web/ErrorHandler.php b/framework/web/ErrorHandler.php index 8b4bff61613..0f45277210c 100644 --- a/framework/web/ErrorHandler.php +++ b/framework/web/ErrorHandler.php @@ -31,11 +31,11 @@ class ErrorHandler extends \yii\base\ErrorHandler { /** - * @var integer maximum number of source code lines to be displayed. Defaults to 19. + * @var int maximum number of source code lines to be displayed. Defaults to 19. */ public $maxSourceLines = 19; /** - * @var integer maximum number of trace source code lines to be displayed. Defaults to 13. + * @var int maximum number of trace source code lines to be displayed. Defaults to 13. */ public $maxTraceSourceLines = 13; /** @@ -272,11 +272,11 @@ public function renderPreviousExceptions($exception) /** * Renders a single call stack element. * @param string|null $file name where call has happened. - * @param integer|null $line number on which call has happened. + * @param int|null $line number on which call has happened. * @param string|null $class called class name. * @param string|null $method called function/method name. * @param array $args array of method arguments. - * @param integer $index number of the call stack element. + * @param int $index number of the call stack element. * @return string HTML content of the rendered call stack element. */ public function renderCallStackItem($file, $line, $class, $method, $args, $index) @@ -329,7 +329,7 @@ public function renderRequest() /** * Determines whether given name of the file belongs to the framework. * @param string $file name to be checked. - * @return boolean whether given name of the file belongs to the framework. + * @return bool whether given name of the file belongs to the framework. */ public function isCoreFile($file) { @@ -338,7 +338,7 @@ public function isCoreFile($file) /** * Creates HTML containing link to the page with the information on given HTTP status code. - * @param integer $statusCode to be used to generate information link. + * @param int $statusCode to be used to generate information link. * @param string $statusDescription Description to display after the the status code. * @return string generated HTML with HTTP status code information. */ diff --git a/framework/web/ForbiddenHttpException.php b/framework/web/ForbiddenHttpException.php index 378feb7a2ac..ca3adf538c0 100644 --- a/framework/web/ForbiddenHttpException.php +++ b/framework/web/ForbiddenHttpException.php @@ -25,7 +25,7 @@ class ForbiddenHttpException extends HttpException /** * Constructor. * @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($message = null, $code = 0, \Exception $previous = null) diff --git a/framework/web/GoneHttpException.php b/framework/web/GoneHttpException.php index fa382b7cd1b..374eaa4905a 100644 --- a/framework/web/GoneHttpException.php +++ b/framework/web/GoneHttpException.php @@ -24,7 +24,7 @@ class GoneHttpException extends HttpException /** * Constructor. * @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($message = null, $code = 0, \Exception $previous = null) diff --git a/framework/web/HeaderCollection.php b/framework/web/HeaderCollection.php index 0cdf8d67522..163c4081845 100644 --- a/framework/web/HeaderCollection.php +++ b/framework/web/HeaderCollection.php @@ -14,7 +14,7 @@ /** * HeaderCollection is used by [[Response]] to maintain the currently registered HTTP headers. * - * @property integer $count The number of headers in the collection. This property is read-only. + * @property int $count The number of headers in the collection. This property is read-only. * @property ArrayIterator $iterator An iterator for traversing the headers in the collection. This property * is read-only. * @@ -44,7 +44,7 @@ public function getIterator() * Returns the number of headers in the collection. * This method is required by the SPL `Countable` interface. * It will be implicitly called when you use `count($collection)`. - * @return integer the number of headers in the collection. + * @return int the number of headers in the collection. */ public function count() { @@ -53,7 +53,7 @@ public function count() /** * Returns the number of headers in the collection. - * @return integer the number of headers in the collection. + * @return int the number of headers in the collection. */ public function getCount() { @@ -64,7 +64,7 @@ public function getCount() * Returns the named header(s). * @param string $name the name of the header to return * @param mixed $default the value to return in case the named header does not exist - * @param boolean $first whether to only return the first header of the specified name. + * @param bool $first whether to only return the first header of the specified name. * If false, all headers of the specified name will be returned. * @return string|array the named header(s). If `$first` is true, a string will be returned; * If `$first` is false, an array will be returned. @@ -130,7 +130,7 @@ public function setDefault($name, $value) /** * Returns a value indicating whether the named header exists. * @param string $name the name of the header - * @return boolean whether the named header exists + * @return bool whether the named header exists */ public function has($name) { @@ -189,7 +189,7 @@ public function fromArray(array $array) * This method is required by the SPL interface [[\ArrayAccess]]. * It is implicitly called when you use something like `isset($collection[$name])`. * @param string $name the header name - * @return boolean whether the named header exists + * @return bool whether the named header exists */ public function offsetExists($name) { diff --git a/framework/web/HttpException.php b/framework/web/HttpException.php index f8b73cb066c..db4a720c9e7 100644 --- a/framework/web/HttpException.php +++ b/framework/web/HttpException.php @@ -30,16 +30,16 @@ class HttpException extends UserException { /** - * @var integer HTTP status code, such as 403, 404, 500, etc. + * @var int HTTP status code, such as 403, 404, 500, etc. */ public $statusCode; /** * Constructor. - * @param integer $status HTTP status code, such as 404, 500, etc. + * @param int $status HTTP status code, such as 404, 500, etc. * @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, $message = null, $code = 0, \Exception $previous = null) diff --git a/framework/web/IdentityInterface.php b/framework/web/IdentityInterface.php index c83f686d662..cf5c0e28fff 100644 --- a/framework/web/IdentityInterface.php +++ b/framework/web/IdentityInterface.php @@ -50,7 +50,7 @@ interface 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 the identity object that matches the given ID. * Null should be returned if such an identity cannot be found * or the identity is not in an active state (disabled, deleted, etc.) @@ -70,7 +70,7 @@ public static function findIdentityByAccessToken($token, $type = null); /** * Returns an ID that can uniquely identify a user identity. - * @return string|integer an ID that uniquely identifies a user identity. + * @return string|int an ID that uniquely identifies a user identity. */ public function getId(); @@ -93,7 +93,7 @@ public function getAuthKey(); * * This is required if [[User::enableAutoLogin]] is enabled. * @param string $authKey the given auth key - * @return boolean whether the given auth key is valid. + * @return bool whether the given auth key is valid. * @see getAuthKey() */ public function validateAuthKey($authKey); diff --git a/framework/web/JsonParser.php b/framework/web/JsonParser.php index bb80e0e7dee..89a3a1a624f 100644 --- a/framework/web/JsonParser.php +++ b/framework/web/JsonParser.php @@ -29,11 +29,11 @@ class JsonParser implements RequestParserInterface { /** - * @var boolean whether to return objects in terms of associative arrays. + * @var bool whether to return objects in terms of associative arrays. */ public $asArray = true; /** - * @var boolean whether to throw a [[BadRequestHttpException]] if the body is invalid json + * @var bool whether to throw a [[BadRequestHttpException]] if the body is invalid json */ public $throwException = true; diff --git a/framework/web/JsonResponseFormatter.php b/framework/web/JsonResponseFormatter.php index 13fb9933f02..ddce8821cf8 100644 --- a/framework/web/JsonResponseFormatter.php +++ b/framework/web/JsonResponseFormatter.php @@ -38,13 +38,13 @@ class JsonResponseFormatter extends Component implements ResponseFormatterInterface { /** - * @var boolean whether to use JSONP response format. When this is true, the [[Response::data|response data]] + * @var bool whether to use JSONP response format. When this is true, the [[Response::data|response data]] * must be an array consisting of `data` and `callback` members. The latter should be a JavaScript * function name while the former will be passed to this function as a parameter. */ public $useJsonp = false; /** - * @var integer the encoding options passed to [[Json::encode()]]. For more details please refer to + * @var int the encoding options passed to [[Json::encode()]]. For more details please refer to * . * Default is `JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE`. * This property has no effect, when [[useJsonp]] is `true`. diff --git a/framework/web/Link.php b/framework/web/Link.php index 0403f046a1b..88542795e1b 100644 --- a/framework/web/Link.php +++ b/framework/web/Link.php @@ -36,7 +36,7 @@ class Link extends Object */ public $type; /** - * @var boolean a value indicating whether [[href]] refers to a URI or URI template. + * @var bool a value indicating whether [[href]] refers to a URI or URI template. */ public $templated = false; /** diff --git a/framework/web/MethodNotAllowedHttpException.php b/framework/web/MethodNotAllowedHttpException.php index 133770d2834..802d5cb98a7 100644 --- a/framework/web/MethodNotAllowedHttpException.php +++ b/framework/web/MethodNotAllowedHttpException.php @@ -18,7 +18,7 @@ class MethodNotAllowedHttpException extends HttpException /** * Constructor. * @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($message = null, $code = 0, \Exception $previous = null) diff --git a/framework/web/MultiFieldSession.php b/framework/web/MultiFieldSession.php index c43b80a057d..c4083e42132 100644 --- a/framework/web/MultiFieldSession.php +++ b/framework/web/MultiFieldSession.php @@ -22,7 +22,7 @@ * While extending this class you should use [[composeFields()]] method - while writing the session data into the storage and * [[extractData()]] - while reading session data from the storage. * - * @property boolean $useCustomStorage Whether to use custom storage. This property is read-only. + * @property bool $useCustomStorage Whether to use custom storage. This property is read-only. * * @author Paul Klimov * @since 2.0.6 @@ -80,7 +80,7 @@ abstract class MultiFieldSession extends Session /** * Returns a value indicating whether to use custom session storage. * This method overrides the parent implementation and always returns true. - * @return boolean whether to use custom storage. + * @return bool whether to use custom storage. */ public function getUseCustomStorage() { diff --git a/framework/web/MultipartFormDataParser.php b/framework/web/MultipartFormDataParser.php index 755eca387e5..cf580cfd32c 100644 --- a/framework/web/MultipartFormDataParser.php +++ b/framework/web/MultipartFormDataParser.php @@ -57,8 +57,8 @@ * Thus functions like `is_uploaded_file()` and `move_uploaded_file()` will fail on them. This also * means [[UploadedFile::saveAs()]] will fail as well. * - * @property integer $uploadFileMaxCount Maximum upload files count. - * @property integer $uploadFileMaxSize Upload file max size in bytes. + * @property int $uploadFileMaxCount Maximum upload files count. + * @property int $uploadFileMaxSize Upload file max size in bytes. * * @author Paul Klimov * @since 2.0.10 @@ -66,17 +66,17 @@ class MultipartFormDataParser extends Object implements RequestParserInterface { /** - * @var integer upload file max size in bytes. + * @var int upload file max size in bytes. */ private $_uploadFileMaxSize; /** - * @var integer maximum upload files count. + * @var int maximum upload files count. */ private $_uploadFileMaxCount; /** - * @return integer upload file max size in bytes. + * @return int upload file max size in bytes. */ public function getUploadFileMaxSize() { @@ -87,7 +87,7 @@ public function getUploadFileMaxSize() } /** - * @param integer $uploadFileMaxSize upload file max size in bytes. + * @param int $uploadFileMaxSize upload file max size in bytes. */ public function setUploadFileMaxSize($uploadFileMaxSize) { @@ -95,7 +95,7 @@ public function setUploadFileMaxSize($uploadFileMaxSize) } /** - * @return integer maximum upload files count. + * @return int maximum upload files count. */ public function getUploadFileMaxCount() { @@ -106,7 +106,7 @@ public function getUploadFileMaxCount() } /** - * @param integer $uploadFileMaxCount maximum upload files count. + * @param int $uploadFileMaxCount maximum upload files count. */ public function setUploadFileMaxCount($uploadFileMaxCount) { @@ -321,7 +321,7 @@ private function addFile(&$files, $name, $info) * Gets the size in bytes from verbose size representation. * For example: '5K' => 5*1024 * @param string $verboseSize verbose size representation. - * @return integer actual size in bytes. + * @return int actual size in bytes. */ private function getByteSize($verboseSize) { @@ -351,4 +351,4 @@ private function getByteSize($verboseSize) return 0; } } -} \ No newline at end of file +} diff --git a/framework/web/NotAcceptableHttpException.php b/framework/web/NotAcceptableHttpException.php index fb66823b604..afc26f32add 100644 --- a/framework/web/NotAcceptableHttpException.php +++ b/framework/web/NotAcceptableHttpException.php @@ -23,7 +23,7 @@ class NotAcceptableHttpException extends HttpException /** * Constructor. * @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($message = null, $code = 0, \Exception $previous = null) diff --git a/framework/web/NotFoundHttpException.php b/framework/web/NotFoundHttpException.php index b4201c10aea..68797e9d188 100644 --- a/framework/web/NotFoundHttpException.php +++ b/framework/web/NotFoundHttpException.php @@ -18,7 +18,7 @@ class NotFoundHttpException extends HttpException /** * Constructor. * @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($message = null, $code = 0, \Exception $previous = null) diff --git a/framework/web/Request.php b/framework/web/Request.php index 1c447c3beed..7bd5abd4640 100644 --- a/framework/web/Request.php +++ b/framework/web/Request.php @@ -47,24 +47,24 @@ * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set. * @property string|null $hostName Hostname part of the request URL (e.g. `www.yiiframework.com`). This * property is read-only. - * @property boolean $isAjax Whether this is an AJAX (XMLHttpRequest) request. This property is read-only. - * @property boolean $isDelete Whether this is a DELETE request. This property is read-only. - * @property boolean $isFlash Whether this is an Adobe Flash or Adobe Flex request. This property is + * @property bool $isAjax Whether this is an AJAX (XMLHttpRequest) request. This property is read-only. + * @property bool $isDelete Whether this is a DELETE request. This property is read-only. + * @property bool $isFlash Whether this is an Adobe Flash or Adobe Flex request. This property is * read-only. - * @property boolean $isGet Whether this is a GET request. This property is read-only. - * @property boolean $isHead Whether this is a HEAD request. This property is read-only. - * @property boolean $isOptions Whether this is a OPTIONS request. This property is read-only. - * @property boolean $isPatch Whether this is a PATCH request. This property is read-only. - * @property boolean $isPjax Whether this is a PJAX request. This property is read-only. - * @property boolean $isPost Whether this is a POST request. This property is read-only. - * @property boolean $isPut Whether this is a PUT request. This property is read-only. - * @property boolean $isSecureConnection If the request is sent via secure channel (https). This property is + * @property bool $isGet Whether this is a GET request. This property is read-only. + * @property bool $isHead Whether this is a HEAD request. This property is read-only. + * @property bool $isOptions Whether this is a OPTIONS request. This property is read-only. + * @property bool $isPatch Whether this is a PATCH request. This property is read-only. + * @property bool $isPjax Whether this is a PJAX request. This property is read-only. + * @property bool $isPost Whether this is a POST request. This property is read-only. + * @property bool $isPut Whether this is a PUT request. This property is read-only. + * @property bool $isSecureConnection If the request is sent via secure channel (https). This property is * read-only. * @property string $method Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE. The value returned is * turned into upper case. This property is read-only. * @property string $pathInfo Part of the request URL that is after the entry script and before the question * mark. Note, the returned path info is already URL-decoded. - * @property integer $port Port number for insecure requests. + * @property int $port Port number for insecure requests. * @property array $queryParams The request GET parameter values. * @property string $queryString Part of the request URL that is after the question mark. This property is * read-only. @@ -72,9 +72,9 @@ * @property string|null $referrer URL referrer, null if not available. This property is read-only. * @property string $scriptFile The entry script file path. * @property string $scriptUrl The relative URL of the entry script. - * @property integer $securePort Port number for secure requests. + * @property int $securePort Port number for secure requests. * @property string $serverName Server name, null if not available. This property is read-only. - * @property integer|null $serverPort Server port number, null if not available. This property is read-only. + * @property int|null $serverPort Server port number, null if not available. This property is read-only. * @property string $url The currently requested relative URL. Note that the URI returned is URL-encoded. * @property string|null $userAgent User agent, null if not available. This property is read-only. * @property string|null $userHost User host name, null if not available. This property is read-only. @@ -95,7 +95,7 @@ class Request extends \yii\base\Request const CSRF_MASK_LENGTH = 8; /** - * @var boolean whether to enable CSRF (Cross-Site Request Forgery) validation. Defaults to true. + * @var bool whether to enable CSRF (Cross-Site Request Forgery) validation. Defaults to true. * When CSRF validation is enabled, forms submitted to an Yii Web application must be originated * from the same application. If not, a 400 HTTP exception will be raised. * @@ -122,13 +122,13 @@ class Request extends \yii\base\Request */ public $csrfCookie = ['httpOnly' => true]; /** - * @var boolean whether to use cookie to persist CSRF token. If false, CSRF token will be stored + * @var bool whether to use cookie to persist CSRF token. If false, CSRF token will be stored * in session under the name of [[csrfParam]]. Note that while storing CSRF tokens in session increases * security, it requires starting a session for every page, which will degrade your site performance. */ public $enableCsrfCookie = true; /** - * @var boolean whether cookies should be validated to ensure they are not tampered. Defaults to true. + * @var bool whether cookies should be validated to ensure they are not tampered. Defaults to true. */ public $enableCookieValidation = true; /** @@ -249,7 +249,7 @@ public function getMethod() /** * Returns whether this is a GET request. - * @return boolean whether this is a GET request. + * @return bool whether this is a GET request. */ public function getIsGet() { @@ -258,7 +258,7 @@ public function getIsGet() /** * Returns whether this is an OPTIONS request. - * @return boolean whether this is a OPTIONS request. + * @return bool whether this is a OPTIONS request. */ public function getIsOptions() { @@ -267,7 +267,7 @@ public function getIsOptions() /** * Returns whether this is a HEAD request. - * @return boolean whether this is a HEAD request. + * @return bool whether this is a HEAD request. */ public function getIsHead() { @@ -276,7 +276,7 @@ public function getIsHead() /** * Returns whether this is a POST request. - * @return boolean whether this is a POST request. + * @return bool whether this is a POST request. */ public function getIsPost() { @@ -285,7 +285,7 @@ public function getIsPost() /** * Returns whether this is a DELETE request. - * @return boolean whether this is a DELETE request. + * @return bool whether this is a DELETE request. */ public function getIsDelete() { @@ -294,7 +294,7 @@ public function getIsDelete() /** * Returns whether this is a PUT request. - * @return boolean whether this is a PUT request. + * @return bool whether this is a PUT request. */ public function getIsPut() { @@ -303,7 +303,7 @@ public function getIsPut() /** * Returns whether this is a PATCH request. - * @return boolean whether this is a PATCH request. + * @return bool whether this is a PATCH request. */ public function getIsPatch() { @@ -316,7 +316,7 @@ public function getIsPatch() * Note that jQuery doesn't set the header in case of cross domain * requests: https://stackoverflow.com/questions/8163703/cross-domain-ajax-doesnt-send-x-requested-with-header * - * @return boolean whether this is an AJAX (XMLHttpRequest) request. + * @return bool whether this is an AJAX (XMLHttpRequest) request. */ public function getIsAjax() { @@ -325,7 +325,7 @@ public function getIsAjax() /** * Returns whether this is a PJAX request - * @return boolean whether this is a PJAX request + * @return bool whether this is a PJAX request */ public function getIsPjax() { @@ -334,7 +334,7 @@ public function getIsPjax() /** * Returns whether this is an Adobe Flash or Flex request. - * @return boolean whether this is an Adobe Flash or Adobe Flex request. + * @return bool whether this is an Adobe Flash or Adobe Flex request. */ public function getIsFlash() { @@ -810,7 +810,7 @@ public function setUrl($value) * Resolves the request URI portion for the currently requested URL. * This refers to the portion that is after the [[hostInfo]] part. It includes the [[queryString]] part if any. * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework. - * @return string|boolean the request URI portion for the currently requested URL. + * @return string|bool the request URI portion for the currently requested URL. * Note that the URI returned is URL-encoded. * @throws InvalidConfigException if the request URI cannot be determined due to unusual server configuration */ @@ -846,7 +846,7 @@ public function getQueryString() /** * Return if the request is sent via secure channel (https). - * @return boolean if the request is sent via secure channel (https) + * @return bool if the request is sent via secure channel (https) */ public function getIsSecureConnection() { @@ -865,7 +865,7 @@ public function getServerName() /** * Returns the server port number. - * @return integer|null server port number, null if not available + * @return int|null server port number, null if not available */ public function getServerPort() { @@ -930,7 +930,7 @@ public function getAuthPassword() * Returns the port to use for insecure requests. * Defaults to 80, or the port specified by the server if the current * request is insecure. - * @return integer port number for insecure requests. + * @return int port number for insecure requests. * @see setPort() */ public function getPort() @@ -946,7 +946,7 @@ public function getPort() * Sets the port to use for insecure requests. * This setter is provided in case a custom port is necessary for certain * server configurations. - * @param integer $value port number. + * @param int $value port number. */ public function setPort($value) { @@ -962,7 +962,7 @@ public function setPort($value) * Returns the port to use for secure requests. * Defaults to 443, or the port specified by the server if the current * request is secure. - * @return integer port number for secure requests. + * @return int port number for secure requests. * @see setSecurePort() */ public function getSecurePort() @@ -978,7 +978,7 @@ public function getSecurePort() * Sets the port to use for secure requests. * This setter is provided in case a custom port is necessary for certain * server configurations. - * @param integer $value port number. + * @param int $value port number. */ public function setSecurePort($value) { @@ -1292,7 +1292,7 @@ protected function loadCookies() * * This token is generated in a way to prevent [BREACH attacks](http://breachattack.com/). It may be passed * along via a hidden field of an HTML form or an HTTP header value to support CSRF validation. - * @param boolean $regenerate whether to regenerate CSRF token. When this parameter is true, each time + * @param bool $regenerate whether to regenerate CSRF token. When this parameter is true, each time * this method is called, a new CSRF token will be generated and persisted (in session or cookie). * @return string the token used to perform CSRF validation. */ @@ -1398,7 +1398,7 @@ protected function createCsrfCookie($token) * @param string $token the user-provided CSRF token to be validated. If null, the token will be retrieved from * the [[csrfParam]] POST field or HTTP header. * This parameter is available since version 2.0.4. - * @return boolean whether CSRF token is valid. If [[enableCsrfValidation]] is false, this method will return true. + * @return bool whether CSRF token is valid. If [[enableCsrfValidation]] is false, this method will return true. */ public function validateCsrfToken($token = null) { @@ -1423,7 +1423,7 @@ public function validateCsrfToken($token = null) * * @param string $token * @param string $trueToken - * @return boolean + * @return bool */ private function validateCsrfTokenInternal($token, $trueToken) { diff --git a/framework/web/Response.php b/framework/web/Response.php index 5c7f07fec78..0d6b78465f0 100644 --- a/framework/web/Response.php +++ b/framework/web/Response.php @@ -40,21 +40,21 @@ * @property CookieCollection $cookies The cookie collection. This property is read-only. * @property string $downloadHeaders The attachment file name. This property is write-only. * @property HeaderCollection $headers The header collection. This property is read-only. - * @property boolean $isClientError Whether this response indicates a client error. This property is + * @property bool $isClientError Whether this response indicates a client error. This property is * read-only. - * @property boolean $isEmpty Whether this response is empty. This property is read-only. - * @property boolean $isForbidden Whether this response indicates the current request is forbidden. This + * @property bool $isEmpty Whether this response is empty. This property is read-only. + * @property bool $isForbidden Whether this response indicates the current request is forbidden. This * property is read-only. - * @property boolean $isInformational Whether this response is informational. This property is read-only. - * @property boolean $isInvalid Whether this response has a valid [[statusCode]]. This property is read-only. - * @property boolean $isNotFound Whether this response indicates the currently requested resource is not + * @property bool $isInformational Whether this response is informational. This property is read-only. + * @property bool $isInvalid Whether this response has a valid [[statusCode]]. This property is read-only. + * @property bool $isNotFound Whether this response indicates the currently requested resource is not * found. This property is read-only. - * @property boolean $isOk Whether this response is OK. This property is read-only. - * @property boolean $isRedirection Whether this response is a redirection. This property is read-only. - * @property boolean $isServerError Whether this response indicates a server error. This property is + * @property bool $isOk Whether this response is OK. This property is read-only. + * @property bool $isRedirection Whether this response is a redirection. This property is read-only. + * @property bool $isServerError Whether this response indicates a server error. This property is * read-only. - * @property boolean $isSuccessful Whether this response is successful. This property is read-only. - * @property integer $statusCode The HTTP status code to send with the response. + * @property bool $isSuccessful Whether this response is successful. This property is read-only. + * @property int $statusCode The HTTP status code to send with the response. * * @author Qiang Xue * @author Carsten Brandt @@ -156,7 +156,7 @@ class Response extends \yii\base\Response */ public $version; /** - * @var boolean whether the response has been sent. If this is true, calling [[send()]] will do nothing. + * @var bool whether the response has been sent. If this is true, calling [[send()]] will do nothing. */ public $isSent = false; /** @@ -232,7 +232,7 @@ class Response extends \yii\base\Response ]; /** - * @var integer the HTTP status code to send with the response. + * @var int the HTTP status code to send with the response. */ private $_statusCode = 200; /** @@ -260,7 +260,7 @@ public function init() } /** - * @return integer the HTTP status code to send with the response. + * @return int the HTTP status code to send with the response. */ public function getStatusCode() { @@ -270,7 +270,7 @@ public function getStatusCode() /** * Sets the response status code. * This method will set the corresponding status text if `$text` is null. - * @param integer $value the status code + * @param int $value the status code * @param string $text the status text. If not set, it will be set automatically based on the status code. * @throws InvalidParamException if the status code is invalid. */ @@ -573,9 +573,9 @@ public function sendStreamAsFile($handle, $attachmentName, $options = []) * Sets a default set of HTTP headers for file downloading purpose. * @param string $attachmentName the attachment file name * @param string $mimeType the MIME type for the response. If null, `Content-Type` header will NOT be set. - * @param boolean $inline whether the browser should open the file within the browser window. Defaults to false, + * @param bool $inline whether the browser should open the file within the browser window. Defaults to false, * meaning a download dialog will pop up. - * @param integer $contentLength the byte length of the file being downloaded. If null, `Content-Length` header will NOT be set. + * @param int $contentLength the byte length of the file being downloaded. If null, `Content-Length` header will NOT be set. * @return $this the response object itself */ public function setDownloadHeaders($attachmentName, $mimeType = null, $inline = false, $contentLength = null) @@ -602,8 +602,8 @@ public function setDownloadHeaders($attachmentName, $mimeType = null, $inline = /** * Determines the HTTP range given in the request. - * @param integer $fileSize the size of the file that will be used to validate the requested HTTP range. - * @return array|boolean the range (begin, end), or false if the range request is invalid. + * @param int $fileSize the size of the file that will be used to validate the requested HTTP range. + * @return array|bool the range (begin, end), or false if the range request is invalid. */ protected function getHttpRange($fileSize) { @@ -800,10 +800,10 @@ protected function getDispositionHeaderValue($disposition, $attachmentName) * Any relative URL will be converted into an absolute one by prepending it with the host info * of the current request. * - * @param integer $statusCode the HTTP status code. Defaults to 302. + * @param int $statusCode the HTTP status code. Defaults to 302. * See * for details about HTTP status code - * @param boolean $checkAjax whether to specially handle AJAX (and PJAX) requests. Defaults to true, + * @param bool $checkAjax whether to specially handle AJAX (and PJAX) requests. Defaults to true, * meaning if the current request is an AJAX or PJAX request, then calling this method will cause the browser * to redirect to the given URL. If this is false, a `Location` header will be sent, which when received as * an AJAX/PJAX response, may NOT cause browser redirection. @@ -894,7 +894,7 @@ public function getCookies() } /** - * @return boolean whether this response has a valid [[statusCode]]. + * @return bool whether this response has a valid [[statusCode]]. */ public function getIsInvalid() { @@ -902,7 +902,7 @@ public function getIsInvalid() } /** - * @return boolean whether this response is informational + * @return bool whether this response is informational */ public function getIsInformational() { @@ -910,7 +910,7 @@ public function getIsInformational() } /** - * @return boolean whether this response is successful + * @return bool whether this response is successful */ public function getIsSuccessful() { @@ -918,7 +918,7 @@ public function getIsSuccessful() } /** - * @return boolean whether this response is a redirection + * @return bool whether this response is a redirection */ public function getIsRedirection() { @@ -926,7 +926,7 @@ public function getIsRedirection() } /** - * @return boolean whether this response indicates a client error + * @return bool whether this response indicates a client error */ public function getIsClientError() { @@ -934,7 +934,7 @@ public function getIsClientError() } /** - * @return boolean whether this response indicates a server error + * @return bool whether this response indicates a server error */ public function getIsServerError() { @@ -942,7 +942,7 @@ public function getIsServerError() } /** - * @return boolean whether this response is OK + * @return bool whether this response is OK */ public function getIsOk() { @@ -950,7 +950,7 @@ public function getIsOk() } /** - * @return boolean whether this response indicates the current request is forbidden + * @return bool whether this response indicates the current request is forbidden */ public function getIsForbidden() { @@ -958,7 +958,7 @@ public function getIsForbidden() } /** - * @return boolean whether this response indicates the currently requested resource is not found + * @return bool whether this response indicates the currently requested resource is not found */ public function getIsNotFound() { @@ -966,7 +966,7 @@ public function getIsNotFound() } /** - * @return boolean whether this response is empty + * @return bool whether this response is empty */ public function getIsEmpty() { diff --git a/framework/web/ServerErrorHttpException.php b/framework/web/ServerErrorHttpException.php index a7bb2763f57..d92c72bb860 100644 --- a/framework/web/ServerErrorHttpException.php +++ b/framework/web/ServerErrorHttpException.php @@ -18,7 +18,7 @@ class ServerErrorHttpException extends HttpException /** * Constructor. * @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($message = null, $code = 0, \Exception $previous = null) diff --git a/framework/web/Session.php b/framework/web/Session.php index c30f14ad517..1969b642639 100644 --- a/framework/web/Session.php +++ b/framework/web/Session.php @@ -48,25 +48,25 @@ * @property array $allFlashes Flash messages (key => message or key => [message1, message2]). This property * is read-only. * @property array $cookieParams The session cookie parameters. This property is read-only. - * @property integer $count The number of session variables. This property is read-only. + * @property int $count The number of session variables. This property is read-only. * @property string $flash The key identifying the flash message. Note that flash messages and normal session * variables share the same name space. If you have a normal session variable using the same name, its value will * be overwritten by this method. This property is write-only. * @property float $gCProbability The probability (percentage) that the GC (garbage collection) process is * started on every session initialization, defaults to 1 meaning 1% chance. - * @property boolean $hasSessionId Whether the current request has sent the session ID. + * @property bool $hasSessionId Whether the current request has sent the session ID. * @property string $id The current session ID. - * @property boolean $isActive Whether the session has started. This property is read-only. + * @property bool $isActive Whether the session has started. This property is read-only. * @property SessionIterator $iterator An iterator for traversing the session variables. This property is * read-only. * @property string $name The current session name. * @property string $savePath The current session save path, defaults to '/tmp'. - * @property integer $timeout The number of seconds after which data will be seen as 'garbage' and cleaned up. + * @property int $timeout The number of seconds after which data will be seen as 'garbage' and cleaned up. * The default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini). - * @property boolean|null $useCookies The value indicating whether cookies should be used to store session + * @property bool|null $useCookies The value indicating whether cookies should be used to store session * IDs. - * @property boolean $useCustomStorage Whether to use custom storage. This property is read-only. - * @property boolean $useTransparentSessionID Whether transparent sid support is enabled or not, defaults to + * @property bool $useCustomStorage Whether to use custom storage. This property is read-only. + * @property bool $useTransparentSessionID Whether transparent sid support is enabled or not, defaults to * false. * * @author Qiang Xue @@ -110,7 +110,7 @@ public function init() * This method should be overridden to return true by child classes that implement custom session storage. * To implement custom session storage, override these methods: [[openSession()]], [[closeSession()]], * [[readSession()]], [[writeSession()]], [[destroySession()]] and [[gcSession()]]. - * @return boolean whether to use custom storage. + * @return bool whether to use custom storage. */ public function getUseCustomStorage() { @@ -206,7 +206,7 @@ public function destroy() } /** - * @return boolean whether the session has started + * @return bool whether the session has started */ public function getIsActive() { @@ -220,7 +220,7 @@ public function getIsActive() * The default implementation will check cookie and $_GET using the session name. * If you send session ID via other ways, you may need to override this method * or call [[setHasSessionId()]] to explicitly set whether the session ID is sent. - * @return boolean whether the current request has sent the session ID. + * @return bool whether the current request has sent the session ID. */ public function getHasSessionId() { @@ -243,7 +243,7 @@ public function getHasSessionId() * Sets the value indicating whether the current request has sent the session ID. * This method is provided so that you can override the default way of determining * whether the session ID is sent. - * @param boolean $value whether the current request has sent the session ID. + * @param bool $value whether the current request has sent the session ID. */ public function setHasSessionId($value) { @@ -273,7 +273,7 @@ public function setId($value) /** * Updates the current session ID with a newly generated one . * Please refer to for more details. - * @param boolean $deleteOldSession Whether to delete the old associated session file or not. + * @param bool $deleteOldSession Whether to delete the old associated session file or not. */ public function regenerateID($deleteOldSession = false) { @@ -375,7 +375,7 @@ private function setCookieParamsInternal() /** * Returns the value indicating whether cookies should be used to store session IDs. - * @return boolean|null the value indicating whether cookies should be used to store session IDs. + * @return bool|null the value indicating whether cookies should be used to store session IDs. * @see setUseCookies() */ public function getUseCookies() @@ -397,7 +397,7 @@ public function getUseCookies() * - false: cookies will not be used to store session IDs. * - null: if possible, cookies will be used to store session IDs; if not, other mechanisms will be used (e.g. GET parameter) * - * @param boolean|null $value the value indicating whether cookies should be used to store session IDs. + * @param bool|null $value the value indicating whether cookies should be used to store session IDs. */ public function setUseCookies($value) { @@ -437,7 +437,7 @@ public function setGCProbability($value) } /** - * @return boolean whether transparent sid support is enabled or not, defaults to false. + * @return bool whether transparent sid support is enabled or not, defaults to false. */ public function getUseTransparentSessionID() { @@ -445,7 +445,7 @@ public function getUseTransparentSessionID() } /** - * @param boolean $value whether transparent sid support is enabled or not. + * @param bool $value whether transparent sid support is enabled or not. */ public function setUseTransparentSessionID($value) { @@ -453,7 +453,7 @@ public function setUseTransparentSessionID($value) } /** - * @return integer the number of seconds after which data will be seen as 'garbage' and cleaned up. + * @return int the number of seconds after which data will be seen as 'garbage' and cleaned up. * The default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini). */ public function getTimeout() @@ -462,7 +462,7 @@ public function getTimeout() } /** - * @param integer $value the number of seconds after which data will be seen as 'garbage' and cleaned up + * @param int $value the number of seconds after which data will be seen as 'garbage' and cleaned up */ public function setTimeout($value) { @@ -475,7 +475,7 @@ public function setTimeout($value) * Do not call this method directly. * @param string $savePath session save path * @param string $sessionName session name - * @return boolean whether session is opened successfully + * @return bool whether session is opened successfully */ public function openSession($savePath, $sessionName) { @@ -486,7 +486,7 @@ public function openSession($savePath, $sessionName) * Session close handler. * This method should be overridden if [[useCustomStorage]] returns true. * Do not call this method directly. - * @return boolean whether session is closed successfully + * @return bool whether session is closed successfully */ public function closeSession() { @@ -511,7 +511,7 @@ public function readSession($id) * Do not call this method directly. * @param string $id session ID * @param string $data session data - * @return boolean whether session write is successful + * @return bool whether session write is successful */ public function writeSession($id, $data) { @@ -523,7 +523,7 @@ public function writeSession($id, $data) * This method should be overridden if [[useCustomStorage]] returns true. * Do not call this method directly. * @param string $id session ID - * @return boolean whether session is destroyed successfully + * @return bool whether session is destroyed successfully */ public function destroySession($id) { @@ -534,8 +534,8 @@ public function destroySession($id) * Session GC (garbage collection) handler. * This method should be overridden if [[useCustomStorage]] returns true. * Do not call this method directly. - * @param integer $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up. - * @return boolean whether session is GCed successfully + * @param int $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up. + * @return bool whether session is GCed successfully */ public function gcSession($maxLifetime) { @@ -555,7 +555,7 @@ public function getIterator() /** * Returns the number of items in the session. - * @return integer the number of session variables + * @return int the number of session variables */ public function getCount() { @@ -566,7 +566,7 @@ public function getCount() /** * Returns the number of items in the session. * This method is required by [[\Countable]] interface. - * @return integer number of items in the session. + * @return int number of items in the session. */ public function count() { @@ -629,7 +629,7 @@ public function removeAll() /** * @param mixed $key session variable name - * @return boolean whether there is the named session variable + * @return bool whether there is the named session variable */ public function has($key) { @@ -663,7 +663,7 @@ protected function updateFlashCounters() * Returns a flash message. * @param string $key the key identifying the flash message * @param mixed $defaultValue value to be returned if the flash message does not exist. - * @param boolean $delete whether to delete this flash message right after this method is called. + * @param bool $delete whether to delete this flash message right after this method is called. * If false, the flash message will be automatically deleted in the next request. * @return mixed the flash message or an array of messages if addFlash was used * @see setFlash() @@ -710,7 +710,7 @@ public function getFlash($key, $defaultValue = null, $delete = false) * * [bootstrap alert]: http://getbootstrap.com/components/#alerts * - * @param boolean $delete whether to delete the flash messages right after this method is called. + * @param bool $delete whether to delete the flash messages right after this method is called. * If false, the flash messages will be automatically deleted in the next request. * @return array flash messages (key => message or key => [message1, message2]). * @see setFlash() @@ -751,7 +751,7 @@ public function getAllFlashes($delete = false) * and normal session variables share the same name space. If you have a normal * session variable using the same name, its value will be overwritten by this method. * @param mixed $value flash message - * @param boolean $removeAfterAccess whether the flash message should be automatically removed only if + * @param bool $removeAfterAccess whether the flash message should be automatically removed only if * it is accessed. If false, the flash message will be automatically removed after the next request, * regardless if it is accessed or not. If true (default value), the flash message will remain until after * it is accessed. @@ -772,7 +772,7 @@ public function setFlash($key, $value = true, $removeAfterAccess = true) * If there are existing flash messages with the same key, the new one will be appended to the existing message array. * @param string $key the key identifying the flash message. * @param mixed $value flash message - * @param boolean $removeAfterAccess whether the flash message should be automatically removed only if + * @param bool $removeAfterAccess whether the flash message should be automatically removed only if * it is accessed. If false, the flash message will be automatically removed after the next request, * regardless if it is accessed or not. If true (default value), the flash message will remain until after * it is accessed. @@ -839,7 +839,7 @@ public function removeAllFlashes() /** * Returns a value indicating whether there are flash messages associated with the specified key. * @param string $key key identifying the flash message type - * @return boolean whether any flash messages exist under specified key + * @return bool whether any flash messages exist under specified key */ public function hasFlash($key) { @@ -849,7 +849,7 @@ public function hasFlash($key) /** * This method is required by the interface [[\ArrayAccess]]. * @param mixed $offset the offset to check on - * @return boolean + * @return bool */ public function offsetExists($offset) { @@ -860,7 +860,7 @@ public function offsetExists($offset) /** * 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) @@ -872,7 +872,7 @@ public function offsetGet($offset) /** * 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) diff --git a/framework/web/SessionIterator.php b/framework/web/SessionIterator.php index ccdbbf49b8c..d8ccdf71ad0 100644 --- a/framework/web/SessionIterator.php +++ b/framework/web/SessionIterator.php @@ -76,7 +76,7 @@ public function next() /** * Returns whether there is an element at current position. * This method is required by the interface [[\Iterator]]. - * @return boolean + * @return bool */ public function valid() { diff --git a/framework/web/TooManyRequestsHttpException.php b/framework/web/TooManyRequestsHttpException.php index a53e1d01dad..56586fae541 100644 --- a/framework/web/TooManyRequestsHttpException.php +++ b/framework/web/TooManyRequestsHttpException.php @@ -23,7 +23,7 @@ class TooManyRequestsHttpException extends HttpException /** * Constructor. * @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($message = null, $code = 0, \Exception $previous = null) diff --git a/framework/web/UnauthorizedHttpException.php b/framework/web/UnauthorizedHttpException.php index b21c42dd668..0770dff8b13 100644 --- a/framework/web/UnauthorizedHttpException.php +++ b/framework/web/UnauthorizedHttpException.php @@ -24,7 +24,7 @@ class UnauthorizedHttpException extends HttpException /** * Constructor. * @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($message = null, $code = 0, \Exception $previous = null) diff --git a/framework/web/UnprocessableEntityHttpException.php b/framework/web/UnprocessableEntityHttpException.php index dca3a74104a..e32faac3a62 100644 --- a/framework/web/UnprocessableEntityHttpException.php +++ b/framework/web/UnprocessableEntityHttpException.php @@ -25,7 +25,7 @@ class UnprocessableEntityHttpException extends HttpException /** * Constructor. * @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($message = null, $code = 0, \Exception $previous = null) diff --git a/framework/web/UnsupportedMediaTypeHttpException.php b/framework/web/UnsupportedMediaTypeHttpException.php index 2e75f821d4d..8cb5e0eeae4 100644 --- a/framework/web/UnsupportedMediaTypeHttpException.php +++ b/framework/web/UnsupportedMediaTypeHttpException.php @@ -24,7 +24,7 @@ class UnsupportedMediaTypeHttpException extends HttpException /** * Constructor. * @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($message = null, $code = 0, \Exception $previous = null) diff --git a/framework/web/UploadedFile.php b/framework/web/UploadedFile.php index 3b886e06249..b3613e2f7cf 100644 --- a/framework/web/UploadedFile.php +++ b/framework/web/UploadedFile.php @@ -22,7 +22,7 @@ * * @property string $baseName Original file base name. This property is read-only. * @property string $extension File extension. This property is read-only. - * @property boolean $hasError Whether there is an error with the uploaded file. Check [[error]] for detailed + * @property bool $hasError Whether there is an error with the uploaded file. Check [[error]] for detailed * error code information. This property is read-only. * * @author Qiang Xue @@ -47,11 +47,11 @@ class UploadedFile extends Object */ public $type; /** - * @var integer the actual size of the uploaded file in bytes + * @var int the actual size of the uploaded file in bytes */ public $size; /** - * @var integer an error code describing the status of this file uploading. + * @var int an error code describing the status of this file uploading. * @see http://www.php.net/manual/en/features.file-upload.errors.php */ public $error; @@ -151,9 +151,9 @@ public static function reset() * Note that this method uses php's move_uploaded_file() method. If the target file `$file` * already exists, it will be overwritten. * @param string $file the file path used to save the uploaded file - * @param boolean $deleteTempFile whether to delete the temporary file after saving. + * @param bool $deleteTempFile whether to delete the temporary file after saving. * If true, you will not be able to save the uploaded file again in the current request. - * @return boolean true whether the file is saved successfully + * @return bool true whether the file is saved successfully * @see error */ public function saveAs($file, $deleteTempFile = true) @@ -187,7 +187,7 @@ public function getExtension() } /** - * @return boolean whether there is an error with the uploaded file. + * @return bool whether there is an error with the uploaded file. * Check [[error]] for detailed error code information. */ public function getHasError() diff --git a/framework/web/UrlManager.php b/framework/web/UrlManager.php index cd2faa71f8d..3072c58e217 100644 --- a/framework/web/UrlManager.php +++ b/framework/web/UrlManager.php @@ -45,14 +45,14 @@ class UrlManager extends Component { /** - * @var boolean whether to enable pretty URLs. Instead of putting all parameters in the query + * @var bool whether to enable pretty URLs. Instead of putting all parameters in the query * string part of a URL, pretty URLs allow using path info to represent some of the parameters * and can thus produce more user-friendly URLs, such as "/news/Yii-is-released", instead of * "/index.php?r=news%2Fview&id=100". */ public $enablePrettyUrl = false; /** - * @var boolean whether to enable strict parsing. If strict parsing is enabled, the incoming + * @var bool whether to enable strict parsing. If strict parsing is enabled, the incoming * requested URL must match at least one of the [[rules]] in order to be treated as a valid request. * Otherwise, the path info part of the request will be treated as the requested route. * This property is used only when [[enablePrettyUrl]] is `true`. @@ -105,7 +105,7 @@ class UrlManager extends Component */ public $suffix; /** - * @var boolean whether to show entry script name in the constructed URL. Defaults to `true`. + * @var bool whether to show entry script name in the constructed URL. Defaults to `true`. * This property is used only if [[enablePrettyUrl]] is `true`. */ public $showScriptName = true; @@ -201,7 +201,7 @@ public function init() * * @param array $rules the new rules to be added. Each array element represents a single rule declaration. * Please refer to [[rules]] for the acceptable rule format. - * @param boolean $append whether to add the new rules by appending them to the end of the existing rules. + * @param bool $append whether to add the new rules by appending them to the end of the existing rules. */ public function addRules($rules, $append = true) { @@ -254,7 +254,7 @@ protected function buildRules($rules) /** * Parses the user request. * @param Request $request the request component - * @return array|boolean the route and the associated parameters. The latter is always empty + * @return array|bool the route and the associated parameters. The latter is always empty * if [[enablePrettyUrl]] is `false`. `false` is returned if the current request cannot be successfully parsed. */ public function parseRequest($request) @@ -412,7 +412,7 @@ public function createUrl($params) * @param string $cacheKey generated cache key to store data. * @param string $route the route (e.g. `site/index`). * @param array $params rule params. - * @return boolean|string the created URL + * @return bool|string the created URL * @see createUrl() * @since 2.0.8 */ diff --git a/framework/web/UrlNormalizer.php b/framework/web/UrlNormalizer.php index dd633b0cafa..712d3560c02 100644 --- a/framework/web/UrlNormalizer.php +++ b/framework/web/UrlNormalizer.php @@ -37,17 +37,17 @@ class UrlNormalizer extends Object const ACTION_NOT_FOUND = 404; /** - * @var boolean whether slashes should be collapsed, for example `site///index` will be + * @var bool whether slashes should be collapsed, for example `site///index` will be * converted into `site/index` */ public $collapseSlashes = true; /** - * @var boolean whether trailing slash should be normalized according to the suffix settings + * @var bool whether trailing slash should be normalized according to the suffix settings * of the rule */ public $normalizeTrailingSlash = true; /** - * @var integer|callable|null action to perform during route normalization. + * @var int|callable|null action to perform during route normalization. * Available options are: * - `null` - no special action will be performed * - `301` - the request should be redirected to the normalized URL using @@ -96,7 +96,7 @@ public function normalizeRoute($route) * Normalizes specified pathInfo. * @param string $pathInfo pathInfo for normalization * @param string $suffix current rule suffix - * @param boolean $normalized if specified, this variable will be set to `true` if $pathInfo + * @param bool $normalized if specified, this variable will be set to `true` if $pathInfo * was changed during normalization * @return string normalized pathInfo */ @@ -147,4 +147,4 @@ protected function normalizeTrailingSlash($pathInfo, $suffix) return $pathInfo; } -} \ No newline at end of file +} diff --git a/framework/web/UrlNormalizerRedirectException.php b/framework/web/UrlNormalizerRedirectException.php index 1063d76a7b9..195d45b8fd4 100644 --- a/framework/web/UrlNormalizerRedirectException.php +++ b/framework/web/UrlNormalizerRedirectException.php @@ -22,12 +22,12 @@ class UrlNormalizerRedirectException extends \yii\base\Exception */ public $url; /** - * @var boolean|string the URI scheme to use in the generated URL for redirection + * @var bool|string the URI scheme to use in the generated URL for redirection * @see [[\yii\helpers\Url::to()]] */ public $scheme; /** - * @var integer the HTTP status code + * @var int the HTTP status code */ public $statusCode; @@ -35,11 +35,11 @@ class UrlNormalizerRedirectException extends \yii\base\Exception /** * @param array|string $url the parameter to be used to generate a valid URL for redirection. * This will be used as first parameter for [[\yii\helpers\Url::to()]] - * @param integer $statusCode HTTP status code used for redirection - * @param boolean|string $scheme the URI scheme to use in the generated URL for redirection. + * @param int $statusCode HTTP status code used for redirection + * @param bool|string $scheme the URI scheme to use in the generated URL for redirection. * This will be used as second parameter for [[\yii\helpers\Url::to()]] * @param string $message the error message - * @param integer $code the error code + * @param int $code the error code * @param \Exception $previous the previous exception used for the exception chaining */ public function __construct($url, $statusCode = 302, $scheme = false, $message = null, $code = 0, \Exception $previous = null) diff --git a/framework/web/UrlRule.php b/framework/web/UrlRule.php index 5f1215e5a81..4a193cbe93e 100644 --- a/framework/web/UrlRule.php +++ b/framework/web/UrlRule.php @@ -78,7 +78,7 @@ class UrlRule extends Object implements UrlRuleInterface */ public $verb; /** - * @var integer a value indicating if this rule should be used for both request parsing and URL creation, + * @var int a value indicating if this rule should be used for both request parsing and URL creation, * parsing only, or creation only. * If not set or 0, it means the rule is both request parsing and URL creation. * If it is [[PARSING_ONLY]], the rule is for request parsing only. @@ -86,7 +86,7 @@ class UrlRule extends Object implements UrlRuleInterface */ public $mode; /** - * @var boolean a value indicating if parameters should be url encoded. + * @var bool a value indicating if parameters should be url encoded. */ public $encodeParams = true; /** @@ -245,7 +245,7 @@ protected function getNormalizer($manager) /** * @param UrlManager $manager the URL manager - * @return boolean + * @return bool * @since 2.0.10 */ protected function hasNormalizer($manager) @@ -257,7 +257,7 @@ protected function hasNormalizer($manager) * Parses the given request and returns the corresponding route and parameters. * @param UrlManager $manager the URL manager * @param Request $request the request component - * @return array|boolean the parsing result. The route and the parameters are returned as an array. + * @return array|bool the parsing result. The route and the parameters are returned as an array. * If `false`, it means this rule cannot be used to parse this path info. */ public function parseRequest($manager, $request) @@ -334,7 +334,7 @@ public function parseRequest($manager, $request) * @param UrlManager $manager the URL manager * @param string $route the route. It should not have slashes at the beginning or the end. * @param array $params the parameters - * @return string|boolean the created URL, or `false` if this rule cannot be used for creating this URL. + * @return string|bool the created URL, or `false` if this rule cannot be used for creating this URL. */ public function createUrl($manager, $route, $params) { diff --git a/framework/web/UrlRuleInterface.php b/framework/web/UrlRuleInterface.php index 8ca6403ccc8..c81018fb2ec 100644 --- a/framework/web/UrlRuleInterface.php +++ b/framework/web/UrlRuleInterface.php @@ -19,7 +19,7 @@ interface UrlRuleInterface * Parses the given request and returns the corresponding route and parameters. * @param UrlManager $manager the URL manager * @param Request $request the request component - * @return array|boolean the parsing result. The route and the parameters are returned as an array. + * @return array|bool the parsing result. The route and the parameters are returned as an array. * If false, it means this rule cannot be used to parse this path info. */ public function parseRequest($manager, $request); @@ -29,7 +29,7 @@ public function parseRequest($manager, $request); * @param UrlManager $manager the URL manager * @param string $route the route. It should not have slashes at the beginning or the end. * @param array $params the parameters - * @return string|boolean the created URL, or false if this rule cannot be used for creating this URL. + * @return string|bool the created URL, or false if this rule cannot be used for creating this URL. */ public function createUrl($manager, $route, $params); } diff --git a/framework/web/User.php b/framework/web/User.php index 6b565c6da29..009131d72fb 100644 --- a/framework/web/User.php +++ b/framework/web/User.php @@ -46,11 +46,11 @@ * ] * ``` * - * @property string|integer $id The unique identifier for the user. If `null`, it means the user is a guest. + * @property string|int $id The unique identifier for the user. If `null`, it means the user is a guest. * This property is read-only. * @property IdentityInterface|null $identity The identity object associated with the currently logged-in * user. `null` is returned if the user is not logged in (not authenticated). - * @property boolean $isGuest Whether the current user is a guest. This property is read-only. + * @property bool $isGuest Whether the current user is a guest. This property is read-only. * @property string $returnUrl The URL that the user should be redirected to after login. Note that the type * of this property differs in getter and setter. See [[getReturnUrl()]] and [[setReturnUrl()]] for details. * @@ -69,12 +69,12 @@ class User extends Component */ public $identityClass; /** - * @var boolean whether to enable cookie-based login. Defaults to `false`. + * @var bool whether to enable cookie-based login. Defaults to `false`. * Note that this property will be ignored if [[enableSession]] is `false`. */ public $enableAutoLogin = false; /** - * @var boolean whether to use session to persist authentication status across multiple requests. + * @var bool whether to use session to persist authentication status across multiple requests. * You set this property to be `false` if your application is stateless, which is often the case * for RESTful APIs. */ @@ -98,7 +98,7 @@ class User extends Component */ public $identityCookie = ['name' => '_identity', 'httpOnly' => true]; /** - * @var integer the number of seconds in which the user will be logged out automatically if he + * @var int the number of seconds in which the user will be logged out automatically if he * remains inactive. If this property is not set, the user will be logged out after * the current session expires (c.f. [[Session::timeout]]). * Note that this will not work if [[enableAutoLogin]] is `true`. @@ -111,13 +111,13 @@ class User extends Component */ public $accessChecker; /** - * @var integer the number of seconds in which the user will be logged out automatically + * @var int the number of seconds in which the user will be logged out automatically * regardless of activity. * Note that this will not work if [[enableAutoLogin]] is `true`. */ public $absoluteAuthTimeout; /** - * @var boolean whether to automatically renew the identity cookie each time a page is requested. + * @var bool whether to automatically renew the identity cookie each time a page is requested. * This property is effective only when [[enableAutoLogin]] is `true`. * When this is `false`, the identity cookie will expire after the specified duration since the user * is initially logged in. When this is `true`, the identity cookie will expire after the specified duration @@ -173,7 +173,7 @@ public function init() * Returns the identity object associated with the currently logged-in user. * When [[enableSession]] is true, this method may attempt to read the user's authentication data * stored in session and reconstruct the corresponding identity object, if it has not done so before. - * @param boolean $autoRenew whether to automatically renew authentication status if it has not been done so before. + * @param bool $autoRenew whether to automatically renew authentication status if it has not been done so before. * This is only useful when [[enableSession]] is true. * @return IdentityInterface|null the identity object associated with the currently logged-in user. * `null` is returned if the user is not logged in (not authenticated). @@ -236,11 +236,11 @@ public function setIdentity($identity) * in this case. * * @param IdentityInterface $identity the user identity (which should already be authenticated) - * @param integer $duration number of seconds that the user can remain in logged-in status. + * @param int $duration number of seconds that the user can remain in logged-in status. * Defaults to 0, meaning login till the user closes the browser or the session is manually destroyed. * If greater than 0 and [[enableAutoLogin]] is true, cookie-based login will be supported. * Note that if [[enableSession]] is false, this parameter will be ignored. - * @return boolean whether the user is logged in + * @return bool whether the user is logged in */ public function login(IdentityInterface $identity, $duration = 0) { @@ -309,9 +309,9 @@ protected function loginByCookie() * Logs out the current user. * This will remove authentication-related session data. * If `$destroySession` is true, all session data will be removed. - * @param boolean $destroySession whether to destroy the whole session. Defaults to true. + * @param bool $destroySession whether to destroy the whole session. Defaults to true. * This parameter is ignored if [[enableSession]] is false. - * @return boolean whether the user is logged out + * @return bool whether the user is logged out */ public function logout($destroySession = true) { @@ -332,7 +332,7 @@ public function logout($destroySession = true) /** * Returns a value indicating whether the user is a guest (not authenticated). - * @return boolean whether the current user is a guest. + * @return bool whether the current user is a guest. * @see getIdentity() */ public function getIsGuest() @@ -342,7 +342,7 @@ public function getIsGuest() /** * Returns a value that uniquely represents the user. - * @return string|integer the unique identifier for the user. If `null`, it means the user is a guest. + * @return string|int the unique identifier for the user. If `null`, it means the user is a guest. * @see getIdentity() */ public function getId() @@ -405,9 +405,9 @@ public function setReturnUrl($url) * * Note that when [[loginUrl]] is set, calling this method will NOT terminate the application execution. * - * @param boolean $checkAjax whether to check if the request is an AJAX request. When this is true and the request + * @param bool $checkAjax whether to check if the request is an AJAX request. When this is true and the request * is an AJAX request, the current URL (for AJAX request) will NOT be set as the return URL. - * @param boolean $checkAcceptHeader whether to check if the request accepts HTML responses. Defaults to `true`. When this is true and + * @param bool $checkAcceptHeader whether to check if the request accepts HTML responses. Defaults to `true`. When this is true and * the request does not accept HTML responses the current URL will not be SET as the return URL. Also instead of * redirecting the user an ForbiddenHttpException is thrown. This parameter is available since version 2.0.8. * @return Response the redirection response if [[loginUrl]] is set @@ -441,10 +441,10 @@ public function loginRequired($checkAjax = true, $checkAcceptHeader = true) * If you override this method, make sure you call the parent implementation * so that the event is triggered. * @param IdentityInterface $identity the user identity information - * @param boolean $cookieBased whether the login is cookie-based - * @param integer $duration number of seconds that the user can remain in logged-in status. + * @param bool $cookieBased whether the login is cookie-based + * @param int $duration number of seconds that the user can remain in logged-in status. * If 0, it means login till the user closes the browser or the session is manually destroyed. - * @return boolean whether the user should continue to be logged in + * @return bool whether the user should continue to be logged in */ protected function beforeLogin($identity, $cookieBased, $duration) { @@ -464,8 +464,8 @@ protected function beforeLogin($identity, $cookieBased, $duration) * If you override this method, make sure you call the parent implementation * so that the event is triggered. * @param IdentityInterface $identity the user identity information - * @param boolean $cookieBased whether the login is cookie-based - * @param integer $duration number of seconds that the user can remain in logged-in status. + * @param bool $cookieBased whether the login is cookie-based + * @param int $duration number of seconds that the user can remain in logged-in status. * If 0, it means login till the user closes the browser or the session is manually destroyed. */ protected function afterLogin($identity, $cookieBased, $duration) @@ -483,7 +483,7 @@ protected function afterLogin($identity, $cookieBased, $duration) * If you override this method, make sure you call the parent implementation * so that the event is triggered. * @param IdentityInterface $identity the user identity information - * @return boolean whether the user should continue to be logged out + * @return bool whether the user should continue to be logged out */ protected function beforeLogout($identity) { @@ -535,7 +535,7 @@ protected function renewIdentityCookie() * It saves [[id]], [[IdentityInterface::getAuthKey()|auth key]], and the duration of cookie-based login * information in the cookie. * @param IdentityInterface $identity - * @param integer $duration number of seconds that the user can remain in logged-in status. + * @param int $duration number of seconds that the user can remain in logged-in status. * @see loginByCookie() */ protected function sendIdentityCookie($identity, $duration) @@ -605,7 +605,7 @@ protected function removeIdentityCookie() * * @param IdentityInterface|null $identity the identity information to be associated with the current user. * If null, it means switching the current user to be a guest. - * @param integer $duration number of seconds that the user can remain in logged-in status. + * @param int $duration number of seconds that the user can remain in logged-in status. * This parameter is used only when `$identity` is not null. */ public function switchIdentity($identity, $duration = 0) @@ -695,13 +695,13 @@ protected function renewAuthStatus() * @param string $permissionName the name of the permission (e.g. "edit post") that needs access check. * @param array $params name-value pairs that would be passed to the rules associated * with the roles and permissions assigned to the user. - * @param boolean $allowCaching whether to allow caching the result of access check. + * @param bool $allowCaching whether to allow caching the result of access check. * When this parameter is true (default), if the access check of an operation was performed * before, its result will be directly returned when calling this method to check the same * operation. If this parameter is false, this method will always call * [[\yii\rbac\CheckAccessInterface::checkAccess()]] to obtain the up-to-date access result. Note that this * caching is effective only within the same request and only works when `$params = []`. - * @return boolean whether the user can perform the operation as specified by the given permission. + * @return bool whether the user can perform the operation as specified by the given permission. */ public function can($permissionName, $params = [], $allowCaching = true) { @@ -723,7 +723,7 @@ public function can($permissionName, $params = [], $allowCaching = true) * Checks if the `Accept` header contains a content type that allows redirection to the login page. * The login page is assumed to serve `text/html` or `application/xhtml+xml` by default. You can change acceptable * content types by modifying [[acceptableRedirectTypes]] property. - * @return boolean whether this request may be redirected to the login page. + * @return bool whether this request may be redirected to the login page. * @see acceptableRedirectTypes * @since 2.0.8 */ diff --git a/framework/web/UserEvent.php b/framework/web/UserEvent.php index cc2e328b6e5..5167194d9b1 100644 --- a/framework/web/UserEvent.php +++ b/framework/web/UserEvent.php @@ -22,17 +22,17 @@ class UserEvent extends Event */ public $identity; /** - * @var boolean whether the login is cookie-based. This property is only meaningful + * @var bool whether the login is cookie-based. This property is only meaningful * for [[User::EVENT_BEFORE_LOGIN]] and [[User::EVENT_AFTER_LOGIN]] events. */ public $cookieBased; /** - * @var integer $duration number of seconds that the user can remain in logged-in status. + * @var int $duration number of seconds that the user can remain in logged-in status. * If 0, it means login till the user closes the browser or the session is manually destroyed. */ public $duration; /** - * @var boolean whether the login or logout should proceed. + * @var bool whether the login or logout should proceed. * Event handlers may modify this property to determine whether the login or logout should proceed. * This property is only meaningful for [[User::EVENT_BEFORE_LOGIN]] and [[User::EVENT_BEFORE_LOGOUT]] events. */ diff --git a/framework/web/View.php b/framework/web/View.php index 33dbec115dd..67214a35075 100644 --- a/framework/web/View.php +++ b/framework/web/View.php @@ -165,7 +165,7 @@ public function endBody() /** * Marks the ending of an HTML page. - * @param boolean $ajaxMode whether the view is rendering in AJAX mode. + * @param bool $ajaxMode whether the view is rendering in AJAX mode. * If true, the JS scripts registered at [[POS_READY]] and [[POS_LOAD]] positions * will be rendered at the end of the view like normal scripts. */ @@ -272,7 +272,7 @@ protected function registerAssetFiles($name) * Registers the named asset bundle. * All dependent asset bundles will be registered. * @param string $name the class name of the asset bundle (without the leading backslash) - * @param integer|null $position if set, this forces a minimum position for javascript files. + * @param int|null $position if set, this forces a minimum position for javascript files. * This will adjust depending assets javascript file position or fail if requirement can not be met. * If this is null, asset bundles position settings will not be changed. * See [[registerJsFile]] for more details on javascript position. @@ -420,7 +420,7 @@ public function registerCssFile($url, $options = [], $key = null) /** * Registers a JS code block. * @param string $js the JS code block to be registered - * @param integer $position the position at which the JS script tag should be inserted + * @param int $position the position at which the JS script tag should be inserted * in a page. The possible values are: * * - [[POS_HEAD]]: in the head section @@ -537,7 +537,7 @@ protected function renderBodyBeginHtml() /** * Renders the content to be inserted at the end of the body section. * The content is rendered using the registered JS code blocks and files. - * @param boolean $ajaxMode whether the view is rendering in AJAX mode. + * @param bool $ajaxMode whether the view is rendering in AJAX mode. * If true, the JS scripts registered at [[POS_READY]] and [[POS_LOAD]] positions * will be rendered at the end of the view like normal scripts. * @return string the rendered content diff --git a/framework/web/XmlResponseFormatter.php b/framework/web/XmlResponseFormatter.php index caa55114c45..ec08656ae4f 100644 --- a/framework/web/XmlResponseFormatter.php +++ b/framework/web/XmlResponseFormatter.php @@ -45,7 +45,7 @@ class XmlResponseFormatter extends Component implements ResponseFormatterInterfa */ public $itemTag = 'item'; /** - * @var boolean whether to interpret objects implementing the [[\Traversable]] interface as arrays. + * @var bool whether to interpret objects implementing the [[\Traversable]] interface as arrays. * Defaults to `true`. * @since 2.0.7 */ diff --git a/framework/widgets/ActiveField.php b/framework/widgets/ActiveField.php index f9478ff7495..eb946f442e5 100644 --- a/framework/widgets/ActiveField.php +++ b/framework/widgets/ActiveField.php @@ -97,33 +97,33 @@ class ActiveField extends Component */ public $hintOptions = ['class' => 'hint-block']; /** - * @var boolean whether to enable client-side data validation. + * @var bool whether to enable client-side data validation. * If not set, it will take the value of [[ActiveForm::enableClientValidation]]. */ public $enableClientValidation; /** - * @var boolean whether to enable AJAX-based data validation. + * @var bool whether to enable AJAX-based data validation. * If not set, it will take the value of [[ActiveForm::enableAjaxValidation]]. */ public $enableAjaxValidation; /** - * @var boolean whether to perform validation when the value of the input field is changed. + * @var bool whether to perform validation when the value of the input field is changed. * If not set, it will take the value of [[ActiveForm::validateOnChange]]. */ public $validateOnChange; /** - * @var boolean whether to perform validation when the input field loses focus. + * @var bool whether to perform validation when the input field loses focus. * If not set, it will take the value of [[ActiveForm::validateOnBlur]]. */ public $validateOnBlur; /** - * @var boolean whether to perform validation while the user is typing in the input field. + * @var bool whether to perform validation while the user is typing in the input field. * If not set, it will take the value of [[ActiveForm::validateOnType]]. * @see validationDelay */ public $validateOnType; /** - * @var integer number of milliseconds that the validation should be delayed when the user types in the field + * @var int number of milliseconds that the validation should be delayed when the user types in the field * and [[validateOnType]] is set `true`. * If not set, it will take the value of [[ActiveForm::validationDelay]]. */ @@ -373,7 +373,7 @@ public function input($type, $options = []) * * The following special options are recognized: * - * - `maxlength`: integer|boolean, when `maxlength` is set `true` and the model attribute is validated + * - `maxlength`: int|bool, when `maxlength` is set `true` and the model attribute is validated * by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]]. * This is available since version 2.0.3. * @@ -501,7 +501,7 @@ public function textarea($options = []) * * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly. * - * @param boolean $enclosedByLabel whether to enclose the radio within the label. + * @param bool $enclosedByLabel whether to enclose the radio within the label. * If `true`, the method will still use [[template]] to layout the radio button and the error message * except that the radio is enclosed by the label tag. * @return $this the field object itself. @@ -547,7 +547,7 @@ public function radio($options = [], $enclosedByLabel = true) * * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly. * - * @param boolean $enclosedByLabel whether to enclose the checkbox within the label. + * @param bool $enclosedByLabel whether to enclose the checkbox within the label. * If `true`, the method will still use [[template]] to layout the checkbox and the error message * except that the checkbox is enclosed by the label tag. * @return $this the field object itself. diff --git a/framework/widgets/ActiveForm.php b/framework/widgets/ActiveForm.php index 9f6ba83b44c..3d304745991 100644 --- a/framework/widgets/ActiveForm.php +++ b/framework/widgets/ActiveForm.php @@ -72,7 +72,7 @@ class ActiveForm extends Widget */ public $fieldConfig = []; /** - * @var boolean whether to perform encoding on the error summary. + * @var bool whether to perform encoding on the error summary. */ public $encodeErrorSummary = true; /** @@ -97,17 +97,17 @@ class ActiveForm extends Widget */ public $validatingCssClass = 'validating'; /** - * @var boolean whether to enable client-side data validation. + * @var bool whether to enable client-side data validation. * If [[ActiveField::enableClientValidation]] is set, its value will take precedence for that input field. */ public $enableClientValidation = true; /** - * @var boolean whether to enable AJAX-based data validation. + * @var bool whether to enable AJAX-based data validation. * If [[ActiveField::enableAjaxValidation]] is set, its value will take precedence for that input field. */ public $enableAjaxValidation = false; /** - * @var boolean whether to hook up `yii.activeForm` JavaScript plugin. + * @var bool whether to hook up `yii.activeForm` JavaScript plugin. * This property must be set `true` if you want to support client validation and/or AJAX validation, or if you * want to take advantage of the `yii.activeForm` plugin. When this is `false`, the form will not generate * any JavaScript. @@ -120,27 +120,27 @@ class ActiveForm extends Widget */ public $validationUrl; /** - * @var boolean whether to perform validation when the form is submitted. + * @var bool whether to perform validation when the form is submitted. */ public $validateOnSubmit = true; /** - * @var boolean whether to perform validation when the value of an input field is changed. + * @var bool whether to perform validation when the value of an input field is changed. * If [[ActiveField::validateOnChange]] is set, its value will take precedence for that input field. */ public $validateOnChange = true; /** - * @var boolean whether to perform validation when an input field loses focus. + * @var bool whether to perform validation when an input field loses focus. * If [[ActiveField::$validateOnBlur]] is set, its value will take precedence for that input field. */ public $validateOnBlur = true; /** - * @var boolean whether to perform validation while the user is typing in an input field. + * @var bool whether to perform validation while the user is typing in an input field. * If [[ActiveField::validateOnType]] is set, its value will take precedence for that input field. * @see validationDelay */ public $validateOnType = false; /** - * @var integer number of milliseconds that the validation should be delayed when the user types in the field + * @var int number of milliseconds that the validation should be delayed when the user types in the field * and [[validateOnType]] is set `true`. * If [[ActiveField::validationDelay]] is set, its value will take precedence for that input field. */ @@ -154,7 +154,7 @@ class ActiveForm extends Widget */ public $ajaxDataType = 'json'; /** - * @var boolean whether to scroll to the first error after validation. + * @var bool whether to scroll to the first error after validation. * @since 2.0.6 */ public $scrollToError = true; diff --git a/framework/widgets/BaseListView.php b/framework/widgets/BaseListView.php index 3efd202ecdf..82e3e3017e7 100644 --- a/framework/widgets/BaseListView.php +++ b/framework/widgets/BaseListView.php @@ -71,7 +71,7 @@ abstract class BaseListView extends Widget */ public $summaryOptions = ['class' => 'summary']; /** - * @var boolean whether to show the list view if [[dataProvider]] returns no data. + * @var bool whether to show the list view if [[dataProvider]] returns no data. */ public $showOnEmpty = false; /** @@ -142,7 +142,7 @@ public function run() * Renders a section of the specified name. * If the named section is not supported, false will be returned. * @param string $name the section name, e.g., `{summary}`, `{items}`. - * @return string|boolean the rendering result of the section, or false if the named section is not supported. + * @return string|bool the rendering result of the section, or false if the named section is not supported. */ public function renderSection($name) { diff --git a/framework/widgets/Block.php b/framework/widgets/Block.php index 998dd6c2bd1..9a1e8193e60 100644 --- a/framework/widgets/Block.php +++ b/framework/widgets/Block.php @@ -39,7 +39,7 @@ class Block extends Widget { /** - * @var boolean whether to render the block content in place. Defaults to false, + * @var bool whether to render the block content in place. Defaults to false, * meaning the captured block content will not be displayed. */ public $renderInPlace = false; diff --git a/framework/widgets/Breadcrumbs.php b/framework/widgets/Breadcrumbs.php index c5f00e3dec3..2dfe1d427b9 100644 --- a/framework/widgets/Breadcrumbs.php +++ b/framework/widgets/Breadcrumbs.php @@ -64,7 +64,7 @@ class Breadcrumbs extends Widget */ public $options = ['class' => 'breadcrumb']; /** - * @var boolean whether to HTML-encode the link labels. + * @var bool whether to HTML-encode the link labels. */ public $encodeLabels = true; /** diff --git a/framework/widgets/DetailView.php b/framework/widgets/DetailView.php index a7586469bab..d66e9490094 100644 --- a/framework/widgets/DetailView.php +++ b/framework/widgets/DetailView.php @@ -157,7 +157,7 @@ public function run() /** * Renders a single attribute. * @param array $attribute the specification of the attribute to be rendered. - * @param integer $index the zero-based index of the attribute in the [[attributes]] array + * @param int $index the zero-based index of the attribute in the [[attributes]] array * @return string the rendering result */ protected function renderAttribute($attribute, $index) diff --git a/framework/widgets/FragmentCache.php b/framework/widgets/FragmentCache.php index fd305429a1a..5b3d17a13c4 100644 --- a/framework/widgets/FragmentCache.php +++ b/framework/widgets/FragmentCache.php @@ -32,7 +32,7 @@ class FragmentCache extends Widget */ public $cache = 'cache'; /** - * @var integer number of seconds that the data can remain valid in cache. + * @var int number of seconds that the data can remain valid in cache. * Use 0 to indicate that the cached data will never expire. */ public $duration = 60; @@ -66,7 +66,7 @@ class FragmentCache extends Widget */ public $variations; /** - * @var boolean whether to enable the fragment cache. You may use this property to turn on and off + * @var bool whether to enable the fragment cache. You may use this property to turn on and off * the fragment cache according to specific setting (e.g. enable fragment cache only for GET requests). */ public $enabled = true; @@ -124,7 +124,7 @@ public function run() } /** - * @var string|boolean the cached content. False if the content is not cached. + * @var string|bool the cached content. False if the content is not cached. */ private $_content; diff --git a/framework/widgets/InputWidget.php b/framework/widgets/InputWidget.php index 46df25dbddd..35aad35ef57 100644 --- a/framework/widgets/InputWidget.php +++ b/framework/widgets/InputWidget.php @@ -75,7 +75,7 @@ public function init() } /** - * @return boolean whether this widget is associated with a data model. + * @return bool whether this widget is associated with a data model. */ protected function hasModel() { diff --git a/framework/widgets/LinkPager.php b/framework/widgets/LinkPager.php index 965594d8bcf..4c7fb14f88b 100644 --- a/framework/widgets/LinkPager.php +++ b/framework/widgets/LinkPager.php @@ -75,40 +75,40 @@ class LinkPager extends Widget */ public $disabledPageCssClass = 'disabled'; /** - * @var integer maximum number of page buttons that can be displayed. Defaults to 10. + * @var int maximum number of page buttons that can be displayed. Defaults to 10. */ public $maxButtonCount = 10; /** - * @var string|boolean the label for the "next" page button. Note that this will NOT be HTML-encoded. + * @var string|bool the label for the "next" page button. Note that this will NOT be HTML-encoded. * If this property is false, the "next" page button will not be displayed. */ public $nextPageLabel = '»'; /** - * @var string|boolean the text label for the previous page button. Note that this will NOT be HTML-encoded. + * @var string|bool the text label for the previous page button. Note that this will NOT be HTML-encoded. * If this property is false, the "previous" page button will not be displayed. */ public $prevPageLabel = '«'; /** - * @var string|boolean the text label for the "first" page button. Note that this will NOT be HTML-encoded. + * @var string|bool the text label for the "first" page button. Note that this will NOT be HTML-encoded. * If it's specified as true, page number will be used as label. * Default is false that means the "first" page button will not be displayed. */ public $firstPageLabel = false; /** - * @var string|boolean the text label for the "last" page button. Note that this will NOT be HTML-encoded. + * @var string|bool the text label for the "last" page button. Note that this will NOT be HTML-encoded. * If it's specified as true, page number will be used as label. * Default is false that means the "last" page button will not be displayed. */ public $lastPageLabel = false; /** - * @var boolean whether to register link tags in the HTML header for prev, next, first and last page. + * @var bool whether to register link tags in the HTML header for prev, next, first and last page. * Defaults to `false` to avoid conflicts when multiple pagers are used on one page. * @see http://www.w3.org/TR/html401/struct/links.html#h-12.1.2 * @see registerLinkTags() */ public $registerLinkTags = false; /** - * @var boolean Hide widget when only one page exist. + * @var bool Hide widget when only one page exist. */ public $hideOnSinglePage = true; @@ -203,10 +203,10 @@ protected function renderPageButtons() * Renders a page button. * You may override this method to customize the generation of page buttons. * @param string $label the text label for the button - * @param integer $page the page number + * @param int $page the page number * @param string $class the CSS class for the page button. - * @param boolean $disabled whether this page button is disabled - * @param boolean $active whether this page button is active + * @param bool $disabled whether this page button is disabled + * @param bool $active whether this page button is active * @return string the rendering result */ protected function renderPageButton($label, $page, $class, $disabled, $active) diff --git a/framework/widgets/ListView.php b/framework/widgets/ListView.php index ac906bf5dbd..a72041dd01b 100644 --- a/framework/widgets/ListView.php +++ b/framework/widgets/ListView.php @@ -86,7 +86,7 @@ public function renderItems() * Renders a single data model. * @param mixed $model the data model to be rendered * @param mixed $key the key value associated with the data model - * @param integer $index the zero-based index of the data model in the model array returned by [[dataProvider]]. + * @param int $index the zero-based index of the data model in the model array returned by [[dataProvider]]. * @return string the rendering result */ public function renderItem($model, $key, $index) diff --git a/framework/widgets/Menu.php b/framework/widgets/Menu.php index b6142d339d8..32d8dd284ce 100644 --- a/framework/widgets/Menu.php +++ b/framework/widgets/Menu.php @@ -105,7 +105,7 @@ class Menu extends Widget */ public $submenuTemplate = "\n
    \n{items}\n
\n"; /** - * @var boolean whether the labels for menu items should be HTML-encoded. + * @var bool whether the labels for menu items should be HTML-encoded. */ public $encodeLabels = true; /** @@ -113,18 +113,18 @@ class Menu extends Widget */ public $activeCssClass = 'active'; /** - * @var boolean whether to automatically activate items according to whether their route setting + * @var bool whether to automatically activate items according to whether their route setting * matches the currently requested route. * @see isItemActive() */ public $activateItems = true; /** - * @var boolean whether to activate parent menu items when one of the corresponding child menu items is active. + * @var bool whether to activate parent menu items when one of the corresponding child menu items is active. * The activated parent menu items will also have its CSS classes appended with [[activeCssClass]]. */ public $activateParents = false; /** - * @var boolean whether to hide empty menu items. An empty menu item is one whose `url` option is not + * @var bool whether to hide empty menu items. An empty menu item is one whose `url` option is not * set and which has no visible child menu items. */ public $hideEmptyItems = true; @@ -253,7 +253,7 @@ protected function renderItem($item) /** * Normalizes the [[items]] property to remove invisible items and activate certain items. * @param array $items the items to be normalized. - * @param boolean $active whether there is an active child menu item. + * @param bool $active whether there is an active child menu item. * @return array the normalized menu items */ protected function normalizeItems($items, &$active) @@ -301,7 +301,7 @@ protected function normalizeItems($items, &$active) * Only when its route and parameters match [[route]] and [[params]], respectively, will a menu item * be considered active. * @param array $item the menu item to be checked - * @return boolean whether the menu item is active + * @return bool whether the menu item is active */ protected function isItemActive($item) { diff --git a/framework/widgets/Pjax.php b/framework/widgets/Pjax.php index 2072d1e868c..fb4002efa27 100644 --- a/framework/widgets/Pjax.php +++ b/framework/widgets/Pjax.php @@ -74,21 +74,21 @@ class Pjax extends Widget */ public $submitEvent = 'submit'; /** - * @var boolean whether to enable push state. + * @var bool whether to enable push state. */ public $enablePushState = true; /** - * @var boolean whether to enable replace state. + * @var bool whether to enable replace state. */ public $enableReplaceState = false; /** - * @var integer pjax timeout setting (in milliseconds). This timeout is used when making AJAX requests. + * @var int pjax timeout setting (in milliseconds). This timeout is used when making AJAX requests. * Use a bigger number if your server is slow. If the server does not respond within the timeout, * a full page load will be triggered. */ public $timeout = 1000; /** - * @var boolean|integer how to scroll the page when pjax response is received. If false, no page scroll will be made. + * @var bool|int how to scroll the page when pjax response is received. If false, no page scroll will be made. * Use a number if you want to scroll to a particular place. */ public $scrollTo = false; @@ -168,7 +168,7 @@ public function run() } /** - * @return boolean whether the current request requires pjax response from this widget + * @return bool whether the current request requires pjax response from this widget */ protected function requiresPjax() { diff --git a/tests/data/ar/Animal.php b/tests/data/ar/Animal.php index 129588f25c4..dfb8ba2a0fd 100644 --- a/tests/data/ar/Animal.php +++ b/tests/data/ar/Animal.php @@ -12,7 +12,7 @@ * Class Animal * * @author Jose Lorente - * @property integer $id + * @property int $id * @property string $type */ class Animal extends ActiveRecord diff --git a/tests/data/ar/BitValues.php b/tests/data/ar/BitValues.php index c3251edede6..f1c5360bd4a 100644 --- a/tests/data/ar/BitValues.php +++ b/tests/data/ar/BitValues.php @@ -11,8 +11,8 @@ /** * https://github.com/yiisoft/yii2/issues/9006 * - * @property integer $id - * @property integer $val + * @property int $id + * @property int $val */ class BitValues extends ActiveRecord { diff --git a/tests/data/ar/Category.php b/tests/data/ar/Category.php index aa193261bb6..1ba58749be5 100644 --- a/tests/data/ar/Category.php +++ b/tests/data/ar/Category.php @@ -10,7 +10,7 @@ /** * Class Category. * - * @property integer $id + * @property int $id * @property string $name */ class Category extends ActiveRecord diff --git a/tests/data/ar/Customer.php b/tests/data/ar/Customer.php index a86fe7fdd56..a451dc34400 100644 --- a/tests/data/ar/Customer.php +++ b/tests/data/ar/Customer.php @@ -7,11 +7,11 @@ /** * Class Customer * - * @property integer $id + * @property int $id * @property string $name * @property string $email * @property string $address - * @property integer $status + * @property int $status * * @method CustomerQuery findBySql($sql, $params = []) static */ diff --git a/tests/data/ar/DefaultPk.php b/tests/data/ar/DefaultPk.php index ffd714f3340..89201304b7f 100644 --- a/tests/data/ar/DefaultPk.php +++ b/tests/data/ar/DefaultPk.php @@ -11,7 +11,7 @@ * DefaultPk * * @author Jan Waś - * @property integer $id + * @property int $id */ class DefaultPk extends ActiveRecord { diff --git a/tests/data/ar/Document.php b/tests/data/ar/Document.php index e4b7bc857ab..c3bd553fee8 100644 --- a/tests/data/ar/Document.php +++ b/tests/data/ar/Document.php @@ -3,10 +3,10 @@ namespace yiiunit\data\ar; /** - * @property integer $id + * @property int $id * @property string $title * @property string $content - * @property integer $version + * @property int $version */ class Document extends ActiveRecord { diff --git a/tests/data/ar/Item.php b/tests/data/ar/Item.php index 6567567a84f..4b4977a0966 100644 --- a/tests/data/ar/Item.php +++ b/tests/data/ar/Item.php @@ -5,9 +5,9 @@ /** * Class Item * - * @property integer $id + * @property int $id * @property string $name - * @property integer $category_id + * @property int $category_id */ class Item extends ActiveRecord { diff --git a/tests/data/ar/NullValues.php b/tests/data/ar/NullValues.php index ad228999e39..047ccf71237 100644 --- a/tests/data/ar/NullValues.php +++ b/tests/data/ar/NullValues.php @@ -5,10 +5,10 @@ /** * Class NullValues * - * @property integer $id - * @property integer $var1 - * @property integer $var2 - * @property integer $var3 + * @property int $id + * @property int $var1 + * @property int $var2 + * @property int $var3 * @property string $stringcol */ class NullValues extends ActiveRecord diff --git a/tests/data/ar/Order.php b/tests/data/ar/Order.php index 9a3157465db..12cc6e59fa4 100644 --- a/tests/data/ar/Order.php +++ b/tests/data/ar/Order.php @@ -5,9 +5,9 @@ /** * Class Order * - * @property integer $id - * @property integer $customer_id - * @property integer $created_at + * @property int $id + * @property int $customer_id + * @property int $created_at * @property string $total */ class Order extends ActiveRecord diff --git a/tests/data/ar/OrderItem.php b/tests/data/ar/OrderItem.php index b1dbe7876dc..5a1492f2bc6 100644 --- a/tests/data/ar/OrderItem.php +++ b/tests/data/ar/OrderItem.php @@ -5,9 +5,9 @@ /** * Class OrderItem * - * @property integer $order_id - * @property integer $item_id - * @property integer $quantity + * @property int $order_id + * @property int $item_id + * @property int $quantity * @property string $subtotal */ class OrderItem extends ActiveRecord diff --git a/tests/data/ar/OrderItemWithNullFK.php b/tests/data/ar/OrderItemWithNullFK.php index 63e6551c45e..52cbc445fda 100644 --- a/tests/data/ar/OrderItemWithNullFK.php +++ b/tests/data/ar/OrderItemWithNullFK.php @@ -5,9 +5,9 @@ /** * Class OrderItem * - * @property integer $order_id - * @property integer $item_id - * @property integer $quantity + * @property int $order_id + * @property int $item_id + * @property int $quantity * @property string $subtotal */ class OrderItemWithNullFK extends ActiveRecord diff --git a/tests/data/ar/OrderWithNullFK.php b/tests/data/ar/OrderWithNullFK.php index 0e4a80bb632..888f1661d23 100644 --- a/tests/data/ar/OrderWithNullFK.php +++ b/tests/data/ar/OrderWithNullFK.php @@ -5,9 +5,9 @@ /** * Class Order * - * @property integer $id - * @property integer $customer_id - * @property integer $created_at + * @property int $id + * @property int $customer_id + * @property int $created_at * @property string $total */ class OrderWithNullFK extends ActiveRecord diff --git a/tests/data/ar/Profile.php b/tests/data/ar/Profile.php index 56cc0a9276f..3806de1c956 100644 --- a/tests/data/ar/Profile.php +++ b/tests/data/ar/Profile.php @@ -8,7 +8,7 @@ /** * Class Profile * - * @property integer $id + * @property int $id * @property string $description * */ diff --git a/tests/data/ar/Type.php b/tests/data/ar/Type.php index 7922ba5629d..2f8051bff44 100644 --- a/tests/data/ar/Type.php +++ b/tests/data/ar/Type.php @@ -5,9 +5,9 @@ /** * Model representing type table * - * @property integer $int_col - * @property integer $int_col2 DEFAULT 1 - * @property integer $smallint_col DEFAULT 1 + * @property int $int_col + * @property int $int_col2 DEFAULT 1 + * @property int $smallint_col DEFAULT 1 * @property string $char_col * @property string $char_col2 DEFAULT 'something' * @property string $char_col3 @@ -16,8 +16,8 @@ * @property string $blob_col * @property float $numeric_col DEFAULT '33.22' * @property string $time DEFAULT '2002-01-01 00:00:00' - * @property boolean $bool_col - * @property boolean $bool_col2 DEFAULT 1 + * @property bool $bool_col + * @property bool $bool_col2 DEFAULT 1 */ class Type extends ActiveRecord { diff --git a/tests/framework/BaseYiiTest.php b/tests/framework/BaseYiiTest.php index 57e14ec4be3..9f61c1dd760 100644 --- a/tests/framework/BaseYiiTest.php +++ b/tests/framework/BaseYiiTest.php @@ -57,7 +57,7 @@ public function testAlias() public function testGetVersion() { - $this->assertTrue((boolean) preg_match('~\d+\.\d+(?:\.\d+)?(?:-\w+)?~', \Yii::getVersion())); + $this->assertTrue((bool) preg_match('~\d+\.\d+(?:\.\d+)?(?:-\w+)?~', \Yii::getVersion())); } public function testPowered() @@ -145,7 +145,7 @@ public function testLog() BaseYii::error('error message', 'error category'); BaseYii::beginProfile('beginProfile message', 'beginProfile category'); BaseYii::endProfile('endProfile message', 'endProfile category'); - + BaseYii::setLogger(null); } } diff --git a/tests/framework/base/SecurityTest.php b/tests/framework/base/SecurityTest.php index fc1abdc478c..59c0b720ffd 100644 --- a/tests/framework/base/SecurityTest.php +++ b/tests/framework/base/SecurityTest.php @@ -1117,8 +1117,8 @@ public function dataProviderPbkdf2() * @param string $hash * @param string $password * @param string $salt - * @param integer $iterations - * @param integer $length + * @param int $iterations + * @param int $length * @param string $okm */ public function testPbkdf2($hash, $password, $salt, $iterations, $length, $okm) @@ -1205,7 +1205,7 @@ public function dataProviderDeriveKey() * @param string $ikm * @param string $salt * @param string $info - * @param integer $l + * @param int $l * @param string $prk * @param string $okm */ diff --git a/tests/framework/behaviors/AttributeTypecastBehaviorTest.php b/tests/framework/behaviors/AttributeTypecastBehaviorTest.php index 49c1b027aa7..8b9764daa8f 100644 --- a/tests/framework/behaviors/AttributeTypecastBehaviorTest.php +++ b/tests/framework/behaviors/AttributeTypecastBehaviorTest.php @@ -181,11 +181,11 @@ public function testSkipNotSelectedAttribute() /** * Test Active Record class with [[AttributeTypecastBehavior]] behavior attached. * - * @property integer $id + * @property int $id * @property string $name - * @property integer $amount + * @property int $amount * @property float $price - * @property boolean $isActive + * @property bool $isActive * @property string $callback * * @property AttributeTypecastBehavior $attributeTypecastBehavior @@ -235,4 +235,4 @@ public function getAttributeTypecastBehavior() { return $this->getBehavior('attributeTypecast'); } -} \ No newline at end of file +} diff --git a/tests/framework/behaviors/SluggableBehaviorTest.php b/tests/framework/behaviors/SluggableBehaviorTest.php index 3bd6b7269f5..c3c19eb4759 100644 --- a/tests/framework/behaviors/SluggableBehaviorTest.php +++ b/tests/framework/behaviors/SluggableBehaviorTest.php @@ -145,10 +145,10 @@ public function testUpdateUnique() /** * Test Active Record class with [[SluggableBehavior]] behavior attached. * - * @property integer $id + * @property int $id * @property string $name * @property string $slug - * @property integer $category_id + * @property int $category_id * * @property SluggableBehavior $sluggable */ diff --git a/tests/framework/behaviors/TimestampBehaviorTest.php b/tests/framework/behaviors/TimestampBehaviorTest.php index 02075d3e686..b37f4a50c48 100644 --- a/tests/framework/behaviors/TimestampBehaviorTest.php +++ b/tests/framework/behaviors/TimestampBehaviorTest.php @@ -193,9 +193,9 @@ public function testUpdateRecordExpression() /** * Test Active Record class with [[TimestampBehavior]] behavior attached. * - * @property integer $id - * @property integer $created_at - * @property integer $updated_at + * @property int $id + * @property int $created_at + * @property int $updated_at */ class ActiveRecordTimestamp extends ActiveRecord { diff --git a/tests/framework/caching/CacheTestCase.php b/tests/framework/caching/CacheTestCase.php index 4d976c4891b..475244a714c 100644 --- a/tests/framework/caching/CacheTestCase.php +++ b/tests/framework/caching/CacheTestCase.php @@ -13,7 +13,7 @@ function time() /** * Mock for the microtime() function for caching classes - * @param boolean $float + * @param bool $float * @return float */ function microtime($float = false) @@ -32,7 +32,7 @@ function microtime($float = false) abstract class CacheTestCase extends TestCase { /** - * @var integer virtual time to be returned by mocked time() function. + * @var int virtual time to be returned by mocked time() function. * Null means normal time() behavior. */ public static $time; diff --git a/tests/framework/caching/DbCacheTest.php b/tests/framework/caching/DbCacheTest.php index 0036ffe84cb..28c3174150f 100644 --- a/tests/framework/caching/DbCacheTest.php +++ b/tests/framework/caching/DbCacheTest.php @@ -34,7 +34,7 @@ protected function setUp() } /** - * @param boolean $reset whether to clean up the test database + * @param bool $reset whether to clean up the test database * @return \yii\db\Connection */ public function getConnection($reset = true) diff --git a/tests/framework/data/PaginationTest.php b/tests/framework/data/PaginationTest.php index 47412ff5d9a..a410b389e2e 100644 --- a/tests/framework/data/PaginationTest.php +++ b/tests/framework/data/PaginationTest.php @@ -59,8 +59,8 @@ public function dataProviderCreateUrl() /** * @dataProvider dataProviderCreateUrl * - * @param integer $page - * @param integer $pageSize + * @param int $page + * @param int $pageSize * @param string $expectedUrl */ public function testCreateUrl($page, $pageSize, $expectedUrl, $params) diff --git a/tests/framework/db/ColumnSchemaBuilderTest.php b/tests/framework/db/ColumnSchemaBuilderTest.php index 7341175041b..36b37a237e9 100644 --- a/tests/framework/db/ColumnSchemaBuilderTest.php +++ b/tests/framework/db/ColumnSchemaBuilderTest.php @@ -11,7 +11,7 @@ abstract class ColumnSchemaBuilderTest extends DatabaseTestCase { /** * @param string $type - * @param integer $length + * @param int $length * @return ColumnSchemaBuilder */ public function getColumnSchemaBuilder($type, $length = null) @@ -54,7 +54,7 @@ public function testCustomTypes($expected, $type, $length, $calls) /** * @param string $expected * @param string $type - * @param integer $length + * @param int $length * @param array $calls */ public function checkBuildString($expected, $type, $length, $calls) diff --git a/tests/framework/db/DatabaseTestCase.php b/tests/framework/db/DatabaseTestCase.php index 774371e0876..7d6de14d873 100644 --- a/tests/framework/db/DatabaseTestCase.php +++ b/tests/framework/db/DatabaseTestCase.php @@ -47,8 +47,8 @@ protected function tearDown() } /** - * @param boolean $reset whether to clean up the test database - * @param boolean $open whether to open and populate test database + * @param bool $reset whether to clean up the test database + * @param bool $open whether to open and populate test database * @return \yii\db\Connection */ public function getConnection($reset = true, $open = true) diff --git a/tests/framework/db/cubrid/ColumnSchemaBuilderTest.php b/tests/framework/db/cubrid/ColumnSchemaBuilderTest.php index d9ba209da44..75aeaa8527f 100644 --- a/tests/framework/db/cubrid/ColumnSchemaBuilderTest.php +++ b/tests/framework/db/cubrid/ColumnSchemaBuilderTest.php @@ -16,7 +16,7 @@ class ColumnSchemaBuilderTest extends \yiiunit\framework\db\ColumnSchemaBuilderT /** * @param string $type - * @param integer $length + * @param int $length * @return ColumnSchemaBuilder */ public function getColumnSchemaBuilder($type, $length = null) diff --git a/tests/framework/db/mssql/ColumnSchemaBuilderTest.php b/tests/framework/db/mssql/ColumnSchemaBuilderTest.php index b20fbaf6c24..976971c7f4d 100644 --- a/tests/framework/db/mssql/ColumnSchemaBuilderTest.php +++ b/tests/framework/db/mssql/ColumnSchemaBuilderTest.php @@ -16,7 +16,7 @@ class ColumnSchemaBuilderTest extends \yiiunit\framework\db\ColumnSchemaBuilderT /** * @param string $type - * @param integer $length + * @param int $length * @return ColumnSchemaBuilder */ public function getColumnSchemaBuilder($type, $length = null) diff --git a/tests/framework/db/mysql/ColumnSchemaBuilderTest.php b/tests/framework/db/mysql/ColumnSchemaBuilderTest.php index 28142d8809c..26e448084e4 100644 --- a/tests/framework/db/mysql/ColumnSchemaBuilderTest.php +++ b/tests/framework/db/mysql/ColumnSchemaBuilderTest.php @@ -16,7 +16,7 @@ class ColumnSchemaBuilderTest extends \yiiunit\framework\db\ColumnSchemaBuilderT /** * @param string $type - * @param integer $length + * @param int $length * @return ColumnSchemaBuilder */ public function getColumnSchemaBuilder($type, $length = null) diff --git a/tests/framework/db/oci/ColumnSchemaBuilderTest.php b/tests/framework/db/oci/ColumnSchemaBuilderTest.php index 7fef47180ec..e6d28d11c14 100644 --- a/tests/framework/db/oci/ColumnSchemaBuilderTest.php +++ b/tests/framework/db/oci/ColumnSchemaBuilderTest.php @@ -16,7 +16,7 @@ class ColumnSchemaBuilderTest extends \yiiunit\framework\db\ColumnSchemaBuilderT /** * @param string $type - * @param integer $length + * @param int $length * @return ColumnSchemaBuilder */ public function getColumnSchemaBuilder($type, $length = null) diff --git a/tests/framework/db/pgsql/ColumnSchemaBuilderTest.php b/tests/framework/db/pgsql/ColumnSchemaBuilderTest.php index ea946bc1fb7..1021554d29e 100644 --- a/tests/framework/db/pgsql/ColumnSchemaBuilderTest.php +++ b/tests/framework/db/pgsql/ColumnSchemaBuilderTest.php @@ -15,7 +15,7 @@ class ColumnSchemaBuilderTest extends \yiiunit\framework\db\ColumnSchemaBuilderT /** * @param string $type - * @param integer $length + * @param int $length * @return ColumnSchemaBuilder */ public function getColumnSchemaBuilder($type, $length = null) diff --git a/tests/framework/db/sqlite/ColumnSchemaBuilderTest.php b/tests/framework/db/sqlite/ColumnSchemaBuilderTest.php index 598c5e5b8d7..5830d3ab3c3 100644 --- a/tests/framework/db/sqlite/ColumnSchemaBuilderTest.php +++ b/tests/framework/db/sqlite/ColumnSchemaBuilderTest.php @@ -16,7 +16,7 @@ class ColumnSchemaBuilderTest extends \yiiunit\framework\db\ColumnSchemaBuilderT /** * @param string $type - * @param integer $length + * @param int $length * @return ColumnSchemaBuilder */ public function getColumnSchemaBuilder($type, $length = null) diff --git a/tests/framework/db/sqlite/ConnectionTest.php b/tests/framework/db/sqlite/ConnectionTest.php index 21d4b95ff7a..27f75fd1262 100644 --- a/tests/framework/db/sqlite/ConnectionTest.php +++ b/tests/framework/db/sqlite/ConnectionTest.php @@ -91,8 +91,8 @@ public function testMasterSlave() } /** - * @param integer $masterCount - * @param integer $slaveCount + * @param int $masterCount + * @param int $slaveCount * @return Connection */ protected function prepareMasterSlave($masterCount, $slaveCount) diff --git a/tests/framework/helpers/FileHelperTest.php b/tests/framework/helpers/FileHelperTest.php index 9c9c516ec33..333994b5d18 100644 --- a/tests/framework/helpers/FileHelperTest.php +++ b/tests/framework/helpers/FileHelperTest.php @@ -112,7 +112,7 @@ protected function createFileStructure(array $items, $basePath = '') /** * Asserts that file has specific permission mode. - * @param integer $expectedMode expected file permission mode. + * @param int $expectedMode expected file permission mode. * @param string $fileName file name. * @param string $message error message */ diff --git a/tests/framework/log/SqliteTargetTest.php b/tests/framework/log/SqliteTargetTest.php index 6f13db03b06..0c2aa726c28 100644 --- a/tests/framework/log/SqliteTargetTest.php +++ b/tests/framework/log/SqliteTargetTest.php @@ -4,7 +4,7 @@ namespace yiiunit\framework\log; -class SQliteTargetTest extends DbTargetTest +class SqliteTargetTest extends DbTargetTest { protected static $driverName = 'sqlite'; } \ No newline at end of file diff --git a/tests/framework/requirements/YiiRequirementCheckerTest.php b/tests/framework/requirements/YiiRequirementCheckerTest.php index f603dfb8c97..b99b44d0d02 100644 --- a/tests/framework/requirements/YiiRequirementCheckerTest.php +++ b/tests/framework/requirements/YiiRequirementCheckerTest.php @@ -160,7 +160,7 @@ public function dataProviderGetByteSize() * @dataProvider dataProviderGetByteSize * * @param string $verboseValue verbose value. - * @param integer $expectedByteSize expected byte size. + * @param int $expectedByteSize expected byte size. */ public function testGetByteSize($verboseValue, $expectedByteSize) { @@ -191,7 +191,7 @@ public function dataProviderCompareByteSize() * @param string $a first value. * @param string $b second value. * @param string $compare comparison. - * @param boolean $expectedComparisonResult expected comparison result. + * @param bool $expectedComparisonResult expected comparison result. */ public function testCompareByteSize($a, $b, $compare, $expectedComparisonResult) { diff --git a/tests/framework/rest/SerializerTest.php b/tests/framework/rest/SerializerTest.php index dd5205d15f9..7508a315f9c 100644 --- a/tests/framework/rest/SerializerTest.php +++ b/tests/framework/rest/SerializerTest.php @@ -260,7 +260,7 @@ public function dataProviderSerializeDataProvider() * * @param \yii\data\DataProviderInterface $dataProvider * @param array $expectedResult - * @param boolean $saveKeys + * @param bool $saveKeys */ public function testSerializeDataProvider($dataProvider, $expectedResult, $saveKeys = false) { diff --git a/tests/framework/validators/DateValidatorTest.php b/tests/framework/validators/DateValidatorTest.php index b85fd4895d5..3516e646dac 100644 --- a/tests/framework/validators/DateValidatorTest.php +++ b/tests/framework/validators/DateValidatorTest.php @@ -555,7 +555,7 @@ public function testIntlValidateAttributeRangeOld() * returns true if the version of ICU is old and has a bug that makes it * impossible to parse two digit years properly. * see http://bugs.icu-project.org/trac/ticket/9836 - * @return boolean + * @return bool */ private function checkOldIcuBug() { diff --git a/tests/framework/web/UserTest.php b/tests/framework/web/UserTest.php index d6c1b34220e..fdbfaa2dcd9 100644 --- a/tests/framework/web/UserTest.php +++ b/tests/framework/web/UserTest.php @@ -34,7 +34,7 @@ function time() class UserTest extends TestCase { /** - * @var integer virtual time to be returned by mocked time() function. + * @var int virtual time to be returned by mocked time() function. * Null means normal time() behavior. */ public static $time;