Browse Source

📖 Updated guide pages - wrap true, false, null

tags/2.0.10
SilverFire - Dmitry Naumenko 8 years ago
parent
commit
685f16e8ef
  1. 8
      docs/guide-es/caching-data.md
  2. 2
      docs/guide-es/concept-configurations.md
  3. 2
      docs/guide-es/concept-events.md
  4. 4
      docs/guide-es/db-dao.md
  5. 10
      docs/guide-es/db-migrations.md
  6. 2
      docs/guide-es/helper-array.md
  7. 20
      docs/guide-es/input-validation.md
  8. 2
      docs/guide-es/rest-authentication.md
  9. 2
      docs/guide-es/rest-controllers.md
  10. 2
      docs/guide-es/rest-rate-limiting.md
  11. 2
      docs/guide-es/rest-routing.md
  12. 2
      docs/guide-es/runtime-handling-errors.md
  13. 6
      docs/guide-es/runtime-routing.md
  14. 6
      docs/guide-es/runtime-sessions-cookies.md
  15. 4
      docs/guide-es/security-authorization.md
  16. 2
      docs/guide-es/structure-models.md
  17. 60
      docs/guide-es/tutorial-core-validators.md
  18. 4
      docs/guide-fr/db-query-builder.md
  19. 2
      docs/guide-fr/start-forms.md
  20. 2
      docs/guide-id/intro-upgrade-from-v1.md
  21. 2
      docs/guide-it/intro-upgrade-from-v1.md
  22. 2
      docs/guide-pl/caching-fragment.md
  23. 2
      docs/guide-pl/rest-routing.md
  24. 4
      docs/guide-pl/structure-entry-scripts.md
  25. 2
      docs/guide-pt-BR/caching-data.md
  26. 2
      docs/guide-pt-BR/concept-configurations.md
  27. 6
      docs/guide-pt-BR/db-active-record.md
  28. 4
      docs/guide-pt-BR/db-migrations.md
  29. 2
      docs/guide-pt-BR/db-query-builder.md
  30. 2
      docs/guide-pt-BR/helper-url.md
  31. 2
      docs/guide-pt-BR/rest-controllers.md
  32. 8
      docs/guide-pt-BR/security-authentication.md
  33. 4
      docs/guide-pt-BR/security-authorization.md
  34. 2
      docs/guide-pt-BR/structure-assets.md
  35. 2
      docs/guide-pt-BR/structure-controllers.md
  36. 4
      docs/guide-pt-BR/structure-models.md
  37. 2
      docs/guide-pt-BR/structure-modules.md
  38. 2
      docs/guide-pt-BR/structure-views.md
  39. 44
      docs/guide-pt-BR/tutorial-core-validators.md
  40. 2
      docs/guide-ru/caching-data.md
  41. 2
      docs/guide-ru/caching-fragment.md
  42. 8
      docs/guide-ru/concept-configurations.md
  43. 4
      docs/guide-ru/concept-events.md
  44. 18
      docs/guide-ru/db-active-record.md
  45. 10
      docs/guide-ru/db-migrations.md
  46. 2
      docs/guide-ru/db-query-builder.md
  47. 2
      docs/guide-ru/helper-array.md
  48. 4
      docs/guide-ru/helper-html.md
  49. 12
      docs/guide-ru/input-validation.md
  50. 4
      docs/guide-ru/rest-authentication.md
  51. 2
      docs/guide-ru/rest-controllers.md
  52. 2
      docs/guide-ru/rest-rate-limiting.md
  53. 2
      docs/guide-ru/rest-routing.md
  54. 8
      docs/guide-ru/runtime-handling-errors.md
  55. 4
      docs/guide-ru/runtime-sessions-cookies.md
  56. 2
      docs/guide-ru/structure-assets.md
  57. 2
      docs/guide-ru/structure-controllers.md
  58. 4
      docs/guide-ru/structure-entry-scripts.md
  59. 2
      docs/guide-ru/structure-modules.md
  60. 50
      docs/guide-ru/tutorial-core-validators.md
  61. 2
      docs/guide-ru/tutorial-performance-tuning.md
  62. 2
      docs/guide-uk/caching-fragment.md
  63. 2
      docs/guide-uk/rest-rate-limiting.md
  64. 2
      docs/guide-uk/structure-controllers.md
  65. 2
      docs/guide-uk/structure-models.md
  66. 2
      docs/guide-uz/structure-controllers.md
  67. 2
      docs/guide-vi/start-gii.md
  68. 2
      docs/guide/caching-data.md
  69. 2
      docs/guide/caching-fragment.md
  70. 2
      docs/guide/db-active-record.md
  71. 2
      docs/guide/db-dao.md
  72. 10
      docs/guide/db-migrations.md
  73. 2
      docs/guide/db-query-builder.md
  74. 2
      docs/guide/helper-array.md
  75. 2
      docs/guide/helper-html.md
  76. 2
      docs/guide/helper-url.md
  77. 12
      docs/guide/input-validation.md
  78. 2
      docs/guide/output-data-providers.md
  79. 4
      docs/guide/output-data-widgets.md
  80. 2
      docs/guide/rest-authentication.md
  81. 2
      docs/guide/rest-controllers.md
  82. 2
      docs/guide/rest-rate-limiting.md
  83. 2
      docs/guide/rest-routing.md
  84. 8
      docs/guide/runtime-handling-errors.md
  85. 4
      docs/guide/runtime-routing.md
  86. 6
      docs/guide/runtime-sessions-cookies.md
  87. 4
      docs/guide/security-authentication.md
  88. 6
      docs/guide/security-authorization.md
  89. 4
      docs/guide/security-best-practices.md
  90. 2
      docs/guide/start-forms.md
  91. 2
      docs/guide/start-gii.md
  92. 2
      docs/guide/structure-assets.md
  93. 2
      docs/guide/structure-controllers.md
  94. 2
      docs/guide/structure-modules.md
  95. 2
      docs/guide/structure-views.md
  96. 2
      docs/guide/structure-widgets.md
  97. 2
      docs/guide/tutorial-console.md
  98. 84
      docs/guide/tutorial-core-validators.md
  99. 4
      docs/guide/tutorial-i18n.md
  100. 8
      docs/guide/tutorial-performance-tuning.md
  101. Some files were not shown because too many files have changed in this diff Show More

8
docs/guide-es/caching-data.md

@ -9,7 +9,7 @@ El siguiente código muestra el típico patrón de uso para el almacenamiento en
// intenta recuperar $data de la caché // intenta recuperar $data de la caché
$data = $cache->get($key); $data = $cache->get($key);
if ($data === false) { if ($data === `false`) {
// $data no ha sido encontrada en la caché, calcularla desde cero // $data no ha sido encontrada en la caché, calcularla desde cero
@ -160,7 +160,7 @@ $cache->set($key, $data, 45);
sleep(50); sleep(50);
$data = $cache->get($key); $data = $cache->get($key);
if ($data === false) { if ($data === `false`) {
// $data ha caducado o no ha sido encontrado en la memoria caché // $data ha caducado o no ha sido encontrado en la memoria caché
} }
``` ```
@ -182,7 +182,7 @@ $cache->set($key, $data, 30, $dependency);
// La caché comprobará si los datos han expirado. // La caché comprobará si los datos han expirado.
// También comprobará si la dependencia ha cambiado. // También comprobará si la dependencia ha cambiado.
// Devolverá false si se encuentran algunas de esas condiciones. // Devolverá `false` si se encuentran algunas de esas condiciones.
$data = $cache->get($key); $data = $cache->get($key);
``` ```
@ -229,7 +229,7 @@ $result = Customer::getDb()->cache(function ($db) {
Las consultas en caché tienen tres opciones configurables globales a través de [[yii\db\Connection]]: Las consultas en caché tienen tres opciones configurables globales a través de [[yii\db\Connection]]:
* [[yii\db\Connection::enableQueryCache|enableQueryCache]]: activa o desactiva el cacheo de consultas. * [[yii\db\Connection::enableQueryCache|enableQueryCache]]: activa o desactiva el cacheo de consultas.
Por defecto es true. Tenga en cuenta que para activar el cacheo de consultas, también necesitas tener una caché válida, especificada por [[yii\db\Connection::queryCache|queryCache]]. Por defecto es `true`. Tenga en cuenta que para activar el cacheo de consultas, también necesitas tener una caché válida, especificada por [[yii\db\Connection::queryCache|queryCache]].
* [[yii\db\Connection::queryCacheDuration|queryCacheDuration]]: representa el número de segundos que un resultado de la consulta permanecerá válida en la memoria caché. Puedes usar 0 para indicar que el resultado de la consulta debe permanecer en la caché para siempre. Esta propiedad es el valor usado por defecto cuando [[yii\db\Connection::cache()]] es llamada sin especificar una duración. * [[yii\db\Connection::queryCacheDuration|queryCacheDuration]]: representa el número de segundos que un resultado de la consulta permanecerá válida en la memoria caché. Puedes usar 0 para indicar que el resultado de la consulta debe permanecer en la caché para siempre. Esta propiedad es el valor usado por defecto cuando [[yii\db\Connection::cache()]] es llamada sin especificar una duración.
* [[yii\db\Connection::queryCache|queryCache]]: representa el ID del componente de aplicación de caché. * [[yii\db\Connection::queryCache|queryCache]]: representa el ID del componente de aplicación de caché.
Por defecto es `'cache'`. El almacenamiento en caché de consultas se habilita sólo si hay un componente de la aplicación de caché válida. Por defecto es `'cache'`. El almacenamiento en caché de consultas se habilita sólo si hay un componente de la aplicación de caché válida.

2
docs/guide-es/concept-configurations.md

@ -121,7 +121,7 @@ Cuando se utiliza [widgets](structure-widgets.md), a menudo es necesario utiliza
use yii\widgets\Menu; use yii\widgets\Menu;
echo Menu::widget([ echo Menu::widget([
'activateItems' => false, 'activateItems' => `false`,
'items' => [ 'items' => [
['label' => 'Home', 'url' => ['site/index']], ['label' => 'Home', 'url' => ['site/index']],
['label' => 'Products', 'url' => ['product/index']], ['label' => 'Products', 'url' => ['product/index']],

2
docs/guide-es/concept-events.md

@ -96,7 +96,7 @@ $foo->on(Foo::EVENT_HELLO, function ($event) {
De forma predeterminada, cada nuevo gestor añadido se pone a la cola de la lista de gestores del evento. Por lo tanto, De forma predeterminada, cada nuevo gestor añadido se pone a la cola de la lista de gestores del evento. Por lo tanto,
el gestor se ejecutará en el último lugar cuando se lance el evento. Para insertar un nuevo gestor al principio de la el gestor se ejecutará en el último lugar cuando se lance el evento. Para insertar un nuevo gestor al principio de la
cola de gestores para que sea ejecutado primero, se debe llamar a [[yii\base\Component::on()]], pasando al cuarto cola de gestores para que sea ejecutado primero, se debe llamar a [[yii\base\Component::on()]], pasando al cuarto
parámetro `$append` el valor false: parámetro `$append` el valor `false`:
```php ```php
$foo->on(Foo::EVENT_HELLO, function ($event) { $foo->on(Foo::EVENT_HELLO, function ($event) {

4
docs/guide-es/db-dao.md

@ -111,7 +111,7 @@ $posts = $db->createCommand('SELECT * FROM post')
->queryAll(); ->queryAll();
// retorna una sola fila (la primera fila) // retorna una sola fila (la primera fila)
// false es retornado si no hay resultados // `false` es retornado si no hay resultados
$post = $db->createCommand('SELECT * FROM post WHERE id=1') $post = $db->createCommand('SELECT * FROM post WHERE id=1')
->queryOne(); ->queryOne();
@ -121,7 +121,7 @@ $titles = $db->createCommand('SELECT title FROM post')
->queryColumn(); ->queryColumn();
// retorna un escalar // retorna un escalar
// false es retornado si no hay resultados // `false` es retornado si no hay resultados
$count = $db->createCommand('SELECT COUNT(*) FROM post') $count = $db->createCommand('SELECT COUNT(*) FROM post')
->queryScalar(); ->queryScalar();
``` ```

10
docs/guide-es/db-migrations.md

@ -147,7 +147,7 @@ serán traducidos a los tipos físicos correspondientes. En el caso de MySQL, `T
en `int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY`, mientras `TYPE_STRING` se vuelve `varchar(255)`. en `int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY`, mientras `TYPE_STRING` se vuelve `varchar(255)`.
Puedes agregar restricciones adicionales al utilizar tipos abstractos. En el ejemplo anterior, ` NOT NULL` es agregado Puedes agregar restricciones adicionales al utilizar tipos abstractos. En el ejemplo anterior, ` NOT NULL` es agregado
a `Schema::TYPE_STRING` para especificar que la columna no puede ser null. a `Schema::TYPE_STRING` para especificar que la columna no puede ser `null`.
> Info: El mapeo entre tipos abstractos y tipos físicos es especificado en > Info: El mapeo entre tipos abstractos y tipos físicos es especificado en
la propiedad [[yii\db\QueryBuilder::$typeMap|$typeMap]] en cada clase concreta `QueryBuilder`. la propiedad [[yii\db\QueryBuilder::$typeMap|$typeMap]] en cada clase concreta `QueryBuilder`.
@ -818,9 +818,9 @@ Hay varias maneras de personalizar el comando de migración.
El comando de migración trae algunas opciones de línea de comandos que pueden ser utilizadas para personalizar su comportamiento: El comando de migración trae algunas opciones de línea de comandos que pueden ser utilizadas para personalizar su comportamiento:
* `interactive`: boolean (por defecto true), especificar si se debe ejecutar la migración en modo interactivo. * `interactive`: boolean (por defecto `true`), especificar si se debe ejecutar la migración en modo interactivo.
Cuando se indica true, se le pedirá confirmación al usuario antes de ejecutar ciertas acciones. Cuando se indica `true`, se le pedirá confirmación al usuario antes de ejecutar ciertas acciones.
Puedes querer definirlo como false si el comando está siendo utilizado como un proceso de fondo. Puedes querer definirlo como `false` si el comando está siendo utilizado como un proceso de fondo.
* `migrationPath`: string (por defecto `@app/migrations`), especifica el directorio que contiene todos los archivos * `migrationPath`: string (por defecto `@app/migrations`), especifica el directorio que contiene todos los archivos
de clase de las migraciones. Este puede ser especificado tanto como una ruta a un directorio un [alias](concept-aliases.md) de ruta. de clase de las migraciones. Este puede ser especificado tanto como una ruta a un directorio un [alias](concept-aliases.md) de ruta.
@ -849,7 +849,7 @@ El comando de migración trae algunas opciones de línea de comandos que pueden
* `fields`: array de strings de definiciones de columna utilizado por el código de migración. Por defecto `[]`. El formato de cada * `fields`: array de strings de definiciones de columna utilizado por el código de migración. Por defecto `[]`. El formato de cada
definición es `COLUMN_NAME:COLUMN_TYPE:COLUMN_DECORATOR`. Por ejemplo, `--fields=name:string(12):notNull` produce definición es `COLUMN_NAME:COLUMN_TYPE:COLUMN_DECORATOR`. Por ejemplo, `--fields=name:string(12):notNull` produce
una columna string de tamaño 12 que es not null. una columna string de tamaño 12 que es not `null`.
El siguiente ejemplo muestra cómo se pueden utilizar estas opciones. El siguiente ejemplo muestra cómo se pueden utilizar estas opciones.

2
docs/guide-es/helper-array.md

@ -116,7 +116,7 @@ del objeto, o una función anónima que debe devolver el valor que será utiliza
El atributo `$groups` es un array de claves, que será utilizado para agrupar el array de entrada en uno o más sub-arrays El atributo `$groups` es un array de claves, que será utilizado para agrupar el array de entrada en uno o más sub-arrays
basado en la clave especificada. basado en la clave especificada.
Si el atributo `$key` o su valor por el elemento en particular es null y `$groups` no está definido, dicho elemento del array Si el atributo `$key` o su valor por el elemento en particular es `null` y `$groups` no está definido, dicho elemento del array
será descartado. De otro modo, si `$groups` es especificado, el elemento del array será agregado al array resultante será descartado. De otro modo, si `$groups` es especificado, el elemento del array será agregado al array resultante
sin una clave. sin una clave.

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

@ -199,7 +199,7 @@ cuyo valor de retorno determina si debe aplicarse la regla o no. Por ejemplo,
La entrada del usuario a menudo debe ser filtrada o pre procesada. Por ejemplo, podrías querer eliminar los espacions alrededor La entrada del usuario a menudo debe ser filtrada o pre procesada. Por ejemplo, podrías querer eliminar los espacions alrededor
de la entrada `username`. Puedes utilizar reglas de validación para lograrlo. de la entrada `username`. Puedes utilizar reglas de validación para lograrlo.
Los siguientes ejemplos muestran cómo eliminar esos espacios en la entrada y cómo transformar entradas vacías en null utilizando Los siguientes ejemplos muestran cómo eliminar esos espacios en la entrada y cómo transformar entradas vacías en `null` utilizando
los validadores del framework [trim](tutorial-core-validators.md#trim) y [default](tutorial-core-validators.md#default): los validadores del framework [trim](tutorial-core-validators.md#trim) y [default](tutorial-core-validators.md#default):
```php ```php
@ -223,7 +223,7 @@ si estas están vacías. Puedes hacerlo utilizando el validador [default](tutori
```php ```php
return [ return [
// convierte "username" y "email" en null si estos están vacíos // convierte "username" y "email" en `null` si estos están vacíos
[['username', 'email'], 'default'], [['username', 'email'], 'default'],
// convierte "level" a 1 si está vacío // convierte "level" a 1 si está vacío
@ -231,7 +231,7 @@ return [
]; ];
``` ```
Por defecto, una entrada se considera vacía si su valor es un string vacío, un array vacío o null. Por defecto, una entrada se considera vacía si su valor es un string vacío, un array vacío o `null`.
Puedes personalizar la lógica de detección de valores vacíos configurando la propiedad [[yii\validators\Validator::isEmpty]] Puedes personalizar la lógica de detección de valores vacíos configurando la propiedad [[yii\validators\Validator::isEmpty]]
con una función PHP invocable. Por ejemplo, con una función PHP invocable. Por ejemplo,
@ -242,7 +242,7 @@ con una función PHP invocable. Por ejemplo,
``` ```
> Note: La mayoría de los validadores no manejan entradas vacías si su propiedad [[yii\validators\Validator::skipOnEmpty]] toma > Note: La mayoría de los validadores no manejan entradas vacías si su propiedad [[yii\validators\Validator::skipOnEmpty]] toma
el valor por defecto true. Estas serán simplemente salteadas durante la validación si sus atributos asociados reciben una entrada vacía. el valor por defecto `true`. Estas serán simplemente salteadas durante la validación si sus atributos asociados reciben una entrada vacía.
Entre los [validadores del framework](tutorial-core-validators.md), sólo `captcha`, `default`, `filter`, Entre los [validadores del framework](tutorial-core-validators.md), sólo `captcha`, `default`, `filter`,
`required`, y `trim` manejarán entradas vacías. `required`, y `trim` manejarán entradas vacías.
@ -375,7 +375,7 @@ class MyForm extends Model
> Note: Por defecto, los validadores en línea no serán aplicados si sus atributos asociados reciben entradas vacías > Note: Por defecto, los validadores en línea no serán aplicados si sus atributos asociados reciben entradas vacías
o si alguna de sus reglas de validación ya falló. Si quieres asegurarte de que una regla siempre sea aplicada, o si alguna de sus reglas de validación ya falló. Si quieres asegurarte de que una regla siempre sea aplicada,
puedes configurar las reglas [[yii\validators\Validator::skipOnEmpty|skipOnEmpty]] y/o [[yii\validators\Validator::skipOnError|skipOnError]] puedes configurar las reglas [[yii\validators\Validator::skipOnEmpty|skipOnEmpty]] y/o [[yii\validators\Validator::skipOnError|skipOnError]]
como false en las declaraciones de las reglas. Por ejemplo: como `false` en las declaraciones de las reglas. Por ejemplo:
> >
> ```php > ```php
> [ > [
@ -512,9 +512,9 @@ y generará el código JavaScript apropiado para los validadores que soportan va
cambia el valor de un campo o envia el formulario, se lanzará la validación JavaScript del lado del cliente. cambia el valor de un campo o envia el formulario, se lanzará la validación JavaScript del lado del cliente.
Si quieres deshabilitar la validación del lado del cliente completamente, puedes configurar Si quieres deshabilitar la validación del lado del cliente completamente, puedes configurar
la propiedad [[yii\widgets\ActiveForm::enableClientValidation]] como false. También puedes deshabilitar la validación la propiedad [[yii\widgets\ActiveForm::enableClientValidation]] como `false`. También puedes deshabilitar la validación
del lado del cliente de campos individuales configurando su propiedad [[yii\widgets\ActiveField::enableClientValidation]] del lado del cliente de campos individuales configurando su propiedad [[yii\widgets\ActiveField::enableClientValidation]]
como false. Cuando `enableClientValidation` es configurado tanto a nivel de campo como a nivel de formulario, como `false`. Cuando `enableClientValidation` es configurado tanto a nivel de campo como a nivel de formulario,
tendrá prioridad la primera. tendrá prioridad la primera.
### Implementar Validación del Lado del Cliente <span id="implementing-client-side-validation"></span> ### Implementar Validación del Lado del Cliente <span id="implementing-client-side-validation"></span>
@ -666,7 +666,7 @@ Puedes utilizar validación basada en AJAX en este caso. Esta lanzará una petic
la entrada mientras se mantiene la misma experiencia de usuario como en una validación del lado del cliente regular. la entrada mientras se mantiene la misma experiencia de usuario como en una validación del lado del cliente regular.
Para habilitar la validación AJAX individualmente un campo de entrada, configura la propiedad [[yii\widgets\ActiveField::enableAjaxValidation|enableAjaxValidation]] Para habilitar la validación AJAX individualmente un campo de entrada, configura la propiedad [[yii\widgets\ActiveField::enableAjaxValidation|enableAjaxValidation]]
de ese campo como true y especifica un único `id` de formulario: de ese campo como `true` y especifica un único `id` de formulario:
```php ```php
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
@ -683,7 +683,7 @@ ActiveForm::end();
``` ```
Para habiliar la validación AJAX en el formulario entero, configura [[yii\widgets\ActiveForm::enableAjaxValidation|enableAjaxValidation]] Para habiliar la validación AJAX en el formulario entero, configura [[yii\widgets\ActiveForm::enableAjaxValidation|enableAjaxValidation]]
como true a nivel del formulario: como `true` a nivel del formulario:
```php ```php
$form = ActiveForm::begin([ $form = ActiveForm::begin([
@ -711,5 +711,5 @@ esta petición ejecutando la validación y devolviendo los errores en formato JS
> Info: Puedes también utilizar [Validación Diferida](#deferred-validation) para realizar validación AJAX. > Info: Puedes también utilizar [Validación Diferida](#deferred-validation) para realizar validación AJAX.
De todos modos, la característica de validación AJAX descrita aquí es más sistemática y requiere menos esfuerzo de escritura de código. De todos modos, la característica de validación AJAX descrita aquí es más sistemática y requiere menos esfuerzo de escritura de código.
Cuando tanto `enableClientValidation` como `enableAjaxValidation` son definidas como true, la petición de validación AJAX será lanzada Cuando tanto `enableClientValidation` como `enableAjaxValidation` son definidas como `true`, la petición de validación AJAX será lanzada
sólo después de una validación del lado del cliente exitosa. sólo después de una validación del lado del cliente exitosa.

2
docs/guide-es/rest-authentication.md

@ -33,7 +33,7 @@ Para activar la autenticación para tus APIs, sigue los pasos siguientes:
3. Implementa [[yii\web\IdentityInterface::findIdentityByAccessToken()]] en tu [[yii\web\User::identityClass|clase de identidad de usuarios]]. 3. Implementa [[yii\web\IdentityInterface::findIdentityByAccessToken()]] en tu [[yii\web\User::identityClass|clase de identidad de usuarios]].
El paso 1 no es necesario pero sí recomendable para las APIs RESTful, pues son sin estado (stateless). El paso 1 no es necesario pero sí recomendable para las APIs RESTful, pues son sin estado (stateless).
Cuando [[yii\web\User::enableSession|enableSession]] es false, el estado de autenticación del usuario puede NO persistir entre peticiones usando sesiones. Cuando [[yii\web\User::enableSession|enableSession]] es `false`, el estado de autenticación del usuario puede NO persistir entre peticiones usando sesiones.
Si embargo, la autenticación será realizada para cada petición, lo que se consigue en los pasos 2 y 3. Si embargo, la autenticación será realizada para cada petición, lo que se consigue en los pasos 2 y 3.
> Tip:Puedes configurar [[yii\web\User::enableSession|enableSession]] del componente de la aplicación `user` en la configuración > Tip:Puedes configurar [[yii\web\User::enableSession|enableSession]] del componente de la aplicación `user` en la configuración

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

@ -135,7 +135,7 @@ sobrescribiendo el método [[yii\rest\ActiveController::checkAccess()|checkAcces
* If the user does not have access, a [[ForbiddenHttpException]] should be thrown. * If the user does not have access, a [[ForbiddenHttpException]] should be thrown.
* *
* @param string $action the ID of the action to be executed * @param string $action the ID of the action to be executed
* @param \yii\base\Model $model the model to be accessed. If null, it means no specific model is being accessed. * @param \yii\base\Model $model the model to be accessed. If `null`, it means no specific model is being accessed.
* @param array $params additional parameters * @param array $params additional parameters
* @throws ForbiddenHttpException if the user does not have access * @throws ForbiddenHttpException if the user does not have access
*/ */

2
docs/guide-es/rest-rate-limiting.md

@ -40,5 +40,5 @@ información sobre el límite actual de rango:
* `X-Rate-Limit-Remaining`, el número de peticiones restantes en el periodo de tiempo actual * `X-Rate-Limit-Remaining`, el número de peticiones restantes en el periodo de tiempo actual
* `X-Rate-Limit-Reset`, el número de segundos a esperar para pedir el máximo número de peticiones permitidas * `X-Rate-Limit-Reset`, el número de segundos a esperar para pedir el máximo número de peticiones permitidas
Puedes desactivar estas cabeceras configurando [[yii\filters\RateLimiter::enableRateLimitHeaders]] a false, Puedes desactivar estas cabeceras configurando [[yii\filters\RateLimiter::enableRateLimitHeaders]] a `false`,
tal y como en el anterior ejemplo. tal y como en el anterior ejemplo.

2
docs/guide-es/rest-routing.md

@ -75,7 +75,7 @@ Por ejemplo, para soportar una nueva acción `search` por el punto final `GET /
Puedes haber notado que el ID del controlador `user` aparece en formato plural `users` en los puntos finales de las URLs. Puedes haber notado que el ID del controlador `user` aparece en formato plural `users` en los puntos finales de las URLs.
Esto se debe a que [[yii\rest\UrlRule]] automáticamente pluraliza los IDs de los controladores al crear reglas URL hijas. Esto se debe a que [[yii\rest\UrlRule]] automáticamente pluraliza los IDs de los controladores al crear reglas URL hijas.
Puedes desactivar este comportamiento definiendo la propiedad [[yii\rest\UrlRule::pluralize]] como false. Puedes desactivar este comportamiento definiendo la propiedad [[yii\rest\UrlRule::pluralize]] como `false`.
> Info: La pluralización de los IDs de los controladores es realizada por [[yii\helpers\Inflector::pluralize()]]. Este método respeta > Info: La pluralización de los IDs de los controladores es realizada por [[yii\helpers\Inflector::pluralize()]]. Este método respeta
reglas especiales de pluralización. Por ejemplo, la palabra `box` (caja) será pluralizada como `boxes` en vez de `boxs`. reglas especiales de pluralización. Por ejemplo, la palabra `box` (caja) será pluralizada como `boxes` en vez de `boxs`.

2
docs/guide-es/runtime-handling-errors.md

@ -11,7 +11,7 @@ anteriormente. En particular, el gestor de errores de Yii hace lo siguiente para
* Soporta diferentes formatos de respuesta (response) de errores. * Soporta diferentes formatos de respuesta (response) de errores.
El [[yii\web\ErrorHandler|error handler]] esta habilitado de forma predeterminada. Se puede deshabilitar definiendo la El [[yii\web\ErrorHandler|error handler]] esta habilitado de forma predeterminada. Se puede deshabilitar definiendo la
constante `YII_ENABLE_ERROR_HANDLER` con valor false en el [script de entrada (entry script)](structure-entry-scripts.md) de la aplicación. constante `YII_ENABLE_ERROR_HANDLER` con valor `false` en el [script de entrada (entry script)](structure-entry-scripts.md) de la aplicación.
## Uso del Gestor de Errores <span id="using-error-handler"></span> ## Uso del Gestor de Errores <span id="using-error-handler"></span>

6
docs/guide-es/runtime-routing.md

@ -247,7 +247,7 @@ amigable. El resto de propiedades son opcionales. Sin embargo, la anterior confi
* [[yii\web\UrlManager::showScriptName|showScriptName]]: esta propiedad determina si el script de entrada debe ser * [[yii\web\UrlManager::showScriptName|showScriptName]]: esta propiedad determina si el script de entrada debe ser
incluido en las URLs generadas. Por ejemplo, en lugar de crear una URL `/index.php/post/100`, estableciendo la incluido en las URLs generadas. Por ejemplo, en lugar de crear una URL `/index.php/post/100`, estableciendo la
propiedad con valor true, la URL que se generará sera `/post/100`. propiedad con valor `true`, la URL que se generará sera `/post/100`.
* [[yii\web\UrlManager::enableStrictParsing|enableStrictParsing]]: esta propiedad determina si se habilita la * [[yii\web\UrlManager::enableStrictParsing|enableStrictParsing]]: esta propiedad determina si se habilita la
conversión de petición estricta, si se habilita, la URL solicitada tiene que encajar al menos con uno de las conversión de petición estricta, si se habilita, la URL solicitada tiene que encajar al menos con uno de las
[[yii\web\UrlManager::rules|rules]] para poder ser tratada como una petición valida, o se lanzará una [[yii\web\UrlManager::rules|rules]] para poder ser tratada como una petición valida, o se lanzará una
@ -351,8 +351,8 @@ Cuando se usen las reglas para convertir URLs:
- `/index.php/post/100` se convierte en la ruta `post/view` y el parámetro `id` cuyo valor es 100 usando la segunda - `/index.php/post/100` se convierte en la ruta `post/view` y el parámetro `id` cuyo valor es 100 usando la segunda
regla; regla;
- `/index.php/posts/php` provocara una [[yii\web\NotFoundHttpException]] cuando - `/index.php/posts/php` provocara una [[yii\web\NotFoundHttpException]] cuando
[[yii\web\UrlManager::enableStrictParsing]] sea true, ya que no coincide ninguno de los parámetros . Si [[yii\web\UrlManager::enableStrictParsing]] sea `true`, ya que no coincide ninguno de los parámetros . Si
[[yii\web\UrlManager::enableStrictParsing]] es false (valor predeterminado), se devolverá como ruta la parte de [[yii\web\UrlManager::enableStrictParsing]] es `false` (valor predeterminado), se devolverá como ruta la parte de
información `posts/php`. información `posts/php`.
Y cuando las se usen las reglas para crear URLs: Y cuando las se usen las reglas para crear URLs:

6
docs/guide-es/runtime-sessions-cookies.md

@ -179,7 +179,7 @@ $session->setFlash('postDeleted', 'You have successfully deleted your post.');
echo $session->getFlash('postDeleted'); echo $session->getFlash('postDeleted');
// Petición #3 // Petición #3
// $result será false ya que el mensaje flash ha sido borrado automáticamente // $result será `false` ya que el mensaje flash ha sido borrado automáticamente
$result = $session->hasFlash('postDeleted'); $result = $session->hasFlash('postDeleted');
``` ```
@ -262,7 +262,7 @@ unset($cookies['language']);
Además de [[yii\web\Cookie::name|name]], [[yii\web\Cookie::value|value]] las propiedades que se muestran en los anteriores ejemplos, la clase [[yii\web\Cookie]] también define otras propiedades para representar toda la información posible de las cookies, tal como [[yii\web\Cookie::domain|domain]], [[yii\web\Cookie::expire|expire]]. Puedes configurar estas propiedades según sea necesario para preparar una cookie y luego añadirlo a la colección de cookies de la respuesta. Además de [[yii\web\Cookie::name|name]], [[yii\web\Cookie::value|value]] las propiedades que se muestran en los anteriores ejemplos, la clase [[yii\web\Cookie]] también define otras propiedades para representar toda la información posible de las cookies, tal como [[yii\web\Cookie::domain|domain]], [[yii\web\Cookie::expire|expire]]. Puedes configurar estas propiedades según sea necesario para preparar una cookie y luego añadirlo a la colección de cookies de la respuesta.
> Note: Para mayor seguridad, el valor por defecto de [[yii\web\Cookie::httpOnly]] es true. Esto ayuda a mitigar el riesgo del acceso a la cookie protegida por script desde el lado del cliente (si el navegador lo soporta). Puedes leer el [httpOnly wiki article](https://www.owasp.org/index.php/HttpOnly) para más detalles. > Note: Para mayor seguridad, el valor por defecto de [[yii\web\Cookie::httpOnly]] es `true`. Esto ayuda a mitigar el riesgo del acceso a la cookie protegida por script desde el lado del cliente (si el navegador lo soporta). Puedes leer el [httpOnly wiki article](https://www.owasp.org/index.php/HttpOnly) para más detalles.
### Validación de la Cookie <span id="cookie-validation"></span> ### Validación de la Cookie <span id="cookie-validation"></span>
@ -271,7 +271,7 @@ Cuando estás leyendo y enviando cookies a través de los componentes `request`
> Info: Si falla la validación de una cookie, aún puedes acceder a la misma a través de `$_COOKIE`. Esto sucede porque librerías de terceros pueden manipular de forma propia las cookies, lo cual no implica la validación de las mismas. > Info: Si falla la validación de una cookie, aún puedes acceder a la misma a través de `$_COOKIE`. Esto sucede porque librerías de terceros pueden manipular de forma propia las cookies, lo cual no implica la validación de las mismas.
La validación de cookies es habilitada por defecto. Puedes desactivar lo ajustando la propiedad [[yii\web\Request::enableCookieValidation]] a false, aunque se recomienda encarecidamente que no lo haga. La validación de cookies es habilitada por defecto. Puedes desactivar lo ajustando la propiedad [[yii\web\Request::enableCookieValidation]] a `false`, aunque se recomienda encarecidamente que no lo haga.
> Note: Las cookies que son directamente leídas/enviadas vía `$_COOKIE` y `setcookie()` no serán validadas. > Note: Las cookies que son directamente leídas/enviadas vía `$_COOKIE` y `setcookie()` no serán validadas.

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

@ -503,7 +503,7 @@ $auth->addChild($admin, $author);
Tenga en cuenta que en el ejemplo anterior, dado que "author" es agregado como hijo de "admin", cuando implementes el método `execute()` Tenga en cuenta que en el ejemplo anterior, dado que "author" es agregado como hijo de "admin", cuando implementes el método `execute()`
de la clase de la regla, necesitas respetar esta jerarquía. Esto se debe a que cuando el nombre del rol es "author", de la clase de la regla, necesitas respetar esta jerarquía. Esto se debe a que cuando el nombre del rol es "author",
el método `execute()` devolverá true si el grupo de usuario es tanto 1 como 2 (lo que significa que el usuario se encuentra en el método `execute()` devolverá `true` si el grupo de usuario es tanto 1 como 2 (lo que significa que el usuario se encuentra en
cualquiera de los dos grupos, "admin" o "author"). cualquiera de los dos grupos, "admin" o "author").
Luego, configura `authManager` enumerando los dos roles en [[yii\rbac\BaseManager::$defaultRoles]]: Luego, configura `authManager` enumerando los dos roles en [[yii\rbac\BaseManager::$defaultRoles]]:
@ -522,6 +522,6 @@ return [
``` ```
Ahora si realizas una comprobación de acceso, tanto el rol `admin` y como el rol `author` serán comprobados evaluando Ahora si realizas una comprobación de acceso, tanto el rol `admin` y como el rol `author` serán comprobados evaluando
las reglas asociadas con ellos. Si la regla devuelve true, significa que la regla aplica al usuario actual. las reglas asociadas con ellos. Si la regla devuelve `true`, significa que la regla aplica al usuario actual.
Basado en la implementación de la regla anterior, esto significa que si el valor `group` en un usuario es 1, el rol `admin` Basado en la implementación de la regla anterior, esto significa que si el valor `group` en un usuario es 1, el rol `admin`
se aplicaría al usuario; y si el valor de `group` es 2, se le aplicaría el rol `author`. se aplicaría al usuario; y si el valor de `group` es 2, se le aplicaría el rol `author`.

2
docs/guide-es/structure-models.md

@ -234,7 +234,7 @@ para ayudar al usuario a corregir estos errores.
Se puede llamar a [[yii\base\Model::validate()]] para validar los datos recibidos. El método se usará para validar las Se puede llamar a [[yii\base\Model::validate()]] para validar los datos recibidos. El método se usará para validar las
reglas declaradas en [[yii\base\Model::rules()]] para validar cada atributo relevante. Si no se encuentran errores, se reglas declaradas en [[yii\base\Model::rules()]] para validar cada atributo relevante. Si no se encuentran errores, se
devolverá true. De otro modo, este almacenará los errores en la propiedad [[yii\base\Model::errors]] y devolverá falso. devolverá `true`. De otro modo, este almacenará los errores en la propiedad [[yii\base\Model::errors]] y devolverá falso.
Por ejemplo: Por ejemplo:
```php ```php

60
docs/guide-es/tutorial-core-validators.md

@ -25,19 +25,19 @@ A continuación, vamos a describir el uso principal y las propiedades de cada va
// comprueba si "selected" es 0 o 1, sin mirar el tipo de dato // comprueba si "selected" es 0 o 1, sin mirar el tipo de dato
['selected', 'boolean'], ['selected', 'boolean'],
// comprueba si "deleted" es del tipo booleano, alguno entre true o false // comprueba si "deleted" es del tipo booleano, alguno entre `true` o `false`
['deleted', 'boolean', 'trueValue' => true, 'falseValue' => false, 'strict' => true], ['deleted', 'boolean', 'trueValue' => true, 'falseValue' => false, 'strict' => true],
] ]
``` ```
Este validador comprueba si el valor de la entrada (input) es booleano. Este validador comprueba si el valor de la entrada (input) es booleano.
- `trueValue`: El valor representando *true*. Valor por defecto a `'1'`. - ``true`Value`: El valor representando *`true`*. Valor por defecto a `'1'`.
- `falseValue`: El valor representando *false*. Valor por defecto a `'0'`. - ``false`Value`: El valor representando *`false`*. Valor por defecto a `'0'`.
- `strict`: Si el tipo del valor de la entrada (input) debe corresponder con `trueValue` y `falseValue`. Valor por defecto a `false`. - `strict`: Si el tipo del valor de la entrada (input) debe corresponder con `trueValue` y `falseValue`. Valor por defecto a `false`.
> Note: Ya que los datos enviados con la entrada, vía formularios HTML,son todos cadenas (strings), usted debe normalmente dejar la propiedad [[yii\validators\BooleanValidator::strict|strict]] a false. > Note: Ya que los datos enviados con la entrada, vía formularios HTML,son todos cadenas (strings), usted debe normalmente dejar la propiedad [[yii\validators\BooleanValidator::strict|strict]] a `false`.
## [[yii\captcha\CaptchaValidator|captcha]] <span id="captcha"></span> ## [[yii\captcha\CaptchaValidator|captcha]] <span id="captcha"></span>
@ -50,10 +50,10 @@ Este validador comprueba si el valor de la entrada (input) es booleano.
Este validador es usualmente usado junto con [[yii\captcha\CaptchaAction]] y [[yii\captcha\Captcha]] para asegurarse que una entrada es la misma que lo es el código de verificación que enseña el widget [[yii\captcha\Captcha|CAPTCHA]]. Este validador es usualmente usado junto con [[yii\captcha\CaptchaAction]] y [[yii\captcha\Captcha]] para asegurarse que una entrada es la misma que lo es el código de verificación que enseña el widget [[yii\captcha\Captcha|CAPTCHA]].
- `caseSensitive`: cuando la comparación del código de verificación depende de que sean mayúsculas y minúsculas (case sensitive). Por defecto a false. - `caseSensitive`: cuando la comparación del código de verificación depende de que sean mayúsculas y minúsculas (case sensitive). Por defecto a `false`.
- `captchaAction`: la [ruta](structure-controllers.md#routes) correspondiente a - `captchaAction`: la [ruta](structure-controllers.md#routes) correspondiente a
[[yii\captcha\CaptchaAction|CAPTCHA action]] que representa (render) la imagen CAPTCHA. Por defecto`'site/captcha'`. [[yii\captcha\CaptchaAction|CAPTCHA action]] que representa (render) la imagen CAPTCHA. Por defecto`'site/captcha'`.
- `skipOnEmpty`: cuando la validación puede saltarse si la entrada está vacía. Por defecto a false, lo caul permite que la entrada sea necesaria (required). - `skipOnEmpty`: cuando la validación puede saltarse si la entrada está vacía. Por defecto a `false`, lo caul permite que la entrada sea necesaria (required).
## [[yii\validators\CompareValidator|compare]] <span id="compare"></span> ## [[yii\validators\CompareValidator|compare]] <span id="compare"></span>
@ -158,12 +158,12 @@ Esta validador comprueba si el valor de entrada es un número de tipo doble. Es
Este validador comprueba si el valor de entrada es una dirección válida de email. Este validador comprueba si el valor de entrada es una dirección válida de email.
- `allowName`: indica cuando permitir el nombre en la dirección de email (p.e. `John Smith <john.smith@example.com>`). Por defecto a false. - `allowName`: indica cuando permitir el nombre en la dirección de email (p.e. `John Smith <john.smith@example.com>`). Por defecto a `false`.
- `checkDNS`, comprobar cuando el dominio del email existe y tiene cualquier registro A o MX. - `checkDNS`, comprobar cuando el dominio del email existe y tiene cualquier registro A o MX.
Es necesario ser consciente que esta comprobación puede fallar debido a problemas temporales de DNS, incluso si el la dirección es válida actualmente. Es necesario ser consciente que esta comprobación puede fallar debido a problemas temporales de DNS, incluso si el la dirección es válida actualmente.
Por defecto a false. Por defecto a `false`.
- `enableIDN`, indica cuando el proceso de validación debe tener en cuenta el informe de IDN (internationalized domain names). - `enableIDN`, indica cuando el proceso de validación debe tener en cuenta el informe de IDN (internationalized domain names).
Por defecto a false. Dese cuenta que para poder usar la validación de IDN has de instalar y activar la extensión de PHP `intl`, o será lanzada una excepción. Por defecto a `false`. Dese cuenta que para poder usar la validación de IDN has de instalar y activar la extensión de PHP `intl`, o será lanzada una excepción.
## [[yii\validators\ExistValidator|exist]] <span id="exist"></span> ## [[yii\validators\ExistValidator|exist]] <span id="exist"></span>
@ -197,7 +197,7 @@ Este validador comprueba si el valor de entrada puede ser encontrado en una colu
Puede usar una array para validar la existencia de múltiples columnas al mismo tiempo. El array de valores son los atributos que pueden ser usados para validar la existencia, mientras que las claves del array son los atributos a ser validados. Si la clave y el valor son los mismos, solo en ese momento puedes especificar el valor. Puede usar una array para validar la existencia de múltiples columnas al mismo tiempo. El array de valores son los atributos que pueden ser usados para validar la existencia, mientras que las claves del array son los atributos a ser validados. Si la clave y el valor son los mismos, solo en ese momento puedes especificar el valor.
- `filter`: filtro adicional a aplicar a la consulta de la base de datos usado para comprobar la existencia de una valor de entrada. - `filter`: filtro adicional a aplicar a la consulta de la base de datos usado para comprobar la existencia de una valor de entrada.
Esto puede ser una cadena o un array representando la condición de la consulta (referirse a [[yii\db\Query::where()]] sobre el formato de la condición de consulta), o una función anónima con la signatura `function ($query)`, donde `$query` es el objeto [[yii\db\Query|Query]] que puedes modificar en la función. Esto puede ser una cadena o un array representando la condición de la consulta (referirse a [[yii\db\Query::where()]] sobre el formato de la condición de consulta), o una función anónima con la signatura `function ($query)`, donde `$query` es el objeto [[yii\db\Query|Query]] que puedes modificar en la función.
- `allowArray`: indica cuando permitir que el valor de entrada sea un array. Por defecto a false.Si la propiedad es true y la entrada es un array, cada elemento del array debe existir en la columna destino. Nota que esta propiedad no puede ser true si estás validando, por el contrario, múltiple columnas poniendo el valor del atributo `targetAttribute` como que es un array. - `allowArray`: indica cuando permitir que el valor de entrada sea un array. Por defecto a `false`.Si la propiedad es `true` y la entrada es un array, cada elemento del array debe existir en la columna destino. Nota que esta propiedad no puede ser `true` si estás validando, por el contrario, múltiple columnas poniendo el valor del atributo `targetAttribute` como que es un array.
## [[yii\validators\FileValidator|file]] <span id="file"></span> ## [[yii\validators\FileValidator|file]] <span id="file"></span>
@ -213,13 +213,13 @@ Este validador comprueba si el valor de entrada puede ser encontrado en una colu
Este validador comprueba que el fichero subido es el adecuado. Este validador comprueba que el fichero subido es el adecuado.
- `extensions`: una lista de extensiones de ficheros que pueden ser subidos. Esto puede ser tanto un array o una cadena conteniendo nombres de extensiones de ficheros separados por un espacio o coma (p.e. "gif, jpg"). - `extensions`: una lista de extensiones de ficheros que pueden ser subidos. Esto puede ser tanto un array o una cadena conteniendo nombres de extensiones de ficheros separados por un espacio o coma (p.e. "gif, jpg").
Los nombres de las extensiones no diferencian mayúsculas de minúsculas (case-insensitive). Por defecto a null, permitiendo todas los nombres de extensiones de fichero. Los nombres de las extensiones no diferencian mayúsculas de minúsculas (case-insensitive). Por defecto a `null`, permitiendo todas los nombres de extensiones de fichero.
- `mimeTypes`: una lista de tipos de ficheros MIME que están permitidos subir. Esto puede ser tanto un array como una cadena conteniendo tipos de fichero MIME separados por un espacio o una coma (p.e. "image/jpeg, image/png"). - `mimeTypes`: una lista de tipos de ficheros MIME que están permitidos subir. Esto puede ser tanto un array como una cadena conteniendo tipos de fichero MIME separados por un espacio o una coma (p.e. "image/jpeg, image/png").
Los tipos Mime no diferencian mayúsculas de minúsculas (case-insensitive). Por defecto a null, permitiendo todos los tipos MIME. Los tipos Mime no diferencian mayúsculas de minúsculas (case-insensitive). Por defecto a `null`, permitiendo todos los tipos MIME.
- `minSize`: el número de bytes mínimo requerido para el fichero subido. El tamaño del fichero ha de ser superior a este valor. Por defecto a null, lo que significa sin límite inferior. - `minSize`: el número de bytes mínimo requerido para el fichero subido. El tamaño del fichero ha de ser superior a este valor. Por defecto a `null`, lo que significa sin límite inferior.
- `maxSize`: El número máximo de bytes del fichero a subir. El tamaño del fichero ha de ser inferior a este valor. Por defecto a null, significando no tener límite superior. - `maxSize`: El número máximo de bytes del fichero a subir. El tamaño del fichero ha de ser inferior a este valor. Por defecto a `null`, significando no tener límite superior.
- `maxFiles`: el máximo número de ficheros que determinado atributo puede manejar. Por defecto a 1, lo que significa que la entrada debe de ser sólo un fichero. Si es mayor que 1, entonces la entrada tiene que ser un array conteniendo como máximo el número `maxFiles` de elementos que representan los ficheros a subir. - `maxFiles`: el máximo número de ficheros que determinado atributo puede manejar. Por defecto a 1, lo que significa que la entrada debe de ser sólo un fichero. Si es mayor que 1, entonces la entrada tiene que ser un array conteniendo como máximo el número `maxFiles` de elementos que representan los ficheros a subir.
- `checkExtensionByMimeType`: cuando comprobar la extensión del fichero por el tipo MIME. Si la extensión producida por la comprobación del tipo MIME difiere la extensión del fichero subido, el fichero será considerado como no válido. Por defecto a true, significando que realiza este tipo de comprobación. - `checkExtensionByMimeType`: cuando comprobar la extensión del fichero por el tipo MIME. Si la extensión producida por la comprobación del tipo MIME difiere la extensión del fichero subido, el fichero será considerado como no válido. Por defecto a `true`, significando que realiza este tipo de comprobación.
`FileValidator` es usado con [[yii\web\UploadedFile]]. Por favor, refiérase a la sección [Subida de ficheros](input-file-upload.md) para una completa cobertura sobre la subida de ficheros y llevar a cabo la validación de los ficheros subidos. `FileValidator` es usado con [[yii\web\UploadedFile]]. Por favor, refiérase a la sección [Subida de ficheros](input-file-upload.md) para una completa cobertura sobre la subida de ficheros y llevar a cabo la validación de los ficheros subidos.
@ -243,8 +243,8 @@ Este validador no valida datos. En su lugar, aplica un filtro sobre el valor de
- `filter`: una retrollamada (callback) de PHP que define un filtro. Tiene que ser un nombre de función global, una función anónima, etc. - `filter`: una retrollamada (callback) de PHP que define un filtro. Tiene que ser un nombre de función global, una función anónima, etc.
La forma de la función ha de ser `function ($value) { return $newValue; }`. Tiene que contener un valor esta propiedad. La forma de la función ha de ser `function ($value) { return $newValue; }`. Tiene que contener un valor esta propiedad.
- `skipOnArray`: cuando evitar el filtro si el valor de la entrada es un array. Por defecto a false. - `skipOnArray`: cuando evitar el filtro si el valor de la entrada es un array. Por defecto a `false`.
A tener en cuenta que si el filtro no puede manejar una entrada de un array, debes poner esta propiedad a true. En otro caso algún error PHP puede ocurrir. A tener en cuenta que si el filtro no puede manejar una entrada de un array, debes poner esta propiedad a `true`. En otro caso algún error PHP puede ocurrir.
> Consejo (Tip): Si quieres recortar los valores de entrada, puedes usar directamente el validador [Recorte (trim)](#trim). > Consejo (Tip): Si quieres recortar los valores de entrada, puedes usar directamente el validador [Recorte (trim)](#trim).
@ -263,10 +263,10 @@ Este validador no valida datos. En su lugar, aplica un filtro sobre el valor de
Este validador comprueba si el valor de entrada representa un fichero de imagen válido. Extiende al validador [Fichero (file)](#file) y, por lo tanto, hereda todas sus propiedades. Además, soporta las siguientes propiedades adicionales específicas para la validación de imágenes: Este validador comprueba si el valor de entrada representa un fichero de imagen válido. Extiende al validador [Fichero (file)](#file) y, por lo tanto, hereda todas sus propiedades. Además, soporta las siguientes propiedades adicionales específicas para la validación de imágenes:
- `minWidth`: el mínimo ancho de la imagen. Por defecto a null, indicando que no hay límite inferior. - `minWidth`: el mínimo ancho de la imagen. Por defecto a `null`, indicando que no hay límite inferior.
- `maxWidth`: el máximo ancho de la imagen. Por defecto a null, indicando que no hay límite superior. - `maxWidth`: el máximo ancho de la imagen. Por defecto a `null`, indicando que no hay límite superior.
- `minHeight`: el mínimo alto de la imagen. Por defecto a null, indicando que no hay límite inferior. - `minHeight`: el mínimo alto de la imagen. Por defecto a `null`, indicando que no hay límite inferior.
- `maxHeight`: el máximo alto de la imagen. Por defecto a null, indicando que no hay límite superior. - `maxHeight`: el máximo alto de la imagen. Por defecto a `null`, indicando que no hay límite superior.
## [[yii\validators\RangeValidator|in]] <span id="in"></span> ## [[yii\validators\RangeValidator|in]] <span id="in"></span>
@ -281,9 +281,9 @@ Este validador comprueba si el valor de entrada representa un fichero de imagen
Este validador comprueba si el valor de entrada puede encontrarse entre determinada lista de valores. Este validador comprueba si el valor de entrada puede encontrarse entre determinada lista de valores.
- `range`: una lista de determinados valores dentro de los cuales el valor de entrada debe de ser mirado. - `range`: una lista de determinados valores dentro de los cuales el valor de entrada debe de ser mirado.
- `strict`: cuando la comparación entre el valor de entrada y los valores determinados debe de ser estricta (ambos el tipo y el valor han de ser iguales). Por defecto a false. - `strict`: cuando la comparación entre el valor de entrada y los valores determinados debe de ser estricta (ambos el tipo y el valor han de ser iguales). Por defecto a `false`.
- `not`: cuando el resultado de la validación debe de ser invertido. Por defecto a false. Cuando esta propiedad está a true, el validador comprueba que el valor de entrada NO ESTÁ en la determinada lista de valores. - `not`: cuando el resultado de la validación debe de ser invertido. Por defecto a `false`. Cuando esta propiedad está a `true`, el validador comprueba que el valor de entrada NO ESTÁ en la determinada lista de valores.
- `allowArray`: si se permite que el valor de entrada sea un array. Cuando es true y el valor de entrada es un array, cada elemento en el array debe de ser encontrado en la lista de valores determinada,o la validación fallará. - `allowArray`: si se permite que el valor de entrada sea un array. Cuando es `true` y el valor de entrada es un array, cada elemento en el array debe de ser encontrado en la lista de valores determinada,o la validación fallará.
## [[yii\validators\NumberValidator|integer]] <span id="integer"></span> ## [[yii\validators\NumberValidator|integer]] <span id="integer"></span>
@ -313,7 +313,7 @@ Esta validador comprueba si el valor de entrada es un entero.
Este validador comprueba si el valor de entrada coincide con la expresión regular especificada. Este validador comprueba si el valor de entrada coincide con la expresión regular especificada.
- `pattern`: la expresión regular conla que el valor de entrada debe coincidir. Esta propiedad no puede estar vacía, o se lanzará una excepción. - `pattern`: la expresión regular conla que el valor de entrada debe coincidir. Esta propiedad no puede estar vacía, o se lanzará una excepción.
- `not`: indica cuando invertir el resultado de la validación. Por defecto a false, significando que la validación es exitosa solamente si el valor de entrada coincide con el patrón. Si esta propiedad está a true, la validación es exitosa solamente si el valor de entrada NO coincide con el patrón. - `not`: indica cuando invertir el resultado de la validación. Por defecto a `false`, significando que la validación es exitosa solamente si el valor de entrada coincide con el patrón. Si esta propiedad está a `true`, la validación es exitosa solamente si el valor de entrada NO coincide con el patrón.
## [[yii\validators\NumberValidator|number]] <span id="number"></span> ## [[yii\validators\NumberValidator|number]] <span id="number"></span>
@ -343,9 +343,9 @@ Este validador comprueba si el valor de entrada es un número. Es equivalente al
El validador comprueba si el valor de entrada es provisto y no está vacío. El validador comprueba si el valor de entrada es provisto y no está vacío.
- `requiredValue`: el valor deseado que la entrada debería tener. Si no tiene valor, significa que la entrada no puede estar vacía. - `requiredValue`: el valor deseado que la entrada debería tener. Si no tiene valor, significa que la entrada no puede estar vacía.
- `strict`: indica como comprobar los tipos de los datos al validar un valor. Por defecto a false. - `strict`: indica como comprobar los tipos de los datos al validar un valor. Por defecto a `false`.
Cuando `requiredValue` no tiene valor, si esta propiedad es true, el validador comprueba si el valor de entrada no es estrictamente null; si la propiedad es false, el validador puede usar una regla suelta para determinar si el valor está vacío o no. Cuando `requiredValue` no tiene valor, si esta propiedad es `true`, el validador comprueba si el valor de entrada no es estrictamente `null`; si la propiedad es `false`, el validador puede usar una regla suelta para determinar si el valor está vacío o no.
Cuando `requiredValue` tiene valor, la comparación entre la entrada y `requiredValue` comprobará tambien los tipos de los datos si esta propiedad es true. Cuando `requiredValue` tiene valor, la comparación entre la entrada y `requiredValue` comprobará tambien los tipos de los datos si esta propiedad es `true`.
> Info: Como determinar si un valor está vacío o no es un tópico separado cubierto en la sección [Valores vacíos](input-validation.md#handling-empty-inputs). > Info: Como determinar si un valor está vacío o no es un tópico separado cubierto en la sección [Valores vacíos](input-validation.md#handling-empty-inputs).
@ -439,7 +439,7 @@ Este validador comprueba si el valor de entrada es una URL válida.
- `validSchemes`: un array especificando el esquema URI que debe ser considerado válido. Por defecto contiene `['http', 'https']`, significando que ambas URLS `http` y `https` son consideradas válidas. - `validSchemes`: un array especificando el esquema URI que debe ser considerado válido. Por defecto contiene `['http', 'https']`, significando que ambas URLS `http` y `https` son consideradas válidas.
- `defaultScheme`: el esquema de URI a poner como prefijo a la entrada si no tiene la parte del esquema. - `defaultScheme`: el esquema de URI a poner como prefijo a la entrada si no tiene la parte del esquema.
Por defecto a null, significando que no modifica el valor de entrada. Por defecto a `null`, significando que no modifica el valor de entrada.
- `enableIDN`: Si el validador debe formar parte del registro IDN (internationalized domain names). - `enableIDN`: Si el validador debe formar parte del registro IDN (internationalized domain names).
Por defecto a false. Nota que para usar la validación IDN tienes que instalar y activar la extensión PHP `intl`, en otro caso una excepción será lanzada. Por defecto a `false`. Nota que para usar la validación IDN tienes que instalar y activar la extensión PHP `intl`, en otro caso una excepción será lanzada.

4
docs/guide-fr/db-query-builder.md

@ -186,7 +186,7 @@ $query->where([
]); ]);
``` ```
Comme vous pouvez le voir, le constructeur de requêtes est assez intelligent pour manipuler correctement les valeurs qui sont soit nulles, soit des tableaux. Comme vous pouvez le voir, le constructeur de requêtes est assez intelligent pour manipuler correctement les valeurs qui sont soit `null`es, soit des tableaux.
Vous pouvez utiliser aussi des sous-requêtes avec le format haché comme suit : Vous pouvez utiliser aussi des sous-requêtes avec le format haché comme suit :
@ -277,7 +277,7 @@ $query->filterWhere([
La seule différence entre [[yii\db\Query::filterWhere()|filterWhere()]] et [[yii\db\Query::where()|where()]] est que la première ignore les valeurs vides fournies dans la condition au [format haché](#hash-format). Ainsi si `$email` est vide alors que `$username` ne l'est pas, le code ci dessus produit la condition SQL `WHERE username=:username`. La seule différence entre [[yii\db\Query::filterWhere()|filterWhere()]] et [[yii\db\Query::where()|where()]] est que la première ignore les valeurs vides fournies dans la condition au [format haché](#hash-format). Ainsi si `$email` est vide alors que `$username` ne l'est pas, le code ci dessus produit la condition SQL `WHERE username=:username`.
> Info: une valeur est considérée comme vide si elle est nulle, un tableau vide, ou un chaîne de caractères vide, ou un chaîne de caractères constituée d'espaces uniquement. > Info: une valeur est considérée comme vide si elle est `null`e, un tableau vide, ou un chaîne de caractères vide, ou un chaîne de caractères constituée d'espaces uniquement.
Comme avec [[yii\db\Query::andWhere()|andWhere()]] et [[yii\db\Query::orWhere()|orWhere()]], vous pouvez utiliser [[yii\db\Query::andFilterWhere()|andFilterWhere()]] et [[yii\db\Query::orFilterWhere()|orFilterWhere()]] pour ajouter des conditions de filtrage supplémentaires à une condition existante. Comme avec [[yii\db\Query::andWhere()|andWhere()]] et [[yii\db\Query::orWhere()|orWhere()]], vous pouvez utiliser [[yii\db\Query::andFilterWhere()|andFilterWhere()]] et [[yii\db\Query::orFilterWhere()|orFilterWhere()]] pour ajouter des conditions de filtrage supplémentaires à une condition existante.

2
docs/guide-fr/start-forms.md

@ -64,7 +64,7 @@ pour valider les données. Les règles de validation déclarées ci-dessus énon
Si vous avez un objet `EntryForm` peuplé par les données saisies par un utilisateur, vous pouvez appeler sa méthode Si vous avez un objet `EntryForm` peuplé par les données saisies par un utilisateur, vous pouvez appeler sa méthode
[[yii\base\Model::validate()|validate()]] pour déclencher les routines de validation de données. Un échec de validation [[yii\base\Model::validate()|validate()]] pour déclencher les routines de validation de données. Un échec de validation
de données affectera la valeur true à la propriété [[yii\base\Model::hasErrors|hasErrors]], et vous pourrez connaître de données affectera la valeur `true` à la propriété [[yii\base\Model::hasErrors|hasErrors]], et vous pourrez connaître
quelles erreurs de validations sont apparues via [[yii\base\Model::getErrors|errors]]. quelles erreurs de validations sont apparues via [[yii\base\Model::getErrors|errors]].
```php ```php

2
docs/guide-id/intro-upgrade-from-v1.md

@ -315,7 +315,7 @@ public function behaviors()
'access' => [ 'access' => [
'class' => 'yii\filters\AccessControl', 'class' => 'yii\filters\AccessControl',
'rules' => [ 'rules' => [
['allow' => true, 'actions' => ['admin'], 'roles' => ['@']], ['allow' => `true`, 'actions' => ['admin'], 'roles' => ['@']],
], ],
], ],
]; ];

2
docs/guide-it/intro-upgrade-from-v1.md

@ -308,7 +308,7 @@ public function behaviors()
'access' => [ 'access' => [
'class' => 'yii\filters\AccessControl', 'class' => 'yii\filters\AccessControl',
'rules' => [ 'rules' => [
['allow' => true, 'actions' => ['admin'], 'roles' => ['@']], ['allow' => `true`, 'actions' => ['admin'], 'roles' => ['@']],
], ],
], ],
]; ];

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

@ -17,7 +17,7 @@ if ($this->beginCache($id)) {
``` ```
Jak widać, chodzi tu o zamknięcie bloku generatora zawartości pomiędzy wywołaniem metod [[yii\base\View::beginCache()|beginCache()]] i [[yii\base\View::endCache()|endCache()]]. Jak widać, chodzi tu o zamknięcie bloku generatora zawartości pomiędzy wywołaniem metod [[yii\base\View::beginCache()|beginCache()]] i [[yii\base\View::endCache()|endCache()]].
Jeśli wskazana zawartość zostanie odnaleziona w pamięci podręcznej, [[yii\base\View::beginCache()|beginCache()]] wyrenderuje zapisaną zawartość i zwróci false, przez co pominie Jeśli wskazana zawartość zostanie odnaleziona w pamięci podręcznej, [[yii\base\View::beginCache()|beginCache()]] wyrenderuje zapisaną zawartość i zwróci `false`, przez co pominie
blok jej generowania. W przeciwnym wypadku generowanie zostanie uruchomione, a w momencie wywołania [[yii\base\View::endCache()|endCache()]] wygenerowana zawartość zostanie zapisana blok jej generowania. W przeciwnym wypadku generowanie zostanie uruchomione, a w momencie wywołania [[yii\base\View::endCache()|endCache()]] wygenerowana zawartość zostanie zapisana
w pamięci podręcznej. w pamięci podręcznej.

2
docs/guide-pl/rest-routing.md

@ -73,7 +73,7 @@ Dla przykładu, aby dodać obsługę nowej akcji `search` dla punktu końcowego
Na pewno zwróciłeś uwagę na to, że ID kontrolera `user` występuje tu w formie mnogiej jako `users` dla URLi punktu końcowego. Na pewno zwróciłeś uwagę na to, że ID kontrolera `user` występuje tu w formie mnogiej jako `users` dla URLi punktu końcowego.
Dzieje się tak, ponieważ [[yii\rest\UrlRule|UrlRule]] automatycznie przechodzi na formę mnogą dla ID kontrolerów podczas tworzenia potomnych zasad URL. Dzieje się tak, ponieważ [[yii\rest\UrlRule|UrlRule]] automatycznie przechodzi na formę mnogą dla ID kontrolerów podczas tworzenia potomnych zasad URL.
Zachowanie to można wyłączyć ustawiając [[yii\rest\UrlRule::pluralize|pluralize]] na false. Zachowanie to można wyłączyć ustawiając [[yii\rest\UrlRule::pluralize|pluralize]] na `false`.
> Info: forma mnoga ID kontrolerów jest tworzona poprzez metodę [[yii\helpers\Inflector::pluralize()|pluralize()]]. Uwzględnia ona specjalne zasady tworzenia form mnogich. > Info: forma mnoga ID kontrolerów jest tworzona poprzez metodę [[yii\helpers\Inflector::pluralize()|pluralize()]]. Uwzględnia ona specjalne zasady tworzenia form mnogich.
> Dla przykładu, od słowa `box` zostanie utworzona liczba mnoga `boxes` a nie `boxs`. > Dla przykładu, od słowa `box` zostanie utworzona liczba mnoga `boxes` a nie `boxs`.

4
docs/guide-pl/structure-entry-scripts.md

@ -84,11 +84,11 @@ Skrypty wejściowe są najlepszym miejscem do definiowania globalnych stałych.
* `YII_DEBUG`: określa czy aplikacja działa w trybie debugowania. Podczas tego trybu aplikacja * `YII_DEBUG`: określa czy aplikacja działa w trybie debugowania. Podczas tego trybu aplikacja
przetrzymuje więcej informacji w logach i zdradza szczegóły stosu błędów, kiedy rzucony jest wyjątek. Z tego powodu przetrzymuje więcej informacji w logach i zdradza szczegóły stosu błędów, kiedy rzucony jest wyjątek. Z tego powodu
tryb debugowania powinien być używany głównie podczas fazy deweloperskiej. Domyślną wartością `YII_DEBUG` jest false. tryb debugowania powinien być używany głównie podczas fazy deweloperskiej. Domyślną wartością `YII_DEBUG` jest `false`.
* `YII_ENV`: określa środowisko, w którym aplikacja działa. Opisane jest to bardziej szczegółowo * `YII_ENV`: określa środowisko, w którym aplikacja działa. Opisane jest to bardziej szczegółowo
w sekcji [Konfiguracje](concept-configurations.md#environment-constants). w sekcji [Konfiguracje](concept-configurations.md#environment-constants).
Domyślną wartością `YII_ENV` jest `'prod'`, co oznacza, że aplikacja jest uruchomiona w środowisku produkcyjnym. Domyślną wartością `YII_ENV` jest `'prod'`, co oznacza, że aplikacja jest uruchomiona w środowisku produkcyjnym.
* `YII_ENABLE_ERROR_HANDLER`: określa czy uruchomić obsługę błędów przygotowaną przez Yii. Domyślną wartością tej stałej jest true. * `YII_ENABLE_ERROR_HANDLER`: określa czy uruchomić obsługę błędów przygotowaną przez Yii. Domyślną wartością tej stałej jest `true`.
Podczas definiowania stałej często korzystamy z poniższego kodu: Podczas definiowania stałej często korzystamy z poniższego kodu:

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

@ -271,7 +271,7 @@ $resultado = Cliente::getDb()->cache(function ($bd) {
Cache de consulta tem três opções configuráveis globalmente através de [[yii\db\Connection]]: Cache de consulta tem três opções configuráveis globalmente através de [[yii\db\Connection]]:
* [[yii\db\Connection::enableQueryCache|enableQueryCache]]: Configura se o cache de consulta está habilitado. * [[yii\db\Connection::enableQueryCache|enableQueryCache]]: Configura se o cache de consulta está habilitado.
O padrão é true. Observe que para ter efetivamente o cache de consulta habilitado, você também deve ter um cache válido como especificado por [[yii\db\Connection::queryCache|queryCache]]. O padrão é `true`. Observe que para ter efetivamente o cache de consulta habilitado, você também deve ter um cache válido como especificado por [[yii\db\Connection::queryCache|queryCache]].
* [[yii\db\Connection::queryCacheDuration|queryCacheDuration]]: representa o número de segundos que o resultado de uma * [[yii\db\Connection::queryCacheDuration|queryCacheDuration]]: representa o número de segundos que o resultado de uma
consulta pode se manter válido em cache. Você pode usar 0 para indicar que o resultado da consulta deve permanecer no consulta pode se manter válido em cache. Você pode usar 0 para indicar que o resultado da consulta deve permanecer no
cache indefinidamente. Este é o valor padrão usado quando [[yii\db\Connection::cache()]] é chamado sem nenhuma cache indefinidamente. Este é o valor padrão usado quando [[yii\db\Connection::cache()]] é chamado sem nenhuma

2
docs/guide-pt-BR/concept-configurations.md

@ -136,7 +136,7 @@ echo Menu::widget([
]); ]);
``` ```
O código acima cria um widget `Menu` e inicializa suas propriedades `activateItems` com false. A propriedade `items` também é configurada com os itens do menu para serem exibidos. O código acima cria um widget `Menu` e inicializa suas propriedades `activateItems` com `false`. A propriedade `items` também é configurada com os itens do menu para serem exibidos.
Observe que, como o nome da classe já está dado, o array de configuração não precisa da chave `class`. Observe que, como o nome da classe já está dado, o array de configuração não precisa da chave `class`.

6
docs/guide-pt-BR/db-active-record.md

@ -617,7 +617,7 @@ $orders = $customer->orders;
> Observação: quando você declara uma relação chamada `xyz` através de um método getter `getXyz()`, você terá acesso a `xyz` como uma [propriedade de objeto](concept-properties.md). Note que o nome é case-sensitive. > Observação: quando você declara uma relação chamada `xyz` através de um método getter `getXyz()`, você terá acesso a `xyz` como uma [propriedade de objeto](concept-properties.md). Note que o nome é case-sensitive.
Se a relação for declarada com [[yii\db\ActiveRecord::hasMany()|hasMany()]], acessar esta propriedade irá retornar um array de instâncias de Active Record relacionais; Se a relação for declarada com [[yii\db\ActiveRecord::hasOne()|hasOne()]], acessar esta propriedade irá retornar a instância de Active Record relacional ou null se não encontrar dados relacionais. Se a relação for declarada com [[yii\db\ActiveRecord::hasMany()|hasMany()]], acessar esta propriedade irá retornar um array de instâncias de Active Record relacionais; Se a relação for declarada com [[yii\db\ActiveRecord::hasOne()|hasOne()]], acessar esta propriedade irá retornar a instância de Active Record relacional ou `null` se não encontrar dados relacionais.
Quando você acessa uma propriedade de relação pela primeira vez, uma instrução SQL será executada, como mostrado no exemplo acima. Se a mesma propriedade for acessada novamente, o resultado anterior será devolvido sem executar novamente a instrução SQL. Para forçar a execução da instrução SQL, você deve primeiramente remover a configuração da propriedade de relação: `unset($customer->orders)`. Quando você acessa uma propriedade de relação pela primeira vez, uma instrução SQL será executada, como mostrado no exemplo acima. Se a mesma propriedade for acessada novamente, o resultado anterior será devolvido sem executar novamente a instrução SQL. Para forçar a execução da instrução SQL, você deve primeiramente remover a configuração da propriedade de relação: `unset($customer->orders)`.
@ -1002,9 +1002,9 @@ $customer->unlink('orders', $customer->orders[0]);
``` ```
Por padrão, o método [[yii\db\ActiveRecord::unlink()|unlink()]] irá definir o(s) valor(es) da(s) chave(s) estrangeira(s) que especificam a relação existente para null. Você pode, entretanto, optar por excluir a linha da tabela que contém a chave estrangeira passando o parâmetro `$delete` como true para o método. Por padrão, o método [[yii\db\ActiveRecord::unlink()|unlink()]] irá definir o(s) valor(es) da(s) chave(s) estrangeira(s) que especificam a relação existente para `null`. Você pode, entretanto, optar por excluir a linha da tabela que contém a chave estrangeira passando o parâmetro `$delete` como `true` para o método.
Quando uma tabela de junção está envolvida numa relação, chamar o método [[yii\db\ActiveRecord::unlink()|unlink()]] fará com que as chaves estrangeiras na tabela de junção sejam apagadas, ou a deleção da linha correspondente na tabela de junção se `$delete` for true. Quando uma tabela de junção está envolvida numa relação, chamar o método [[yii\db\ActiveRecord::unlink()|unlink()]] fará com que as chaves estrangeiras na tabela de junção sejam apagadas, ou a deleção da linha correspondente na tabela de junção se `$delete` for `true`.
## Relações Entre Banco de Dados Diferentes <span id="cross-database-relations"></span> ## Relações Entre Banco de Dados Diferentes <span id="cross-database-relations"></span>

4
docs/guide-pt-BR/db-migrations.md

@ -314,8 +314,8 @@ Existem várias maneiras de customizar o comando de migração.
O comando de migração vem com algumas opções de linha de comando que podem ser usadas para customizar o seu comportamento: O comando de migração vem com algumas opções de linha de comando que podem ser usadas para customizar o seu comportamento:
* `interactive`: boolean (o padrão é true), especifica se as migrações serão executadas em modo interativo. * `interactive`: boolean (o padrão é `true`), especifica se as migrações serão executadas em modo interativo.
Quando for true, ao usuário será perguntado se a execução deve continuar antes de o comando executar certas ações. Quando for `true`, ao usuário será perguntado se a execução deve continuar antes de o comando executar certas ações.
Você provavelmente marcará isto para falso se o comando estiver sendo feito em algum processo em segundo plano. Você provavelmente marcará isto para falso se o comando estiver sendo feito em algum processo em segundo plano.
* `migrationPath`: string (o padrão é `@app/migrations`), especifica o diretório em que os arquivos das classes de migração estão. Isto pode ser especificado ou como um diretório ou como um [alias](concept-aliases.md). * `migrationPath`: string (o padrão é `@app/migrations`), especifica o diretório em que os arquivos das classes de migração estão. Isto pode ser especificado ou como um diretório ou como um [alias](concept-aliases.md).

2
docs/guide-pt-BR/db-query-builder.md

@ -272,7 +272,7 @@ $query->filterWhere([
A única diferença entre [[yii\db\Query::filterWhere()|filterWhere()]] e [[yii\db\Query::where()|where()]] é que o primeiro irá ignorar valores vazios fornecidos na condição no [formato hash](#hash-format). Então se `$email` for vazio e `$username` não, o código acima resultará um SQL como: `...WHERE username=:username`. A única diferença entre [[yii\db\Query::filterWhere()|filterWhere()]] e [[yii\db\Query::where()|where()]] é que o primeiro irá ignorar valores vazios fornecidos na condição no [formato hash](#hash-format). Então se `$email` for vazio e `$username` não, o código acima resultará um SQL como: `...WHERE username=:username`.
> Observação: Um valor é considerado vazio se ele for null, um array vazio, uma string vazia ou uma string que consiste em apenas espaços em branco. Assim como [[yii\db\Query::andWhere()|andWhere()]] e [[yii\db\Query::orWhere()|orWhere()]], você pode usar [[yii\db\Query::andFilterWhere()|andFilterWhere()]] e [[yii\db\Query::orFilterWhere()|orFilterWhere()]] para inserir condições de filtro adicionais. > Observação: Um valor é considerado vazio se ele for `null`, um array vazio, uma string vazia ou uma string que consiste em apenas espaços em branco. Assim como [[yii\db\Query::andWhere()|andWhere()]] e [[yii\db\Query::orWhere()|orWhere()]], você pode usar [[yii\db\Query::andFilterWhere()|andFilterWhere()]] e [[yii\db\Query::orFilterWhere()|orFilterWhere()]] para inserir condições de filtro adicionais.
### [[yii\db\Query::orderBy()|orderBy()]] <span id="order-by"></span> ### [[yii\db\Query::orderBy()|orderBy()]] <span id="order-by"></span>

2
docs/guide-pt-BR/helper-url.md

@ -90,7 +90,7 @@ O primeiro argumento pode ser:
- uma string vazia: A URL da requisição corrente será retornado; - uma string vazia: A URL da requisição corrente será retornado;
- uma string normal: será devolvida como ele foi passada (como ela é). - uma string normal: será devolvida como ele foi passada (como ela é).
Quando `$scheme` é espefificado (como uma string ou true),uma URL absoluta com informações do host (obtida de Quando `$scheme` é espefificado (como uma string ou `true`),uma URL absoluta com informações do host (obtida de
[[\yii\web\UrlManager::hostInfo]]) será retornada. Se `$url` já é uma URL absoluta, seu scheme [[\yii\web\UrlManager::hostInfo]]) será retornada. Se `$url` já é uma URL absoluta, seu scheme
irá ser substituído pelo o especificado. irá ser substituído pelo o especificado.

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

@ -112,7 +112,7 @@ Ao disponibilizar recursos por meio de APIs RESTful, muitas vezes você precisa
* se o usuário não tiver acesso, uma [[ForbiddenHttpException]] deve ser lançada. * se o usuário não tiver acesso, uma [[ForbiddenHttpException]] deve ser lançada.
* *
* @param string $action o ID da ação a ser executada * @param string $action o ID da ação a ser executada
* @param \yii\base\Model $model o model a ser acessado. Se null, isso significa que nenhum model específico está sendo acessado. * @param \yii\base\Model $model o model a ser acessado. Se `null`, isso significa que nenhum model específico está sendo acessado.
* @param array $params parâmetros adicionais * @param array $params parâmetros adicionais
* @throws ForbiddenHttpException se o usuário não tiver acesso * @throws ForbiddenHttpException se o usuário não tiver acesso
*/ */

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

@ -131,7 +131,7 @@ class User extends ActiveRecord implements IdentityInterface
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]]: É 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]]:
```php ```php
// identidade do usuário atual. Null se o usuário não estiver autenticado. // identidade do usuário atual. Null se o usuário não estiver autenticado.
@ -157,7 +157,7 @@ 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. 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: Para realizar o logout de um usuário, simplesmente chame:
@ -173,9 +173,9 @@ 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: 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()]]. * [[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_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. * [[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

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

@ -444,7 +444,7 @@ $auth->addChild($admin, $author);
// ... adiciona permissões como filhas de $admin ... // ... adiciona permissões como filhas de $admin ...
``` ```
Note que no exemplo acima, porque "author" é adicionado como filho de "admin", quando você implementar o método `execute()` da classe rule, você também precisa respeitar essa hierarquia. É por isso que quando o nome da role é "author", o método `execute()` retornará true se o grupo de usuário for 1 or 2 (significa que o usuário está no grupo "admin" ou "author"). Note que no exemplo acima, porque "author" é adicionado como filho de "admin", quando você implementar o método `execute()` da classe rule, você também precisa respeitar essa hierarquia. É por isso que quando o nome da role é "author", o método `execute()` retornará `true` se o grupo de usuário for 1 or 2 (significa que o usuário está no grupo "admin" ou "author").
Em seguida, configure `authManager` listando as duas roles [[yii\rbac\BaseManager::$defaultRoles]]: Em seguida, configure `authManager` listando as duas roles [[yii\rbac\BaseManager::$defaultRoles]]:
@ -461,7 +461,7 @@ return [
]; ];
``` ```
Agora, se você executar uma verificação de acesso, ambas as roles `admin` e `author` serão verificadas através da avaliação das regras associado com elas. se a regra retornar true, isso significa que a role se aplica ao usuário atual. A partir da implementação da regra acima, isto significa que se o valor do ‘grupo’ de um usuário for 1, a role `admin` seria aplicável ao usuário; e se o valor do `grupo` for 2, seria a role `author`. Agora, se você executar uma verificação de acesso, ambas as roles `admin` e `author` serão verificadas através da avaliação das regras associado com elas. se a regra retornar `true`, isso significa que a role se aplica ao usuário atual. A partir da implementação da regra acima, isto significa que se o valor do ‘grupo’ de um usuário for 1, a role `admin` seria aplicável ao usuário; e se o valor do `grupo` for 2, seria a role `author`.

2
docs/guide-pt-BR/structure-assets.md

@ -434,7 +434,7 @@ as propriedades [[yii\web\AssetManager::basePath|basePath]] e
Ao invés de publicar os assets pela cópia de arquivos, você pode considerar o uso Ao invés de publicar os assets pela cópia de arquivos, você pode considerar o uso
de links simbólicos, caso o seu sistema operacional e o servidor Web permita-os. de links simbólicos, caso o seu sistema operacional e o servidor Web permita-os.
Este recurso pode ser habilitado definindo o Este recurso pode ser habilitado definindo o
[[yii\web\AssetManager::linkAssets|linkAssets]] como true. [[yii\web\AssetManager::linkAssets|linkAssets]] como `true`.
```php ```php
return [ return [

2
docs/guide-pt-BR/structure-controllers.md

@ -456,7 +456,7 @@ ao seguinte ciclo de vida para concluir a requisição:
* Se o ID da ação for encontrada para corresponder a um método de ação, uma ação inline será criada; * Se o ID da ação for encontrada para corresponder a um método de ação, uma ação inline será criada;
* Caso contrário, uma exceção [[yii\base\InvalidRouteException]] será lançada. * Caso contrário, uma exceção [[yii\base\InvalidRouteException]] será lançada.
3. De forma sequencial, o controller chama o método `beforeAction()` da aplicação, o módulo (se o controller pertencer a um módulo) e o controller. 3. De forma sequencial, o controller chama o método `beforeAction()` da aplicação, o módulo (se o controller pertencer a um módulo) e o controller.
* Se uma das chamadas retornar false, o restante dos métodos subsequentes `beforeAction()` serão ignoradas e a execução da ação será cancelada. * Se uma das chamadas retornar `false`, o restante dos métodos subsequentes `beforeAction()` serão ignoradas e a execução da ação será cancelada.
* Por padrão, cada método `beforeAction()` desencadeia a execução de um evento chamado `beforeAction` na qual você pode associar a uma função (handler). * Por padrão, cada método `beforeAction()` desencadeia a execução de um evento chamado `beforeAction` na qual você pode associar a uma função (handler).
4. O controller executa a ação: 4. O controller executa a ação:
* Os parâmetros da ação serão analizados e populados a partir dos dados obtidos pela requisição; * Os parâmetros da ação serão analizados e populados a partir dos dados obtidos pela requisição;

4
docs/guide-pt-BR/structure-models.md

@ -266,8 +266,8 @@ mensagens apropriadas de erros serão exibidas para ajudar o usuário a corrigi-
Você pode chamar o método [[yii\base\Model::validate()]] para validar os dados Você pode chamar o método [[yii\base\Model::validate()]] para validar os dados
recebidos. O método usará as regras de validação declaradas em [[yii\base\Model::rules()]] recebidos. O método usará as regras de validação declaradas em [[yii\base\Model::rules()]]
para validar todos os atributos relevantes. Se nenhum erro for encontrado, o método para validar todos os atributos relevantes. Se nenhum erro for encontrado, o método
retornará true. Caso contrário, o método irá manter os erros na propriedade retornará `true`. Caso contrário, o método irá manter os erros na propriedade
[[yii\base\Model::errors]] e retornará false. Por exemplo, [[yii\base\Model::errors]] e retornará `false`. Por exemplo,
```php ```php
$model = new \app\models\ContactForm; $model = new \app\models\ContactForm;

2
docs/guide-pt-BR/structure-modules.md

@ -186,7 +186,7 @@ $module = MyModuleClass::getInstance();
O `MyModuleClass` refere-se ao nome da classe do módulo que você está interessado. O `MyModuleClass` refere-se ao nome da classe do módulo que você está interessado.
O método `getInstance()` retornará a instância que foi solicitada pela requisição. O método `getInstance()` retornará a instância que foi solicitada pela requisição.
Se o módulo não for solicitado pela requisição, o método retornará null. Observe Se o módulo não for solicitado pela requisição, o método retornará `null`. Observe
que você não vai querer criar uma nova instância manualmente da classe do módulo que você não vai querer criar uma nova instância manualmente da classe do módulo
pois será diferente do criado pelo Yii em resposta a uma requisição. pois será diferente do criado pelo Yii em resposta a uma requisição.

2
docs/guide-pt-BR/structure-views.md

@ -757,7 +757,7 @@ antes de serem enviados para os usuários finais.
- [[yii\base\View::EVENT_BEFORE_RENDER|EVENT_BEFORE_RENDER]]: é disparado no - [[yii\base\View::EVENT_BEFORE_RENDER|EVENT_BEFORE_RENDER]]: é disparado no
início da renderização de um arquivo no controlador. Na função deste evento início da renderização de um arquivo no controlador. Na função deste evento
pode definir a propriedade [[yii\base\ViewEvent::isValid]] como false para pode definir a propriedade [[yii\base\ViewEvent::isValid]] como `false` para
cancelar o processo de renderização. cancelar o processo de renderização.
- [[yii\base\View::EVENT_AFTER_RENDER|EVENT_AFTER_RENDER]]: é disparado depois - [[yii\base\View::EVENT_AFTER_RENDER|EVENT_AFTER_RENDER]]: é disparado depois
da renderização de um arquivo pela chamada do método [[yii\base\View::afterRender()]]. da renderização de um arquivo pela chamada do método [[yii\base\View::afterRender()]].

44
docs/guide-pt-BR/tutorial-core-validators.md

@ -170,7 +170,7 @@ Este validador verifica se o valor de entrada é um double. É equivalente ao va
Este validador só funciona com um atributo array. Ele valida *todos* os elementos do array com uma regra de validação especificada. No exemplo acima, o atributo `categoryIDs` deve ter um array e cada elemento do array será validado pela regra de validação `integer`. Este validador só funciona com um atributo array. Ele valida *todos* os elementos do array com uma regra de validação especificada. No exemplo acima, o atributo `categoryIDs` deve ter um array e cada elemento do array será validado pela regra de validação `integer`.
- `rule`: um array especificando as regras de validação. O primeiro elemento do array determina o nome da classe ou o alias do validador. O restante dos pares nome-valor no array são utilizados para configurar o objeto do validador. - `rule`: um array especificando as regras de validação. O primeiro elemento do array determina o nome da classe ou o alias do validador. O restante dos pares nome-valor no array são utilizados para configurar o objeto do validador.
- `allowMessageFromRule`: se pretende usar a mensagem de erro retornada pela regra de validação incorporada. Padrão é true. Se for false, ele usará `message` como a mensagem de erro. - `allowMessageFromRule`: se pretende usar a mensagem de erro retornada pela regra de validação incorporada. Padrão é `true`. Se for `false`, ele usará `message` como a mensagem de erro.
> Observação: Se o valor do atributo não for um array, a validação será considerada como falha e a `mensagem` será retornada como erro. > Observação: Se o valor do atributo não for um array, a validação será considerada como falha e a `mensagem` será retornada como erro.
@ -186,9 +186,9 @@ Este validador só funciona com um atributo array. Ele valida *todos* os element
Este validador verifica se o valor de entrada é um endereço de email válido. Este validador verifica se o valor de entrada é um endereço de email válido.
- `allowName`: permitir nome no endereço de email (ex. `John Smith <john.smith@example.com>`). O padrão é false; - `allowName`: permitir nome no endereço de email (ex. `John Smith <john.smith@example.com>`). O padrão é `false`;
- `checkDNS`, para verificar se o domínio do e-mail existe e tem tanto um A ou registro MX. Esteja ciente de que esta verificação pode falhar devido a problemas de DNS temporários, mesmo se o endereço de e-mail for realmente válido. O padrão é false; - `checkDNS`, para verificar se o domínio do e-mail existe e tem tanto um A ou registro MX. Esteja ciente de que esta verificação pode falhar devido a problemas de DNS temporários, mesmo se o endereço de e-mail for realmente válido. O padrão é `false`;
- `enableIDN`, se o processo de validação deve verificar uma conta IDN (internationalized domain names). O padrão é false. Observe que para usar a validação IDN você deve instalar e habilitar a extensão PHP `intl`, caso contrário uma exceção será lançada. - `enableIDN`, se o processo de validação deve verificar uma conta IDN (internationalized domain names). O padrão é `false`. Observe que para usar a validação IDN você deve instalar e habilitar a extensão PHP `intl`, caso contrário uma exceção será lançada.
## [[yii\validators\ExistValidator|exist]] <span id="exist"></span> ## [[yii\validators\ExistValidator|exist]] <span id="exist"></span>
@ -222,7 +222,7 @@ Você pode usar este validador para validar uma ou várias colunas (ex., a combi
- `targetClass`: o nome da classe [Active Record](db-active-record.md) que deve ser usada para procurar o valor de entrada que está sendo validado. Se não for configurada, a atual classe do model (modelo) que está sendo validado será usada. - `targetClass`: o nome da classe [Active Record](db-active-record.md) que deve ser usada para procurar o valor de entrada que está sendo validado. Se não for configurada, a atual classe do model (modelo) que está sendo validado será usada.
- `targetAttribute`: o nome do atributo em `targetClass` que deve ser utilizado para validar a existência do valor de entrada. Se não for configurado, será usado o nome do atual atributo que está sendo validado. Você pode utilizar um array para validar a existência de múltiplas colunas ao mesmo tempo. Os valores do array são os atributos que serão utilizados para validar a existência, enquanto as chaves são os atributos cujos valores devem ser validados. Se a chave e o valor forem os mesmos, você pode especificar apenas o valor. - `targetAttribute`: o nome do atributo em `targetClass` que deve ser utilizado para validar a existência do valor de entrada. Se não for configurado, será usado o nome do atual atributo que está sendo validado. Você pode utilizar um array para validar a existência de múltiplas colunas ao mesmo tempo. Os valores do array são os atributos que serão utilizados para validar a existência, enquanto as chaves são os atributos cujos valores devem ser validados. Se a chave e o valor forem os mesmos, você pode especificar apenas o valor.
- `filter`: filtro adicional para ser aplicado na consulta do banco de dados utilizada para verificar a existência do valor de entrada. Pode ser uma string ou um array representando a condição da consulta adicional (consulte o formato de condição [[yii\db\Query::where()]]), ou uma função anônima com a assinatura `function ($query)`, onde `$query` é o objeto [[yii\db\Query|Query]] que você pode modificar. - `filter`: filtro adicional para ser aplicado na consulta do banco de dados utilizada para verificar a existência do valor de entrada. Pode ser uma string ou um array representando a condição da consulta adicional (consulte o formato de condição [[yii\db\Query::where()]]), ou uma função anônima com a assinatura `function ($query)`, onde `$query` é o objeto [[yii\db\Query|Query]] que você pode modificar.
- `allowArray`: se permitir que o valor de entrada seja um array. Padrão é false. Se esta propriedade for definida como true e a entrada for um array, então, cada elemento do array deve existir na coluna destinada. Observe que essa propriedade não pode ser definida como true se você estiver validando várias colunas configurando `targetAttribute` como um array. - `allowArray`: se permitir que o valor de entrada seja um array. Padrão é `false`. Se esta propriedade for definida como `true` e a entrada for um array, então, cada elemento do array deve existir na coluna destinada. Observe que essa propriedade não pode ser definida como `true` se você estiver validando várias colunas configurando `targetAttribute` como um array.
## [[yii\validators\FileValidator|file]] <span id="file"></span> ## [[yii\validators\FileValidator|file]] <span id="file"></span>
@ -237,12 +237,12 @@ Você pode usar este validador para validar uma ou várias colunas (ex., a combi
Este validador verifica se o dados de entrada é um arquivo válido. Este validador verifica se o dados de entrada é um arquivo válido.
- `extensions`: uma lista de extensões de arquivos que são permitidos para upload. Pode ser utilizado tanto um array quanto uma string constituída de extensões de arquivos separados por espaços ou por vírgulas (Ex. "gif, jpg"). Os nomes das extensões são case-insensitive. O padrão é null, significa que todas as extensões são permitidas. - `extensions`: uma lista de extensões de arquivos que são permitidos para upload. Pode ser utilizado tanto um array quanto uma string constituída de extensões de arquivos separados por espaços ou por vírgulas (Ex. "gif, jpg"). Os nomes das extensões são case-insensitive. O padrão é `null`, significa que todas as extensões são permitidas.
- `mimeTypes`: uma lista de tipos de arquivos MIME que são permitidos no upload. Pode ser utilizado tanto um array quanto uma string constituída de tipos MIME separados por espaços ou por virgulas (ex. "image/jpeg, image/png"). Os nomes dos tipos MIME são case-insensitivo. O padrão é null, significa que todos os tipos MIME são permitidos. Para mais detalhes, consulte o artigo [common media types](http://en.wikipedia.org/wiki/Internet_media_type#List_of_common_media_types). - `mimeTypes`: uma lista de tipos de arquivos MIME que são permitidos no upload. Pode ser utilizado tanto um array quanto uma string constituída de tipos MIME separados por espaços ou por virgulas (ex. "image/jpeg, image/png"). Os nomes dos tipos MIME são case-insensitivo. O padrão é `null`, significa que todos os tipos MIME são permitidos. Para mais detalhes, consulte o artigo [common media types](http://en.wikipedia.org/wiki/Internet_media_type#List_of_common_media_types).
- `minSize`: o número mínimo de bytes exigido para o arquivo carregado. O padrão é null, significa não ter limite mínimo. - `minSize`: o número mínimo de bytes exigido para o arquivo carregado. O padrão é `null`, significa não ter limite mínimo.
- `maxSize`: o número máximo de bytes exigido para o arquivo carregado. O padrão é null, significa não ter limite máximo. - `maxSize`: o número máximo de bytes exigido para o arquivo carregado. O padrão é `null`, significa não ter limite máximo.
- `maxFiles`: o número máximo de arquivos que o atributo pode receber. O padrão é 1, ou seja, a entrada de dados deve ser composto de um único arquivo. Se o `maxFiles` for maior que 1, então a entrada de dados deve ser composto por um array constituído de no máximo `maxFiles` arquivos. - `maxFiles`: o número máximo de arquivos que o atributo pode receber. O padrão é 1, ou seja, a entrada de dados deve ser composto de um único arquivo. Se o `maxFiles` for maior que 1, então a entrada de dados deve ser composto por um array constituído de no máximo `maxFiles` arquivos.
- `checkExtensionByMimeType`: verificação da extensão do arquivo por tipo MIME do arquivo. Se a extensão produzido pela verificação do tipo MIME difere da extensão do arquivo carregado, o arquivo será considerado inválido. O padrão é true, o que significa realizar tal verificação. - `checkExtensionByMimeType`: verificação da extensão do arquivo por tipo MIME do arquivo. Se a extensão produzido pela verificação do tipo MIME difere da extensão do arquivo carregado, o arquivo será considerado inválido. O padrão é `true`, o que significa realizar tal verificação.
`FileValidator` é usado junto com [[yii\web\UploadedFile]]. Consulte a seção [Upload de Arquivos](input-file-upload.md) para mais informações sobre o upload de arquivos e de uma validação sobre os arquivos carregados. `FileValidator` é usado junto com [[yii\web\UploadedFile]]. Consulte a seção [Upload de Arquivos](input-file-upload.md) para mais informações sobre o upload de arquivos e de uma validação sobre os arquivos carregados.
@ -265,7 +265,7 @@ Este validador verifica se o dados de entrada é um arquivo válido.
Este validador não valida dados. Em vez disso, aplica um filtro no valor de entrada e retorna para o atributo que está sendo validado. Este validador não valida dados. Em vez disso, aplica um filtro no valor de entrada e retorna para o atributo que está sendo validado.
- `filter`: um PHP callback que define um filtro. Pode ser um nome de função global, uma função anônima, etc. A assinatura da função deve ser `function ($value) { return $newValue; }`. Esta propriedade deve ser definida. - `filter`: um PHP callback que define um filtro. Pode ser um nome de função global, uma função anônima, etc. A assinatura da função deve ser `function ($value) { return $newValue; }`. Esta propriedade deve ser definida.
- `skipOnArray`: para ignorar o filtro se o valor de entrada for um array. O padrão é false. Observe que se o filtro não puder manipular a entrada de array, você deve configurar esta propriedade como true. De outra forma algum erro do PHP deve ocorrer. - `skipOnArray`: para ignorar o filtro se o valor de entrada for um array. O padrão é `false`. Observe que se o filtro não puder manipular a entrada de array, você deve configurar esta propriedade como `true`. De outra forma algum erro do PHP deve ocorrer.
> Dica: Se você quiser trimar valores de entrada, você deve utilizar o validador [trim](#trim). > Dica: Se você quiser trimar valores de entrada, você deve utilizar o validador [trim](#trim).
@ -294,10 +294,10 @@ Este validador não valida dados. Em vez disso, aplica um filtro no valor de ent
Este validador verifica se o valor de entrada representa um arquivo de imagem válido. Por estender o validador [file](#file), ele herda todas as suas propriedades. Além disso, suporta as seguintes propriedades adicionais específicas para fins de validação de imagem: Este validador verifica se o valor de entrada representa um arquivo de imagem válido. Por estender o validador [file](#file), ele herda todas as suas propriedades. Além disso, suporta as seguintes propriedades adicionais específicas para fins de validação de imagem:
- `minWidth`: a largura mínima da imagem. O padrão é null, significa não ter limite mínimo. - `minWidth`: a largura mínima da imagem. O padrão é `null`, significa não ter limite mínimo.
- `maxWidth`: a largura máxima da imagem. O padrão é null, significa não ter limite máximo. - `maxWidth`: a largura máxima da imagem. O padrão é `null`, significa não ter limite máximo.
- `minHeight`: a altura mínima da imagem. O padrão é null, significa não ter limite mínimo. - `minHeight`: a altura mínima da imagem. O padrão é `null`, significa não ter limite mínimo.
- `maxHeight`: a altura máxima da imagem. O padrão é null, significa não ter limite máximo. - `maxHeight`: a altura máxima da imagem. O padrão é `null`, significa não ter limite máximo.
## [[yii\validators\RangeValidator|in]] <span id="in"></span> ## [[yii\validators\RangeValidator|in]] <span id="in"></span>
@ -313,9 +313,9 @@ Este validador verifica se o valor de entrada pode ser encontrado entre os valor
- `range`: uma lista de determinados valores dentro da qual o valor de entrada deve ser procurado. - `range`: uma lista de determinados valores dentro da qual o valor de entrada deve ser procurado.
- `strict`: se a comparação entre o valor de entrada e os valores dados devem ser strict - `strict`: se a comparação entre o valor de entrada e os valores dados devem ser strict
(o tipo e o valor devem ser idênticos). O padrão é false. (o tipo e o valor devem ser idênticos). O padrão é `false`.
- `not`: se o resultado de validação deve ser invertido. O padrão é false. Quando esta propriedade é definida como true, o validador verifica se o valor de entrada NÃO está entre os valores da lista fornecida. - `not`: se o resultado de validação deve ser invertido. O padrão é `false`. Quando esta propriedade é definida como `true`, o validador verifica se o valor de entrada NÃO está entre os valores da lista fornecida.
- `allowArray`: para permitir que o valor de entrada seja um array. Quando esta propriedade é marcada como true e o valor de entrada é um array, todos os elementos neste array devem ser encontrados na lista de valores fornecida, caso contrário a validação falhará. - `allowArray`: para permitir que o valor de entrada seja um array. Quando esta propriedade é marcada como `true` e o valor de entrada é um array, todos os elementos neste array devem ser encontrados na lista de valores fornecida, caso contrário a validação falhará.
## [[yii\validators\NumberValidator|integer]] <span id="integer"></span> ## [[yii\validators\NumberValidator|integer]] <span id="integer"></span>
@ -345,7 +345,7 @@ Este validador verifica se o valor de entrada é um inteiro.
Este validador verifica se o valor de entrada atende a expressão regular especificada. Este validador verifica se o valor de entrada atende a expressão regular especificada.
- `pattern`: a expressão regular que o valor de entrada deve corresponder. Esta propriedade deve ser configurada, caso contrário uma exceção será lançada. - `pattern`: a expressão regular que o valor de entrada deve corresponder. Esta propriedade deve ser configurada, caso contrário uma exceção será lançada.
- `not`: para inverter o resultado da validação. O padrão é false, significa que a validação terá sucesso apenas se o valor de entrada corresponder ao padrão definido. Se for configurado como true a validação terá sucesso apenas se o valor de entrada NÃO corresponder ao padrão definido. - `not`: para inverter o resultado da validação. O padrão é `false`, significa que a validação terá sucesso apenas se o valor de entrada corresponder ao padrão definido. Se for configurado como `true` a validação terá sucesso apenas se o valor de entrada NÃO corresponder ao padrão definido.
## [[yii\validators\NumberValidator|number]] <span id="number"></span> ## [[yii\validators\NumberValidator|number]] <span id="number"></span>
@ -375,7 +375,7 @@ Este validador verifica se o valor de entrada é um number. É equivalente ao va
Este validador verifica se o valor de entrada foi fornecido e não está vazio. Este validador verifica se o valor de entrada foi fornecido e não está vazio.
- `requiredValue`: o valor desejado que a entrada deve ter. Se não configurado, significa que o valor de entrada apenas não deve estar vazio. - `requiredValue`: o valor desejado que a entrada deve ter. Se não configurado, significa que o valor de entrada apenas não deve estar vazio.
- `strict`: para verificar os tipos de dados ao validar um valor. O padrão é false. Quando `requiredValue` não é configurado, se esta propriedade for true, o validador verificará se o valor de entrada não é estritamente nulo; Se esta propriedade for false, o validador usará uma regra solta para determinar se o valor está vazio ou não. Quando `requiredValue` está configurado, a comparação entre o valor de entrada e `requiredValue` também verificará os tipos de dados se esta propriedade for true. - `strict`: para verificar os tipos de dados ao validar um valor. O padrão é `false`. Quando `requiredValue` não é configurado, se esta propriedade for `true`, o validador verificará se o valor de entrada não é estritamente nulo; Se esta propriedade for `false`, o validador usará uma regra solta para determinar se o valor está vazio ou não. Quando `requiredValue` está configurado, a comparação entre o valor de entrada e `requiredValue` também verificará os tipos de dados se esta propriedade for `true`.
> Observação: Como determinar se um valor está vazio ou não é um tópico separado descrito na seção [Valores Vazios](input-validation.md#handling-empty-inputs). > Observação: Como determinar se um valor está vazio ou não é um tópico separado descrito na seção [Valores Vazios](input-validation.md#handling-empty-inputs).
@ -465,7 +465,7 @@ Este validador verifica se o valor de entrada é único na coluna da tabela. Ele
Este validador verifica se o valor de entrada é uma URL válida. Este validador verifica se o valor de entrada é uma URL válida.
- `validSchemes`: um array especificando o esquema da URI que deve ser considerada válida. O padrão é `['http', 'https']`, significa que ambas URLs `http` e `https` são considerados como válidos. - `validSchemes`: um array especificando o esquema da URI que deve ser considerada válida. O padrão é `['http', 'https']`, significa que ambas URLs `http` e `https` são considerados como válidos.
- `defaultScheme`: o esquema padrão da URI para ser anexado à entrada, se a parte do esquema não for informada na entrada. O padrão é null, significa que o valor de entrada não será modificado. - `defaultScheme`: o esquema padrão da URI para ser anexado à entrada, se a parte do esquema não for informada na entrada. O padrão é `null`, significa que o valor de entrada não será modificado.
- `enableIDN`: se o validador deve ter uma conta IDN (internationalized domain names). O padrão é false. Observe que para usar a validação IDN você tem que instalar e ativar a extenção PHP `intl`, caso contrário uma exceção será lançada. - `enableIDN`: se o validador deve ter uma conta IDN (internationalized domain names). O padrão é `false`. Observe que para usar a validação IDN você tem que instalar e ativar a extenção PHP `intl`, caso contrário uma exceção será lançada.

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

@ -179,7 +179,7 @@ $cache->set($key, $data, 30, $dependency);
// Кэш будет проверен, если данные устарели. // Кэш будет проверен, если данные устарели.
// Он также будет проверен, если указанная зависимость была изменена. // Он также будет проверен, если указанная зависимость была изменена.
// Вернется false, если какое-либо из этих условий выполнено. // Вернется `false`, если какое-либо из этих условий выполнено.
$data = $cache->get($key); $data = $cache->get($key);
``` ```

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

@ -16,7 +16,7 @@ if ($this->beginCache($id)) {
Таким образом заключите то, что вы хотите закэшировать между вызовом [[yii\base\View::beginCache()|beginCache()]] и Таким образом заключите то, что вы хотите закэшировать между вызовом [[yii\base\View::beginCache()|beginCache()]] и
[[yii\base\View::endCache()|endCache()]]. Если содержимое будет найдено в кэше, [[yii\base\View::beginCache()|beginCache()]] [[yii\base\View::endCache()|endCache()]]. Если содержимое будет найдено в кэше, [[yii\base\View::beginCache()|beginCache()]]
отобразит закэшированное содержимое и вернёт false, минуя генерацию содержимого. отобразит закэшированное содержимое и вернёт `false`, минуя генерацию содержимого.
В противном случае, будет выполнен код генерации контента и когда будет вызван [[yii\base\View::endCache()|endCache()]], то сгенерированное содержимое будет записано и сохранено в кэше. В противном случае, будет выполнен код генерации контента и когда будет вызван [[yii\base\View::endCache()|endCache()]], то сгенерированное содержимое будет записано и сохранено в кэше.
Также как и [кэширование данных](caching-data.md), для кэширования фрагментов требуется уникальный идентификатор для определения кэшируемого фрагмента. Также как и [кэширование данных](caching-data.md), для кэширования фрагментов требуется уникальный идентификатор для определения кэшируемого фрагмента.

8
docs/guide-ru/concept-configurations.md

@ -155,7 +155,7 @@ echo Menu::widget([
]); ]);
``` ```
Данный код создает виджет `Menu` и устанавливает параметр виджета `activeItems` в значение false. Данный код создает виджет `Menu` и устанавливает параметр виджета `activeItems` в значение `false`.
Также устанавливается параметр `items`, состоящий из элементов меню. Также устанавливается параметр `items`, состоящий из элементов меню.
Обратите внимание что параметр `class` НЕ передается, так как полное имя уже указано. Обратите внимание что параметр `class` НЕ передается, так как полное имя уже указано.
@ -246,10 +246,10 @@ defined('YII_ENV') or define('YII_ENV', 'dev');
`YII_ENV` может принимать следующие значения: `YII_ENV` может принимать следующие значения:
- `prod`: окружение production, т.е. эксплуатационный режим сервера. Константа `YII_ENV_PROD` установлена в true. - `prod`: окружение production, т.е. эксплуатационный режим сервера. Константа `YII_ENV_PROD` установлена в `true`.
Значение по умолчанию. Значение по умолчанию.
- `dev`: окружение development, т.е. режим для разработки. Константа `YII_ENV_DEV` установлена в true. - `dev`: окружение development, т.е. режим для разработки. Константа `YII_ENV_DEV` установлена в `true`.
- `test`: окружение testing, т.е. режим для тестирования. Константа `YII_ENV_TEST` установлена в true. - `test`: окружение testing, т.е. режим для тестирования. Константа `YII_ENV_TEST` установлена в `true`.
Используя эти константы, вы можете задать в конфигурации значения параметров зависящие от текущего окружения. Используя эти константы, вы можете задать в конфигурации значения параметров зависящие от текущего окружения.
Например, чтобы включить [отладочную панель и отладчик](tool-debugger.md) в режиме разработки, вы можете использовать Например, чтобы включить [отладочную панель и отладчик](tool-debugger.md) в режиме разработки, вы можете использовать

4
docs/guide-ru/concept-events.md

@ -72,7 +72,7 @@ function function_name($event) {
Порядок обработки событий Порядок обработки событий
------------------- -------------------
К одному событию можно присоединить несколько обработчиков. При срабатывании события обработчики будут вызываться в том порядке, к котором они присоединялись к событию. Чтобы запретить в обработчике вызов всех следующих за ним обработчиков, необходимо установить свойство [[yii\base\Event::handled]] параметра `$event` в true: К одному событию можно присоединить несколько обработчиков. При срабатывании события обработчики будут вызываться в том порядке, к котором они присоединялись к событию. Чтобы запретить в обработчике вызов всех следующих за ним обработчиков, необходимо установить свойство [[yii\base\Event::handled]] параметра `$event` в `true`:
```php ```php
$foo->on(Foo::EVENT_HELLO, function ($event) { $foo->on(Foo::EVENT_HELLO, function ($event) {
@ -82,7 +82,7 @@ $foo->on(Foo::EVENT_HELLO, function ($event) {
По умолчанию, новые обработчики присоединяются к концу очереди обработчиков, уже существующей у события. По умолчанию, новые обработчики присоединяются к концу очереди обработчиков, уже существующей у события.
В результате при срабатывании события обработчик выполнится последним. В результате при срабатывании события обработчик выполнится последним.
Чтобы обработчик присоединился к началу очереди и запускался первым, при вызове [[yii\base\Component::on()]] в качестве четвертого параметра `$append` следует передать false: Чтобы обработчик присоединился к началу очереди и запускался первым, при вызове [[yii\base\Component::on()]] в качестве четвертого параметра `$append` следует передать `false`:
```php ```php
$foo->on(Foo::EVENT_HELLO, function ($event) { $foo->on(Foo::EVENT_HELLO, function ($event) {

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

@ -569,15 +569,15 @@ Customer::deleteAll(['status' => Customer::STATUS_INACTIVE]);
следующий жизненный цикл имеет место: следующий жизненный цикл имеет место:
1. Вызывается [[yii\db\ActiveRecord::beforeValidate()|beforeValidate()]]: инициируется событие 1. Вызывается [[yii\db\ActiveRecord::beforeValidate()|beforeValidate()]]: инициируется событие
[[yii\db\ActiveRecord::EVENT_BEFORE_VALIDATE|EVENT_BEFORE_VALIDATE]]. Если метод возвращает false или свойство [[yii\db\ActiveRecord::EVENT_BEFORE_VALIDATE|EVENT_BEFORE_VALIDATE]]. Если метод возвращает `false` или свойство
события [[yii\base\ModelEvent::isValid]] равно false, оставшиеся шаги не выполняются. события [[yii\base\ModelEvent::isValid]] равно `false`, оставшиеся шаги не выполняются.
2. Осуществляется валидация данных. Если валидация закончилась неудачей, после 3-го шага остальные шаги не выполняются. 2. Осуществляется валидация данных. Если валидация закончилась неудачей, после 3-го шага остальные шаги не выполняются.
3. Вызывается [[yii\db\ActiveRecord::afterValidate()|afterValidate()]]: инициируется событие 3. Вызывается [[yii\db\ActiveRecord::afterValidate()|afterValidate()]]: инициируется событие
[[yii\db\ActiveRecord::EVENT_AFTER_VALIDATE|EVENT_AFTER_VALIDATE]]. [[yii\db\ActiveRecord::EVENT_AFTER_VALIDATE|EVENT_AFTER_VALIDATE]].
4. Вызывается [[yii\db\ActiveRecord::beforeSave()|beforeSave()]]: инициируется событие 4. Вызывается [[yii\db\ActiveRecord::beforeSave()|beforeSave()]]: инициируется событие
[[yii\db\ActiveRecord::EVENT_BEFORE_INSERT|EVENT_BEFORE_INSERT]] или событие [[yii\db\ActiveRecord::EVENT_BEFORE_INSERT|EVENT_BEFORE_INSERT]] или событие
[[yii\db\ActiveRecord::EVENT_BEFORE_UPDATE|EVENT_BEFORE_UPDATE]]. Если метод возвращает false или свойство события [[yii\db\ActiveRecord::EVENT_BEFORE_UPDATE|EVENT_BEFORE_UPDATE]]. Если метод возвращает `false` или свойство события
[[yii\base\ModelEvent::isValid]] равно false, оставшиеся шаги не выполняются. [[yii\base\ModelEvent::isValid]] равно `false`, оставшиеся шаги не выполняются.
5. Осуществляется фактическая вставка или обновление данных в базу данных; 5. Осуществляется фактическая вставка или обновление данных в базу данных;
6. Вызывается [[yii\db\ActiveRecord::afterSave()|afterSave()]]: инициируется событие 6. Вызывается [[yii\db\ActiveRecord::afterSave()|afterSave()]]: инициируется событие
[[yii\db\ActiveRecord::EVENT_AFTER_INSERT|EVENT_AFTER_INSERT]] или событие [[yii\db\ActiveRecord::EVENT_AFTER_INSERT|EVENT_AFTER_INSERT]] или событие
@ -590,8 +590,8 @@ Customer::deleteAll(['status' => Customer::STATUS_INACTIVE]);
жизненный цикл имеет место: жизненный цикл имеет место:
1. Вызывается [[yii\db\ActiveRecord::beforeDelete()|beforeDelete()]]: инициируется событие 1. Вызывается [[yii\db\ActiveRecord::beforeDelete()|beforeDelete()]]: инициируется событие
[[yii\db\ActiveRecord::EVENT_BEFORE_DELETE|EVENT_BEFORE_DELETE]]. Если метод возвращает false или свойство события [[yii\db\ActiveRecord::EVENT_BEFORE_DELETE|EVENT_BEFORE_DELETE]]. Если метод возвращает `false` или свойство события
[[yii\base\ModelEvent::isValid]] равно false, остальные шаги не выполняются. [[yii\base\ModelEvent::isValid]] равно `false`, остальные шаги не выполняются.
2. Осуществляется фактическое удаление данных из базы данных. 2. Осуществляется фактическое удаление данных из базы данных.
3. Вызывается [[yii\db\ActiveRecord::afterDelete()|afterDelete()]]: инициируется событие 3. Вызывается [[yii\db\ActiveRecord::afterDelete()|afterDelete()]]: инициируется событие
[[yii\db\ActiveRecord::EVENT_AFTER_DELETE|EVENT_AFTER_DELETE]]. [[yii\db\ActiveRecord::EVENT_AFTER_DELETE|EVENT_AFTER_DELETE]].
@ -1094,7 +1094,7 @@ $customers = Customer::find()
Вызов метода [[yii\db\ActiveQuery::joinWith()|joinWith()]] будет [жадно загружать](#lazy-eager-loading) связные данные Вызов метода [[yii\db\ActiveQuery::joinWith()|joinWith()]] будет [жадно загружать](#lazy-eager-loading) связные данные
по умолчанию. Если вы не хотите получать связные данные, вы можете передать во втором параметре `$eagerLoading` значение по умолчанию. Если вы не хотите получать связные данные, вы можете передать во втором параметре `$eagerLoading` значение
false. `false`.
Подобно методу [[yii\db\ActiveQuery::with()|with()]] вы можете объединять данные с одной или несколькими связями; вы Подобно методу [[yii\db\ActiveQuery::with()|with()]] вы можете объединять данные с одной или несколькими связями; вы
можете настроить запрос на получение связных данных "на лету"; вы можете объединять данные с вложенными связями; вы можете настроить запрос на получение связных данных "на лету"; вы можете объединять данные с вложенными связями; вы
@ -1276,11 +1276,11 @@ $customer->unlink('orders', $customer->orders[0]);
По умолчанию метод [[yii\db\ActiveRecord::unlink()|unlink()]] задаст вторичному ключу (или ключам), который определяет По умолчанию метод [[yii\db\ActiveRecord::unlink()|unlink()]] задаст вторичному ключу (или ключам), который определяет
существующую связь, значение `null`. Однако вы можете запросить удаление строки таблицы, которая содержит значение существующую связь, значение `null`. Однако вы можете запросить удаление строки таблицы, которая содержит значение
вторичного ключа, передав значение true в параметре `$delete` для этого метода. вторичного ключа, передав значение `true` в параметре `$delete` для этого метода.
Если связь построена на основе промежуточной таблицы, вызов метода [[yii\db\ActiveRecord::unlink()|unlink()]] инициирует Если связь построена на основе промежуточной таблицы, вызов метода [[yii\db\ActiveRecord::unlink()|unlink()]] инициирует
очистку вторичных ключей в промежуточной таблице, или же удаление соответствующей строки данных в промежуточной таблице, очистку вторичных ключей в промежуточной таблице, или же удаление соответствующей строки данных в промежуточной таблице,
если параметр `$delete` равен true. если параметр `$delete` равен `true`.
## Связывание объектов из разных баз данных <span id="cross-database-relations"></span> ## Связывание объектов из разных баз данных <span id="cross-database-relations"></span>

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

@ -124,7 +124,7 @@ class m150101_185401_create_news_table extends Migration
Когда миграция применяется к конкретной базе данных, абстрактные типы будут переведены в соответствующие физические типы. Когда миграция применяется к конкретной базе данных, абстрактные типы будут переведены в соответствующие физические типы.
В случае с MySQL, `TYPE_PK` будет превращено в `int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY`, а `TYPE_STRING` станет `varchar(255)`. В случае с MySQL, `TYPE_PK` будет превращено в `int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY`, а `TYPE_STRING` станет `varchar(255)`.
Вы можете добавить дополнительные ограничения при использовании абстрактных типов. В приведенном выше примере, ` NOT NULL` добавляется к `Schema::TYPE_STRING` чтобы указать, что столбец не может быть NULL. Вы можете добавить дополнительные ограничения при использовании абстрактных типов. В приведенном выше примере, ` NOT NULL` добавляется к `Schema::TYPE_STRING` чтобы указать, что столбец не может быть `NULL`.
> Info: Сопоставление абстрактных типов и физических типов определяется свойством [[yii\db\QueryBuilder::$typeMap|$typeMap]] в каждом конкретном `QueryBuilder` классе. > Info: Сопоставление абстрактных типов и физических типов определяется свойством [[yii\db\QueryBuilder::$typeMap|$typeMap]] в каждом конкретном `QueryBuilder` классе.
@ -534,9 +534,9 @@ yii migrate/mark 1392853618 # используя вре
В команду миграций входит несколько параметров командной строки, которые могут использоваться, для того, чтобы настроить В команду миграций входит несколько параметров командной строки, которые могут использоваться, для того, чтобы настроить
поведение миграции: поведение миграции:
* `interactive`: логический тип - boolean (по умолчанию true). Указывает, следует ли выполнять миграцию в интерактивном * `interactive`: логический тип - boolean (по умолчанию `true`). Указывает, следует ли выполнять миграцию в интерактивном
режиме. Если это значение является - true, то пользователю будет выдан запрос, перед выполнением командой определенных режиме. Если это значение является - `true`, то пользователю будет выдан запрос, перед выполнением командой определенных
действий. Вы можете установить это значение в false если команда используется в фоновом режиме. действий. Вы можете установить это значение в `false` если команда используется в фоновом режиме.
* `migrationPath`: строка - string (по умолчанию `@app/migrations`). Указывает каталог для хранения всех файлов классов * `migrationPath`: строка - string (по умолчанию `@app/migrations`). Указывает каталог для хранения всех файлов классов
миграций. Этот параметр может быть определён либо как путь до директории, либо как [псевдоним](concept-aliases.md) пути. миграций. Этот параметр может быть определён либо как путь до директории, либо как [псевдоним](concept-aliases.md) пути.
@ -564,7 +564,7 @@ yii migrate/mark 1392853618 # используя вре
* `fields`: массив конфигураций столбцов, который используется для генерации кода миграции. По умолчанию пуст. Формат * `fields`: массив конфигураций столбцов, который используется для генерации кода миграции. По умолчанию пуст. Формат
каждой конфигурации `ИМЯ_СТОЛБЦА:ТИП_СТОЛБЦА:ДЕКОРАТОР_СТОЛБЦА`. Например, `--fields=name:string(12):notNull` даст нам каждой конфигурации `ИМЯ_СТОЛБЦА:ТИП_СТОЛБЦА:ДЕКОРАТОР_СТОЛБЦА`. Например, `--fields=name:string(12):notNull` даст нам
столбец типа строка размера 12 с ограничением not null. столбец типа строка размера 12 с ограничением `not null`.
В следующем примере показано, как можно использовать эти параметры. В следующем примере показано, как можно использовать эти параметры.

2
docs/guide-ru/db-query-builder.md

@ -320,7 +320,7 @@ $query->filterWhere([
заключается в игнорировании пустых значений, переданных в условие в [форме массива](#hash-format). Таким образом заключается в игнорировании пустых значений, переданных в условие в [форме массива](#hash-format). Таким образом
если `$email` будет пустым, а `$username` нет, то приведённый выше код сформирует условие `WHERE username=:username`. если `$email` будет пустым, а `$username` нет, то приведённый выше код сформирует условие `WHERE username=:username`.
> Info: значение признаётся пустым, если это null, пустой массив, пустая строка или строка состоящая из одних пробельных символов. > Info: значение признаётся пустым, если это `null`, пустой массив, пустая строка или строка состоящая из одних пробельных символов.
Также вместо [[yii\db\Query::andWhere()|andWhere()]] и [[yii\db\Query::orWhere()|orWhere()]], вы можете использовать Также вместо [[yii\db\Query::andWhere()|andWhere()]] и [[yii\db\Query::orWhere()|orWhere()]], вы можете использовать
[[yii\db\Query::andFilterWhere()|andFilterWhere()]] и [[yii\db\Query::orFilterWhere()|orFilterWhere()]] [[yii\db\Query::andFilterWhere()|andFilterWhere()]] и [[yii\db\Query::orFilterWhere()|orFilterWhere()]]

2
docs/guide-ru/helper-array.md

@ -41,7 +41,7 @@ $fullName = ArrayHelper::getValue($user, function ($user, $defaultValue) {
}); });
``` ```
Третий, необязательный, аргумент определяет значение по-умолчанию. Если не установлен – равен null. Используется так: Третий, необязательный, аргумент определяет значение по-умолчанию. Если не установлен – равен `null`. Используется так:
```php ```php
$username = ArrayHelper::getValue($comment, 'user.username', 'Unknown'); $username = ArrayHelper::getValue($comment, 'user.username', 'Unknown');

4
docs/guide-ru/helper-html.md

@ -43,7 +43,7 @@ Html-помощник
Дополнительные атрибуты используются во многих методах Html-помощника и в различных виджетах. Во всех этих случаях в Дополнительные атрибуты используются во многих методах Html-помощника и в различных виджетах. Во всех этих случаях в
дело вступают механизмы дополнительной обработки данных, о которых следует знать: дело вступают механизмы дополнительной обработки данных, о которых следует знать:
- Если значение равно null, соответствующий атрибут не будет выведен. - Если значение равно `null`, соответствующий атрибут не будет выведен.
- Атрибуты, значения которых имеют тип boolean, будут интерпретированы как - Атрибуты, значения которых имеют тип boolean, будут интерпретированы как
[логические атрибуты](http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes). [логические атрибуты](http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes).
- Значения атрибутов будут экранированы с использованием метода [[yii\helpers\Html::encode()|Html::encode()]]. - Значения атрибутов будут экранированы с использованием метода [[yii\helpers\Html::encode()|Html::encode()]].
@ -441,4 +441,4 @@ echo Html::getAttributeName('dates[0]');
}]) ?> }]) ?>
``` ```
Для формирования упорядоченных списков используйте `Html::ol()`. Для формирования упорядоченных списков используйте `Html::ol()`.

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

@ -186,7 +186,7 @@ function ($model, $attribute)
Например, вы хотите обрезать пробелы вокруг `username`. Вы можете использовать правила валидации для Например, вы хотите обрезать пробелы вокруг `username`. Вы можете использовать правила валидации для
достижения этой цели. достижения этой цели.
В следующих примерах показано, как обрезать пробелы в входных данных и превратить пустые входные данные в NULL В следующих примерах показано, как обрезать пробелы в входных данных и превратить пустые входные данные в `NULL`
с помощью [trim](tutorial-core-validators.md#trim) и указать значения по умолчанию с помощью свойства с помощью [trim](tutorial-core-validators.md#trim) и указать значения по умолчанию с помощью свойства
[default](tutorial-core-validators.md#default) основного валидатора: [default](tutorial-core-validators.md#default) основного валидатора:
@ -220,7 +220,7 @@ return [
]; ];
``` ```
По умолчанию входные данные считаются пустыми, если их значением является пустая строка, пустой массив или null. По умолчанию входные данные считаются пустыми, если их значением является пустая строка, пустой массив или `null`.
Вы можете настроить значение по умолчанию с помощью свойства [[yii\validators\Validator::isEmpty]] Вы можете настроить значение по умолчанию с помощью свойства [[yii\validators\Validator::isEmpty]]
используя анонимную функцию. Например: используя анонимную функцию. Например:
@ -231,7 +231,7 @@ return [
``` ```
> Note: большинство валидаторов не обрабатывает пустые входные данные, если их > Note: большинство валидаторов не обрабатывает пустые входные данные, если их
[[yii\base\Validator::skipOnEmpty]] свойство принимает значение по умолчанию true. [[yii\base\Validator::skipOnEmpty]] свойство принимает значение по умолчанию `true`.
Они просто будут пропущены во время проверки, если связанные с ними атрибуты являются пустыми. Они просто будут пропущены во время проверки, если связанные с ними атрибуты являются пустыми.
Среди [основных валидаторов](tutorial-core-validators.md), только `captcha`, `default`, `filter`, Среди [основных валидаторов](tutorial-core-validators.md), только `captcha`, `default`, `filter`,
`required`, и `trim` будут обрабатывать пустые входные данные. `required`, и `trim` будут обрабатывать пустые входные данные.
@ -369,7 +369,7 @@ class MyForm extends Model
получат пустые входные данные, или если они уже не смогли пройти некоторые правила валидации. получат пустые входные данные, или если они уже не смогли пройти некоторые правила валидации.
Если вы хотите, чтобы, это правило применялось всегда, вы можете настроить свойства Если вы хотите, чтобы, это правило применялось всегда, вы можете настроить свойства
[[yii\validators\Validator::skipOnEmpty|skipOnEmpty]] и/или [[yii\validators\Validator::skipOnError|skipOnError]] [[yii\validators\Validator::skipOnEmpty|skipOnEmpty]] и/или [[yii\validators\Validator::skipOnError|skipOnError]]
свойства false в правиле объявления. Например: свойства `false` в правиле объявления. Например:
> >
> ```php > ```php
> [ > [
@ -483,9 +483,9 @@ HTML-форма построена с помощью следующего код
будет срабатывать и проверять введенные данные. будет срабатывать и проверять введенные данные.
Если вы хотите отключить проверку на стороне клиента полностью, вы можете настроить свойство Если вы хотите отключить проверку на стороне клиента полностью, вы можете настроить свойство
[[yii\widgets\ActiveForm::enableClientValidation]] установив значение false. Вы также можете отключить [[yii\widgets\ActiveForm::enableClientValidation]] установив значение `false`. Вы также можете отключить
проверку на стороне клиента отдельных полей ввода, настроив их с помощью свойства проверку на стороне клиента отдельных полей ввода, настроив их с помощью свойства
[[yii\widgets\ActiveField::enableClientValidation]] установив значение false. [[yii\widgets\ActiveField::enableClientValidation]] установив значение `false`.
### Реализация проверки на стороне клиента <span id="implementing-client-side-validation"></span> ### Реализация проверки на стороне клиента <span id="implementing-client-side-validation"></span>

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

@ -26,13 +26,13 @@ Yii поддерживает все выше перечисленные мето
Чтобы включить аутентификацию для ваших API, выполните следующие шаги: Чтобы включить аутентификацию для ваших API, выполните следующие шаги:
1. У [компонента приложения](structure-application-components.md) `user` установите свойство 1. У [компонента приложения](structure-application-components.md) `user` установите свойство
[[yii\web\User::enableSession|enableSession]] равным false. [[yii\web\User::enableSession|enableSession]] равным `false`.
2. Укажите, какие методы аутентификации вы планируете использовать, настроив поведение `authenticator` 2. Укажите, какие методы аутентификации вы планируете использовать, настроив поведение `authenticator`
в ваших классах REST-контроллеров. в ваших классах REST-контроллеров.
3. Реализуйте метод [[yii\web\IdentityInterface::findIdentityByAccessToken()]] в вашем [[yii\web\User::identityClass|классе UserIdentity]]. 3. Реализуйте метод [[yii\web\IdentityInterface::findIdentityByAccessToken()]] в вашем [[yii\web\User::identityClass|классе UserIdentity]].
Шаг 1 не обязателен, но рекомендуется его всё-таки выполнить, так как RESTful API не должен сохранять информацию о Шаг 1 не обязателен, но рекомендуется его всё-таки выполнить, так как RESTful API не должен сохранять информацию о
состоянии клиента. Когда свойство [[yii\web\User::enableSession|enableSession]] установлено в false, состояние состоянии клиента. Когда свойство [[yii\web\User::enableSession|enableSession]] установлено в `false`, состояние
аутентификации пользователя НЕ БУДЕТ сохраняться между запросами с использованием сессий. Вместо этого аутентификация аутентификации пользователя НЕ БУДЕТ сохраняться между запросами с использованием сессий. Вместо этого аутентификация
будет выполняться для каждого запроса, что достигается шагами 2 и 3. будет выполняться для каждого запроса, что достигается шагами 2 и 3.

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

@ -136,7 +136,7 @@ public function prepareDataProvider()
* Если у пользователя нет доступа, следует выбросить исключение [[ForbiddenHttpException]]. * Если у пользователя нет доступа, следует выбросить исключение [[ForbiddenHttpException]].
* *
* @param string $action ID действия, которое надо выполнить * @param string $action ID действия, которое надо выполнить
* @param \yii\base\Model $model модель, к которой нужно получить доступ. Если null, это означает, что модель, к которой нужно получить доступ, отсутствует. * @param \yii\base\Model $model модель, к которой нужно получить доступ. Если `null`, это означает, что модель, к которой нужно получить доступ, отсутствует.
* @param array $params дополнительные параметры * @param array $params дополнительные параметры
* @throws ForbiddenHttpException если у пользователя нет доступа * @throws ForbiddenHttpException если у пользователя нет доступа
*/ */

2
docs/guide-ru/rest-rate-limiting.md

@ -65,5 +65,5 @@ public function behaviors()
* `X-Rate-Limit-Reset`: количество секунд, которое нужно подождать до получения максимального количества разрешённых * `X-Rate-Limit-Reset`: количество секунд, которое нужно подождать до получения максимального количества разрешённых
запросов. запросов.
Вы можете отключить эти заголовки, установив свойство [[yii\filters\RateLimiter::enableRateLimitHeaders]] в false, Вы можете отключить эти заголовки, установив свойство [[yii\filters\RateLimiter::enableRateLimitHeaders]] в `false`,
как показано в примере кода выше. как показано в примере кода выше.

2
docs/guide-ru/rest-routing.md

@ -75,7 +75,7 @@
Как вы могли заметить, ID контроллера `user` в этих точках входа используется в форме множественного числа (как `users`). Как вы могли заметить, ID контроллера `user` в этих точках входа используется в форме множественного числа (как `users`).
Это происходит потому, что [[yii\rest\UrlRule]] автоматически приводит идентификаторы контроллеров к множественной форме. Это происходит потому, что [[yii\rest\UrlRule]] автоматически приводит идентификаторы контроллеров к множественной форме.
Вы можете отключить такое поведение, назначив свойству [[yii\rest\UrlRule::pluralize]] значение false. Вы можете отключить такое поведение, назначив свойству [[yii\rest\UrlRule::pluralize]] значение `false`.
> Info: Приведение ID контроллера к множественной форме производится в методе [[yii\helpers\Inflector::pluralize()]]. > Info: Приведение ID контроллера к множественной форме производится в методе [[yii\helpers\Inflector::pluralize()]].
При этом соблюдаются правила английского языка. Например, `box` будет преобразован в `boxes`, а не в `boxs`. При этом соблюдаются правила английского языка. Например, `box` будет преобразован в `boxes`, а не в `boxs`.

8
docs/guide-ru/runtime-handling-errors.md

@ -10,7 +10,7 @@
* Поддерживаются различные форматы ответа. * Поддерживаются различные форматы ответа.
По умолчанию [[yii\web\ErrorHandler|обработчик ошибок]] включен. Вы можете выключить его объявив константу По умолчанию [[yii\web\ErrorHandler|обработчик ошибок]] включен. Вы можете выключить его объявив константу
`YII_ENABLE_ERROR_HANDLER` со значением false во [входном скрипте](structure-entry-scripts.md) вашего приложения. `YII_ENABLE_ERROR_HANDLER` со значением `false` во [входном скрипте](structure-entry-scripts.md) вашего приложения.
## Использование обработчика ошибок <span id="using-error-handler"></span> ## Использование обработчика ошибок <span id="using-error-handler"></span>
@ -60,8 +60,8 @@ throw new NotFoundHttpException();
## Настройка отображения ошибок <span id="customizing-error-display"></span> ## Настройка отображения ошибок <span id="customizing-error-display"></span>
[[yii\web\ErrorHandler|Обработчик ошибок]] меняет отображение ошибок в зависимости от значения константы `YII_DEBUG`. [[yii\web\ErrorHandler|Обработчик ошибок]] меняет отображение ошибок в зависимости от значения константы `YII_DEBUG`.
При `YII_DEBUG` равной true (режим отладки), обработчик ошибок будет отображать для облегчения отладки детальный стек При `YII_DEBUG` равной `true` (режим отладки), обработчик ошибок будет отображать для облегчения отладки детальный стек
вызовов и исходный код. При `YII_DEBUG` равной false отображается только сообщение об ошибке, тем самым не позволяя вызовов и исходный код. При `YII_DEBUG` равной `false` отображается только сообщение об ошибке, тем самым не позволяя
получить информацию о внутренностях приложения. получить информацию о внутренностях приложения.
> Info: Если исключение является наследником [[yii\base\UserException]], стек вызовов не отображается вне > Info: Если исключение является наследником [[yii\base\UserException]], стек вызовов не отображается вне
@ -71,7 +71,7 @@ throw new NotFoundHttpException();
По умолчанию [[yii\web\ErrorHandler|обработчик ошибок]] показывает ошибки используя два [представления](structure-views.md): По умолчанию [[yii\web\ErrorHandler|обработчик ошибок]] показывает ошибки используя два [представления](structure-views.md):
* `@yii/views/errorHandler/error.php`: используется для отображения ошибок БЕЗ стека вызовов. * `@yii/views/errorHandler/error.php`: используется для отображения ошибок БЕЗ стека вызовов.
При `YII_DEBUG` равной false используется только это преставление. При `YII_DEBUG` равной `false` используется только это преставление.
* `@yii/views/errorHandler/exception.php`: используется для отображения ошибок СО стеком вызовов. * `@yii/views/errorHandler/exception.php`: используется для отображения ошибок СО стеком вызовов.
Вы можете настроить свойства [[yii\web\ErrorHandler::errorView|errorView]] и [[yii\web\ErrorHandler::exceptionView|exceptionView]] Вы можете настроить свойства [[yii\web\ErrorHandler::errorView|errorView]] и [[yii\web\ErrorHandler::exceptionView|exceptionView]]

4
docs/guide-ru/runtime-sessions-cookies.md

@ -261,7 +261,7 @@ unset($cookies['language']);
Кроме свойств [[yii\web\Cookie::name|name]] и [[yii\web\Cookie::value|value]], класс [[yii\web\Cookie]] также предоставляет ряд свойств для получения информации о куках: [[yii\web\Cookie::domain|domain]], [[yii\web\Cookie::expire|expire]]. Эти свойства можно сконфигурировать и затем добавить куку в коллекцию для HTTP-ответа. Кроме свойств [[yii\web\Cookie::name|name]] и [[yii\web\Cookie::value|value]], класс [[yii\web\Cookie]] также предоставляет ряд свойств для получения информации о куках: [[yii\web\Cookie::domain|domain]], [[yii\web\Cookie::expire|expire]]. Эти свойства можно сконфигурировать и затем добавить куку в коллекцию для HTTP-ответа.
> Note: Для большей безопасности значение свойства [[yii\web\Cookie::httpOnly]] по умолчанию установлено в true. Это уменьшает риски доступа к защищенной куке на клиентской стороне (если браузер поддерживает такую возможность). Вы можете обратиться к [httpOnly wiki](https://www.owasp.org/index.php/HttpOnly) для дополнительной информации. > Note: Для большей безопасности значение свойства [[yii\web\Cookie::httpOnly]] по умолчанию установлено в `true`. Это уменьшает риски доступа к защищенной куке на клиентской стороне (если браузер поддерживает такую возможность). Вы можете обратиться к [httpOnly wiki](https://www.owasp.org/index.php/HttpOnly) для дополнительной информации.
### Валидация кук <span id="cookie-validation"></span> ### Валидация кук <span id="cookie-validation"></span>
@ -270,7 +270,7 @@ unset($cookies['language']);
> Note: Валидация кук защищает только от их модификации. Если валидация не была пройдена, получить доступ к кукам все еще можно через глобальную переменную `$_COOKIE`. Это связано с тем, что дополнительные пакеты и библиотеки могут манипулировать куками без вызова валидации, которую обеспечивает Yii. > Note: Валидация кук защищает только от их модификации. Если валидация не была пройдена, получить доступ к кукам все еще можно через глобальную переменную `$_COOKIE`. Это связано с тем, что дополнительные пакеты и библиотеки могут манипулировать куками без вызова валидации, которую обеспечивает Yii.
По-умолчанию валидация кук включена. Её можно отключить, установив свойство [[yii\web\Request::enableCookieValidation]] По-умолчанию валидация кук включена. Её можно отключить, установив свойство [[yii\web\Request::enableCookieValidation]]
в false, однако мы настоятельно не рекомендуем это делать. в `false`, однако мы настоятельно не рекомендуем это делать.
> Note: Куки, которые напрямую читаются/пишутся через `$_COOKIE` и `setcookie()` НЕ БУДУТ валидироваться. > Note: Куки, которые напрямую читаются/пишутся через `$_COOKIE` и `setcookie()` НЕ БУДУТ валидироваться.

2
docs/guide-ru/structure-assets.md

@ -343,7 +343,7 @@ return [
По умолчанию, ресурсы публикуются в директорию `@webroot/assets` которая соответствует URL `@web/assets`. Можно настроить это местоположение сконфигурировав свойства [[yii\web\AssetManager::basePath|basePath]] и [[yii\web\AssetManager::baseUrl|baseUrl]]. По умолчанию, ресурсы публикуются в директорию `@webroot/assets` которая соответствует URL `@web/assets`. Можно настроить это местоположение сконфигурировав свойства [[yii\web\AssetManager::basePath|basePath]] и [[yii\web\AssetManager::baseUrl|baseUrl]].
Вместо публикации ресурсов путём копирования файлов, можно рассмотреть использование символических ссылок, если Ваша операционная система или Web сервер это разрешают. Эта функция может быть включена путем установки [[yii\web\AssetManager::linkAssets|linkAssets]] в true. Вместо публикации ресурсов путём копирования файлов, можно рассмотреть использование символических ссылок, если Ваша операционная система или Web сервер это разрешают. Эта функция может быть включена путем установки [[yii\web\AssetManager::linkAssets|linkAssets]] в `true`.
```php ```php
return [ return [

2
docs/guide-ru/structure-controllers.md

@ -348,7 +348,7 @@ class PostController extends Controller
Для разных запросов параметры действий будут определены следующим образом: Для разных запросов параметры действий будут определены следующим образом:
* `http://hostname/index.php?r=post/view&id=123`: параметр `$id` будет присвоено значение `'123'`, в то время * `http://hostname/index.php?r=post/view&id=123`: параметр `$id` будет присвоено значение `'123'`, в то время
как `$version` будет иметь значение null, т. к. строка запроса не содержит параметра `version`; как `$version` будет иметь значение `null`, т. к. строка запроса не содержит параметра `version`;
* `http://hostname/index.php?r=post/view&id=123&version=2`: параметрам `$id` и `$version` будут присвоены * `http://hostname/index.php?r=post/view&id=123&version=2`: параметрам `$id` и `$version` будут присвоены
значения `'123'` и `'2'` соответственно; значения `'123'` и `'2'` соответственно;
* `http://hostname/index.php?r=post/view`: будет брошено исключение [[yii\web\BadRequestHttpException]], т. к. * `http://hostname/index.php?r=post/view`: будет брошено исключение [[yii\web\BadRequestHttpException]], т. к.

4
docs/guide-ru/structure-entry-scripts.md

@ -85,11 +85,11 @@ exit($exitCode);
* `YII_DEBUG`: указывает работает ли приложение в отладочном режиме. Находясь в отладочном режиме, приложение будет собирать * `YII_DEBUG`: указывает работает ли приложение в отладочном режиме. Находясь в отладочном режиме, приложение будет собирать
больше информации в логи и покажет детальный стек вызовов если возникнет исключение. По этой причине, отладочный режим должен больше информации в логи и покажет детальный стек вызовов если возникнет исключение. По этой причине, отладочный режим должен
быть использован только в процессе разработки. По-умолчанию значение `YII_DEBUG` равно false; быть использован только в процессе разработки. По-умолчанию значение `YII_DEBUG` равно `false`;
* `YII_ENV`: указывает в каком окружении запущено приложение. Данная тема подробно описана в разделе [Конфигурации](concept-configurations.md#environment-constants). * `YII_ENV`: указывает в каком окружении запущено приложение. Данная тема подробно описана в разделе [Конфигурации](concept-configurations.md#environment-constants).
По-умолчанию значение `YII_ENV` равно `'prod'`, означающие, что приложение запущено в производственном режиме; По-умолчанию значение `YII_ENV` равно `'prod'`, означающие, что приложение запущено в производственном режиме;
* `YII_ENABLE_ERROR_HANDLER`: указывает нужно ли включать имеющийся в Yii обработчик ошибок. По-умолчанию значение данной константы * `YII_ENABLE_ERROR_HANDLER`: указывает нужно ли включать имеющийся в Yii обработчик ошибок. По-умолчанию значение данной константы
равно true. равно `true`.
При определении константы, мы обычно используем следующий код: При определении константы, мы обычно используем следующий код:

2
docs/guide-ru/structure-modules.md

@ -182,7 +182,7 @@ $module = MyModuleClass::getInstance();
``` ```
где `MyModuleClass` соответствует имени класса модуля, доступ к которому нужно получить. Метод `getInstance()` возвращает где `MyModuleClass` соответствует имени класса модуля, доступ к которому нужно получить. Метод `getInstance()` возвращает
запрошенный в данный момент экземпляр класса модуля. Если модуль не запрошен, метод вернет null. Учтите, что обычно запрошенный в данный момент экземпляр класса модуля. Если модуль не запрошен, метод вернет `null`. Учтите, что обычно
экземпляры класса модуля вручную не создаются, так как созданный вручную экземпляр будет отличаться от экземпляра, экземпляры класса модуля вручную не создаются, так как созданный вручную экземпляр будет отличаться от экземпляра,
созданного Yii в качестве ответа на запрос. созданного Yii в качестве ответа на запрос.

50
docs/guide-ru/tutorial-core-validators.md

@ -38,7 +38,7 @@ public function rules()
- `strict`: должна ли проверка учитывать соответствие типов данных `trueValue` или `falseValue`. По умолчанию - `false`. - `strict`: должна ли проверка учитывать соответствие типов данных `trueValue` или `falseValue`. По умолчанию - `false`.
> Note: Из-за того, что как правило данные, полученные из HTML-форм, представляются в виде строки, обычно вам стоит > Note: Из-за того, что как правило данные, полученные из HTML-форм, представляются в виде строки, обычно вам стоит
оставить свойство [[yii\validators\BooleanValidator::strict|strict]] равным false. оставить свойство [[yii\validators\BooleanValidator::strict|strict]] равным `false`.
## [[yii\captcha\CaptchaValidator|captcha]] <span id="captcha"></span> ## [[yii\captcha\CaptchaValidator|captcha]] <span id="captcha"></span>
@ -52,10 +52,10 @@ public function rules()
убедиться, что данные в инпуте соответствуют верификационному коду, отображенному с помощью виджета убедиться, что данные в инпуте соответствуют верификационному коду, отображенному с помощью виджета
[[yii\captcha\Captcha|CAPTCHA]]. [[yii\captcha\Captcha|CAPTCHA]].
- `caseSensitive`: необходимо ли учитывать чувствительность к регистру при сравнении. По умолчанию - false. - `caseSensitive`: необходимо ли учитывать чувствительность к регистру при сравнении. По умолчанию - `false`.
- `captchaAction`: [маршрут](structure-controllers.md#routes), соответствующий - `captchaAction`: [маршрут](structure-controllers.md#routes), соответствующий
[[yii\captcha\CaptchaAction|CAPTCHA action]], который рендерит изображение с *CAPTCHA*. По умолчанию - `'site/captcha'`. [[yii\captcha\CaptchaAction|CAPTCHA action]], который рендерит изображение с *CAPTCHA*. По умолчанию - `'site/captcha'`.
- `skipOnEmpty`: может ли валидация быть пропущена, если *input* пустой. По умолчанию - false, - `skipOnEmpty`: может ли валидация быть пропущена, если *input* пустой. По умолчанию - `false`,
что означает, что *input* обязателен. что означает, что *input* обязателен.
@ -170,11 +170,11 @@ function foo($model, $attribute) {
``` ```
Валидатор проверяет, что значение входящих данных является корректным email-адресом. Валидатор проверяет, что значение входящих данных является корректным email-адресом.
- `allowName`: можно ли передавать в атрибут имя (пример: `John Smith <john.smith@example.com>`). По умолчанию - false. - `allowName`: можно ли передавать в атрибут имя (пример: `John Smith <john.smith@example.com>`). По умолчанию - `false`.
- `checkDNS`, проверяет, существует ли доменное имя для введенного адреса (и A, и MX запись). - `checkDNS`, проверяет, существует ли доменное имя для введенного адреса (и A, и MX запись).
Учтите, что проверка может закончится неудачей, что может быть вызвано временными проблемами с DNS, даже если Учтите, что проверка может закончится неудачей, что может быть вызвано временными проблемами с DNS, даже если
email-адрес корректен. По умолчанию - false. email-адрес корректен. По умолчанию - `false`.
- `enableIDN`, нужно ли учитывать IDN (многоязычные доменные имена). По умолчанию - false. Учтите, что для использования - `enableIDN`, нужно ли учитывать IDN (многоязычные доменные имена). По умолчанию - `false`. Учтите, что для использования
IDN-валидации вам нужно установить и включить PHP расширение `intl`, иначе будет выброшено исключение. IDN-валидации вам нужно установить и включить PHP расширение `intl`, иначе будет выброшено исключение.
@ -216,9 +216,9 @@ function foo($model, $attribute) {
Это может быть строка или массив, представляющие дополнительные условия в запросе (подробнее о формате Это может быть строка или массив, представляющие дополнительные условия в запросе (подробнее о формате
значений запроса: [[yii\db\Query::where()]]), или анонимная функция с сигнатурой `function ($query)`, значений запроса: [[yii\db\Query::where()]]), или анонимная функция с сигнатурой `function ($query)`,
где `$query` - это [[yii\db\Query|Query]] объект, который вы можете модифицировать в функции. где `$query` - это [[yii\db\Query|Query]] объект, который вы можете модифицировать в функции.
- `allowArray`: разрешать ли значению быть массивом. По умолчанию - false. Если свойство установлено в true - `allowArray`: разрешать ли значению быть массивом. По умолчанию - `false`. Если свойство установлено в `true`
и тип входящих данных - массив, тогда каждый его элемент должен существовать в соответствующем столбце таблицы. и тип входящих данных - массив, тогда каждый его элемент должен существовать в соответствующем столбце таблицы.
Помните, что это свойство не может быть установлено в true, если вы валидируете несколько столбцов, передавая Помните, что это свойство не может быть установлено в `true`, если вы валидируете несколько столбцов, передавая
их в `targetAttribute` как массив. их в `targetAttribute` как массив.
@ -252,7 +252,7 @@ function foo($model, $attribute) {
input должен быть файлом в единственном экземпляре. Если больше, чем 1, то атрибут должен быть массивом, input должен быть файлом в единственном экземпляре. Если больше, чем 1, то атрибут должен быть массивом,
состоящим из не более, чем `maxFiles` загруженных файлов. состоящим из не более, чем `maxFiles` загруженных файлов.
- `checkExtensionByMimeType`: нужно ли проверять расширение файла исходя из его MIME-типа. Если они не соответствуют - `checkExtensionByMimeType`: нужно ли проверять расширение файла исходя из его MIME-типа. Если они не соответствуют
друг другу, то файл будет считаться некорректным. По умолчанию - true, то есть проверка будет произведена. друг другу, то файл будет считаться некорректным. По умолчанию - `true`, то есть проверка будет произведена.
`FileValidator` используется вместе с [[yii\web\UploadedFile]]. Пожалуйста, посмотрите раздел `FileValidator` используется вместе с [[yii\web\UploadedFile]]. Пожалуйста, посмотрите раздел
[Загрузка файлов](input-file-upload.md) для более полного понимания загрузки и проверки файлов. [Загрузка файлов](input-file-upload.md) для более полного понимания загрузки и проверки файлов.
@ -279,8 +279,8 @@ function foo($model, $attribute) {
- `filter`: PHP-callback, осуществляющий фильтрацию. Это может быть глобальная php функция, анонимная функция - `filter`: PHP-callback, осуществляющий фильтрацию. Это может быть глобальная php функция, анонимная функция
и т.д. Функция должна выглядеть как `function ($value) { return $newValue; }`. Это свойство обязательно должно и т.д. Функция должна выглядеть как `function ($value) { return $newValue; }`. Это свойство обязательно должно
быть установлено. быть установлено.
- `skipOnArray`: нужно ли пропускать валидацию, если входящим значением является массив. По умолчанию - false. - `skipOnArray`: нужно ли пропускать валидацию, если входящим значением является массив. По умолчанию - `false`.
Помните, что если фильтр не может принимать массив, вы должны установить это значение в true. Иначе могут Помните, что если фильтр не может принимать массив, вы должны установить это значение в `true`. Иначе могут
произойти различные ошибки PHP. произойти различные ошибки PHP.
> Трюк: Если вы хотите удалить пробелы вокруг значений атрибута, вы можете использовать валидатор [trim](#trim). > Трюк: Если вы хотите удалить пробелы вокруг значений атрибута, вы можете использовать валидатор [trim](#trim).
@ -329,22 +329,22 @@ function foo($model, $attribute) {
Валидатор имеет такие свойства: Валидатор имеет такие свойства:
- `ipv4`: может ли проверяемое значение быть IPv4 адрессом. По умолчанию true. - `ipv4`: может ли проверяемое значение быть IPv4 адрессом. По умолчанию `true`.
- `ipv6`: может ли проверяемое значение быть IPv6 адрессом. По умолчанию true. - `ipv6`: может ли проверяемое значение быть IPv6 адрессом. По умолчанию `true`.
- `subnet`: может ли проверяемое значение быть IP адресом с CIDR (подсетью), например `192.168.10.0/24` - `subnet`: может ли проверяемое значение быть IP адресом с CIDR (подсетью), например `192.168.10.0/24`
* `true` - указание подсети обязательно; * `true` - указание подсети обязательно;
* `false` - указание подсети запрещено; * `false` - указание подсети запрещено;
* `null` - указание подсети возможно, но не обязательно. * `null` - указание подсети возможно, но не обязательно.
По умолчанию false. По умолчанию `false`.
- `normalize`: нормализировать ли проверяемый IP адрес без CIDR к IP адресу с наименьшим CIDR - `normalize`: нормализировать ли проверяемый IP адрес без CIDR к IP адресу с наименьшим CIDR
(32 для IPv4 или 128 для IPv6). Свойство действует только если `subnet` не установлен в `false`. Например: (32 для IPv4 или 128 для IPv6). Свойство действует только если `subnet` не установлен в `false`. Например:
* `10.0.1.5` будет приведен к `10.0.1.5/32` * `10.0.1.5` будет приведен к `10.0.1.5/32`
* `2008:db0::1` будет приведен к `2008:db0::1/128` * `2008:db0::1` будет приведен к `2008:db0::1/128`
- `negation`: может ли проверяемое значение иметь символ отрицания `!` в начале, например `!192.168.0.1`. - `negation`: может ли проверяемое значение иметь символ отрицания `!` в начале, например `!192.168.0.1`.
По умолчанию false. По умолчанию `false`.
- `expandIPv6`: разворачивать ли IPv6 адрес в формат полной записи. - `expandIPv6`: разворачивать ли IPv6 адрес в формат полной записи.
Например, IPv6 адрес `2008:db0::1` будет развернут в `2008:0db0:0000:0000:0000:0000:0000:0001`. По умолчанию false. Например, IPv6 адрес `2008:db0::1` будет развернут в `2008:0db0:0000:0000:0000:0000:0000:0001`. По умолчанию `false`.
- `ranges`: массив IPv4 или IPv6 диапазонов, которые разрешены или запрещены. - `ranges`: массив IPv4 или IPv6 диапазонов, которые разрешены или запрещены.
Если свойство не установлено, все IP адреса разрешены. Иначе, правила будут проверяться последовательно до первого Если свойство не установлено, все IP адреса разрешены. Иначе, правила будут проверяться последовательно до первого
@ -392,10 +392,10 @@ IPv4 адрес `192.168.10.128` также разрешен, так как на
- `range`: список значений, с которыми будет сравниваться входящее значение. - `range`: список значений, с которыми будет сравниваться входящее значение.
- `strict`: должно ли сравнение входящего значения со списком значений быть строгим (учитывать тип данных). - `strict`: должно ли сравнение входящего значения со списком значений быть строгим (учитывать тип данных).
По умолчанию false. По умолчанию `false`.
- `not`: должен ли результат проверки быть инвертирован. По умолчанию - false. Если свойство установлено в true, - `not`: должен ли результат проверки быть инвертирован. По умолчанию - `false`. Если свойство установлено в `true`,
валидатор проверяет, что входящее значение НЕ соответствует ни одному из значений, указанных в `range`. валидатор проверяет, что входящее значение НЕ соответствует ни одному из значений, указанных в `range`.
- `allowArray`: устанавливает, допустимо ли использовать массив в качестве входных данных. Если установлено в true - `allowArray`: устанавливает, допустимо ли использовать массив в качестве входных данных. Если установлено в `true`
и входящие данные являются массивом, для каждого элемента входящего массива должно быть найдено соответствие в и входящие данные являются массивом, для каждого элемента входящего массива должно быть найдено соответствие в
`range`. `range`.
@ -429,8 +429,8 @@ IPv4 адрес `192.168.10.128` также разрешен, так как на
- `pattern`: регулярное выражение, с которым должно совпадать входящее значение. Это свойство должно быть установлено, - `pattern`: регулярное выражение, с которым должно совпадать входящее значение. Это свойство должно быть установлено,
иначе будет выброшено исключение. иначе будет выброшено исключение.
- `not`: инвертирует регулярное выражение. По умолчанию false, что значит, что валидация будет успешна, - `not`: инвертирует регулярное выражение. По умолчанию `false`, что значит, что валидация будет успешна,
только если входящее значение совпадают с шаблоном. Если установлено в true, валидация будет успешна, только если входящее значение совпадают с шаблоном. Если установлено в `true`, валидация будет успешна,
только если входящее значение НЕ совпадает с шаблоном. только если входящее значение НЕ совпадает с шаблоном.
@ -463,11 +463,11 @@ IPv4 адрес `192.168.10.128` также разрешен, так как на
- `requiredValue`: желаемое значение, которому должны соответствовать проверяемые данные. Если не установлено, - `requiredValue`: желаемое значение, которому должны соответствовать проверяемые данные. Если не установлено,
это значит, что данные должны быть не пусты. это значит, что данные должны быть не пусты.
- `strict`: учитывать или нет соответствие типу данных при валидации (строгое сравнение). - `strict`: учитывать или нет соответствие типу данных при валидации (строгое сравнение).
Если `requiredValue` не установлено, а это свойство установлено в true, валидатор проверит, что входящее значение Если `requiredValue` не установлено, а это свойство установлено в `true`, валидатор проверит, что входящее значение
строго не соответствует `null`; если свойство установлено в false, валидатор будет проверять значение на пустоту с строго не соответствует `null`; если свойство установлено в `false`, валидатор будет проверять значение на пустоту с
приведением типов. приведением типов.
Если `requiredValue` установлено, сравнение между входящими данными и `requiredValue` будет также учитывать тип Если `requiredValue` установлено, сравнение между входящими данными и `requiredValue` будет также учитывать тип
данных, если это свойство установлено в true. данных, если это свойство установлено в `true`.
> Info: как определить, является ли значение пустым или нет, подробнее рассказывается > Info: как определить, является ли значение пустым или нет, подробнее рассказывается
в секции [Пустые значения](input-validation.md#handling-empty-inputs). в секции [Пустые значения](input-validation.md#handling-empty-inputs).
@ -582,6 +582,6 @@ IPv4 адрес `192.168.10.128` также разрешен, так как на
- `defaultScheme`: схема URI, которая будет присоединена к входящим данным, если в них отсутствует URI-схема. - `defaultScheme`: схема URI, которая будет присоединена к входящим данным, если в них отсутствует URI-схема.
По умолчанию `null`, что значит, что входящие данные не будут изменены. По умолчанию `null`, что значит, что входящие данные не будут изменены.
- `enableIDN`: должна ли валидация учитывать IDN (интернационализованные доменные имена). - `enableIDN`: должна ли валидация учитывать IDN (интернационализованные доменные имена).
По умолчанию - false. Учтите, что для того, чтобы IDN валидация работала корректно, вы должны установить `intl` По умолчанию - `false`. Учтите, что для того, чтобы IDN валидация работала корректно, вы должны установить `intl`
PHP расширение, иначе будет выброшено исключение. PHP расширение, иначе будет выброшено исключение.

2
docs/guide-ru/tutorial-performance-tuning.md

@ -28,7 +28,7 @@
defined('YII_DEBUG') or define('YII_DEBUG', false); defined('YII_DEBUG') or define('YII_DEBUG', false);
``` ```
> Info: Значение по умолчанию для константы `YII_DEBUG` — false. > Info: Значение по умолчанию для константы `YII_DEBUG``false`.
Так что, если вы уверены, что не изменяете значение по умолчанию где-то в коде приложения, можете просто удалить эту Так что, если вы уверены, что не изменяете значение по умолчанию где-то в коде приложения, можете просто удалить эту
строку, чтобы отключить режим отладки. строку, чтобы отключить режим отладки.

2
docs/guide-uk/caching-fragment.md

@ -18,7 +18,7 @@ if ($this->beginCache($id)) {
Таким чином, розташуйте логіку генерування вмісту у комбінацію викликів [[yii\base\View::beginCache()|beginCache()]] та Таким чином, розташуйте логіку генерування вмісту у комбінацію викликів [[yii\base\View::beginCache()|beginCache()]] та
[[yii\base\View::endCache()|endCache()]]. Якщо вміст буде знайдено у кеші, [[yii\base\View::beginCache()|beginCache()]] [[yii\base\View::endCache()|endCache()]]. Якщо вміст буде знайдено у кеші, [[yii\base\View::beginCache()|beginCache()]]
відобразить закешований вміст і поверне false, оминаючи генерування вмісту. відобразить закешований вміст і поверне `false`, оминаючи генерування вмісту.
В іншому випадку, буде виконано логіку генерування вмісту і з викликом [[yii\base\View::endCache()|endCache()]] В іншому випадку, буде виконано логіку генерування вмісту і з викликом [[yii\base\View::endCache()|endCache()]]
згенерований вміст буде записаний до кешу. згенерований вміст буде записаний до кешу.

2
docs/guide-uk/rest-rate-limiting.md

@ -62,5 +62,5 @@ public function behaviors()
* `X-Rate-Limit-Remaining`: скільки залишилось дозволених запитів в поточний період часу * `X-Rate-Limit-Remaining`: скільки залишилось дозволених запитів в поточний період часу
* `X-Rate-Limit-Reset`: скільки часу у секундах потрібно почекати до отримання максимальної кількості дозволених запитів * `X-Rate-Limit-Reset`: скільки часу у секундах потрібно почекати до отримання максимальної кількості дозволених запитів
Ви можете відключити ці заголовки, встановивши властивість [[yii\filters\RateLimiter::enableRateLimitHeaders]] у false, Ви можете відключити ці заголовки, встановивши властивість [[yii\filters\RateLimiter::enableRateLimitHeaders]] у `false`,
як показано у прикладі вище. як показано у прикладі вище.

2
docs/guide-uk/structure-controllers.md

@ -356,7 +356,7 @@ class PostController extends Controller
Параметри дії будуть заповнені для різних запитів наступним чином: Параметри дії будуть заповнені для різних запитів наступним чином:
* `http://hostname/index.php?r=post/view&id=123`: параметру `$id` буде присвоєне значення `'123'`, у той час, * `http://hostname/index.php?r=post/view&id=123`: параметру `$id` буде присвоєне значення `'123'`, у той час,
як `$version` буде мати значення null, бо рядок запиту не містить параметра `version`. як `$version` буде мати значення `null`, бо рядок запиту не містить параметра `version`.
* `http://hostname/index.php?r=post/view&id=123&version=2`: параметрам `$id` і `$version` будуть присвоєні * `http://hostname/index.php?r=post/view&id=123&version=2`: параметрам `$id` і `$version` будуть присвоєні
значення `'123'` і `'2'` відповідно. значення `'123'` і `'2'` відповідно.
* `http://hostname/index.php?r=post/view`: буде отримане виключення [[yii\web\BadRequestHttpException]], оскільки * `http://hostname/index.php?r=post/view`: буде отримане виключення [[yii\web\BadRequestHttpException]], оскільки

2
docs/guide-uk/structure-models.md

@ -237,7 +237,7 @@ class User extends ActiveRecord
Ви можете викликати [[yii\base\Model::validate()|validate()]] для перевірки отриманих даних. Даний метод використає Ви можете викликати [[yii\base\Model::validate()|validate()]] для перевірки отриманих даних. Даний метод використає
правила перевірки, оголошені у [[yii\base\Model::rules()|rules()]], для перевірки кожного необхідного атрибуту. При відсутності правила перевірки, оголошені у [[yii\base\Model::rules()|rules()]], для перевірки кожного необхідного атрибуту. При відсутності
помилок він поверне `true`. В іншому випадку, він збереже помилки у властивості [[yii\base\Model::errors]] помилок він поверне `true`. В іншому випадку, він збереже помилки у властивості [[yii\base\Model::errors]]
та поверне false. Наприклад: та поверне `false`. Наприклад:
```php ```php
$model = new \app\models\ContactForm; $model = new \app\models\ContactForm;

2
docs/guide-uz/structure-controllers.md

@ -346,7 +346,7 @@ class PostController extends Controller
Для разных запросов параметры действий будут определены следующим образом: Для разных запросов параметры действий будут определены следующим образом:
* `http://hostname/index.php?r=post/view&id=123`: параметр `$id` будет присвоено значение `'123'`, в то время * `http://hostname/index.php?r=post/view&id=123`: параметр `$id` будет присвоено значение `'123'`, в то время
как `$version` будет иметь значение null, т. к. строка запроса не содержит параметра `version`; как `$version` будет иметь значение `null`, т. к. строка запроса не содержит параметра `version`;
* `http://hostname/index.php?r=post/view&id=123&version=2`: параметрам `$id` и `$version` будут присвоены * `http://hostname/index.php?r=post/view&id=123&version=2`: параметрам `$id` и `$version` будут присвоены
значения `'123'` и `'2'` соответственно; значения `'123'` и `'2'` соответственно;
* `http://hostname/index.php?r=post/view`: будет брошено исключение [[yii\web\BadRequestHttpException]], т. к. * `http://hostname/index.php?r=post/view`: будет брошено исключение [[yii\web\BadRequestHttpException]], т. к.

2
docs/guide-vi/start-gii.md

@ -34,7 +34,7 @@ Phần cấu hình trên được đề cập ở mục [Môi trường phát tr
ứng dụng bao gồm module tên là `gii`, nằm ở lớp [[yii\gii\Module]]. ứng dụng bao gồm module tên là `gii`, nằm ở lớp [[yii\gii\Module]].
Nếu bạn xem qua file [entry script](structure-entry-scripts.md) `web/index.php` trong ứng dụng của bạn, bạn sẽ thấy dòng sau, Nếu bạn xem qua file [entry script](structure-entry-scripts.md) `web/index.php` trong ứng dụng của bạn, bạn sẽ thấy dòng sau,
Điều này chủ yếu thiết lập tham số `YII_ENV_DEV` có giá trị true. Điều này chủ yếu thiết lập tham số `YII_ENV_DEV` có giá trị `true`.
```php ```php
defined('YII_ENV') or define('YII_ENV', 'dev'); defined('YII_ENV') or define('YII_ENV', 'dev');

2
docs/guide/caching-data.md

@ -296,7 +296,7 @@ components in your web and console application configs to reach the proper effec
Query caching has three global configurable options through [[yii\db\Connection]]: Query caching has three global configurable options through [[yii\db\Connection]]:
* [[yii\db\Connection::enableQueryCache|enableQueryCache]]: whether to turn on or off query caching. * [[yii\db\Connection::enableQueryCache|enableQueryCache]]: whether to turn on or off query caching.
It defaults to true. Note that to effectively turn on query caching, you also need to have a valid It defaults to `true`. Note that to effectively turn on query caching, you also need to have a valid
cache, as specified by [[yii\db\Connection::queryCache|queryCache]]. cache, as specified by [[yii\db\Connection::queryCache|queryCache]].
* [[yii\db\Connection::queryCacheDuration|queryCacheDuration]]: this represents the number of seconds * [[yii\db\Connection::queryCacheDuration|queryCacheDuration]]: this represents the number of seconds
that a query result can remain valid in the cache. You can use 0 to indicate a query result should that a query result can remain valid in the cache. You can use 0 to indicate a query result should

2
docs/guide/caching-fragment.md

@ -18,7 +18,7 @@ if ($this->beginCache($id)) {
That is, enclose content generation logic in a pair of [[yii\base\View::beginCache()|beginCache()]] and That is, enclose content generation logic in a pair of [[yii\base\View::beginCache()|beginCache()]] and
[[yii\base\View::endCache()|endCache()]] calls. If the content is found in the cache, [[yii\base\View::beginCache()|beginCache()]] [[yii\base\View::endCache()|endCache()]] calls. If the content is found in the cache, [[yii\base\View::beginCache()|beginCache()]]
will render the cached content and return false, thus skip the content generation logic. will render the cached content and return `false`, thus skip the content generation logic.
Otherwise, your content generation logic will be called, and when [[yii\base\View::endCache()|endCache()]] Otherwise, your content generation logic will be called, and when [[yii\base\View::endCache()|endCache()]]
is called, the generated content will be captured and stored in the cache. is called, the generated content will be captured and stored in the cache.

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

@ -1032,7 +1032,7 @@ In the code example above, we are modifying the relational query by appending an
> >
> ```php > ```php
> $orders = Order::find()->select(['id', 'amount'])->with('customer')->all(); > $orders = Order::find()->select(['id', 'amount'])->with('customer')->all();
> // $orders[0]->customer is always null. To fix the problem, you should do the following: > // $orders[0]->customer is always `null`. To fix the problem, you should do the following:
> $orders = Order::find()->select(['id', 'amount', 'customer_id'])->with('customer')->all(); > $orders = Order::find()->select(['id', 'amount', 'customer_id'])->with('customer')->all();
> ``` > ```

2
docs/guide/db-dao.md

@ -588,7 +588,7 @@ $rows = Yii::$app->db->useMaster(function ($db) {
}); });
``` ```
You may also directly set `Yii::$app->db->enableSlaves` to be false to direct all queries to the master connection. You may also directly set `Yii::$app->db->enableSlaves` to be `false` to direct all queries to the master connection.
## Working with Database Schema <span id="database-schema"></span> ## Working with Database Schema <span id="database-schema"></span>

10
docs/guide/db-migrations.md

@ -147,7 +147,7 @@ will be translated into the corresponding physical types. In the case of MySQL,
into `int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY`, while `TYPE_STRING` becomes `varchar(255)`. into `int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY`, while `TYPE_STRING` becomes `varchar(255)`.
You can append additional constraints when using abstract types. In the above example, ` NOT NULL` is appended You can append additional constraints when using abstract types. In the above example, ` NOT NULL` is appended
to `Schema::TYPE_STRING` to specify that the column cannot be null. to `Schema::TYPE_STRING` to specify that the column cannot be `null`.
> Info: The mapping between abstract types and physical types is specified by > Info: The mapping between abstract types and physical types is specified by
the [[yii\db\QueryBuilder::$typeMap|$typeMap]] property in each concrete `QueryBuilder` class. the [[yii\db\QueryBuilder::$typeMap|$typeMap]] property in each concrete `QueryBuilder` class.
@ -817,9 +817,9 @@ There are several ways to customize the migration command.
The migration command comes with a few command-line options that can be used to customize its behaviors: The migration command comes with a few command-line options that can be used to customize its behaviors:
* `interactive`: boolean (defaults to true), specifies whether to perform migrations in an interactive mode. * `interactive`: boolean (defaults to `true`), specifies whether to perform migrations in an interactive mode.
When this is true, the user will be prompted before the command performs certain actions. When this is `true`, the user will be prompted before the command performs certain actions.
You may want to set this to false if the command is being used in a background process. You may want to set this to `false` if the command is being used in a background process.
* `migrationPath`: string (defaults to `@app/migrations`), specifies the directory storing all migration * `migrationPath`: string (defaults to `@app/migrations`), specifies the directory storing all migration
class files. This can be specified as either a directory path or a path [alias](concept-aliases.md). class files. This can be specified as either a directory path or a path [alias](concept-aliases.md).
@ -848,7 +848,7 @@ The migration command comes with a few command-line options that can be used to
* `fields`: array of column definition strings used for creating migration code. Defaults to `[]`. The format of each * `fields`: array of column definition strings used for creating migration code. Defaults to `[]`. The format of each
definition is `COLUMN_NAME:COLUMN_TYPE:COLUMN_DECORATOR`. For example, `--fields=name:string(12):notNull` produces definition is `COLUMN_NAME:COLUMN_TYPE:COLUMN_DECORATOR`. For example, `--fields=name:string(12):notNull` produces
a string column of size 12 which is not null. a string column of size 12 which is not `null`.
The following example shows how you can use these options. The following example shows how you can use these options.

2
docs/guide/db-query-builder.md

@ -345,7 +345,7 @@ The only difference between [[yii\db\Query::filterWhere()|filterWhere()]] and [[
is that the former will ignore empty values provided in the condition in [hash format](#hash-format). So if `$email` is that the former will ignore empty values provided in the condition in [hash format](#hash-format). So if `$email`
is empty while `$username` is not, the above code will result in the SQL condition `WHERE username=:username`. is empty while `$username` is not, the above code will result in the SQL condition `WHERE username=:username`.
> Info: A value is considered empty if it is null, an empty array, an empty string or a string consisting of whitespaces only. > Info: A value is considered empty if it is `null`, an empty array, an empty string or a string consisting of whitespaces only.
Like [[yii\db\Query::andWhere()|andWhere()]] and [[yii\db\Query::orWhere()|orWhere()]], you can use Like [[yii\db\Query::andWhere()|andWhere()]] and [[yii\db\Query::orWhere()|orWhere()]], you can use
[[yii\db\Query::andFilterWhere()|andFilterWhere()]] and [[yii\db\Query::orFilterWhere()|orFilterWhere()]] [[yii\db\Query::andFilterWhere()|andFilterWhere()]] and [[yii\db\Query::orFilterWhere()|orFilterWhere()]]

2
docs/guide/helper-array.md

@ -116,7 +116,7 @@ object, or an anonymous function that must return the value that will be used as
The `$groups` attribute is an array of keys, that will be used to group the input array into one or more sub-arrays The `$groups` attribute is an array of keys, that will be used to group the input array into one or more sub-arrays
based on keys specified. based on keys specified.
If the `$key` attribute or its value for the particular element is null and `$groups` is not defined, the array If the `$key` attribute or its value for the particular element is `null` and `$groups` is not defined, the array
element will be discarded. Otherwise, if `$groups` is specified, array element will be added to the result array element will be discarded. Otherwise, if `$groups` is specified, array element will be added to the result array
without any key. without any key.

2
docs/guide/helper-html.md

@ -40,7 +40,7 @@ In case you need just an opening or closing tag, you can use the `Html::beginTag
Options are used in many methods of the Html helper and various widgets. In all these cases there is some extra handling to Options are used in many methods of the Html helper and various widgets. In all these cases there is some extra handling to
know about: know about:
- If a value is null, the corresponding attribute will not be rendered. - If a value is `null`, the corresponding attribute will not be rendered.
- Attributes whose values are of boolean type will be treated as - Attributes whose values are of boolean type will be treated as
[boolean attributes](http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes). [boolean attributes](http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes).
- The values of attributes will be HTML-encoded using [[yii\helpers\Html::encode()|Html::encode()]]. - The values of attributes will be HTML-encoded using [[yii\helpers\Html::encode()|Html::encode()]].

2
docs/guide/helper-url.md

@ -98,7 +98,7 @@ The first argument could be:
- an empty string: the currently requested URL will be returned; - an empty string: the currently requested URL will be returned;
- a normal string: it will be returned as is. - a normal string: it will be returned as is.
When `$scheme` is specified (either a string or true), an absolute URL with host info (obtained from When `$scheme` is specified (either a string or `true`), an absolute URL with host info (obtained from
[[\yii\web\UrlManager::hostInfo]]) will be returned. If `$url` is already an absolute URL, its scheme [[\yii\web\UrlManager::hostInfo]]) will be returned. If `$url` is already an absolute URL, its scheme
will be replaced with the specified one. will be replaced with the specified one.

12
docs/guide/input-validation.md

@ -242,7 +242,7 @@ with a PHP callable. For example,
``` ```
> Note: Most validators do not handle empty inputs if their [[yii\validators\Validator::skipOnEmpty]] property takes > Note: Most validators do not handle empty inputs if their [[yii\validators\Validator::skipOnEmpty]] property takes
the default value true. They will simply be skipped during validation if their associated attributes receive empty the default value `true`. They will simply be skipped during validation if their associated attributes receive empty
inputs. Among the [core validators](tutorial-core-validators.md), only the `captcha`, `default`, `filter`, inputs. Among the [core validators](tutorial-core-validators.md), only the `captcha`, `default`, `filter`,
`required`, and `trim` validators will handle empty inputs. `required`, and `trim` validators will handle empty inputs.
@ -375,7 +375,7 @@ class MyForm extends Model
> Note: By default, inline validators will not be applied if their associated attributes receive empty inputs > Note: By default, inline validators will not be applied if their associated attributes receive empty inputs
or if they have already failed some validation rules. If you want to make sure a rule is always applied, or if they have already failed some validation rules. If you want to make sure a rule is always applied,
you may configure the [[yii\validators\Validator::skipOnEmpty|skipOnEmpty]] and/or [[yii\validators\Validator::skipOnError|skipOnError]] you may configure the [[yii\validators\Validator::skipOnEmpty|skipOnEmpty]] and/or [[yii\validators\Validator::skipOnError|skipOnError]]
properties to be false in the rule declarations. For example: properties to be `false` in the rule declarations. For example:
> >
> ```php > ```php
> [ > [
@ -512,7 +512,7 @@ and generate appropriate JavaScript code for validators that support client-side
changes the value of an input field or submit the form, the client-side validation JavaScript will be triggered. changes the value of an input field or submit the form, the client-side validation JavaScript will be triggered.
If you want to turn off client-side validation completely, you may configure the If you want to turn off client-side validation completely, you may configure the
[[yii\widgets\ActiveForm::enableClientValidation]] property to be false. You may also turn off client-side [[yii\widgets\ActiveForm::enableClientValidation]] property to be `false`. You may also turn off client-side
validation of individual input fields by configuring their [[yii\widgets\ActiveField::enableClientValidation]] validation of individual input fields by configuring their [[yii\widgets\ActiveField::enableClientValidation]]
property to be false. When `enableClientValidation` is configured at both the input field level and the form level, property to be false. When `enableClientValidation` is configured at both the input field level and the form level,
the former will take precedence. the former will take precedence.
@ -666,7 +666,7 @@ You can use AJAX-based validation in this case. It will trigger an AJAX request
input while keeping the same user experience as the regular client-side validation. input while keeping the same user experience as the regular client-side validation.
To enable AJAX validation for a single input field, configure the [[yii\widgets\ActiveField::enableAjaxValidation|enableAjaxValidation]] To enable AJAX validation for a single input field, configure the [[yii\widgets\ActiveField::enableAjaxValidation|enableAjaxValidation]]
property of that field to be true and specify a unique form `id`: property of that field to be `true` and specify a unique form `id`:
```php ```php
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
@ -683,7 +683,7 @@ ActiveForm::end();
``` ```
To enable AJAX validation for the whole form, configure [[yii\widgets\ActiveForm::enableAjaxValidation|enableAjaxValidation]] To enable AJAX validation for the whole form, configure [[yii\widgets\ActiveForm::enableAjaxValidation|enableAjaxValidation]]
to be true at the form level: to be `true` at the form level:
```php ```php
$form = ActiveForm::begin([ $form = ActiveForm::begin([
@ -711,5 +711,5 @@ this request by running the validation and returning the errors in JSON format.
> Info: You can also use [Deferred Validation](#deferred-validation) to perform AJAX validation. > Info: You can also use [Deferred Validation](#deferred-validation) to perform AJAX validation.
However, the AJAX validation feature described here is more systematic and requires less coding effort. However, the AJAX validation feature described here is more systematic and requires less coding effort.
When both `enableClientValidation` and `enableAjaxValidation` are set to true, AJAX validation request will be triggered When both `enableClientValidation` and `enableAjaxValidation` are set to `true`, AJAX validation request will be triggered
only after the successful client validation. only after the successful client validation.

2
docs/guide/output-data-providers.md

@ -39,7 +39,7 @@ $totalCount = $provider->getTotalCount();
You specify the pagination and sorting behaviors of a data provider by configuring its You specify the pagination and sorting behaviors of a data provider by configuring its
[[yii\data\BaseDataProvider::pagination|pagination]] and [[yii\data\BaseDataProvider::sort|sort]] properties [[yii\data\BaseDataProvider::pagination|pagination]] and [[yii\data\BaseDataProvider::sort|sort]] properties
which correspond to the configurations for [[yii\data\Pagination]] and [[yii\data\Sort]], respectively. which correspond to the configurations for [[yii\data\Pagination]] and [[yii\data\Sort]], respectively.
You may also configure them to be false to disable pagination and/or sorting features. You may also configure them to be `false` to disable pagination and/or sorting features.
[Data widgets](output-data-widgets.md), such as [[yii\grid\GridView]], have a property named `dataProvider` which [Data widgets](output-data-widgets.md), such as [[yii\grid\GridView]], have a property named `dataProvider` which
can take a data provider instance and display the data it provides. For example, can take a data provider instance and display the data it provides. For example,

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

@ -272,7 +272,7 @@ Available properties you can configure are:
the callback should be the same as that of [[yii\grid\ActionColumn::createUrl()]]. If this property is not set, the callback should be the same as that of [[yii\grid\ActionColumn::createUrl()]]. If this property is not set,
button URLs will be created using [[yii\grid\ActionColumn::createUrl()]]. button URLs will be created using [[yii\grid\ActionColumn::createUrl()]].
- [[yii\grid\ActionColumn::visibleButtons|visibleButtons]] is an array of visibility conditions for each button. - [[yii\grid\ActionColumn::visibleButtons|visibleButtons]] is an array of visibility conditions for each button.
The array keys are the button names (without curly brackets), and the values are the boolean true/false or the The array keys are the button names (without curly brackets), and the values are the boolean `true`/`false` or the
anonymous function. When the button name is not specified in this array it will be shown by default. anonymous function. When the button name is not specified in this array it will be shown by default.
The callbacks must use the following signature: The callbacks must use the following signature:
@ -576,7 +576,7 @@ $query->andFilterWhere(['LIKE', 'author.name', $this->getAttribute('author.name'
> $query->andFilterWhere(['LIKE', 'au.name', $this->getAttribute('author.name')]); > $query->andFilterWhere(['LIKE', 'au.name', $this->getAttribute('author.name')]);
> ``` > ```
> >
> The same is true for the sorting definition: > The same is `true` for the sorting definition:
> >
> ```php > ```php
> $dataProvider->sort->attributes['author.name'] = [ > $dataProvider->sort->attributes['author.name'] = [

2
docs/guide/rest-authentication.md

@ -33,7 +33,7 @@ To enable authentication for your APIs, do the following steps:
3. Implement [[yii\web\IdentityInterface::findIdentityByAccessToken()]] in your [[yii\web\User::identityClass|user identity class]]. 3. Implement [[yii\web\IdentityInterface::findIdentityByAccessToken()]] in your [[yii\web\User::identityClass|user identity class]].
Step 1 is not required but is recommended for RESTful APIs which should be stateless. When [[yii\web\User::enableSession|enableSession]] Step 1 is not required but is recommended for RESTful APIs which should be stateless. When [[yii\web\User::enableSession|enableSession]]
is false, the user authentication status will NOT be persisted across requests using sessions. Instead, authentication is `false`, the user authentication status will NOT be persisted across requests using sessions. Instead, authentication
will be performed for every request, which is accomplished by Step 2 and 3. will be performed for every request, which is accomplished by Step 2 and 3.
> Tip: You may configure [[yii\web\User::enableSession|enableSession]] of the `user` application component > Tip: You may configure [[yii\web\User::enableSession|enableSession]] of the `user` application component

2
docs/guide/rest-controllers.md

@ -170,7 +170,7 @@ by overriding the [[yii\rest\ActiveController::checkAccess()|checkAccess()]] met
* If the user does not have access, a [[ForbiddenHttpException]] should be thrown. * If the user does not have access, a [[ForbiddenHttpException]] should be thrown.
* *
* @param string $action the ID of the action to be executed * @param string $action the ID of the action to be executed
* @param \yii\base\Model $model the model to be accessed. If null, it means no specific model is being accessed. * @param \yii\base\Model $model the model to be accessed. If `null`, it means no specific model is being accessed.
* @param array $params additional parameters * @param array $params additional parameters
* @throws ForbiddenHttpException if the user does not have access * @throws ForbiddenHttpException if the user does not have access
*/ */

2
docs/guide/rest-rate-limiting.md

@ -62,5 +62,5 @@ the current rate limiting information:
* `X-Rate-Limit-Remaining`, the number of remaining requests in the current time period * `X-Rate-Limit-Remaining`, the number of remaining requests in the current time period
* `X-Rate-Limit-Reset`, the number of seconds to wait in order to get the maximum number of allowed requests * `X-Rate-Limit-Reset`, the number of seconds to wait in order to get the maximum number of allowed requests
You may disable these headers by configuring [[yii\filters\RateLimiter::enableRateLimitHeaders]] to be false, You may disable these headers by configuring [[yii\filters\RateLimiter::enableRateLimitHeaders]] to be `false`,
as shown in the above code example. as shown in the above code example.

2
docs/guide/rest-routing.md

@ -75,7 +75,7 @@ For example, to support a new action `search` by the endpoint `GET /users/search
You may have noticed that the controller ID `user` appears in plural form as `users` in the endpoint URLs. You may have noticed that the controller ID `user` appears in plural form as `users` in the endpoint URLs.
This is because [[yii\rest\UrlRule]] automatically pluralizes controller IDs when creating child URL rules. This is because [[yii\rest\UrlRule]] automatically pluralizes controller IDs when creating child URL rules.
You may disable this behavior by setting [[yii\rest\UrlRule::pluralize]] to be false. You may disable this behavior by setting [[yii\rest\UrlRule::pluralize]] to be `false`.
> Info: The pluralization of controller IDs is done by [[yii\helpers\Inflector::pluralize()]]. The method respects > Info: The pluralization of controller IDs is done by [[yii\helpers\Inflector::pluralize()]]. The method respects
special pluralization rules. For example, the word `box` will be pluralized as `boxes` instead of `boxs`. special pluralization rules. For example, the word `box` will be pluralized as `boxes` instead of `boxs`.

8
docs/guide/runtime-handling-errors.md

@ -11,7 +11,7 @@ experience than before. In particular, the Yii error handler does the following
* Supports different error response formats. * Supports different error response formats.
The [[yii\web\ErrorHandler|error handler]] is enabled by default. You may disable it by defining the constant The [[yii\web\ErrorHandler|error handler]] is enabled by default. You may disable it by defining the constant
`YII_ENABLE_ERROR_HANDLER` to be false in the [entry script](structure-entry-scripts.md) of your application. `YII_ENABLE_ERROR_HANDLER` to be `false` in the [entry script](structure-entry-scripts.md) of your application.
## Using Error Handler <span id="using-error-handler"></span> ## Using Error Handler <span id="using-error-handler"></span>
@ -62,8 +62,8 @@ throw new NotFoundHttpException();
## Customizing Error Display <span id="customizing-error-display"></span> ## Customizing Error Display <span id="customizing-error-display"></span>
The [[yii\web\ErrorHandler|error handler]] adjusts the error display according to the value of the constant `YII_DEBUG`. The [[yii\web\ErrorHandler|error handler]] adjusts the error display according to the value of the constant `YII_DEBUG`.
When `YII_DEBUG` is true (meaning in debug mode), the error handler will display exceptions with detailed call When `YII_DEBUG` is `true` (meaning in debug mode), the error handler will display exceptions with detailed call
stack information and source code lines to help easier debugging. And when `YII_DEBUG` is false, only the error stack information and source code lines to help easier debugging. And when `YII_DEBUG` is `false`, only the error
message will be displayed to prevent revealing sensitive information about the application. message will be displayed to prevent revealing sensitive information about the application.
> Info: If an exception is a descendant of [[yii\base\UserException]], no call stack will be displayed regardless > Info: If an exception is a descendant of [[yii\base\UserException]], no call stack will be displayed regardless
@ -73,7 +73,7 @@ developers do not need to fix anything.
By default, the [[yii\web\ErrorHandler|error handler]] displays errors using two [views](structure-views.md): By default, the [[yii\web\ErrorHandler|error handler]] displays errors using two [views](structure-views.md):
* `@yii/views/errorHandler/error.php`: used when errors should be displayed WITHOUT call stack information. * `@yii/views/errorHandler/error.php`: used when errors should be displayed WITHOUT call stack information.
When `YII_DEBUG` is false, this is the only error view to be displayed. When `YII_DEBUG` is `false`, this is the only error view to be displayed.
* `@yii/views/errorHandler/exception.php`: used when errors should be displayed WITH call stack information. * `@yii/views/errorHandler/exception.php`: used when errors should be displayed WITH call stack information.
You can configure the [[yii\web\ErrorHandler::errorView|errorView]] and [[yii\web\ErrorHandler::exceptionView|exceptionView]] You can configure the [[yii\web\ErrorHandler::errorView|errorView]] and [[yii\web\ErrorHandler::exceptionView|exceptionView]]

4
docs/guide/runtime-routing.md

@ -267,7 +267,7 @@ The rest of the properties are optional. However, their configuration shown abov
* [[yii\web\UrlManager::showScriptName|showScriptName]]: this property determines whether the entry script * [[yii\web\UrlManager::showScriptName|showScriptName]]: this property determines whether the entry script
should be included in the created URLs. For example, instead of creating a URL `/index.php/post/100`, should be included in the created URLs. For example, instead of creating a URL `/index.php/post/100`,
by setting this property to be false, a URL `/post/100` will be generated. by setting this property to be `false`, a URL `/post/100` will be generated.
* [[yii\web\UrlManager::enableStrictParsing|enableStrictParsing]]: this property determines whether to enable * [[yii\web\UrlManager::enableStrictParsing|enableStrictParsing]]: this property determines whether to enable
strict request parsing. If strict parsing is enabled, the incoming requested URL must match at least one of strict request parsing. If strict parsing is enabled, the incoming requested URL must match at least one of
the [[yii\web\UrlManager::rules|rules]] in order to be treated as a valid request, or a [[yii\web\NotFoundHttpException]] the [[yii\web\UrlManager::rules|rules]] in order to be treated as a valid request, or a [[yii\web\NotFoundHttpException]]
@ -278,7 +278,7 @@ The rest of the properties are optional. However, their configuration shown abov
particular application requirement. particular application requirement.
> Note: In order to hide the entry script name in the created URLs, besides setting > Note: In order to hide the entry script name in the created URLs, besides setting
[[yii\web\UrlManager::showScriptName|showScriptName]] to be false, you may also need to configure your Web server [[yii\web\UrlManager::showScriptName|showScriptName]] to be `false`, you may also need to configure your Web server
so that it can correctly identify which PHP script should be executed when a requested URL does not explicitly so that it can correctly identify which PHP script should be executed when a requested URL does not explicitly
specify one. If you are using Apache Web server, you may refer to the recommended configuration as described in the specify one. If you are using Apache Web server, you may refer to the recommended configuration as described in the
[Installation](start-installation.md#recommended-apache-configuration) section. [Installation](start-installation.md#recommended-apache-configuration) section.

6
docs/guide/runtime-sessions-cookies.md

@ -200,7 +200,7 @@ $session->setFlash('postDeleted', 'You have successfully deleted your post.');
echo $session->getFlash('postDeleted'); echo $session->getFlash('postDeleted');
// Request #3 // Request #3
// $result will be false since the flash message was automatically deleted // $result will be `false` since the flash message was automatically deleted
$result = $session->hasFlash('postDeleted'); $result = $session->hasFlash('postDeleted');
``` ```
@ -302,7 +302,7 @@ examples, the [[yii\web\Cookie]] class also defines other properties to fully re
information, such as [[yii\web\Cookie::domain|domain]], [[yii\web\Cookie::expire|expire]]. You may configure these information, such as [[yii\web\Cookie::domain|domain]], [[yii\web\Cookie::expire|expire]]. You may configure these
properties as needed to prepare a cookie and then add it to the response's cookie collection. properties as needed to prepare a cookie and then add it to the response's cookie collection.
> Note: For better security, the default value of [[yii\web\Cookie::httpOnly]] is set to true. This helps mitigate > Note: For better security, the default value of [[yii\web\Cookie::httpOnly]] is set to `true`. This helps mitigate
the risk of a client-side script accessing the protected cookie (if the browser supports it). You may read the risk of a client-side script accessing the protected cookie (if the browser supports it). You may read
the [httpOnly wiki article](https://www.owasp.org/index.php/HttpOnly) for more details. the [httpOnly wiki article](https://www.owasp.org/index.php/HttpOnly) for more details.
@ -320,7 +320,7 @@ you may still access it through `$_COOKIE`. This is because third-party librarie
in their own way, which does not involve cookie validation. in their own way, which does not involve cookie validation.
Cookie validation is enabled by default. You can disable it by setting the [[yii\web\Request::enableCookieValidation]] Cookie validation is enabled by default. You can disable it by setting the [[yii\web\Request::enableCookieValidation]]
property to be false, although we strongly recommend you do not do so. property to be `false`, although we strongly recommend you do not do so.
> Note: Cookies that are directly read/sent via `$_COOKIE` and `setcookie()` will NOT be validated. > Note: Cookies that are directly read/sent via `$_COOKIE` and `setcookie()` will NOT be validated.

4
docs/guide/security-authentication.md

@ -155,10 +155,10 @@ or `null` if the current user is not authenticated (meaning a guest). The follow
other authentication-related information from [[yii\web\User]]: other authentication-related information from [[yii\web\User]]:
```php ```php
// the current user identity. Null if the user is not authenticated. // the current user identity. `null` if the user is not authenticated.
$identity = Yii::$app->user->identity; $identity = Yii::$app->user->identity;
// the ID of the current user. Null if the user not authenticated. // the ID of the current user. `null` if the user not authenticated.
$id = Yii::$app->user->id; $id = Yii::$app->user->id;
// whether the current user is a guest (not authenticated) // whether the current user is a guest (not authenticated)

6
docs/guide/security-authorization.md

@ -178,7 +178,7 @@ During access checking, if the user is NOT the post creator, he/she will be cons
Both roles and permissions can be organized in a hierarchy. In particular, a role may consist of other roles or permissions; Both roles and permissions can be organized in a hierarchy. In particular, a role may consist of other roles or permissions;
and a permission may consist of other permissions. Yii implements a *partial order* hierarchy which includes the and a permission may consist of other permissions. Yii implements a *partial order* hierarchy which includes the
more special *tree* hierarchy. While a role can contain a permission, it is not true vice versa. more special *tree* hierarchy. While a role can contain a permission, it is not `true` vice versa.
### Configuring RBAC <span id="configuring-rbac"></span> ### Configuring RBAC <span id="configuring-rbac"></span>
@ -547,7 +547,7 @@ $auth->addChild($admin, $author);
Note that in the above, because "author" is added as a child of "admin", when you implement the `execute()` method Note that in the above, because "author" is added as a child of "admin", when you implement the `execute()` method
of the rule class, you need to respect this hierarchy as well. That is why when the role name is "author", of the rule class, you need to respect this hierarchy as well. That is why when the role name is "author",
the `execute()` method will return true if the user group is either 1 or 2 (meaning the user is in either "admin" the `execute()` method will return `true` if the user group is either 1 or 2 (meaning the user is in either "admin"
group or "author" group). group or "author" group).
Next, configure `authManager` by listing the two roles in [[yii\rbac\BaseManager::$defaultRoles]]: Next, configure `authManager` by listing the two roles in [[yii\rbac\BaseManager::$defaultRoles]]:
@ -566,6 +566,6 @@ return [
``` ```
Now if you perform an access check, both of the `admin` and `author` roles will be checked by evaluating Now if you perform an access check, both of the `admin` and `author` roles will be checked by evaluating
the rules associated with them. If the rule returns true, it means the role applies to the current user. the rules associated with them. If the rule returns `true`, it means the role applies to the current user.
Based on the above rule implementation, this means if the `group` value of a user is 1, the `admin` role Based on the above rule implementation, this means if the `group` value of a user is 1, the `admin` role
would apply to the user; and if the `group` value is 2, the `author` role would apply. would apply to the user; and if the `group` value is 2, the `author` role would apply.

4
docs/guide/security-best-practices.md

@ -134,7 +134,7 @@ Avoiding CSRF
------------- -------------
CSRF is an abbreviation for cross-site request forgery. The idea is that many applications assume that requests coming CSRF is an abbreviation for cross-site request forgery. The idea is that many applications assume that requests coming
from a user browser are made by the user himself. It could be false. from a user browser are made by the user himself. It could be `false`.
For example, `an.example.com` website has `/logout` URL that, when accessed using a simple GET, logs user out. As long For example, `an.example.com` website has `/logout` URL that, when accessed using a simple GET, logs user out. As long
as it's requested by the user itself everything is OK but one day bad guys are somehow posting as it's requested by the user itself everything is OK but one day bad guys are somehow posting
@ -179,7 +179,7 @@ class SiteController extends Controller
public function beforeAction($action) public function beforeAction($action)
{ {
// ...set `$this->enableCsrfValidation` here based on some conditions... // ...set `$this->enableCsrfValidation` here based on some conditions...
// call parent method that will check CSRF if such property is true. // call parent method that will check CSRF if such property is `true`.
return parent::beforeAction($action); return parent::beforeAction($action);
} }
} }

2
docs/guide/start-forms.md

@ -60,7 +60,7 @@ of rules for validating the data. The validation rules declared above state that
If you have an `EntryForm` object populated with the data entered by a user, you may call If you have an `EntryForm` object populated with the data entered by a user, you may call
its [[yii\base\Model::validate()|validate()]] to trigger the data validation routines. A data validation its [[yii\base\Model::validate()|validate()]] to trigger the data validation routines. A data validation
failure will set the [[yii\base\Model::hasErrors|hasErrors]] property to true, and you may learn what validation failure will set the [[yii\base\Model::hasErrors|hasErrors]] property to `true`, and you may learn what validation
errors occurred through [[yii\base\Model::getErrors|errors]]. errors occurred through [[yii\base\Model::getErrors|errors]].
```php ```php

2
docs/guide/start-gii.md

@ -33,7 +33,7 @@ The above configuration states that when in [development environment](concept-co
the application should include a module named `gii`, which is of class [[yii\gii\Module]]. the application should include a module named `gii`, which is of class [[yii\gii\Module]].
If you check the [entry script](structure-entry-scripts.md) `web/index.php` of your application, you will If you check the [entry script](structure-entry-scripts.md) `web/index.php` of your application, you will
find the following line, which essentially makes `YII_ENV_DEV` to be true. find the following line, which essentially makes `YII_ENV_DEV` to be `true`.
```php ```php
defined('YII_ENV') or define('YII_ENV', 'dev'); defined('YII_ENV') or define('YII_ENV', 'dev');

2
docs/guide/structure-assets.md

@ -441,7 +441,7 @@ You may customize this location by configuring the [[yii\web\AssetManager::baseP
[[yii\web\AssetManager::baseUrl|baseUrl]] properties. [[yii\web\AssetManager::baseUrl|baseUrl]] properties.
Instead of publishing assets by file copying, you may consider using symbolic links, if your OS and Web server allow. Instead of publishing assets by file copying, you may consider using symbolic links, if your OS and Web server allow.
This feature can be enabled by setting [[yii\web\AssetManager::linkAssets|linkAssets]] to be true. This feature can be enabled by setting [[yii\web\AssetManager::linkAssets|linkAssets]] to be `true`.
```php ```php
return [ return [

2
docs/guide/structure-controllers.md

@ -421,7 +421,7 @@ to fulfill the request:
* Otherwise an [[yii\base\InvalidRouteException]] exception will be thrown. * Otherwise an [[yii\base\InvalidRouteException]] exception will be thrown.
3. The controller sequentially calls the `beforeAction()` method of the application, the module (if the controller 3. The controller sequentially calls the `beforeAction()` method of the application, the module (if the controller
belongs to a module), and the controller. belongs to a module), and the controller.
* If one of the calls returns false, the rest of the uncalled `beforeAction()` methods will be skipped and the * If one of the calls returns `false`, the rest of the uncalled `beforeAction()` methods will be skipped and the
action execution will be cancelled. action execution will be cancelled.
* By default, each `beforeAction()` method call will trigger a `beforeAction` event to which you can attach a handler. * By default, each `beforeAction()` method call will trigger a `beforeAction` event to which you can attach a handler.
4. The controller runs the action. 4. The controller runs the action.

2
docs/guide/structure-modules.md

@ -188,7 +188,7 @@ $module = MyModuleClass::getInstance();
where `MyModuleClass` refers to the name of the module class that you are interested in. The `getInstance()` method where `MyModuleClass` refers to the name of the module class that you are interested in. The `getInstance()` method
will return the currently requested instance of the module class. If the module is not requested, the method will will return the currently requested instance of the module class. If the module is not requested, the method will
return null. Note that you do not want to manually create a new instance of the module class because it will be return `null`. Note that you do not want to manually create a new instance of the module class because it will be
different from the one created by Yii in response to a request. different from the one created by Yii in response to a request.
> Info: When developing a module, you should not assume the module will use a fixed ID. This is because a module > Info: When developing a module, you should not assume the module will use a fixed ID. This is because a module

2
docs/guide/structure-views.md

@ -636,7 +636,7 @@ Similar as [[yii\web\View::registerMetaTag()|registerMetaTag()]], you can specif
to these events to inject content into views or process the rendering results before they are sent to end users. to these events to inject content into views or process the rendering results before they are sent to end users.
- [[yii\base\View::EVENT_BEFORE_RENDER|EVENT_BEFORE_RENDER]]: triggered at the beginning of rendering a file - [[yii\base\View::EVENT_BEFORE_RENDER|EVENT_BEFORE_RENDER]]: triggered at the beginning of rendering a file
in a controller. Handlers of this event may set [[yii\base\ViewEvent::isValid]] to be false to cancel the rendering process. in a controller. Handlers of this event may set [[yii\base\ViewEvent::isValid]] to be `false` to cancel the rendering process.
- [[yii\base\View::EVENT_AFTER_RENDER|EVENT_AFTER_RENDER]]: triggered after rendering a file by the call of [[yii\base\View::afterRender()]]. - [[yii\base\View::EVENT_AFTER_RENDER|EVENT_AFTER_RENDER]]: triggered after rendering a file by the call of [[yii\base\View::afterRender()]].
Handlers of this event may obtain the rendering result through [[yii\base\ViewEvent::output]] and may modify Handlers of this event may obtain the rendering result through [[yii\base\ViewEvent::output]] and may modify
this property to change the rendering result. this property to change the rendering result.

2
docs/guide/structure-widgets.md

@ -109,7 +109,7 @@ class HelloWidget extends Widget
public function init() public function init()
{ {
parent::init(); parent::init();
if ($this->message === null) { if ($this->message === `null`) {
$this->message = 'Hello World'; $this->message = 'Hello World';
} }
} }

2
docs/guide/tutorial-console.md

@ -68,7 +68,7 @@ It contains code like the following:
* Yii console bootstrap file. * Yii console bootstrap file.
*/ */
defined('YII_DEBUG') or define('YII_DEBUG', true); defined('YII_DEBUG') or define('YII_DEBUG', `true`);
defined('YII_ENV') or define('YII_ENV', 'dev'); defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . '/vendor/autoload.php'); require(__DIR__ . '/vendor/autoload.php');

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

@ -26,20 +26,20 @@ In the following, we will describe the main usage and properties of every core v
// checks if "selected" is either 0 or 1, regardless of data type // checks if "selected" is either 0 or 1, regardless of data type
['selected', 'boolean'], ['selected', 'boolean'],
// checks if "deleted" is of boolean type, either true or false // checks if "deleted" is of boolean type, either `true` or `false`
['deleted', 'boolean', 'trueValue' => true, 'falseValue' => false, 'strict' => true], ['deleted', 'boolean', '`true`Value' => `true`, '`false`Value' => `false`, 'strict' => `true`],
] ]
``` ```
This validator checks if the input value is a boolean. This validator checks if the input value is a boolean.
- `trueValue`: the value representing *true*. Defaults to `'1'`. - ``true`Value`: the value representing *`true`*. Defaults to `'1'`.
- `falseValue`: the value representing *false*. Defaults to `'0'`. - ``false`Value`: the value representing *`false`*. Defaults to `'0'`.
- `strict`: whether the type of the input value should match that of `trueValue` and `falseValue`. Defaults to `false`. - `strict`: whether the type of the input value should match that of ``true`Value` and ``false`Value`. Defaults to `false`.
> Note: Because data input submitted via HTML forms are all strings, you normally should leave the > Note: Because data input submitted via HTML forms are all strings, you normally should leave the
[[yii\validators\BooleanValidator::strict|strict]] property as false. [[yii\validators\BooleanValidator::strict|strict]] property as `false`.
## [[yii\captcha\CaptchaValidator|captcha]] <span id="captcha"></span> ## [[yii\captcha\CaptchaValidator|captcha]] <span id="captcha"></span>
@ -53,10 +53,10 @@ This validator checks if the input value is a boolean.
This validator is usually used together with [[yii\captcha\CaptchaAction]] and [[yii\captcha\Captcha]] This validator is usually used together with [[yii\captcha\CaptchaAction]] and [[yii\captcha\Captcha]]
to make sure an input is the same as the verification code displayed by [[yii\captcha\Captcha|CAPTCHA]] widget. to make sure an input is the same as the verification code displayed by [[yii\captcha\Captcha|CAPTCHA]] widget.
- `caseSensitive`: whether the comparison of the verification code is case sensitive. Defaults to false. - `caseSensitive`: whether the comparison of the verification code is case sensitive. Defaults to `false`.
- `captchaAction`: the [route](structure-controllers.md#routes) corresponding to the - `captchaAction`: the [route](structure-controllers.md#routes) corresponding to the
[[yii\captcha\CaptchaAction|CAPTCHA action]] that renders the CAPTCHA image. Defaults to `'site/captcha'`. [[yii\captcha\CaptchaAction|CAPTCHA action]] that renders the CAPTCHA image. Defaults to `'site/captcha'`.
- `skipOnEmpty`: whether the validation can be skipped if the input is empty. Defaults to false, - `skipOnEmpty`: whether the validation can be skipped if the input is empty. Defaults to `false`,
which means the input is required. which means the input is required.
@ -105,7 +105,7 @@ you can use a combination of compare and date validator like the following:
```php ```php
['fromDate', 'date', 'timestampAttribute' => 'fromDate'], ['fromDate', 'date', 'timestampAttribute' => 'fromDate'],
['toDate', 'date', 'timestampAttribute' => 'toDate'], ['toDate', 'date', 'timestampAttribute' => 'toDate'],
['fromDate', 'compare', 'compareAttribute' => 'toDate', 'operator' => '<', 'enableClientValidation' => false], ['fromDate', 'compare', 'compareAttribute' => 'toDate', 'operator' => '<', 'enableClientValidation' => `false`],
``` ```
As validators are executed in the order they are specified this will first validate that the values entered in As validators are executed in the order they are specified this will first validate that the values entered in
@ -153,7 +153,7 @@ or `1970-01-01` in the input field of a date picker.
```php ```php
[ [
[['from_date', 'to_date'], 'default', 'value' => null], [['from_date', 'to_date'], 'default', 'value' => `null`],
[['from_date', 'to_date'], 'date'], [['from_date', 'to_date'], 'date'],
], ],
``` ```
@ -162,8 +162,8 @@ or `1970-01-01` in the input field of a date picker.
```php ```php
[ [
// set "age" to be null if it is empty // set "age" to be `null` if it is empty
['age', 'default', 'value' => null], ['age', 'default', 'value' => `null`],
// set "country" to be "USA" if it is empty // set "country" to be "USA" if it is empty
['country', 'default', 'value' => 'USA'], ['country', 'default', 'value' => 'USA'],
@ -224,8 +224,8 @@ and each array element will be validated by the `integer` validation rule.
- `rule`: an array specifying a validation rule. The first element in the array specifies the class name or - `rule`: an array specifying a validation rule. The first element in the array specifies the class name or
the alias of the validator. The rest of the name-value pairs in the array are used to configure the validator object. the alias of the validator. The rest of the name-value pairs in the array are used to configure the validator object.
- `allowMessageFromRule`: whether to use the error message returned by the embedded validation rule. Defaults to true. - `allowMessageFromRule`: whether to use the error message returned by the embedded validation rule. Defaults to `true`.
If false, it will use `message` as the error message. If `false`, it will use `message` as the error message.
> Note: If the attribute value is not an array, it is considered validation fails and the `message` will be returned > Note: If the attribute value is not an array, it is considered validation fails and the `message` will be returned
as the error message. as the error message.
@ -242,12 +242,12 @@ and each array element will be validated by the `integer` validation rule.
This validator checks if the input value is a valid email address. This validator checks if the input value is a valid email address.
- `allowName`: whether to allow name in the email address (e.g. `John Smith <john.smith@example.com>`). Defaults to false. - `allowName`: whether to allow name in the email address (e.g. `John Smith <john.smith@example.com>`). Defaults to `false`.
- `checkDNS`, whether to check whether the email's domain exists and has either an A or MX record. - `checkDNS`, whether to check whether the email's domain exists and has either an A or MX record.
Be aware that this check may fail due to temporary DNS problems, even if the email address is actually valid. Be aware that this check may fail due to temporary DNS problems, even if the email address is actually valid.
Defaults to false. Defaults to `false`.
- `enableIDN`, whether the validation process should take into account IDN (internationalized domain names). - `enableIDN`, whether the validation process should take into account IDN (internationalized domain names).
Defaults to false. Note that in order to use IDN validation you have to install and enable the `intl` PHP extension, Defaults to `false`. Note that in order to use IDN validation you have to install and enable the `intl` PHP extension,
or an exception would be thrown. or an exception would be thrown.
@ -271,7 +271,7 @@ This validator checks if the input value is a valid email address.
['a1', 'exist', 'targetAttribute' => ['a2', 'a1' => 'a3']], ['a1', 'exist', 'targetAttribute' => ['a2', 'a1' => 'a3']],
// a1 needs to exist. If a1 is an array, then every element of it must exist. // a1 needs to exist. If a1 is an array, then every element of it must exist.
['a1', 'exist', 'allowArray' => true], ['a1', 'exist', 'allowArray' => `true`],
] ]
``` ```
@ -294,9 +294,9 @@ multiple attribute values should exist).
This can be a string or an array representing the additional query condition (refer to [[yii\db\Query::where()]] This can be a string or an array representing the additional query condition (refer to [[yii\db\Query::where()]]
on the format of query condition), or an anonymous function with the signature `function ($query)`, where `$query` on the format of query condition), or an anonymous function with the signature `function ($query)`, where `$query`
is the [[yii\db\Query|Query]] object that you can modify in the function. is the [[yii\db\Query|Query]] object that you can modify in the function.
- `allowArray`: whether to allow the input value to be an array. Defaults to false. If this property is true - `allowArray`: whether to allow the input value to be an array. Defaults to `false`. If this property is `true`
and the input is an array, then every element of the array must exist in the target column. Note that and the input is an array, then every element of the array must exist in the target column. Note that
this property cannot be set true if you are validating against multiple columns by setting `targetAttribute` as an array. this property cannot be set `true` if you are validating against multiple columns by setting `targetAttribute` as an array.
## [[yii\validators\FileValidator|file]] <span id="file"></span> ## [[yii\validators\FileValidator|file]] <span id="file"></span>
@ -327,7 +327,7 @@ This validator checks if the input is a valid uploaded file.
the input must be a single uploaded file. If it is greater than 1, then the input must be an array the input must be a single uploaded file. If it is greater than 1, then the input must be an array
consisting of at most `maxFiles` number of uploaded files. consisting of at most `maxFiles` number of uploaded files.
- `checkExtensionByMimeType`: whether to check the file extension by the file's MIME type. If the extension produced by - `checkExtensionByMimeType`: whether to check the file extension by the file's MIME type. If the extension produced by
MIME type check differs from the uploaded file extension, the file will be considered as invalid. Defaults to true, MIME type check differs from the uploaded file extension, the file will be considered as invalid. Defaults to `true`,
meaning perform such check. meaning perform such check.
`FileValidator` is used together with [[yii\web\UploadedFile]]. Please refer to the [Uploading Files](input-file-upload.md) `FileValidator` is used together with [[yii\web\UploadedFile]]. Please refer to the [Uploading Files](input-file-upload.md)
@ -339,7 +339,7 @@ section for complete coverage about uploading files and performing validation ab
```php ```php
[ [
// trim "username" and "email" inputs // trim "username" and "email" inputs
[['username', 'email'], 'filter', 'filter' => 'trim', 'skipOnArray' => true], [['username', 'email'], 'filter', 'filter' => 'trim', 'skipOnArray' => `true`],
// normalize "phone" input // normalize "phone" input
['phone', 'filter', 'filter' => function ($value) { ['phone', 'filter', 'filter' => function ($value) {
@ -354,8 +354,8 @@ back to the attribute being validated.
- `filter`: a PHP callback that defines a filter. This can be a global function name, an anonymous function, etc. - `filter`: a PHP callback that defines a filter. This can be a global function name, an anonymous function, etc.
The function signature must be `function ($value) { return $newValue; }`. This property must be set. The function signature must be `function ($value) { return $newValue; }`. This property must be set.
- `skipOnArray`: whether to skip the filter if the input value is an array. Defaults to false. - `skipOnArray`: whether to skip the filter if the input value is an array. Defaults to `false`.
Note that if the filter cannot handle array input, you should set this property to be true. Otherwise some Note that if the filter cannot handle array input, you should set this property to be `true`. Otherwise some
PHP error might occur. PHP error might occur.
> Tip: If you want to trim input values, you may directly use the [trim](#trim) validator. > Tip: If you want to trim input values, you may directly use the [trim](#trim) validator.
@ -400,11 +400,11 @@ validation purpose:
// checks if "ip_address" is a valid IPv6 address or subnet, // checks if "ip_address" is a valid IPv6 address or subnet,
// value will be expanded to full IPv6 notation. // value will be expanded to full IPv6 notation.
['ip_address', 'ip', 'ipv4' => false, 'subnet' => null, 'expandIPv6' => true], ['ip_address', 'ip', 'ipv4' => `false`, 'subnet' => `null`, 'expandIPv6' => `true`],
// checks if "ip_address" is a valid IPv4 or IPv6 address, // checks if "ip_address" is a valid IPv4 or IPv6 address,
// allows negation character `!` at the beginning // allows negation character `!` at the beginning
['ip_address', 'ip', 'negation' => true], ['ip_address', 'ip', 'negation' => `true`],
] ]
``` ```
@ -413,23 +413,23 @@ It also may change attribute's value if normalization or IPv6 expansion is enabl
The validator has such configuration options: The validator has such configuration options:
- `ipv4`: whether the validating value can be an IPv4 address. Defaults to true. - `ipv4`: whether the validating value can be an IPv4 address. Defaults to `true`.
- `ipv6`: whether the validating value can be an IPv6 address. Defaults to true. - `ipv6`: whether the validating value can be an IPv6 address. Defaults to `true`.
- `subnet`: whether the address can be an IP with CIDR subnet, like `192.168.10.0/24` - `subnet`: whether the address can be an IP with CIDR subnet, like `192.168.10.0/24`
* `true` - the subnet is required, addresses without CIDR will be rejected * `true` - the subnet is required, addresses without CIDR will be rejected
* `false` - the address can not have the CIDR * `false` - the address can not have the CIDR
* `null` - the CIDR is optional * `null` - the CIDR is optional
Defaults to false. Defaults to `false`.
- `normalize`: whether to add the CIDR prefix with the smallest length (32 for IPv4 and 128 for IPv6) to an - `normalize`: 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: address without it. Works only when `subnet` is not `false`. For example:
* `10.0.1.5` will normalized to `10.0.1.5/32` * `10.0.1.5` will normalized to `10.0.1.5/32`
* `2008:db0::1` will be normalized to `2008:db0::1/128` * `2008:db0::1` will be normalized to `2008:db0::1/128`
Defaults to false. Defaults to `false`.
- `negation`: whether the validation address can have a negation character `!` at the beginning. Defaults to false. - `negation`: whether the validation address can have a negation character `!` at the beginning. Defaults to `false`.
- `expandIPv6`: whether to expand an IPv6 address to the full notation format. - `expandIPv6`: whether to expand an IPv6 address to the full notation format.
For example, `2008:db0::1` will be expanded to `2008:0db0:0000:0000:0000:0000:0000:0001`. Defaults to false. For example, `2008:db0::1` will be expanded to `2008:0db0:0000:0000:0000:0000:0000:0001`. Defaults to `false`.
- `ranges`: array of IPv4 or IPv6 ranges that are allowed or forbidden. - `ranges`: array of IPv4 or IPv6 ranges that are allowed or forbidden.
When the array is empty, or the option is not set, all the IP addresses are allowed. When the array is empty, or the option is not set, all the IP addresses are allowed.
@ -479,10 +479,10 @@ This validator checks if the input value can be found among the given list of va
- `range`: a list of given values within which the input value should be looked for. - `range`: a list of given values within which the input value should be looked for.
- `strict`: whether the comparison between the input value and the given values should be strict - `strict`: whether the comparison between the input value and the given values should be strict
(both the type and value must be the same). Defaults to false. (both the type and value must be the same). Defaults to `false`.
- `not`: whether the validation result should be inverted. Defaults to false. When this property is set true, - `not`: whether the validation result should be inverted. Defaults to `false`. When this property is set `true`,
the validator checks if the input value is NOT among the given list of values. the validator checks if the input value is NOT among the given list of values.
- `allowArray`: whether to allow the input value to be an array. When this is true and the input value is an array, - `allowArray`: whether to allow the input value to be an array. When this is `true` and the input value is an array,
every element in the array must be found in the given list of values, or the validation would fail. every element in the array must be found in the given list of values, or the validation would fail.
@ -514,8 +514,8 @@ This validator checks if the input value matches the specified regular expressio
- `pattern`: the regular expression that the input value should match. This property must be set, - `pattern`: the regular expression that the input value should match. This property must be set,
or an exception will be thrown. or an exception will be thrown.
- `not`: whether to invert the validation result. Defaults to false, meaning the validation succeeds - `not`: whether to invert the validation result. Defaults to `false`, meaning the validation succeeds
only if the input value matches the pattern. If this is set true, the validation is considered only if the input value matches the pattern. If this is set `true`, the validation is considered
successful only if the input value does NOT match the pattern. successful only if the input value does NOT match the pattern.
@ -546,11 +546,11 @@ This validator checks if the input value is a number. It is equivalent to the [d
This validator checks if the input value is provided and not empty. This validator checks if the input value is provided and not empty.
- `requiredValue`: the desired value that the input should be. If not set, it means the input should not be empty. - `requiredValue`: the desired value that the input should be. If not set, it means the input should not be empty.
- `strict`: whether to check data types when validating a value. Defaults to false. - `strict`: whether to check data types when validating a value. Defaults to `false`.
When `requiredValue` is not set, if this property is true, the validator will check if the input value is When `requiredValue` is not set, if this property is `true`, the validator will check if the input value is
not strictly `null`; If this property is false, the validator will use a loose rule to determine a value is empty or not. not strictly `null`; If this property is `false`, the validator will use a loose rule to determine a value is empty or not.
When `requiredValue` is set, the comparison between the input and `requiredValue` will also check data types When `requiredValue` is set, the comparison between the input and `requiredValue` will also check data types
if this property is true. if this property is `true`.
> Info: How to determine if a value is empty or not is a separate topic covered > Info: How to determine if a value is empty or not is a separate topic covered
in the [Empty Values](input-validation.md#handling-empty-inputs) section. in the [Empty Values](input-validation.md#handling-empty-inputs) section.
@ -660,6 +660,6 @@ This validator checks if the input value is a valid URL.
- `defaultScheme`: the default URI scheme to be prepended to the input if it does not have the scheme part. - `defaultScheme`: the default URI scheme to be prepended to the input if it does not have the scheme part.
Defaults to `null`, meaning do not modify the input value. Defaults to `null`, meaning do not modify the input value.
- `enableIDN`: whether the validator should take into account IDN (internationalized domain names). - `enableIDN`: whether the validator should take into account IDN (internationalized domain names).
Defaults to false. Note that in order to use IDN validation you have to install and enable the `intl` PHP Defaults to `false`. Note that in order to use IDN validation you have to install and enable the `intl` PHP
extension, otherwise an exception would be thrown. extension, otherwise an exception would be thrown.

4
docs/guide/tutorial-i18n.md

@ -496,7 +496,7 @@ class Module extends \yii\base\Module
]; ];
} }
public static function t($category, $message, $params = [], $language = null) public static function t($category, $message, $params = [], $language = `null`)
{ {
return Yii::t('modules/users/' . $category, $message, $params, $language); return Yii::t('modules/users/' . $category, $message, $params, $language);
} }
@ -547,7 +547,7 @@ class Menu extends Widget
echo $this->render('index'); echo $this->render('index');
} }
public static function t($category, $message, $params = [], $language = null) public static function t($category, $message, $params = [], $language = `null`)
{ {
return Yii::t('widgets/menu/' . $category, $message, $params, $language); return Yii::t('widgets/menu/' . $category, $message, $params, $language);
} }

8
docs/guide/tutorial-performance-tuning.md

@ -27,10 +27,10 @@ You may place the following line of code at the beginning of the [entry script](
disable debug mode: disable debug mode:
```php ```php
defined('YII_DEBUG') or define('YII_DEBUG', false); defined('YII_DEBUG') or define('YII_DEBUG', `false`);
``` ```
> Info: The default value of `YII_DEBUG` is false. So if you are certain that you do not change its default > Info: The default value of `YII_DEBUG` is `false`. So if you are certain that you do not change its default
value somewhere else in your application code, you may simply remove the above line to disable debug mode. value somewhere else in your application code, you may simply remove the above line to disable debug mode.
@ -66,7 +66,7 @@ return [
'dsn' => 'mysql:host=localhost;dbname=mydatabase', 'dsn' => 'mysql:host=localhost;dbname=mydatabase',
'username' => 'root', 'username' => 'root',
'password' => '', 'password' => '',
'enableSchemaCache' => true, 'enableSchemaCache' => `true`,
// Duration of schema cache. // Duration of schema cache.
'schemaCacheDuration' => 3600, 'schemaCacheDuration' => 3600,
@ -121,7 +121,7 @@ component as the database connection and store the session data in the `session`
```sql ```sql
CREATE TABLE session ( CREATE TABLE session (
id CHAR(40) NOT NULL PRIMARY KEY, id CHAR(40) NOT `NULL` PRIMARY KEY,
expire INTEGER, expire INTEGER,
data BLOB data BLOB
) )

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

Loading…
Cancel
Save