rasuvaeff/yii3-respect-validation
Composer 安装命令:
composer require rasuvaeff/yii3-respect-validation
包简介
Bridge exposing Respect/Validation rules as native yiisoft/validator rules for Yii3 applications
README 文档
README
Bridge exposing Respect/Validation rules as
native yiisoft/validator rules — usable as a #[RespectRule] attribute on a
FormModel/DTO property, alongside built-in Yii3 rules, with results going through
the same Result/Yiisoft\Translator pipeline.
Using an AI coding assistant? llms.txt contains a compact API reference you can share with the model. Contributors: see AGENTS.md.
Requirements
| Requirement | Version |
|---|---|
| PHP | >=8.5 (required by respect/validation ^3.1) |
respect/validation |
^3.1 |
yiisoft/validator |
^2.6 |
yiisoft/translator |
^3.0 |
Installation
composer require rasuvaeff/yii3-respect-validation
Usage
use Rasuvaeff\Yii3RespectValidation\RespectRule; use Respect\Validation\Validators\AllOf; use Respect\Validation\Validators\Between; use Respect\Validation\Validators\Length; use Respect\Validation\Validators\StringType; final class RegisterForm { #[RespectRule(new AllOf(new StringType(), new Length(new Between(1, 50))))] public string $username = ''; }
use Yiisoft\Validator\Validator; $result = (new Validator())->validate(new RegisterForm()); $result->isValid(); // false $result->getPropertyErrorMessages('username'); // ['Username must be between 1 and 50']
v:: fluent chains work too, since RespectRule accepts either a
Respect\Validation\Validator instance or a Respect\Validation\ValidatorBuilder
(what v:: returns):
#[RespectRule(new StringType())] public string $username = ''; // equivalent, built at runtime instead of in the attribute: $rule = new RespectRule(v::stringType());
PHP attribute arguments must be constant expressions, so only rule chains built from
new Validator(...)calls work directly in#[RespectRule(...)].v::chains need to be built outside the attribute and passed to the constructor.
Fluent v:: chains on a model: RulesProviderInterface
To keep the fluent v:: API without giving up per-model rule declarations,
implement Yiisoft\Validator\RulesProviderInterface instead of attributes —
getRules() is ordinary runtime code, so any chain works there:
use Respect\Validation\Validator as v; use Yiisoft\Validator\RulesProviderInterface; final class RegisterForm implements RulesProviderInterface { public string $username = ''; public string $email = ''; public function getRules(): iterable { return [ 'username' => new RespectRule(v::stringType()->length(v::between(1, 50))), 'email' => new RespectRule(v::email()), ]; } }
Both styles produce identical results and can be mixed: attributes for simple
new-constructible chains, getRules() where the fluent builder is worth it.
Skip / conditional validation
RespectRule implements the same SkipOnEmptyInterface / SkipOnErrorInterface /
WhenInterface contracts as built-in rules:
#[RespectRule(new StringType(), skipOnEmpty: true, skipOnError: true)] public string $bio = '';
Messages and translation
Respect's own message templates (e.g. {{subject}} must be a string) are rendered
by the handler itself — not by Respect's internal InterpolationRenderer (which
needs symfony/translation-contracts) — so the whole app keeps a single i18n
pipeline: Yiisoft\Translator.
By default (no TranslatorInterface wired), messages are rendered in English via
RespectMessageFormatter.
A complete Russian catalog ships with the package (messages/ru/, all ~310
Respect template strings). To activate it, install the PHP message reader and set
the application locale to ru — the shipped config/di.php picks it up
automatically:
composer require yiisoft/translator-message-php
A build-time test (RussianMessageCatalogTest) pins every catalog key to the
installed respect/validation templates, so an upstream wording change turns CI
red instead of silently dropping translations.
For other locales, add your own catalog next to the app (same category):
// messages/de/yii3-respect-validation.php return [ '{{subject}} must be a string' => '{{subject}} muss eine Zeichenkette sein', ];
DI configuration (Yii3)
This package ships config/di.php + config/params.php via config-plugin —
installing it alongside yiisoft/config is enough to get RespectRuleHandler
wired with a dedicated translation category (yii3-respect-validation) using a
{{placeholder}}-aware RespectMessageFormatter (Respect templates use double
braces, not the ICU syntax the rest of yiisoft/validator uses — mixing the two
under one formatter would break placeholder substitution for one of them).
The category reads the bundled messages/{locale} catalogs when
yiisoft/translator-message-php is installed; without it, messages pass through
untranslated (English template text).
Override the category name in your application config if needed:
// config/params.php return [ 'rasuvaeff/yii3-respect-validation' => [ 'translation.category' => 'yii3-respect-validation', ], ];
Components
RespectRule
| Parameter | Type | Default | Description |
|---|---|---|---|
validator |
Respect\Validation\Validator|Respect\Validation\ValidatorBuilder |
— | The wrapped Respect rule/chain. |
skipOnEmpty |
bool|callable|null |
null |
Skip on empty, see SkipOnEmptyInterface. |
skipOnError |
bool |
false |
Skip on prior error, see SkipOnErrorInterface. |
when |
?Closure |
null |
Conditional execution, see WhenInterface. |
getOptions() (for frontend/client-side metadata export, per
DumpedRuleInterface) returns the wrapped validator's own $parameters property
when present (e.g. Between exposes minValue/maxValue — the same values
Respect uses to fill in its own templates), plus skipOnEmpty/skipOnError.
No JavaScript runtime is shipped — Respect has ~150 rules, many encoding
arbitrary PHP logic (Luhn checksums, locale-aware checks, Callback closures);
porting all of them to JS is not realistic to maintain, so this package limits
itself to the same metadata-export mechanism yiisoft/validator itself uses.
RespectRuleHandler
| Parameter | Type | Default | Description |
|---|---|---|---|
translator |
?Yiisoft\Translator\TranslatorInterface |
null |
If null, falls back to RespectMessageFormatter directly (English only). |
translationCategory |
string |
'yii3-respect-validation' |
Category looked up on $translator. |
Walks the Respect\Validation\Result tree returned by evaluate() and emits one
Yiisoft\Validator\Result error per failed leaf (and per failed adjacent
message), each with its own valuePath built from Respect's own nested Path
(e.g. failing array keys under Each/KeySet).
RespectMessageFormatter
Yiisoft\Translator\MessageFormatterInterface implementation substituting
Respect's own {{param}} placeholder syntax (not ICU). Register it on a
Yiisoft\Translator\CategorySource — see DI configuration.
Security
- No user input is ever interpolated into anything executed — this package only
moves data between two validation result structures (Respect's
Resulttree and Yii3'sResult); it performs no I/O, SQL, or shell access itself. RespectMessageFormatteronly does{{key}}string substitution (strtr()) — nevereval/preg_replacewith the/emodifier or similar.
Examples
See examples/ for a runnable script.
| Script | Shows | Needs server? |
|---|---|---|
validate-form.php |
Wrapping Respect rules on a DTO, reading Result errors |
no |
Development
No PHP/Composer on the host — run in Docker via the composer:2 image:
docker run --rm -v "$PWD":/app -w /app composer:2 composer install docker run --rm -v "$PWD":/app -w /app composer:2 composer build docker run --rm -v "$PWD":/app -w /app composer:2 composer cs:fix docker run --rm -v "$PWD":/app -w /app composer:2 composer test
Or with Make:
make install
make build
make cs-fix
make test
CI runs composer build on PHP 8.5 only — respect/validation requires
php: >=8.5, so the usual 8.3/8.4/8.5 matrix does not apply to this package.
License
统计信息
- 总下载量: 0
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 1
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: BSD-3-Clause
- 更新时间: 2026-07-03