diff --git a/docs/guide/ru/README.md b/docs/guide/ru/README.md index 15e6586f5..0adccbf61 100644 --- a/docs/guide/ru/README.md +++ b/docs/guide/ru/README.md @@ -14,6 +14,7 @@ - [Compare](built-in-rules-compare.md) - [Composite](built-in-rules-composite.md) - [Each](built-in-rules-each.md) + - [File](built-in-rules-file.md) - [Nested](built-in-rules-nested.md) - [Required](built-in-rules-required.md) - [StopOnError](built-in-rules-stop-on-error.md) diff --git a/docs/guide/ru/built-in-rules-callback.md b/docs/guide/ru/built-in-rules-callback.md index 51eb39c35..ff7e1281b 100644 --- a/docs/guide/ru/built-in-rules-callback.md +++ b/docs/guide/ru/built-in-rules-callback.md @@ -1,23 +1,26 @@ -# `Callback` - a wrapper around `callable` +# `Callback` - обертка вокруг `вызываемого выражения` -This rule allows validation of the current property value (but not limited to it) with an arbitrary condition within a -callable. The benefit is that there is no need to create a separate custom -rule and handler. +Это правило позволяет проверять текущее значение свойства (но не только его) с помощью произвольного условия внутри -A condition can be within: +вызываемой функции. Преимущество заключается в том, что нет необходимости +создавать отдельное пользовательское правило и обработчик. -- Standalone callable function. -- Callable class. -- DTO (data transfer object) method. +Условие может находиться в: -The downside of using standalone functions and DTO methods is a lack of -reusability. So they are mainly useful for some specific non-repetitive -conditions. Reusability can be achieved with callable classes, but depending -on other factors (the need for additional parameters for example), it might -be a good idea to create a full-fledged [custom -rule](creating-custom-rules.md) with a separate handler instead. +- Отдельная вызываемая функция. +- Вызываемый класс. +- Метод DTO (объекта передачи данных). -The callback function signature is the following: +Недостатком использования отдельных функций и методов DTO является +отсутствие возможности повторного использования. Поэтому они в основном +полезны в определенных не повторяющихся конкретных ситуациях. Повторное +использование можно обеспечить с помощью вызываемых классов, но в +зависимости от других факторов (например, необходимости дополнительных +параметров) может оказаться целесообразным вместо этого создать полноценное +[пользовательское правило](creating-custom-rules.md) с отдельным +обработчиком. + +Сигнатура функции обратного вызова выглядит следующим образом: ```php use Yiisoft\Validator\Result; @@ -29,14 +32,15 @@ function (mixed $value, Callback $rule, ValidationContext $context): Result; где: -- `$value` is the validated value; -- `$rule` is a reference to the original `Callback` rule; +- `$value` проверяемое значение; +- `$rule` это ссылка на исходное `Callback` правило; - `$context` контекст валидации; -- returned value is a validation result instance with or without errors. +- возвращаемое значение представляет собой экземпляр результата проверки, + содержащий или не содержащий ошибки. -## Using as a function +## Использование как функции -An example of passing a standalone callable function to a `Callback` rule: +Пример передачи вызываемой функции в правило `Callback`: ```php use Yiisoft\Validator\Result; @@ -45,21 +49,22 @@ use Yiisoft\Validator\ValidationContext; new Callback( static function (mixed $value, Callback $rule, ValidationContext $context): Result { - // The actual validation code. + // Фактический код проверки. return new Result(); }, ); ``` -## Examples +## Примеры -### Value validation +### Проверка значения -`Callback` rule can be used to add validation missing in built-in rules for -a single property's value. Below is the example verifying that a value is a -valid [YAML](https://en.wikipedia.org/wiki/YAML) string (additionally -requires `yaml` PHP extension): +Правило `Callback` можно использовать для добавления проверки, отсутствующей +во встроенных правилах, для значения одного свойства. Ниже приведен пример, +подтверждающий, что значение является допустимой строкой +[YAML](https://en.wikipedia.org/wiki/YAML) (дополнительно требуется `yaml` +модуль для PHP): ```php use Exception; @@ -89,13 +94,13 @@ new Callback( ); ``` -> **Note:** Processing untrusted user input with `yaml_parse()` can be dangerous with certain settings. Please refer to -> [`yaml_parse()` docs](https://www.php.net/manual/en/function.yaml-parse.php) for more details. +> **Примечание:** Обработка непроверенного пользовательского ввода с помощью `yaml_parse()` может быть опасной при определенных настройках. +> Для получения более подробной информации обратитесь к [документации `yaml_parse()`](https://www.php.net/manual/en/function.yaml-parse.php). -### Usage of validation context for validating multiple properties depending on each other +### Использование контекста валидации для проверки нескольких свойств, зависящих друг от друга -In the example below, the 3 angles are validated as degrees to form a valid -triangle: +В приведенном ниже примере три угла проверяются на соответствие +градусам,чтобы сформировался корректный треугольник: ```php use Yiisoft\Validator\Result; @@ -139,10 +144,10 @@ $rules = [ ]; ``` -### Replacing boilerplate code with separate rules and `when` +### Замена шаблонного кода отдельными правилами и `when` -However, some cases of using validation context can lead to boilerplate -code: +Однако в некоторых случаях использование контекста валидации может привести +к появлению шаблонного кода: ```php use Yiisoft\Validator\Result; @@ -171,8 +176,9 @@ static function (mixed $value, Callback $rule, ValidationContext $context): Resu }; ``` -They can be rewritten using multiple rules and conditional validation making -code more intuitive. We can use built-in rules where possible: +Их можно переписать, используя несколько правил и условную проверку, что +сделает код более интуитивно понятным. Можно использовать встроенные правила +там где это возможно: ```php use Yiisoft\Validator\Rule\BooleanValue; @@ -191,11 +197,12 @@ $rules = [ ]; ``` -## Using as an object's method +## Использование в качестве метода объекта -### For property +### Для свойства -When using as a PHP attribute, set an object's method as a callback instead: +При использовании в качестве PHP-атрибута установите метод объекта в +качестве функции обратного вызова: ```php use Exception; @@ -232,17 +239,17 @@ final class Config { } ``` -The signature is the same as in a regular function. Note that there are no -restrictions on visibility levels and static modifiers, all of them can be -used (`public`, `protected`, `private`, `static`). +Сигнатура такая же, как и в обычной функции. Обратите внимание, что +ограничений на уровни видимости и статические модификаторы нет, все они +могут быть использованы (`public`, `protected`, `private`, `static`). -Using a `callback` argument instead of `method` with PHP attributes is -prohibited due to current PHP language restrictions (a callback can't be -inside a PHP attribute). +Использование аргумента `callback` вместо `method` с PHP-атрибутами +запрещено из-за текущих ограничений языка PHP (функция обратного вызова не +может находиться внутри PHP-атрибута). -### For the whole object +### Для всего объекта -It's also possible to check the whole object: +Также можно проверить весь объект: ```php use Exception; @@ -279,11 +286,12 @@ final class Config { } ``` -Note the use of property value (`$this->yaml`) instead of method argument (`$value`). +Обратите внимание на использование значения свойства ($this->yaml) вместо аргумента метода ($value). -## Using a callable class +## Использование вызываемого класса -A class that implements `__invoke()` can also be used as a callable: +Класс, реализующий метод `__invoke()`, также можно использовать как +вызываемый объект (callable): ```php use Exception; @@ -316,9 +324,10 @@ final class YamlCallback } ``` -The signature is the same as in a regular function. +Сигнатура такая же, как и в обычной функции. -Using in rules (note that a new instance must be passed, not a class name): +Использование в правилах (обратите внимание, что необходимо передать +экземпляр, а не имя класса): ```php use Yiisoft\Validator\Rule\Callback; @@ -328,11 +337,12 @@ $rules = [ ]; ``` -## Shortcut for use with validator +## Сокращение при использовании в валидаторе -When using with the validator and default `Callback` rule settings, a rule -declaration can be omitted, so just including a callable is enough. It will -be normalized automatically before validation: +При использовании в валидаторе и настройках по умолчанию для `Callback` +правила, объявление правила можно опустить, поэтому достаточно просто +указать вызываемую функцию. Она будет автоматически нормализована перед +проверкой: ```php use Exception; @@ -364,7 +374,7 @@ $rules = [ $result = (new Validator())->validate($data, $rules); ``` -Or it can be set within an array of other rules: +Или же его можно задать в массиве вместе с другими правилами: ```php use Exception; diff --git a/docs/guide/ru/built-in-rules-file.md b/docs/guide/ru/built-in-rules-file.md new file mode 100644 index 000000000..af5766765 --- /dev/null +++ b/docs/guide/ru/built-in-rules-file.md @@ -0,0 +1,103 @@ +# File + +`File` checks that a value is a file and can validate its extension, MIME +type, and size. + +Supported values: + +- string file paths; +- `SplFileInfo` instances; +- [PSR-7] `UploadedFileInterface` instances. + +Use `Each` for multiple files: + +```php +use Yiisoft\Validator\Rule\Each; +use Yiisoft\Validator\Rule\File; + +$rules = [ + 'attachments' => new Each(new File(extensions: ['pdf', 'txt'])), +]; +``` + +For example, with a PSR-7 request: + +```php +use Yiisoft\Validator\Rule\Each; +use Yiisoft\Validator\Rule\File; +use Yiisoft\Validator\Validator; + +$uploadedFiles = $request->getUploadedFiles()['attachments'] ?? []; + +$result = (new Validator())->validate( + ['attachments' => $uploadedFiles], + ['attachments' => new Each(new File(maxSize: 5_000_000))], +); +``` + +If your application works with native PHP `$_FILES` data directly, convert +it to supported values such as PSR-7 uploaded file objects before passing it +to the validator. + +## Uploaded Files + +`File` handles PSR-7 upload error codes. `UPLOAD_ERR_NO_FILE` is treated as +a missing value, so optional upload fields can use `skipOnEmpty`: + +```php +use Yiisoft\Validator\Rule\File; + +$rule = new File(skipOnEmpty: true); +``` + +Other upload error codes fail validation with `uploadFailedMessage`. + +The rule does not prove that arbitrary string paths or `SplFileInfo` values +came from PHP's HTTP upload mechanism. Do not pass user-submitted paths +directly. Use PSR-7 uploaded file objects from a trusted request +implementation, or perform [upload provenance checks] before validating +filesystem paths. + +## MIME Types + +For filesystem-backed files, MIME type validation uses PHP's file +information facilities through `mime_content_type()`. If the MIME type can't +be determined, MIME validation fails. + +For pathless PSR-7 uploads backed only by an in-memory stream, `File` +doesn't trust client-provided media type by default. If your application has +already decided that the client metadata is acceptable for this field, +enable it explicitly: + +```php +use Yiisoft\Validator\Rule\File; + +$rule = new File( + mimeTypes: ['text/plain'], + trustClientMediaType: true, +); +``` + +This option should be used with care because the client can send any media +type value. + +## Size + +For filesystem-backed uploads, size checks use the actual file size on +disk. For pathless streams, size checks use the PSR-7 upload size when +available. If a size constraint is configured and the size can't be +determined, validation fails. + +`size` is mutually exclusive with `minSize` and `maxSize`. When both +`minSize` and `maxSize` are set, `minSize` must be less than or equal to +`maxSize`. + +## Request Body Streams + +`File` doesn't validate generic request body streams such as data read from +`php://input` for PUT requests. Convert such input to a supported value +first, or write a custom rule that validates your stream format and storage +flow. + +[PSR-7]: https://www.php-fig.org/psr/psr-7/ +[upload provenance checks]: https://www.php.net/manual/en/features.file-upload.post-method.php diff --git a/docs/guide/ru/built-in-rules-nested.md b/docs/guide/ru/built-in-rules-nested.md index 6be93f9ca..71412045e 100644 --- a/docs/guide/ru/built-in-rules-nested.md +++ b/docs/guide/ru/built-in-rules-nested.md @@ -262,7 +262,7 @@ $rule = new Nested([ и `Each`. Если вам это необходимо, используйте явную форму конфигурации (см. пример в разделе [Базовое использование]). -### Использование атрибутов +### Using PHP attributes Правила и отношения можно объявлять через DTO с PHP атрибутами: @@ -510,5 +510,5 @@ $data = [ [Базовое использование]: #базовое-использование-связь-один-к-одному [JSFiddle]: https://jsfiddle.net/fys8uadr/ [Conditional validation]: conditional-validation.md -[Настройка правил с помощью PHP атрибутов]: configuring-rules-via-php-attributes.md +[Configuring rules via PHP attributes]: configuring-rules-via-php-attributes.md [Использование валидатора]: using-validator.md diff --git a/docs/guide/ru/built-in-rules.md b/docs/guide/ru/built-in-rules.md index f1ca5ca91..d5f2857ed 100644 --- a/docs/guide/ru/built-in-rules.md +++ b/docs/guide/ru/built-in-rules.md @@ -57,6 +57,7 @@ Here is a list of all available built-in rules, divided by category. ### File rules +- [File](../../../src/Rule/File.php) - [Image](../../../src/Rule/Image/Image.php) ### Date rules @@ -86,6 +87,7 @@ Some rules also have guides in addition to PHPDoc: - [Compare](built-in-rules-compare.md) - [Composite](built-in-rules-composite.md) - [Each](built-in-rules-each.md) +- [File](built-in-rules-file.md) - [Nested](built-in-rules-nested.md) - [Required](built-in-rules-required.md) - [StopOnError](built-in-rules-stop-on-error.md) diff --git a/docs/guide/ru/conditional-validation.md b/docs/guide/ru/conditional-validation.md index 7915df5fb..4b61ee7d7 100644 --- a/docs/guide/ru/conditional-validation.md +++ b/docs/guide/ru/conditional-validation.md @@ -287,13 +287,13 @@ $rules = [ $result = (new Validator())->validate($data, $rules); ``` -### `when` within nested structures +### `when` внутри вложенных структур -`$context->getDataSet()->getPropertyValue()` also works within nested validation, giving access to sibling properties -at the same nesting level. +Метод `$context->getDataSet()->getPropertyValue()` также работает внутри вложенной проверки, предоставляя доступ к свойствам соседних элементов +на том же уровне вложенности. -In this example `content` is only required when its sibling property -`isEnabled` is `true`: +В этом примере свойство `content` требуется только тогда, когда соседнее +свойство `isEnabled` имеет значение `true`: ```php use Yiisoft\Validator\Rule\BooleanValue; @@ -323,11 +323,12 @@ $rules = new Nested([ $result = (new Validator())->validate($data, $rules); ``` -Since `isEnabled` is `true`, the `Required` rule is applied and `content` -fails validation because it is `null`. Setting `isEnabled` to `false` would -skip the `Required` rule entirely. +Поскольку `isEnabled` имеет значение `true`, применяется правило `Required` +и `content` не проходит проверку, поскольку имеет значение `null`. Установка +`isEnabled` в значение `false` полностью пропустит правило `Required`. -This approach works at any depth, including inside `Each`: +Этот подход работает на любом уровне вложенности, в том числе и внутри +`Each`: ```php use Yiisoft\Validator\Rule\BooleanValue; diff --git a/docs/guide/ru/customizing-error-messages.md b/docs/guide/ru/customizing-error-messages.md index 80751a034..d9681c06f 100644 --- a/docs/guide/ru/customizing-error-messages.md +++ b/docs/guide/ru/customizing-error-messages.md @@ -69,17 +69,18 @@ $validator = new Validator(translator: $translator); ## Перевод имен свойств -Almost all error templates have support for `{property}` and `{Property}` -placeholders which are substituted with an actual property name that was set -during rules configuration. The `{Property}` variant capitalizes the first -letter. By default, a property name is formatted as is. It can be acceptable -for English language (for example, `currentPassword is required.`), but when -using translations for error messages, it's better to provide an additional -property translation. - -The simplest approach for properties defined via PHP attributes is to use -the `Label` attribute directly on the property. See [Configuring rules via -PHP attributes] for details. +Практически все шаблоны ошибок поддерживают заполнители `{property}` и +`{Property}`, которые заменяются на фактическое имя свойства, заданное при +настройке правил. Вариант `{Property}` преобразует первую букву в +заглавную. По умолчанию имя свойства форматируется без изменений. Это может +быть приемлемо для английского языка (например, `currentPassword is +required.`), но при использовании переводов для сообщений об ошибках лучше +предоставить дополнительный перевод свойства. + +Самый простой способ настройки свойств, определяемых с помощью +PHP-атрибутов, — это непосредственное использование атрибута `Label` для +данного свойства. Подробнее см. в разделе [Настройка правил с помощью +PHP-атрибутов]. Для решения именно этой задачи существует отдельный интерфейс `PropertyTranslatorInterface`. Он поставляется с тремя реализациями из @@ -157,7 +158,7 @@ $result = (new Validator())->validate($form); ``` [PR]: https://github.com/yiisoft/validator/pulls -[Настройка правил с помощью PHP атрибутов]: configuring-rules-via-php-attributes.md +[Configuring rules via PHP attributes]: configuring-rules-via-php-attributes.md [Yii Translator]: https://github.com/yiisoft/translator [Yii Config]: https://github.com/yiisoft/config [Yii DI]: https://github.com/yiisoft/di diff --git a/docs/guide/ru/result.md b/docs/guide/ru/result.md index e9c2beb08..74c23f99f 100644 --- a/docs/guide/ru/result.md +++ b/docs/guide/ru/result.md @@ -1,7 +1,7 @@ # Результат -The validation result is an object containing errors that occurred during -validation. +Результатом валидации является объект, содержащий ошибки, возникшие во время +проверки. ## Валидация успешна? @@ -172,10 +172,10 @@ $rule = new Each([new Number(min: 21)]); ] ``` -### First error messages indexed by property +### Первые сообщения об ошибках, сгруппированные по свойству -To get only the first error message for each property (useful for displaying -a single error per field), use: +Чтобы получить только первое сообщение об ошибке для каждого свойства (что +полезно для отображения одной ошибки для каждого поля), используйте: ```php use Yiisoft\Validator\Result; @@ -194,8 +194,8 @@ $result->getFirstErrorMessagesIndexedByProperty(); ]; ``` -Note that unlike `getErrorMessagesIndexedByProperty()`, each value is a -single string, not an array. +Обратите внимание, что в отличие от `getErrorMessagesIndexedByProperty()`, +каждое значение представляет собой отдельную строку, а не массив. ### Сообщения об ошибках, сгруппированные по пути @@ -233,10 +233,10 @@ $result->getErrorMessagesIndexedByPath(); ]; ``` -#### First error messages indexed by path +#### Первые сообщения об ошибках, сгруппированные по пути -To get only the first error message for each path (useful for displaying a -single error per field), use: +Чтобы получить только первое сообщение об ошибке для каждого пути (это +полезно для отображения одной ошибки для каждого поля), используйте: ```php use Yiisoft\Validator\Result; @@ -256,8 +256,8 @@ $result->getFirstErrorMessagesIndexedByPath(); ]; ``` -Note that unlike `getErrorMessagesIndexedByPath()`, each value is a single -string, not an array. +Обратите внимание, что в отличие от `getErrorMessagesIndexedByPath()`, +каждое значение представляет собой отдельную строку, а не массив. #### Разрешение конфликтов специальных символов в именах свойств @@ -375,17 +375,18 @@ use Yiisoft\Validator\Result; $result->getPropertyErrors('email'); ``` -## Adding errors +## Добавление ошибок -When writing custom rule handlers, errors are added to a `Result` -object. There are three methods available, each with different -post-processing behavior: +При написании пользовательских обработчиков правил ошибки добавляются в +объект `Result`. Доступны три метода, каждый из которых имеет различное +поведение при постобработке: -- `addError()` — message is translated and formatted (default behavior). -- `addErrorWithFormatOnly()` — message is formatted (parameter substitution) - but not translated. -- `addErrorWithoutPostProcessing()` — message is used as-is, with no - formatting or translation. +- `addError()` — сообщение переводится и форматируется (поведение по + умолчанию). +- `addErrorWithFormatOnly()` — сообщение отформатировано (подстановка + параметров), но не переведено. +- `addErrorWithoutPostProcessing()` — сообщение используется как есть, без + форматирования или перевода. ```php use Yiisoft\Validator\Result; @@ -396,10 +397,10 @@ $result->addErrorWithFormatOnly('Already formatted: {value}.', ['value' => 42]); $result->addErrorWithoutPostProcessing('This message is used exactly as written.'); ``` -## Merging results +## Объединение результатов -To merge other validation results into the current one, use the `add()` -method: +Для объединения результатов других проверок с текущими используйте метод +`add()`: ```php use Yiisoft\Validator\Result; diff --git a/docs/guide/ru/using-validator.md b/docs/guide/ru/using-validator.md index 1dcd1c299..475854abb 100644 --- a/docs/guide/ru/using-validator.md +++ b/docs/guide/ru/using-validator.md @@ -177,7 +177,7 @@ $result = (new Validator())->validate($value, $rule); местах. Возможны два способа: использование атрибутов и явное указание через реализацию метода интерфейса. -#### Использование атрибутов +#### Using PHP attributes В этом случае правила будут парситься автоматически, дополнительно ничего делать не нужно. @@ -203,10 +203,10 @@ $result = (new Validator())->validate($data, $rulesProvider); #### Использование реализации метода интерфейса -When an object implementing `RulesProviderInterface` is passed as the -`$rules` argument (second argument of `validate()`), only the rules from -`getRules()` are used. PHP attributes on the object are not parsed in this -case. +Когда в качестве аргумента `$rules` (второй аргумент функции `validate()`) +передается объект, реализующий интерфейс `RulesProviderInterface`, +используются только правила из функции `getRules()`. PHP-атрибуты объекта в +этом случае не анализируются. ```php use Yiisoft\Validator\Rule\Length; @@ -216,10 +216,10 @@ use Yiisoft\Validator\Validator; final class PersonRulesProvider implements RulesProviderInterface { - #[Length(min: 2)] // Ignored because the object is passed as the $rules argument. + #[Length(min: 2)] // Будет проигнорировано, т.к. объект передан как аргумент $rules. public string $name; - #[Number(min: 21)] // Ignored because the object is passed as the $rules argument. + #[Number(min: 21)] // Будет проигнорировано, т.к. объект передан как аргумент $rules. public int $age; public function getRules(): iterable @@ -235,10 +235,10 @@ $result = (new Validator())->validate($data, $rulesProvider); ### Передача правил через объект данных -In this way, rules are provided in addition to data in the same object. Both -PHP attributes and `getRules()` method are supported — their rules are -merged (attribute rules are applied first). Note that the `rules` argument -is `null` in the `validate()` method call. +В этом случае правила передаются в дополнение к данным в одном и том же +объекте. Поддерживаются как PHP-атрибуты, так и метод `getRules()` — их +правила объединяются (правила атрибутов применяются первыми). Обратите +внимание, что аргумент `rules` в вызове метода `validate()` равен `null`. ```php use Yiisoft\Validator\Rule\Length; @@ -249,9 +249,9 @@ use Yiisoft\Validator\Validator; final class Person implements RulesProviderInterface { public function __construct( - #[Length(min: 2)] // Merged with rules from getRules(). Attribute rules are applied first. + #[Length(min: 2)] // Объединяется с правилами из getRules(). Правила атрибутов применяются первыми. public string $name = '', - #[Number(min: 21)] // Merged with rules from getRules(). Attribute rules are applied first. + #[Number(min: 21)] // Объединяется с правилами из getRules(). Правила атрибутов применяются первыми. public int $age = 0, ) { } diff --git a/docs/po/ru/README.md.po b/docs/po/ru/README.md.po index d64d0a694..ceaf3614b 100644 --- a/docs/po/ru/README.md.po +++ b/docs/po/ru/README.md.po @@ -6,7 +6,7 @@ msgid "" msgstr "" "Project-Id-Version: \n" -"POT-Creation-Date: 2026-04-21 14:32+0000\n" +"POT-Creation-Date: 2026-06-08 12:31+0000\n" "PO-Revision-Date: 2025-04-06 12:34+0500\n" "Last-Translator: Automatically generated\n" "Language-Team: none\n" @@ -84,6 +84,15 @@ msgstr "" msgid "[Each](built-in-rules-each.md)" msgstr "" +#. type: Bullet: '- ' +#: guide/en/README.md guide/en/built-in-rules.md +#, fuzzy +msgid "[File](built-in-rules-file.md)" +msgstr "" +"#-#-#-#-# README.md.po #-#-#-#-#\n" +"[Each]: built-in-rules-each.md\n" +"#-#-#-#-# built-in-rules.md.po (PACKAGE VERSION) #-#-#-#-#\n" + #. type: Bullet: '- ' #: guide/en/README.md guide/en/built-in-rules.md msgid "[Nested](built-in-rules-nested.md)" diff --git a/docs/po/ru/built-in-rules-callback.md.po b/docs/po/ru/built-in-rules-callback.md.po index a537f68eb..6614afbdd 100644 --- a/docs/po/ru/built-in-rules-callback.md.po +++ b/docs/po/ru/built-in-rules-callback.md.po @@ -5,9 +5,9 @@ # msgid "" msgstr "" -"Project-Id-Version: PACKAGE VERSION\n" +"Project-Id-Version: \n" "POT-Creation-Date: 2026-04-21 14:32+0000\n" -"PO-Revision-Date: 2026-04-21 14:32+0000\n" +"PO-Revision-Date: 2026-06-09 16:14+0500\n" "Last-Translator: Automatically generated\n" "Language-Team: none\n" "Language: ru\n" @@ -15,53 +15,56 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n" +"X-Generator: Poedit 3.9\n" #. type: Title # #: guide/en/built-in-rules-callback.md #, no-wrap msgid "`Callback` - a wrapper around `callable`" -msgstr "" +msgstr "`Callback` - обертка вокруг `вызываемого выражения`" #. type: Plain text #: guide/en/built-in-rules-callback.md #, no-wrap msgid "This rule allows validation of the current property value (but not limited to it) with an arbitrary condition within a \n" msgstr "" +"Это правило позволяет проверять текущее значение свойства (но не только его) с помощью произвольного условия внутри\n" +"\n" #. type: Plain text #: guide/en/built-in-rules-callback.md msgid "callable. The benefit is that there is no need to create a separate custom rule and handler." -msgstr "" +msgstr "вызываемой функции. Преимущество заключается в том, что нет необходимости создавать отдельное пользовательское правило и обработчик." #. type: Plain text #: guide/en/built-in-rules-callback.md msgid "A condition can be within:" -msgstr "" +msgstr "Условие может находиться в:" #. type: Bullet: '- ' #: guide/en/built-in-rules-callback.md msgid "Standalone callable function." -msgstr "" +msgstr "Отдельная вызываемая функция." #. type: Bullet: '- ' #: guide/en/built-in-rules-callback.md msgid "Callable class." -msgstr "" +msgstr "Вызываемый класс." #. type: Bullet: '- ' #: guide/en/built-in-rules-callback.md msgid "DTO (data transfer object) method." -msgstr "" +msgstr "Метод DTO (объекта передачи данных)." #. type: Plain text #: guide/en/built-in-rules-callback.md msgid "The downside of using standalone functions and DTO methods is a lack of reusability. So they are mainly useful for some specific non-repetitive conditions. Reusability can be achieved with callable classes, but depending on other factors (the need for additional parameters for example), it might be a good idea to create a full-fledged [custom rule](creating-custom-rules.md) with a separate handler instead." -msgstr "" +msgstr "Недостатком использования отдельных функций и методов DTO является отсутствие возможности повторного использования. Поэтому они в основном полезны в определенных не повторяющихся конкретных ситуациях. Повторное использование можно обеспечить с помощью вызываемых классов, но в зависимости от других факторов (например, необходимости дополнительных параметров) может оказаться целесообразным вместо этого создать полноценное [пользовательское правило](creating-custom-rules.md) с отдельным обработчиком." #. type: Plain text #: guide/en/built-in-rules-callback.md msgid "The callback function signature is the following:" -msgstr "" +msgstr "Сигнатура функции обратного вызова выглядит следующим образом:" #. type: Fenced code block (php) #: guide/en/built-in-rules-callback.md @@ -82,12 +85,12 @@ msgstr "где:" #. type: Bullet: '- ' #: guide/en/built-in-rules-callback.md msgid "`$value` is the validated value;" -msgstr "" +msgstr "`$value` проверяемое значение;" #. type: Bullet: '- ' #: guide/en/built-in-rules-callback.md msgid "`$rule` is a reference to the original `Callback` rule;" -msgstr "" +msgstr "`$rule` это ссылка на исходное `Callback` правило;" #. type: Bullet: '- ' #: guide/en/built-in-rules-callback.md guide/en/conditional-validation.md @@ -97,18 +100,18 @@ msgstr "`$context` контекст валидации;" #. type: Bullet: '- ' #: guide/en/built-in-rules-callback.md msgid "returned value is a validation result instance with or without errors." -msgstr "" +msgstr "возвращаемое значение представляет собой экземпляр результата проверки, содержащий или не содержащий ошибки." #. type: Title ## #: guide/en/built-in-rules-callback.md #, no-wrap msgid "Using as a function" -msgstr "" +msgstr "Использование как функции" #. type: Plain text #: guide/en/built-in-rules-callback.md msgid "An example of passing a standalone callable function to a `Callback` rule:" -msgstr "" +msgstr "Пример передачи вызываемой функции в правило `Callback`:" #. type: Fenced code block (php) #: guide/en/built-in-rules-callback.md @@ -126,23 +129,34 @@ msgid "" " },\n" ");\n" msgstr "" +"use Yiisoft\\Validator\\Result;\n" +"use Yiisoft\\Validator\\Rule\\Callback;\n" +"use Yiisoft\\Validator\\ValidationContext;\n" +"\n" +"new Callback(\n" +" static function (mixed $value, Callback $rule, ValidationContext $context): Result {\n" +" // Фактический код проверки.\n" +" \n" +" return new Result();\n" +" },\n" +");\n" #. type: Title ## #: guide/en/built-in-rules-callback.md #, no-wrap msgid "Examples" -msgstr "" +msgstr "Примеры" #. type: Title ### #: guide/en/built-in-rules-callback.md #, no-wrap msgid "Value validation" -msgstr "" +msgstr "Проверка значения" #. type: Plain text #: guide/en/built-in-rules-callback.md msgid "`Callback` rule can be used to add validation missing in built-in rules for a single property's value. Below is the example verifying that a value is a valid [YAML](https://en.wikipedia.org/wiki/YAML) string (additionally requires `yaml` PHP extension):" -msgstr "" +msgstr "Правило `Callback` можно использовать для добавления проверки, отсутствующей во встроенных правилах, для значения одного свойства. Ниже приведен пример, подтверждающий, что значение является допустимой строкой [YAML](https://en.wikipedia.org/wiki/YAML) (дополнительно требуется `yaml` модуль для PHP):" #. type: Fenced code block (php) #: guide/en/built-in-rules-callback.md @@ -182,17 +196,19 @@ msgid "" "> **Note:** Processing untrusted user input with `yaml_parse()` can be dangerous with certain settings. Please refer to\n" "> [`yaml_parse()` docs](https://www.php.net/manual/en/function.yaml-parse.php) for more details. \n" msgstr "" +"> **Примечание:** Обработка непроверенного пользовательского ввода с помощью `yaml_parse()` может быть опасной при определенных настройках.\n" +"> Для получения более подробной информации обратитесь к [документации `yaml_parse()`](https://www.php.net/manual/en/function.yaml-parse.php).\n" #. type: Title ### #: guide/en/built-in-rules-callback.md #, no-wrap msgid "Usage of validation context for validating multiple properties depending on each other" -msgstr "" +msgstr "Использование контекста валидации для проверки нескольких свойств, зависящих друг от друга" #. type: Plain text #: guide/en/built-in-rules-callback.md msgid "In the example below, the 3 angles are validated as degrees to form a valid triangle:" -msgstr "" +msgstr "В приведенном ниже примере три угла проверяются на соответствие градусам,чтобы сформировался корректный треугольник:" #. type: Fenced code block (php) #: guide/en/built-in-rules-callback.md @@ -243,12 +259,12 @@ msgstr "" #: guide/en/built-in-rules-callback.md #, no-wrap msgid "Replacing boilerplate code with separate rules and `when`" -msgstr "" +msgstr "Замена шаблонного кода отдельными правилами и `when`" #. type: Plain text #: guide/en/built-in-rules-callback.md msgid "However, some cases of using validation context can lead to boilerplate code:" -msgstr "" +msgstr "Однако в некоторых случаях использование контекста валидации может привести к появлению шаблонного кода:" #. type: Fenced code block (php) #: guide/en/built-in-rules-callback.md @@ -283,7 +299,7 @@ msgstr "" #. type: Plain text #: guide/en/built-in-rules-callback.md msgid "They can be rewritten using multiple rules and conditional validation making code more intuitive. We can use built-in rules where possible:" -msgstr "" +msgstr "Их можно переписать, используя несколько правил и условную проверку, что сделает код более интуитивно понятным. Можно использовать встроенные правила там где это возможно:" #. type: Fenced code block (php) #: guide/en/built-in-rules-callback.md @@ -309,18 +325,18 @@ msgstr "" #: guide/en/built-in-rules-callback.md #, no-wrap msgid "Using as an object's method" -msgstr "" +msgstr "Использование в качестве метода объекта" #. type: Title ### #: guide/en/built-in-rules-callback.md #, no-wrap msgid "For property" -msgstr "" +msgstr "Для свойства" #. type: Plain text #: guide/en/built-in-rules-callback.md msgid "When using as a PHP attribute, set an object's method as a callback instead:" -msgstr "" +msgstr "При использовании в качестве PHP-атрибута установите метод объекта в качестве функции обратного вызова:" #. type: Fenced code block (php) #: guide/en/built-in-rules-callback.md @@ -363,23 +379,23 @@ msgstr "" #. type: Plain text #: guide/en/built-in-rules-callback.md msgid "The signature is the same as in a regular function. Note that there are no restrictions on visibility levels and static modifiers, all of them can be used (`public`, `protected`, `private`, `static`)." -msgstr "" +msgstr "Сигнатура такая же, как и в обычной функции. Обратите внимание, что ограничений на уровни видимости и статические модификаторы нет, все они могут быть использованы (`public`, `protected`, `private`, `static`)." #. type: Plain text #: guide/en/built-in-rules-callback.md msgid "Using a `callback` argument instead of `method` with PHP attributes is prohibited due to current PHP language restrictions (a callback can't be inside a PHP attribute)." -msgstr "" +msgstr "Использование аргумента `callback` вместо `method` с PHP-атрибутами запрещено из-за текущих ограничений языка PHP (функция обратного вызова не может находиться внутри PHP-атрибута)." #. type: Title ### #: guide/en/built-in-rules-callback.md #, no-wrap msgid "For the whole object" -msgstr "" +msgstr "Для всего объекта" #. type: Plain text #: guide/en/built-in-rules-callback.md msgid "It's also possible to check the whole object:" -msgstr "" +msgstr "Также можно проверить весь объект:" #. type: Fenced code block (php) #: guide/en/built-in-rules-callback.md @@ -423,18 +439,18 @@ msgstr "" #: guide/en/built-in-rules-callback.md #, no-wrap msgid "Note the use of property value (`$this->yaml`) instead of method argument (`$value`).\n" -msgstr "" +msgstr "Обратите внимание на использование значения свойства ($this->yaml) вместо аргумента метода ($value).\n" #. type: Title ## #: guide/en/built-in-rules-callback.md #, no-wrap msgid "Using a callable class" -msgstr "" +msgstr "Использование вызываемого класса" #. type: Plain text #: guide/en/built-in-rules-callback.md msgid "A class that implements `__invoke()` can also be used as a callable:" -msgstr "" +msgstr "Класс, реализующий метод `__invoke()`, также можно использовать как вызываемый объект (callable):" #. type: Fenced code block (php) #: guide/en/built-in-rules-callback.md @@ -473,12 +489,12 @@ msgstr "" #. type: Plain text #: guide/en/built-in-rules-callback.md msgid "The signature is the same as in a regular function." -msgstr "" +msgstr "Сигнатура такая же, как и в обычной функции." #. type: Plain text #: guide/en/built-in-rules-callback.md msgid "Using in rules (note that a new instance must be passed, not a class name):" -msgstr "" +msgstr "Использование в правилах (обратите внимание, что необходимо передать экземпляр, а не имя класса):" #. type: Fenced code block (php) #: guide/en/built-in-rules-callback.md @@ -495,12 +511,12 @@ msgstr "" #: guide/en/built-in-rules-callback.md #, no-wrap msgid "Shortcut for use with validator" -msgstr "" +msgstr "Сокращение при использовании в валидаторе" #. type: Plain text #: guide/en/built-in-rules-callback.md msgid "When using with the validator and default `Callback` rule settings, a rule declaration can be omitted, so just including a callable is enough. It will be normalized automatically before validation:" -msgstr "" +msgstr "При использовании в валидаторе и настройках по умолчанию для `Callback` правила, объявление правила можно опустить, поэтому достаточно просто указать вызываемую функцию. Она будет автоматически нормализована перед проверкой:" #. type: Fenced code block (php) #: guide/en/built-in-rules-callback.md @@ -538,7 +554,7 @@ msgstr "" #. type: Plain text #: guide/en/built-in-rules-callback.md msgid "Or it can be set within an array of other rules:" -msgstr "" +msgstr "Или же его можно задать в массиве вместе с другими правилами:" #. type: Fenced code block (php) #: guide/en/built-in-rules-callback.md diff --git a/docs/po/ru/built-in-rules-file.md.po b/docs/po/ru/built-in-rules-file.md.po new file mode 100644 index 000000000..b9033bcce --- /dev/null +++ b/docs/po/ru/built-in-rules-file.md.po @@ -0,0 +1,206 @@ +# Russian translations for PACKAGE package +# Copyright (C) 2026 Free Software Foundation, Inc. +# This file is distributed under the same license as the PACKAGE package. +# Automatically generated, 2026. +# +msgid "" +msgstr "" +"Project-Id-Version: PACKAGE VERSION\n" +"POT-Creation-Date: 2026-06-08 12:31+0000\n" +"PO-Revision-Date: 2026-06-08 12:31+0000\n" +"Last-Translator: Automatically generated\n" +"Language-Team: none\n" +"Language: ru\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n" + +#. type: Title # +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "File" +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "`File` checks that a value is a file and can validate its extension, MIME type, and size." +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "Supported values:" +msgstr "" + +#. type: Bullet: '- ' +#: guide/en/built-in-rules-file.md +msgid "string file paths;" +msgstr "" + +#. type: Bullet: '- ' +#: guide/en/built-in-rules-file.md +msgid "`SplFileInfo` instances;" +msgstr "" + +#. type: Bullet: '- ' +#: guide/en/built-in-rules-file.md +msgid "[PSR-7] `UploadedFileInterface` instances." +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "Use `Each` for multiple files:" +msgstr "" + +#. type: Fenced code block (php) +#: guide/en/built-in-rules-file.md +#, fuzzy, no-wrap +#| msgid "" +#| "use Yiisoft\\Validator\\Rule\\Each;\n" +#| "use Yiisoft\\Validator\\Rule\\Integer;\n" +#| "\n" +#| "new Each([\n" +#| " new Integer(min: 0, max: 255),\n" +#| "]);\n" +msgid "" +"use Yiisoft\\Validator\\Rule\\Each;\n" +"use Yiisoft\\Validator\\Rule\\File;\n" +"\n" +"$rules = [\n" +" 'attachments' => new Each(new File(extensions: ['pdf', 'txt'])),\n" +"];\n" +msgstr "" +"use Yiisoft\\Validator\\Rule\\Each;\n" +"use Yiisoft\\Validator\\Rule\\Integer;\n" +"\n" +"new Each([\n" +" new Integer(min: 0, max: 255),\n" +"]);\n" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "For example, with a PSR-7 request:" +msgstr "" + +#. type: Fenced code block (php) +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "" +"use Yiisoft\\Validator\\Rule\\Each;\n" +"use Yiisoft\\Validator\\Rule\\File;\n" +"use Yiisoft\\Validator\\Validator;\n" +"\n" +"$uploadedFiles = $request->getUploadedFiles()['attachments'] ?? [];\n" +"\n" +"$result = (new Validator())->validate(\n" +" ['attachments' => $uploadedFiles],\n" +" ['attachments' => new Each(new File(maxSize: 5_000_000))],\n" +");\n" +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "If your application works with native PHP `$_FILES` data directly, convert it to supported values such as PSR-7 uploaded file objects before passing it to the validator." +msgstr "" + +#. type: Title ## +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "Uploaded Files" +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "`File` handles PSR-7 upload error codes. `UPLOAD_ERR_NO_FILE` is treated as a missing value, so optional upload fields can use `skipOnEmpty`:" +msgstr "" + +#. type: Fenced code block (php) +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "" +"use Yiisoft\\Validator\\Rule\\File;\n" +"\n" +"$rule = new File(skipOnEmpty: true);\n" +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "Other upload error codes fail validation with `uploadFailedMessage`." +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "The rule does not prove that arbitrary string paths or `SplFileInfo` values came from PHP's HTTP upload mechanism. Do not pass user-submitted paths directly. Use PSR-7 uploaded file objects from a trusted request implementation, or perform [upload provenance checks] before validating filesystem paths." +msgstr "" + +#. type: Title ## +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "MIME Types" +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "For filesystem-backed files, MIME type validation uses PHP's file information facilities through `mime_content_type()`. If the MIME type can't be determined, MIME validation fails." +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "For pathless PSR-7 uploads backed only by an in-memory stream, `File` doesn't trust client-provided media type by default. If your application has already decided that the client metadata is acceptable for this field, enable it explicitly:" +msgstr "" + +#. type: Fenced code block (php) +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "" +"use Yiisoft\\Validator\\Rule\\File;\n" +"\n" +"$rule = new File(\n" +" mimeTypes: ['text/plain'],\n" +" trustClientMediaType: true,\n" +");\n" +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "This option should be used with care because the client can send any media type value." +msgstr "" + +#. type: Title ## +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "Size" +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "For filesystem-backed uploads, size checks use the actual file size on disk. For pathless streams, size checks use the PSR-7 upload size when available. If a size constraint is configured and the size can't be determined, validation fails." +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "`size` is mutually exclusive with `minSize` and `maxSize`. When both `minSize` and `maxSize` are set, `minSize` must be less than or equal to `maxSize`." +msgstr "" + +#. type: Title ## +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "Request Body Streams" +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "`File` doesn't validate generic request body streams such as data read from `php://input` for PUT requests. Convert such input to a supported value first, or write a custom rule that validates your stream format and storage flow." +msgstr "" + +#. type: Link reference +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "[PSR-7]: https://www.php-fig.org/psr/psr-7/" +msgstr "" + +#. type: Link reference +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "[upload provenance checks]: https://www.php.net/manual/en/features.file-upload.post-method.php" +msgstr "" diff --git a/docs/po/ru/built-in-rules-nested.md.po b/docs/po/ru/built-in-rules-nested.md.po index e0159d1ed..058a537a7 100644 --- a/docs/po/ru/built-in-rules-nested.md.po +++ b/docs/po/ru/built-in-rules-nested.md.po @@ -561,9 +561,13 @@ msgstr "Это менее многословно, но недостаток та #. type: Title #### #: guide/en/built-in-rules-nested.md guide/en/using-validator.md -#, no-wrap +#, fuzzy, no-wrap msgid "Using PHP attributes" -msgstr "Использование атрибутов" +msgstr "" +"#-#-#-#-# built-in-rules-nested.md.po #-#-#-#-#\n" +"Использование атрибутов\n" +"#-#-#-#-# using-validator.md.po #-#-#-#-#\n" +"Использование PHP-атрибутов" #. type: Plain text #: guide/en/built-in-rules-nested.md @@ -845,7 +849,7 @@ msgstr "" #. type: Fenced code block (php) #: guide/en/built-in-rules-nested.md guide/en/conditional-validation.md -#, fuzzy, no-wrap +#, no-wrap msgid "" "use Yiisoft\\Validator\\Rule\\BooleanValue;\n" "use Yiisoft\\Validator\\Rule\\Nested;\n" @@ -873,23 +877,30 @@ msgid "" "]);\n" "$result = (new Validator())->validate($data, $rules);\n" msgstr "" -"use Yiisoft\\Validator\\Rule\\Length;\n" +"use Yiisoft\\Validator\\Rule\\BooleanValue;\n" +"use Yiisoft\\Validator\\Rule\\Nested;\n" "use Yiisoft\\Validator\\Rule\\Required;\n" "use Yiisoft\\Validator\\ValidationContext;\n" "use Yiisoft\\Validator\\Validator;\n" "\n" -"$data = [];\n" -"$rules = [\n" -" 'country' => [\n" -" new Required(),\n" -" new Length(min: 2),\n" +"$data = [\n" +" 'push' => [\n" +" 'isEnabled' => true,\n" +" 'content' => null,\n" " ],\n" -" 'state' => new Required(\n" -" when: static function (mixed $value, ValidationContext $context): bool {\n" -" return $context->getDataSet()->getPropertyValue('country') === 'Brazil';\n" -" },\n" -" )\n" "];\n" +"$rules = new Nested([\n" +" 'push' => new Nested([\n" +" 'isEnabled' => [new BooleanValue()],\n" +" 'content' => [\n" +" new Required(\n" +" when: static function (mixed $value, ValidationContext $context): bool {\n" +" return (bool) $context->getDataSet()->getPropertyValue('isEnabled');\n" +" },\n" +" ),\n" +" ],\n" +" ]),\n" +"]);\n" "$result = (new Validator())->validate($data, $rules);\n" #. type: Plain text @@ -1069,9 +1080,13 @@ msgstr "" #. type: Link reference #: guide/en/built-in-rules-nested.md guide/en/customizing-error-messages.md -#, no-wrap +#, fuzzy, no-wrap msgid "[Configuring rules via PHP attributes]: configuring-rules-via-php-attributes.md" -msgstr "[Настройка правил с помощью PHP атрибутов]: configuring-rules-via-php-attributes.md" +msgstr "" +"#-#-#-#-# built-in-rules-nested.md.po #-#-#-#-#\n" +"[Настройка правил с помощью PHP атрибутов]: configuring-rules-via-php-attributes.md\n" +"#-#-#-#-# customizing-error-messages.md.po #-#-#-#-#\n" +"[Настройка правил с помощью PHP-атрибутов]: configuring-rules-via-php-attributes.md" #. type: Link reference #: guide/en/built-in-rules-nested.md diff --git a/docs/po/ru/built-in-rules.md.po b/docs/po/ru/built-in-rules.md.po index 207cceeb0..8104fe5e2 100644 --- a/docs/po/ru/built-in-rules.md.po +++ b/docs/po/ru/built-in-rules.md.po @@ -6,7 +6,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" -"POT-Creation-Date: 2026-04-21 14:32+0000\n" +"POT-Creation-Date: 2026-06-08 12:31+0000\n" "PO-Revision-Date: 2026-04-21 14:32+0000\n" "Last-Translator: Automatically generated\n" "Language-Team: none\n" @@ -40,6 +40,15 @@ msgstr "" msgid "[Each](built-in-rules-each.md)" msgstr "" +#. type: Bullet: '- ' +#: guide/en/README.md guide/en/built-in-rules.md +#, fuzzy +msgid "[File](built-in-rules-file.md)" +msgstr "" +"#-#-#-#-# README.md.po #-#-#-#-#\n" +"[Each]: built-in-rules-each.md\n" +"#-#-#-#-# built-in-rules.md.po (PACKAGE VERSION) #-#-#-#-#\n" + #. type: Bullet: '- ' #: guide/en/README.md guide/en/built-in-rules.md msgid "[Nested](built-in-rules-nested.md)" @@ -270,6 +279,11 @@ msgstr "" msgid "File rules" msgstr "" +#. type: Bullet: '- ' +#: guide/en/built-in-rules.md +msgid "[File](../../../src/Rule/File.php)" +msgstr "" + #. type: Bullet: '- ' #: guide/en/built-in-rules.md msgid "[Image](../../../src/Rule/Image/Image.php)" diff --git a/docs/po/ru/conditional-validation.md.po b/docs/po/ru/conditional-validation.md.po index 074a54883..e5ca6a694 100644 --- a/docs/po/ru/conditional-validation.md.po +++ b/docs/po/ru/conditional-validation.md.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: \n" "POT-Creation-Date: 2026-04-21 14:32+0000\n" -"PO-Revision-Date: 2025-04-19 08:13+0500\n" +"PO-Revision-Date: 2026-06-08 19:29+0500\n" "Last-Translator: Automatically generated\n" "Language-Team: none\n" "Language: ru\n" @@ -15,7 +15,7 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n" -"X-Generator: Poedit 3.6\n" +"X-Generator: Poedit 3.9\n" #. type: Plain text #: guide/en/built-in-rules-callback.md guide/en/conditional-validation.md @@ -29,7 +29,7 @@ msgstr "`$context` контекст валидации;" #. type: Fenced code block (php) #: guide/en/built-in-rules-nested.md guide/en/conditional-validation.md -#, fuzzy, no-wrap +#, no-wrap msgid "" "use Yiisoft\\Validator\\Rule\\BooleanValue;\n" "use Yiisoft\\Validator\\Rule\\Nested;\n" @@ -57,23 +57,30 @@ msgid "" "]);\n" "$result = (new Validator())->validate($data, $rules);\n" msgstr "" -"use Yiisoft\\Validator\\Rule\\Length;\n" +"use Yiisoft\\Validator\\Rule\\BooleanValue;\n" +"use Yiisoft\\Validator\\Rule\\Nested;\n" "use Yiisoft\\Validator\\Rule\\Required;\n" "use Yiisoft\\Validator\\ValidationContext;\n" "use Yiisoft\\Validator\\Validator;\n" "\n" -"$data = [];\n" -"$rules = [\n" -" 'country' => [\n" -" new Required(),\n" -" new Length(min: 2),\n" +"$data = [\n" +" 'push' => [\n" +" 'isEnabled' => true,\n" +" 'content' => null,\n" " ],\n" -" 'state' => new Required(\n" -" when: static function (mixed $value, ValidationContext $context): bool {\n" -" return $context->getDataSet()->getPropertyValue('country') === 'Brazil';\n" -" },\n" -" )\n" "];\n" +"$rules = new Nested([\n" +" 'push' => new Nested([\n" +" 'isEnabled' => [new BooleanValue()],\n" +" 'content' => [\n" +" new Required(\n" +" when: static function (mixed $value, ValidationContext $context): bool {\n" +" return (bool) $context->getDataSet()->getPropertyValue('isEnabled');\n" +" },\n" +" ),\n" +" ],\n" +" ]),\n" +"]);\n" "$result = (new Validator())->validate($data, $rules);\n" #. type: Title # @@ -623,7 +630,7 @@ msgstr "" #: guide/en/conditional-validation.md #, no-wrap msgid "`when` within nested structures" -msgstr "" +msgstr "`when` внутри вложенных структур" #. type: Plain text #: guide/en/conditional-validation.md @@ -632,44 +639,27 @@ msgid "" "`$context->getDataSet()->getPropertyValue()` also works within nested validation, giving access to sibling properties\n" "at the same nesting level.\n" msgstr "" +"Метод `$context->getDataSet()->getPropertyValue()` также работает внутри вложенной проверки, предоставляя доступ к свойствам соседних элементов\n" +"на том же уровне вложенности.\n" #. type: Plain text #: guide/en/conditional-validation.md msgid "In this example `content` is only required when its sibling property `isEnabled` is `true`:" -msgstr "" +msgstr "В этом примере свойство `content` требуется только тогда, когда соседнее свойство `isEnabled` имеет значение `true`:" #. type: Plain text #: guide/en/conditional-validation.md msgid "Since `isEnabled` is `true`, the `Required` rule is applied and `content` fails validation because it is `null`. Setting `isEnabled` to `false` would skip the `Required` rule entirely." -msgstr "" +msgstr "Поскольку `isEnabled` имеет значение `true`, применяется правило `Required` и `content` не проходит проверку, поскольку имеет значение `null`. Установка `isEnabled` в значение `false` полностью пропустит правило `Required`." #. type: Plain text #: guide/en/conditional-validation.md msgid "This approach works at any depth, including inside `Each`:" -msgstr "" +msgstr "Этот подход работает на любом уровне вложенности, в том числе и внутри `Each`:" #. type: Fenced code block (php) #: guide/en/conditional-validation.md -#, fuzzy, no-wrap -#| msgid "" -#| "use Yiisoft\\Validator\\Rule\\Length;\n" -#| "use Yiisoft\\Validator\\Rule\\Required;\n" -#| "use Yiisoft\\Validator\\ValidationContext;\n" -#| "use Yiisoft\\Validator\\Validator;\n" -#| "\n" -#| "$data = [];\n" -#| "$rules = [\n" -#| " 'country' => [\n" -#| " new Required(),\n" -#| " new Length(min: 2),\n" -#| " ],\n" -#| " 'state' => new Required(\n" -#| " when: static function (mixed $value, ValidationContext $context): bool {\n" -#| " return $context->getDataSet()->getPropertyValue('country') === 'Brazil';\n" -#| " },\n" -#| " )\n" -#| "];\n" -#| "$result = (new Validator())->validate($data, $rules);\n" +#, no-wrap msgid "" "use Yiisoft\\Validator\\Rule\\BooleanValue;\n" "use Yiisoft\\Validator\\Rule\\Each;\n" @@ -706,23 +696,39 @@ msgid "" "]);\n" "$result = (new Validator())->validate($data, $rules);\n" msgstr "" -"use Yiisoft\\Validator\\Rule\\Length;\n" +"use Yiisoft\\Validator\\Rule\\BooleanValue;\n" +"use Yiisoft\\Validator\\Rule\\Each;\n" +"use Yiisoft\\Validator\\Rule\\Nested;\n" "use Yiisoft\\Validator\\Rule\\Required;\n" "use Yiisoft\\Validator\\ValidationContext;\n" "use Yiisoft\\Validator\\Validator;\n" "\n" -"$data = [];\n" -"$rules = [\n" -" 'country' => [\n" -" new Required(),\n" -" new Length(min: 2),\n" +"$data = [\n" +" 'tasks' => [\n" +" [\n" +" 'push' => [\n" +" 'isEnabled' => false,\n" +" 'content' => null,\n" +" ],\n" +" ],\n" " ],\n" -" 'state' => new Required(\n" -" when: static function (mixed $value, ValidationContext $context): bool {\n" -" return $context->getDataSet()->getPropertyValue('country') === 'Brazil';\n" -" },\n" -" )\n" "];\n" +"$rules = new Nested([\n" +" 'tasks' => new Each(\n" +" new Nested([\n" +" 'push' => new Nested([\n" +" 'isEnabled' => [new BooleanValue()],\n" +" 'content' => [\n" +" new Required(\n" +" when: static function (mixed $value, ValidationContext $context): bool {\n" +" return (bool) $context->getDataSet()->getPropertyValue('isEnabled');\n" +" },\n" +" ),\n" +" ],\n" +" ]),\n" +" ]),\n" +" ),\n" +"]);\n" "$result = (new Validator())->validate($data, $rules);\n" #. type: Plain text diff --git a/docs/po/ru/customizing-error-messages.md.po b/docs/po/ru/customizing-error-messages.md.po index 0aeac4f0e..ae2b9b0ef 100644 --- a/docs/po/ru/customizing-error-messages.md.po +++ b/docs/po/ru/customizing-error-messages.md.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: \n" "POT-Creation-Date: 2026-04-21 14:32+0000\n" -"PO-Revision-Date: 2025-04-19 07:44+0500\n" +"PO-Revision-Date: 2026-06-09 13:13+0500\n" "Last-Translator: Automatically generated\n" "Language-Team: none\n" "Language: ru\n" @@ -15,13 +15,17 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n" -"X-Generator: Poedit 3.6\n" +"X-Generator: Poedit 3.9\n" #. type: Link reference #: guide/en/built-in-rules-nested.md guide/en/customizing-error-messages.md -#, no-wrap +#, fuzzy, no-wrap msgid "[Configuring rules via PHP attributes]: configuring-rules-via-php-attributes.md" -msgstr "[Настройка правил с помощью PHP атрибутов]: configuring-rules-via-php-attributes.md" +msgstr "" +"#-#-#-#-# built-in-rules-nested.md.po #-#-#-#-#\n" +"[Настройка правил с помощью PHP атрибутов]: configuring-rules-via-php-attributes.md\n" +"#-#-#-#-# customizing-error-messages.md.po #-#-#-#-#\n" +"[Настройка правил с помощью PHP-атрибутов]: configuring-rules-via-php-attributes.md" #. type: Title # #: guide/en/customizing-error-messages.md @@ -150,15 +154,13 @@ msgstr "Перевод имен свойств" #. type: Plain text #: guide/en/customizing-error-messages.md -#, fuzzy -#| msgid "Almost all error templates have support for a `{property}` placeholder which is substituted with an actual property name that was set during rules configuration. By default, a property name is formatted as is. It can be acceptable for English language (for example, `currentPassword is required.`), but when using translations for error messages, it's better to provide an additional property translation." msgid "Almost all error templates have support for `{property}` and `{Property}` placeholders which are substituted with an actual property name that was set during rules configuration. The `{Property}` variant capitalizes the first letter. By default, a property name is formatted as is. It can be acceptable for English language (for example, `currentPassword is required.`), but when using translations for error messages, it's better to provide an additional property translation." -msgstr "Почти все шаблоны ошибок поддерживают плейсхолдер `{property}`, который заменяется фактическим именем свойства, заданным во время настройки правил. По умолчанию имя свойства форматируется без изменений. Это может быть приемлемо для английского языка (например, `currentPassword is required.`), но при использовании перевода сообщений об ошибках, лучше предоставить дополнительный перевод свойства." +msgstr "Практически все шаблоны ошибок поддерживают заполнители `{property}` и `{Property}`, которые заменяются на фактическое имя свойства, заданное при настройке правил. Вариант `{Property}` преобразует первую букву в заглавную. По умолчанию имя свойства форматируется без изменений. Это может быть приемлемо для английского языка (например, `currentPassword is required.`), но при использовании переводов для сообщений об ошибках лучше предоставить дополнительный перевод свойства." #. type: Plain text #: guide/en/customizing-error-messages.md msgid "The simplest approach for properties defined via PHP attributes is to use the `Label` attribute directly on the property. See [Configuring rules via PHP attributes] for details." -msgstr "" +msgstr "Самый простой способ настройки свойств, определяемых с помощью PHP-атрибутов, — это непосредственное использование атрибута `Label` для данного свойства. Подробнее см. в разделе [Настройка правил с помощью PHP-атрибутов]." #. type: Plain text #: guide/en/customizing-error-messages.md diff --git a/docs/po/ru/result.md.po b/docs/po/ru/result.md.po index cdadb0f98..cc0515264 100644 --- a/docs/po/ru/result.md.po +++ b/docs/po/ru/result.md.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: \n" "POT-Creation-Date: 2026-03-24 11:57+0000\n" -"PO-Revision-Date: 2025-09-03 15:50+0500\n" +"PO-Revision-Date: 2026-06-08 18:55+0500\n" "Last-Translator: Automatically generated\n" "Language-Team: none\n" "Language: ru\n" @@ -15,7 +15,7 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n" -"X-Generator: Poedit 3.7\n" +"X-Generator: Poedit 3.9\n" #. type: Title # #: guide/en/result.md @@ -25,8 +25,6 @@ msgstr "Результат" #. type: Plain text #: guide/en/result.md -#, fuzzy -#| msgid "The validation result is an object containing of errors occurred during validation." msgid "The validation result is an object containing errors that occurred during validation." msgstr "Результатом валидации является объект, содержащий ошибки, возникшие во время проверки." @@ -43,12 +41,7 @@ msgstr "Чтобы просто проверить статус валидаци #. type: Fenced code block (php) #: guide/en/result.md -#, fuzzy, no-wrap -#| msgid "" -#| "use Yiisoft\\Validator\\Result;\n" -#| "\n" -#| "/** @var Result */\n" -#| "$result->isValid();\n" +#, no-wrap msgid "" "use Yiisoft\\Validator\\Result;\n" "\n" @@ -57,9 +50,8 @@ msgid "" msgstr "" "use Yiisoft\\Validator\\Result;\n" "\n" -"/** @var Result */\n" +"/** @var Result $result */\n" "$result->isValid();\n" -"\n" #. type: Plain text #: guide/en/result.md @@ -104,12 +96,7 @@ msgstr "Одним из самых простых случаев являетс #. type: Fenced code block (php) #: guide/en/result.md -#, fuzzy, no-wrap -#| msgid "" -#| "use Yiisoft\\Validator\\Result;\n" -#| "\n" -#| "/** @var Result */\n" -#| "$result->getErrorMessages();\n" +#, no-wrap msgid "" "use Yiisoft\\Validator\\Result;\n" "\n" @@ -118,7 +105,7 @@ msgid "" msgstr "" "use Yiisoft\\Validator\\Result;\n" "\n" -"/** @var Result */\n" +"/** @var Result $result */\n" "$result->getErrorMessages();\n" #. type: Plain text @@ -240,12 +227,7 @@ msgstr "Для группировки сообщений об ошибках п #. type: Fenced code block (php) #: guide/en/result.md -#, fuzzy, no-wrap -#| msgid "" -#| "use Yiisoft\\Validator\\Result;\n" -#| "\n" -#| "/** @var Result */\n" -#| "$result->getErrorMessagesIndexedByProperty();\n" +#, no-wrap msgid "" "use Yiisoft\\Validator\\Result;\n" "\n" @@ -254,7 +236,7 @@ msgid "" msgstr "" "use Yiisoft\\Validator\\Result;\n" "\n" -"/** @var Result */\n" +"/** @var Result $result */\n" "$result->getErrorMessagesIndexedByProperty();\n" #. type: Plain text @@ -324,10 +306,9 @@ msgstr "Также имейте в виду, что имена свойств в #. type: Fenced code block (php) #: guide/en/result.md -#, fuzzy, no-wrap -#| msgid "$rule = new Each([new Number(min: 21)]),\n" +#, no-wrap msgid "$rule = new Each([new Number(min: 21)]);\n" -msgstr "$rule = new Each([new Number(min: 21)]),\n" +msgstr "$rule = new Each([new Number(min: 21)]);\n" #. type: Plain text #: guide/en/result.md @@ -364,24 +345,18 @@ msgstr "" #. type: Title ### #: guide/en/result.md -#, fuzzy, no-wrap -#| msgid "Error messages indexed by property" +#, no-wrap msgid "First error messages indexed by property" -msgstr "Сообщения об ошибках, сгруппированные по свойству" +msgstr "Первые сообщения об ошибках, сгруппированные по свойству" #. type: Plain text #: guide/en/result.md msgid "To get only the first error message for each property (useful for displaying a single error per field), use:" -msgstr "" +msgstr "Чтобы получить только первое сообщение об ошибке для каждого свойства (что полезно для отображения одной ошибки для каждого поля), используйте:" #. type: Fenced code block (php) #: guide/en/result.md -#, fuzzy, no-wrap -#| msgid "" -#| "use Yiisoft\\Validator\\Result;\n" -#| "\n" -#| "/** @var Result */\n" -#| "$result->getErrorMessagesIndexedByProperty();\n" +#, no-wrap msgid "" "use Yiisoft\\Validator\\Result;\n" "\n" @@ -390,18 +365,12 @@ msgid "" msgstr "" "use Yiisoft\\Validator\\Result;\n" "\n" -"/** @var Result */\n" -"$result->getErrorMessagesIndexedByProperty();\n" +"/** @var Result $result */\n" +"$result->getFirstErrorMessagesIndexedByProperty();\n" #. type: Fenced code block (php) #: guide/en/result.md -#, fuzzy, no-wrap -#| msgid "" -#| "[\n" -#| " 'Value must be no less than 21.',\n" -#| " 'This value is not a valid email address.',\n" -#| " 'A custom error message.',\n" -#| "];\n" +#, no-wrap msgid "" "[\n" " 'name' => 'Value cannot be blank.',\n" @@ -410,15 +379,15 @@ msgid "" "];\n" msgstr "" "[\n" -" 'Value must be no less than 21.',\n" -" 'This value is not a valid email address.',\n" -" 'A custom error message.',\n" +" 'name' => 'Value cannot be blank.',\n" +" 'email' => 'This value is not a valid email address.',\n" +" '' => 'A custom error message.',\n" "];\n" #. type: Plain text #: guide/en/result.md msgid "Note that unlike `getErrorMessagesIndexedByProperty()`, each value is a single string, not an array." -msgstr "" +msgstr "Обратите внимание, что в отличие от `getErrorMessagesIndexedByProperty()`, каждое значение представляет собой отдельную строку, а не массив." #. type: Title ### #: guide/en/result.md @@ -433,12 +402,7 @@ msgstr "Вероятно, это самое продвинутое предст #. type: Fenced code block (php) #: guide/en/result.md -#, fuzzy, no-wrap -#| msgid "" -#| "use Yiisoft\\Validator\\Result;\n" -#| "\n" -#| "/** @var Result */\n" -#| "$result->getErrorMessagesIndexedByPath();\n" +#, no-wrap msgid "" "use Yiisoft\\Validator\\Result;\n" "\n" @@ -447,7 +411,7 @@ msgid "" msgstr "" "use Yiisoft\\Validator\\Result;\n" "\n" -"/** @var Result */\n" +"/** @var Result $result */\n" "$result->getErrorMessagesIndexedByPath();\n" #. type: Fenced code block (php) @@ -489,24 +453,18 @@ msgstr "" #. type: Title #### #: guide/en/result.md -#, fuzzy, no-wrap -#| msgid "Error messages indexed by path" +#, no-wrap msgid "First error messages indexed by path" -msgstr "Сообщения об ошибках, сгруппированные по пути" +msgstr "Первые сообщения об ошибках, сгруппированные по пути" #. type: Plain text #: guide/en/result.md msgid "To get only the first error message for each path (useful for displaying a single error per field), use:" -msgstr "" +msgstr "Чтобы получить только первое сообщение об ошибке для каждого пути (это полезно для отображения одной ошибки для каждого поля), используйте:" #. type: Fenced code block (php) #: guide/en/result.md -#, fuzzy, no-wrap -#| msgid "" -#| "use Yiisoft\\Validator\\Result;\n" -#| "\n" -#| "/** @var Result */\n" -#| "$result->getErrorMessagesIndexedByPath();\n" +#, no-wrap msgid "" "use Yiisoft\\Validator\\Result;\n" "\n" @@ -515,20 +473,12 @@ msgid "" msgstr "" "use Yiisoft\\Validator\\Result;\n" "\n" -"/** @var Result */\n" -"$result->getErrorMessagesIndexedByPath();\n" +"/** @var Result $result */\n" +"$result->getFirstErrorMessagesIndexedByPath();\n" #. type: Fenced code block (php) #: guide/en/result.md -#, fuzzy, no-wrap -#| msgid "" -#| "[\n" -#| " 'user.firstName' => ['Value cannot be blank.'],\n" -#| " 'user.lastName' => ['This value must contain at least 4 characters.'],\n" -#| " 'email' => ['This value is not a valid email address.'],\n" -#| " // Error messages not bound to specific property are grouped under empty string key.\n" -#| " '' => ['A custom error message.'],\n" -#| "];\n" +#, no-wrap msgid "" "[\n" " 'user.firstName' => 'Value cannot be blank.',\n" @@ -538,17 +488,16 @@ msgid "" "];\n" msgstr "" "[\n" -" 'user.firstName' => ['Value cannot be blank.'],\n" -" 'user.lastName' => ['This value must contain at least 4 characters.'],\n" -" 'email' => ['This value is not a valid email address.'],\n" -" // Сообщения об ошибках, не привязанные к конкретному свойству, группируются в ключе со значением пустая строка.\n" -" '' => ['A custom error message.'],\n" +" 'user.firstName' => 'Value cannot be blank.',\n" +" 'user.lastName' => 'This value must contain at least 4 characters.',\n" +" 'email' => 'This value is not a valid email address.',\n" +" '' => 'A custom error message.',\n" "];\n" #. type: Plain text #: guide/en/result.md msgid "Note that unlike `getErrorMessagesIndexedByPath()`, each value is a single string, not an array." -msgstr "" +msgstr "Обратите внимание, что в отличие от `getErrorMessagesIndexedByPath()`, каждое значение представляет собой отдельную строку, а не массив." #. type: Title #### #: guide/en/result.md @@ -658,12 +607,7 @@ msgstr "Когда даже этих представлений недостат #. type: Fenced code block (php) #: guide/en/result.md -#, fuzzy, no-wrap -#| msgid "" -#| "use Yiisoft\\Validator\\Result;\n" -#| "\n" -#| "/** @var Result */\n" -#| "$result->getErrors();\n" +#, no-wrap msgid "" "use Yiisoft\\Validator\\Result;\n" "\n" @@ -672,7 +616,7 @@ msgid "" msgstr "" "use Yiisoft\\Validator\\Result;\n" "\n" -"/** @var Result */\n" +"/** @var Result $result */\n" "$result->getErrors();\n" #. type: Plain text @@ -758,27 +702,27 @@ msgstr "" #: guide/en/result.md #, no-wrap msgid "Adding errors" -msgstr "" +msgstr "Добавление ошибок" #. type: Plain text #: guide/en/result.md msgid "When writing custom rule handlers, errors are added to a `Result` object. There are three methods available, each with different post-processing behavior:" -msgstr "" +msgstr "При написании пользовательских обработчиков правил ошибки добавляются в объект `Result`. Доступны три метода, каждый из которых имеет различное поведение при постобработке:" #. type: Bullet: '- ' #: guide/en/result.md msgid "`addError()` — message is translated and formatted (default behavior)." -msgstr "" +msgstr "`addError()` — сообщение переводится и форматируется (поведение по умолчанию)." #. type: Bullet: '- ' #: guide/en/result.md msgid "`addErrorWithFormatOnly()` — message is formatted (parameter substitution) but not translated." -msgstr "" +msgstr "`addErrorWithFormatOnly()` — сообщение отформатировано (подстановка параметров), но не переведено." #. type: Bullet: '- ' #: guide/en/result.md msgid "`addErrorWithoutPostProcessing()` — message is used as-is, with no formatting or translation." -msgstr "" +msgstr "`addErrorWithoutPostProcessing()` — сообщение используется как есть, без форматирования или перевода." #. type: Fenced code block (php) #: guide/en/result.md @@ -791,17 +735,23 @@ msgid "" "$result->addErrorWithFormatOnly('Already formatted: {value}.', ['value' => 42]);\n" "$result->addErrorWithoutPostProcessing('This message is used exactly as written.');\n" msgstr "" +"use Yiisoft\\Validator\\Result;\n" +"\n" +"$result = new Result();\n" +"$result->addError('Value must be no less than {min}.', ['min' => 7]);\n" +"$result->addErrorWithFormatOnly('Already formatted: {value}.', ['value' => 42]);\n" +"$result->addErrorWithoutPostProcessing('This message is used exactly as written.');\n" #. type: Title ## #: guide/en/result.md #, no-wrap msgid "Merging results" -msgstr "" +msgstr "Объединение результатов" #. type: Plain text #: guide/en/result.md msgid "To merge other validation results into the current one, use the `add()` method:" -msgstr "" +msgstr "Для объединения результатов других проверок с текущими используйте метод `add()`:" #. type: Fenced code block (php) #: guide/en/result.md @@ -818,6 +768,16 @@ msgid "" "$result1->add($result2);\n" "$result1->getErrorMessages(); // ['Error 1.', 'Error 2.']\n" msgstr "" +"use Yiisoft\\Validator\\Result;\n" +"\n" +"$result1 = new Result();\n" +"$result1->addError('Error 1.');\n" +"\n" +"$result2 = new Result();\n" +"$result2->addError('Error 2.');\n" +"\n" +"$result1->add($result2);\n" +"$result1->getErrorMessages(); // ['Error 1.', 'Error 2.']\n" #. type: Link reference #: guide/en/result.md diff --git a/docs/po/ru/using-validator.md.po b/docs/po/ru/using-validator.md.po index 738f36554..40432fe54 100644 --- a/docs/po/ru/using-validator.md.po +++ b/docs/po/ru/using-validator.md.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: \n" "POT-Creation-Date: 2026-04-24 09:45+0000\n" -"PO-Revision-Date: 2025-04-12 20:36+0500\n" +"PO-Revision-Date: 2026-06-08 18:32+0500\n" "Last-Translator: Automatically generated\n" "Language-Team: none\n" "Language: ru\n" @@ -15,7 +15,7 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n" -"X-Generator: Poedit 3.6\n" +"X-Generator: Poedit 3.9\n" #. type: Title ## #: guide/en/README.md guide/en/using-validator.md @@ -25,9 +25,13 @@ msgstr "Правила" #. type: Title #### #: guide/en/built-in-rules-nested.md guide/en/using-validator.md -#, no-wrap +#, fuzzy, no-wrap msgid "Using PHP attributes" -msgstr "Использование атрибутов" +msgstr "" +"#-#-#-#-# built-in-rules-nested.md.po #-#-#-#-#\n" +"Использование атрибутов\n" +"#-#-#-#-# using-validator.md.po #-#-#-#-#\n" +"Использование PHP-атрибутов" #. type: Link reference #: guide/en/configuring-rules-via-php-attributes.md @@ -97,16 +101,16 @@ msgid "" "];\n" "$result = (new Validator())->validate($value, $rules);\n" msgstr "" -"use Yiisoft\\Validator\\Rule\\Length;\r\n" -"use Yiisoft\\Validator\\Rule\\Regex;\r\n" -"use Yiisoft\\Validator\\Validator;\r\n" -"\r\n" -"$value = 'mrX';\r\n" -"$rules = [\r\n" -" new Length(min: 4, max: 20),\r\n" -" new Regex('~^[a-z_\\-]*$~i'),\r\n" -"];\r\n" -"$result = (new Validator())->validate($value, $rules);\r\n" +"use Yiisoft\\Validator\\Rule\\Length;\n" +"use Yiisoft\\Validator\\Rule\\Regex;\n" +"use Yiisoft\\Validator\\Validator;\n" +"\n" +"$value = 'mrX';\n" +"$rules = [\n" +" new Length(min: 4, max: 20),\n" +" new Regex('~^[a-z_\\-]*$~i'),\n" +"];\n" +"$result = (new Validator())->validate($value, $rules);\n" #. type: Plain text #: guide/en/using-validator.md @@ -419,24 +423,7 @@ msgstr "В этом случае правила будут парситься а #. type: Fenced code block (php) #: guide/en/using-validator.md -#, fuzzy, no-wrap -#| msgid "" -#| "use Yiisoft\\Validator\\Rule\\Length;\n" -#| "use Yiisoft\\Validator\\Rule\\Number;\n" -#| "use Yiisoft\\Validator\\Validator;\n" -#| "\n" -#| "final class PersonRulesProvider\n" -#| "{\n" -#| " #[Length(min: 2)]\n" -#| " public string $name;\n" -#| "\n" -#| " #[Number(min: 21)]\n" -#| " protected int $age;\n" -#| "}\n" -#| "\n" -#| "$data = ['name' => 'John', 'age' => 18];\n" -#| "$rulesProvider = new PersonRulesProvider();\n" -#| "$result = (new Validator())->validate($data, $rulesProvider);\n" +#, no-wrap msgid "" "use Yiisoft\\Validator\\Rule\\Length;\n" "use Yiisoft\\Validator\\Rule\\Number;\n" @@ -465,7 +452,7 @@ msgstr "" " public string $name;\n" "\n" " #[Number(min: 21)]\n" -" protected int $age;\n" +" public int $age;\n" "}\n" "\n" "$data = ['name' => 'John', 'age' => 18];\n" @@ -481,34 +468,11 @@ msgstr "Использование реализации метода интер #. type: Plain text #: guide/en/using-validator.md msgid "When an object implementing `RulesProviderInterface` is passed as the `$rules` argument (second argument of `validate()`), only the rules from `getRules()` are used. PHP attributes on the object are not parsed in this case." -msgstr "" +msgstr "Когда в качестве аргумента `$rules` (второй аргумент функции `validate()`) передается объект, реализующий интерфейс `RulesProviderInterface`, используются только правила из функции `getRules()`. PHP-атрибуты объекта в этом случае не анализируются." #. type: Fenced code block (php) #: guide/en/using-validator.md -#, fuzzy, no-wrap -#| msgid "" -#| "use Yiisoft\\Validator\\Rule\\Length;\n" -#| "use Yiisoft\\Validator\\Rule\\Number;\n" -#| "use Yiisoft\\Validator\\RulesProviderInterface;\n" -#| "use Yiisoft\\Validator\\Validator;\n" -#| "\n" -#| "final class PersonRulesProvider implements RulesProviderInterface\n" -#| "{\n" -#| " #[Length(min: 2)] // Will be silently ignored.\n" -#| " public string $name;\n" -#| "\n" -#| " #[Number(min: 21)] // Will be silently ignored.\n" -#| " protected int $age;\n" -#| " \n" -#| " public function getRules() : iterable\n" -#| " {\n" -#| " return ['name' => new Length(min: 2), 'age' => new Number(min: 21)];\n" -#| " }\n" -#| "}\n" -#| "\n" -#| "$data = ['name' => 'John', 'age' => 18];\n" -#| "$rulesProvider = new PersonRulesProvider();\n" -#| "$result = (new Validator())->validate($data, $rulesProvider);\n" +#, no-wrap msgid "" "use Yiisoft\\Validator\\Rule\\Length;\n" "use Yiisoft\\Validator\\Rule\\Number;\n" @@ -540,13 +504,13 @@ msgstr "" "\n" "final class PersonRulesProvider implements RulesProviderInterface\n" "{\n" -" #[Length(min: 2)] // Будет тихо проигнорировано.\n" +" #[Length(min: 2)] // Будет проигнорировано, т.к. объект передан как аргумент $rules.\n" " public string $name;\n" "\n" -" #[Number(min: 21)] // Будет тихо проигнорировано.\n" -" protected int $age;\n" -" \n" -" public function getRules() : iterable\n" +" #[Number(min: 21)] // Будет проигнорировано, т.к. объект передан как аргумент $rules.\n" +" public int $age;\n" +"\n" +" public function getRules(): iterable\n" " {\n" " return ['name' => new Length(min: 2), 'age' => new Number(min: 21)];\n" " }\n" @@ -564,38 +528,12 @@ msgstr "Передача правил через объект данных" #. type: Plain text #: guide/en/using-validator.md -#, fuzzy -#| msgid "In this way, rules are provided in addition to data in the same object. Only interface method implementation is supported. Note that the `rules` argument is `null` in the `validate()` method call." msgid "In this way, rules are provided in addition to data in the same object. Both PHP attributes and `getRules()` method are supported — their rules are merged (attribute rules are applied first). Note that the `rules` argument is `null` in the `validate()` method call." -msgstr "" -"В этом случае правила передаются в дополнение к данным в одном и том же объекте.\n" -"Поддерживается только реализация метода интерфейса. Обратите внимание, что аргумент `rules` имеет значение `null` при вызове метода `validate()`." +msgstr "В этом случае правила передаются в дополнение к данным в одном и том же объекте. Поддерживаются как PHP-атрибуты, так и метод `getRules()` — их правила объединяются (правила атрибутов применяются первыми). Обратите внимание, что аргумент `rules` в вызове метода `validate()` равен `null`." #. type: Fenced code block (php) #: guide/en/using-validator.md -#, fuzzy, no-wrap -#| msgid "" -#| "use Yiisoft\\Validator\\Rule\\Length;\n" -#| "use Yiisoft\\Validator\\Rule\\Number;\n" -#| "use Yiisoft\\Validator\\RulesProviderInterface;\n" -#| "use Yiisoft\\Validator\\Validator;\n" -#| "\n" -#| "final class Person implements RulesProviderInterface\n" -#| "{\n" -#| " #[Length(min: 2)] // Not supported for using with data objects. Will be silently ignored.\n" -#| " public string $name;\n" -#| "\n" -#| " #[Number(min: 21)] // Not supported for using with data objects. Will be silently ignored.\n" -#| " protected int $age;\n" -#| " \n" -#| " public function getRules(): iterable\n" -#| " {\n" -#| " return ['name' => new Length(min: 2), 'age' => new Number(min: 21)];\n" -#| " }\n" -#| "}\n" -#| "\n" -#| "$data = new Person(name: 'John', age: 18);\n" -#| "$result = (new Validator())->validate($data);\n" +#, no-wrap msgid "" "use Yiisoft\\Validator\\Rule\\Length;\n" "use Yiisoft\\Validator\\Rule\\Number;\n" @@ -628,12 +566,14 @@ msgstr "" "\n" "final class Person implements RulesProviderInterface\n" "{\n" -" #[Length(min: 2)] // Не поддерживается для использования с объектами данных. Будет тихо проигнорировано.\n" -" public string $name;\n" +" public function __construct(\n" +" #[Length(min: 2)] // Объединяется с правилами из getRules(). Правила атрибутов применяются первыми.\n" +" public string $name = '',\n" +" #[Number(min: 21)] // Объединяется с правилами из getRules(). Правила атрибутов применяются первыми.\n" +" public int $age = 0,\n" +" ) {\n" +" }\n" "\n" -" #[Number(min: 21)] // Не поддерживается для использования с объектами данных. Будет тихо проигнорировано.\n" -" protected int $age;\n" -" \n" " public function getRules(): iterable\n" " {\n" " return ['name' => new Length(min: 2), 'age' => new Number(min: 21)];\n" diff --git a/docs/po4a.conf b/docs/po4a.conf index 78cdf03e7..121ae209a 100644 --- a/docs/po4a.conf +++ b/docs/po4a.conf @@ -9,6 +9,7 @@ [type: markdown] guide/en/built-in-rules-compare.md $lang:guide/$lang/built-in-rules-compare.md pot=built-in-rules-compare.md [type: markdown] guide/en/built-in-rules-composite.md $lang:guide/$lang/built-in-rules-composite.md pot=built-in-rules-composite.md [type: markdown] guide/en/built-in-rules-each.md $lang:guide/$lang/built-in-rules-each.md pot=built-in-rules-each.md +[type: markdown] guide/en/built-in-rules-file.md $lang:guide/$lang/built-in-rules-file.md pot=built-in-rules-file.md [type: markdown] guide/en/built-in-rules-nested.md $lang:guide/$lang/built-in-rules-nested.md pot=built-in-rules-nested.md [type: markdown] guide/en/built-in-rules-required.md $lang:guide/$lang/built-in-rules-required.md pot=built-in-rules-required.md [type: markdown] guide/en/built-in-rules-stop-on-error.md $lang:guide/$lang/built-in-rules-stop-on-error.md pot=built-in-rules-stop-on-error.md diff --git a/docs/pot/README.md.pot b/docs/pot/README.md.pot index 3bc849d67..c75532485 100644 --- a/docs/pot/README.md.pot +++ b/docs/pot/README.md.pot @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" -"POT-Creation-Date: 2026-04-21 14:32+0000\n" +"POT-Creation-Date: 2026-06-08 12:31+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -79,6 +79,11 @@ msgstr "" msgid "[Each](built-in-rules-each.md)" msgstr "" +#. type: Bullet: '- ' +#: guide/en/README.md guide/en/built-in-rules.md +msgid "[File](built-in-rules-file.md)" +msgstr "" + #. type: Bullet: '- ' #: guide/en/README.md guide/en/built-in-rules.md msgid "[Nested](built-in-rules-nested.md)" diff --git a/docs/pot/built-in-rules-file.md.pot b/docs/pot/built-in-rules-file.md.pot new file mode 100644 index 000000000..360a48767 --- /dev/null +++ b/docs/pot/built-in-rules-file.md.pot @@ -0,0 +1,225 @@ +# SOME DESCRIPTIVE TITLE +# Copyright (C) YEAR Free Software Foundation, Inc. +# This file is distributed under the same license as the PACKAGE package. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: PACKAGE VERSION\n" +"POT-Creation-Date: 2026-06-08 12:31+0000\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: en_US\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +#. type: Title # +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "File" +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "" +"`File` checks that a value is a file and can validate its extension, MIME " +"type, and size." +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "Supported values:" +msgstr "" + +#. type: Bullet: '- ' +#: guide/en/built-in-rules-file.md +msgid "string file paths;" +msgstr "" + +#. type: Bullet: '- ' +#: guide/en/built-in-rules-file.md +msgid "`SplFileInfo` instances;" +msgstr "" + +#. type: Bullet: '- ' +#: guide/en/built-in-rules-file.md +msgid "[PSR-7] `UploadedFileInterface` instances." +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "Use `Each` for multiple files:" +msgstr "" + +#. type: Fenced code block (php) +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "" +"use Yiisoft\\Validator\\Rule\\Each;\n" +"use Yiisoft\\Validator\\Rule\\File;\n" +"\n" +"$rules = [\n" +" 'attachments' => new Each(new File(extensions: ['pdf', 'txt'])),\n" +"];\n" +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "For example, with a PSR-7 request:" +msgstr "" + +#. type: Fenced code block (php) +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "" +"use Yiisoft\\Validator\\Rule\\Each;\n" +"use Yiisoft\\Validator\\Rule\\File;\n" +"use Yiisoft\\Validator\\Validator;\n" +"\n" +"$uploadedFiles = $request->getUploadedFiles()['attachments'] ?? [];\n" +"\n" +"$result = (new Validator())->validate(\n" +" ['attachments' => $uploadedFiles],\n" +" ['attachments' => new Each(new File(maxSize: 5_000_000))],\n" +");\n" +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "" +"If your application works with native PHP `$_FILES` data directly, convert " +"it to supported values such as PSR-7 uploaded file objects before passing it " +"to the validator." +msgstr "" + +#. type: Title ## +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "Uploaded Files" +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "" +"`File` handles PSR-7 upload error codes. `UPLOAD_ERR_NO_FILE` is treated as " +"a missing value, so optional upload fields can use `skipOnEmpty`:" +msgstr "" + +#. type: Fenced code block (php) +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "" +"use Yiisoft\\Validator\\Rule\\File;\n" +"\n" +"$rule = new File(skipOnEmpty: true);\n" +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "Other upload error codes fail validation with `uploadFailedMessage`." +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "" +"The rule does not prove that arbitrary string paths or `SplFileInfo` values " +"came from PHP's HTTP upload mechanism. Do not pass user-submitted paths " +"directly. Use PSR-7 uploaded file objects from a trusted request " +"implementation, or perform [upload provenance checks] before validating " +"filesystem paths." +msgstr "" + +#. type: Title ## +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "MIME Types" +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "" +"For filesystem-backed files, MIME type validation uses PHP's file " +"information facilities through `mime_content_type()`. If the MIME type can't " +"be determined, MIME validation fails." +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "" +"For pathless PSR-7 uploads backed only by an in-memory stream, `File` " +"doesn't trust client-provided media type by default. If your application has " +"already decided that the client metadata is acceptable for this field, " +"enable it explicitly:" +msgstr "" + +#. type: Fenced code block (php) +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "" +"use Yiisoft\\Validator\\Rule\\File;\n" +"\n" +"$rule = new File(\n" +" mimeTypes: ['text/plain'],\n" +" trustClientMediaType: true,\n" +");\n" +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "" +"This option should be used with care because the client can send any media " +"type value." +msgstr "" + +#. type: Title ## +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "Size" +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "" +"For filesystem-backed uploads, size checks use the actual file size on disk. " +"For pathless streams, size checks use the PSR-7 upload size when available. " +"If a size constraint is configured and the size can't be determined, " +"validation fails." +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "" +"`size` is mutually exclusive with `minSize` and `maxSize`. When both " +"`minSize` and `maxSize` are set, `minSize` must be less than or equal to " +"`maxSize`." +msgstr "" + +#. type: Title ## +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "Request Body Streams" +msgstr "" + +#. type: Plain text +#: guide/en/built-in-rules-file.md +msgid "" +"`File` doesn't validate generic request body streams such as data read from " +"`php://input` for PUT requests. Convert such input to a supported value " +"first, or write a custom rule that validates your stream format and storage " +"flow." +msgstr "" + +#. type: Link reference +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "[PSR-7]: https://www.php-fig.org/psr/psr-7/" +msgstr "" + +#. type: Link reference +#: guide/en/built-in-rules-file.md +#, no-wrap +msgid "[upload provenance checks]: https://www.php.net/manual/en/features.file-upload.post-method.php" +msgstr "" diff --git a/docs/pot/built-in-rules.md.pot b/docs/pot/built-in-rules.md.pot index a899e886d..2c4f60a5b 100644 --- a/docs/pot/built-in-rules.md.pot +++ b/docs/pot/built-in-rules.md.pot @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" -"POT-Creation-Date: 2026-04-21 14:32+0000\n" +"POT-Creation-Date: 2026-06-08 12:31+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -36,6 +36,11 @@ msgstr "" msgid "[Each](built-in-rules-each.md)" msgstr "" +#. type: Bullet: '- ' +#: guide/en/README.md guide/en/built-in-rules.md +msgid "[File](built-in-rules-file.md)" +msgstr "" + #. type: Bullet: '- ' #: guide/en/README.md guide/en/built-in-rules.md msgid "[Nested](built-in-rules-nested.md)" @@ -266,6 +271,11 @@ msgstr "" msgid "File rules" msgstr "" +#. type: Bullet: '- ' +#: guide/en/built-in-rules.md +msgid "[File](../../../src/Rule/File.php)" +msgstr "" + #. type: Bullet: '- ' #: guide/en/built-in-rules.md msgid "[Image](../../../src/Rule/Image/Image.php)"