Skip to content

Commit 16b89ca

Browse files
Adjust messages in Boolean and IsTrue rules, rename rules (#491)
* Adjust messages in Boolean and IsTrue rules * Apply fixes from StyleCI * Fix Psalm * Rename IsTrue rule as well * Fix unit tests * Add translation * Rename BoolValue to BooleanValue Co-authored-by: StyleCI Bot <[email protected]>
1 parent e3a6c11 commit 16b89ca

15 files changed

Lines changed: 334 additions & 313 deletions

messages/ru/yii-validator.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
return [
66
'The data must have at least "{min}" filled attributes.' => 'Данные должны содержать минимум {min, number} {min, plural, one{заполненный атрибут} few{заполненных атрибута} many{заполненных атрибутов} other{заполненных атрибута}}.',
77
'Value must be an array or an object.' => 'Значение должно быть массивом или объектом.',
8+
'The allowed types are integer, float, string, boolean. {type} given.' => 'Разрешённые типы: integer, float, string, boolean. Передан {type}.',
89
'Value must be either "{true}" or "{false}".' => 'Значение должно быть «{true}» или «{false}».',
910
'The allowed types are integer, float, string, boolean and null.' => 'Разрешённые типы: integer, float, string, boolean и null.',
1011
'The attribute value returned from a custom data set must have a scalar type.' => 'Значение, получаемое из набора данных, должно иметь скалярный тип.',

src/Rule/BooleanHandler.php

Lines changed: 0 additions & 51 deletions
This file was deleted.
Lines changed: 23 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -20,24 +20,19 @@
2020
* settings accordingly. There is also an option to choose between strict and non-strict mode of comparison
2121
* (see {@see $strict}).
2222
*
23-
* If the purpose is to check the truthiness only, use {@see IsTrue} rule instead.
23+
* If the purpose is to check the truthiness only, use {@see TrueValue} rule instead.
2424
*
25-
* @see BooleanHandler Corresponding handler performing the actual validation.
25+
* @see BooleanValueHandler Corresponding handler performing the actual validation.
2626
*
2727
* @psalm-import-type WhenType from WhenInterface
2828
*/
2929
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
30-
final class Boolean implements RuleWithOptionsInterface, SkipOnEmptyInterface, SkipOnErrorInterface, WhenInterface
30+
final class BooleanValue implements RuleWithOptionsInterface, SkipOnEmptyInterface, SkipOnErrorInterface, WhenInterface
3131
{
3232
use SkipOnEmptyTrait;
3333
use SkipOnErrorTrait;
3434
use WhenTrait;
3535

36-
/**
37-
* @const Default message used for all cases.
38-
*/
39-
private const DEFAULT_MESSAGE = 'Value must be either "{true}" or "{false}".';
40-
4136
/**
4237
* @param scalar $trueValue The value that is considered to be "true". Only scalar values (either int, float, string
4338
* or bool) are allowed. Defaults to `1` string.
@@ -55,8 +50,8 @@ final class Boolean implements RuleWithOptionsInterface, SkipOnEmptyInterface, S
5550
* - {@link https://www.php.net/manual/en/language.types.type-juggling.php}
5651
*
5752
* Defaults to `false` meaning non-strict mode is used.
58-
* @param string $messageWithType Error message used when validation fails and neither non-scalar value (int,
59-
* float, string, bool) nor null was provided as input. The type is used instead of value here for more predictable
53+
* @param string $incorrectInputMessage Error message used when validation fails because the type of validated value
54+
* is incorrect. Only scalar values are allowed - either int, float, string or bool. Used for more predictable
6055
* formatting.
6156
*
6257
* You may use the following placeholders in the message:
@@ -65,8 +60,8 @@ final class Boolean implements RuleWithOptionsInterface, SkipOnEmptyInterface, S
6560
* - `{true}`: the value set in {@see $trueValue} option.
6661
* - `{false}`: the value set in {@see $falseValue} option.
6762
* - `{type}`: the type of the value being validated.
68-
* @param string $messageWithValue Error message used when validation fails and either scalar value (int, float,
69-
* string, bool) or null was provided as input.
63+
* @param string $message Error message used when validation fails because the validated value does not match
64+
* neither "true" nor "false" values.
7065
*
7166
* You may use the following placeholders in the message:
7267
*
@@ -85,8 +80,8 @@ public function __construct(
8580
private int|float|string|bool $trueValue = '1',
8681
private int|float|string|bool $falseValue = '0',
8782
private bool $strict = false,
88-
private string $messageWithType = self::DEFAULT_MESSAGE,
89-
private string $messageWithValue = self::DEFAULT_MESSAGE,
83+
private string $incorrectInputMessage = 'The allowed types are integer, float, string, boolean. {type} given.',
84+
private string $message = 'Value must be either "{true}" or "{false}".',
9085
private mixed $skipOnEmpty = null,
9186
private bool $skipOnError = false,
9287
private Closure|null $when = null,
@@ -135,27 +130,28 @@ public function isStrict(): bool
135130
}
136131

137132
/**
138-
* Gets error message used when validation fails and value is complex to format, so its type is used instead.
133+
* Gets error message used when validation fails because the type of validated value is incorrect.
139134
*
140135
* @return string Error message / template.
141136
*
142-
* @see $messageWithType
137+
* @see $incorrectInputMessage
143138
*/
144-
public function getMessageWithType(): string
139+
public function getIncorrectInputMessage(): string
145140
{
146-
return $this->messageWithType;
141+
return $this->incorrectInputMessage;
147142
}
148143

149144
/**
150-
* Gets error message used when validation fails and value can be formatted.
145+
* Error message used when validation fails because the validated value does not match neither "true" nor "false"
146+
* values.
151147
*
152148
* @return string Error message / template.
153149
*
154-
* @see $messageWithValue
150+
* @see $message
155151
*/
156-
public function getMessageWithValue(): string
152+
public function getMessage(): string
157153
{
158-
return $this->messageWithValue;
154+
return $this->message;
159155
}
160156

161157
public function getOptions(): array
@@ -169,12 +165,12 @@ public function getOptions(): array
169165
'trueValue' => $this->trueValue,
170166
'falseValue' => $this->falseValue,
171167
'strict' => $this->strict,
172-
'messageWithType' => [
173-
'template' => $this->messageWithType,
168+
'incorrectInputMessage' => [
169+
'template' => $this->incorrectInputMessage,
174170
'parameters' => $messageParameters,
175171
],
176-
'messageWithValue' => [
177-
'template' => $this->messageWithValue,
172+
'message' => [
173+
'template' => $this->message,
178174
'parameters' => $messageParameters,
179175
],
180176
'skipOnEmpty' => $this->getSkipOnEmptyOption(),
@@ -184,6 +180,6 @@ public function getOptions(): array
184180

185181
public function getHandler(): string
186182
{
187-
return BooleanHandler::class;
183+
return BooleanValueHandler::class;
188184
}
189185
}

src/Rule/BooleanValueHandler.php

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Yiisoft\Validator\Rule;
6+
7+
use Yiisoft\Validator\Exception\UnexpectedRuleException;
8+
use Yiisoft\Validator\Result;
9+
use Yiisoft\Validator\RuleHandlerInterface;
10+
use Yiisoft\Validator\ValidationContext;
11+
12+
/**
13+
* A handler for {@see BooleanValue} rule.
14+
*/
15+
final class BooleanValueHandler implements RuleHandlerInterface
16+
{
17+
public function validate(mixed $value, object $rule, ValidationContext $context): Result
18+
{
19+
if (!$rule instanceof BooleanValue) {
20+
throw new UnexpectedRuleException(BooleanValue::class, $rule);
21+
}
22+
23+
if (!is_scalar($value)) {
24+
$parameters = $this->getCommonResultParameters($rule, $context);
25+
$parameters['type'] = get_debug_type($value);
26+
27+
return (new Result())->addError($rule->getIncorrectInputMessage(), $parameters);
28+
}
29+
30+
if ($rule->isStrict()) {
31+
$valid = $value === $rule->getTrueValue() || $value === $rule->getFalseValue();
32+
} else {
33+
$valid = $value == $rule->getTrueValue() || $value == $rule->getFalseValue();
34+
}
35+
36+
if ($valid) {
37+
return new Result();
38+
}
39+
40+
$parameters = $this->getCommonResultParameters($rule, $context);
41+
$parameters['value'] = $value;
42+
43+
return (new Result())->addError($rule->getMessage(), $parameters);
44+
}
45+
46+
/**
47+
* @param BooleanValue $rule A rule instance.
48+
* @param ValidationContext $context Validation context.
49+
*
50+
* @return array A mapping between attribute names and their values.
51+
* @psalm-return array<string,scalar|null>
52+
*/
53+
private function getCommonResultParameters(BooleanValue $rule, ValidationContext $context): array
54+
{
55+
return [
56+
'attribute' => $context->getTranslatedAttribute(),
57+
'true' => $rule->getTrueValue() === true ? 'true' : $rule->getTrueValue(),
58+
'false' => $rule->getFalseValue() === false ? 'false' : $rule->getFalseValue(),
59+
];
60+
}
61+
}

src/Rule/IsTrueHandler.php

Lines changed: 0 additions & 50 deletions
This file was deleted.

0 commit comments

Comments
 (0)