From e83339a05a7f64305e4b8fbaca547f400f2bb829 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20Alejandro=20L=C3=B3pez=20L=C3=B3pez?= Date: Mon, 27 Jan 2025 15:28:50 -0500 Subject: [PATCH 1/5] Add support for enums on Html methods --- framework/helpers/BaseHtml.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/framework/helpers/BaseHtml.php b/framework/helpers/BaseHtml.php index ff81df22752..bdb7b189ca9 100644 --- a/framework/helpers/BaseHtml.php +++ b/framework/helpers/BaseHtml.php @@ -2311,6 +2311,12 @@ public static function getAttributeValue($model, $attribute) $value = $value->getPrimaryKey(false); return is_array($value) ? json_encode($value) : $value; + } elseif (version_compare(PHP_VERSION, '8.1.0') >= 0) { + if ($value instanceof \BackedEnum) { + $value = $value->value; + } elseif ($value instanceof \UnitEnum) { + $value = $value->name; + } } return $value; From 17d7e687a2ff3dd2f1cea3d30b7d2ecb3d790b62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20Alejandro=20L=C3=B3pez=20L=C3=B3pez?= Date: Mon, 27 Jan 2025 15:30:18 -0500 Subject: [PATCH 2/5] Add support for enum on RangeValidator's client validation --- framework/validators/RangeValidator.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/framework/validators/RangeValidator.php b/framework/validators/RangeValidator.php index e58ea601096..8c3a7184f51 100644 --- a/framework/validators/RangeValidator.php +++ b/framework/validators/RangeValidator.php @@ -124,6 +124,13 @@ public function getClientOptions($model, $attribute) { $range = []; foreach ($this->range as $value) { + if (version_compare(PHP_VERSION, '8.1.0') >= 0) { + if ($value instanceof \BackedEnum) { + $value = $value->value; + } elseif ($value instanceof \UnitEnum) { + $value = $value->name; + } + } $range[] = (string) $value; } $options = [ From 4bfe496029d840d26a39394da7eeafec7dc4265b Mon Sep 17 00:00:00 2001 From: Wilmer Arambula Date: Thu, 1 Oct 2026 10:38:44 -0300 Subject: [PATCH 3/5] Apply fixed review. --- framework/CHANGELOG.md | 1 + framework/helpers/BaseHtml.php | 83 +++++-- framework/validators/RangeValidator.php | 74 +++++- phpstan-baseline-7x.neon | 126 +++++++++++ tests/data/enums/ColorEnum.php | 16 ++ tests/data/enums/PriorityEnum.php | 19 ++ tests/data/enums/StatusEnum.php | 16 ++ tests/framework/helpers/HtmlTest.php | 210 ++++++++++++++++++ .../validators/RangeValidatorTest.php | 188 ++++++++++++++++ 9 files changed, 706 insertions(+), 27 deletions(-) create mode 100644 tests/data/enums/ColorEnum.php create mode 100644 tests/data/enums/PriorityEnum.php create mode 100644 tests/data/enums/StatusEnum.php diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 657ed1169e8..04de2a3a137 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -39,6 +39,7 @@ Yii Framework 2 Change Log - Enh #21079: Add the missing `@property` tags (mspirkov) - Bug #21094: Log a warning instead of silently ignoring `$isolationLevel` when `yii\db\Transaction::begin()` is called for a nested transaction (terabytesoftw) - Bug #21086: Allow integer and string keys in the `yii\base\Model::rules()` return annotation (terabytesoftw) +- Enh #20318: Add support for PHP enums as attribute values and list selections in `yii\helpers\Html` and as range items in `yii\validators\RangeValidator` (glpzzz, terabytesoftw) 2.0.55 May 09, 2026 ------------------- diff --git a/framework/helpers/BaseHtml.php b/framework/helpers/BaseHtml.php index 160e4c960ea..fb1398119aa 100644 --- a/framework/helpers/BaseHtml.php +++ b/framework/helpers/BaseHtml.php @@ -577,7 +577,7 @@ public static function input($type, $name = null, $value = null, $options = []) $options['type'] = $type; } $options['name'] = $name; - $options['value'] = $value === null ? null : (string) $value; + $options['value'] = $value === null ? null : (string) self::enumToScalar($value); return static::tag('input', '', $options); } @@ -979,9 +979,8 @@ public static function checkboxList($name, $selection = null, $items = [], $opti if (substr($name, -2) !== '[]') { $name .= '[]'; } - if (ArrayHelper::isTraversable($selection)) { - $selection = array_map('strval', ArrayHelper::toArray($selection)); - } + + $selection = self::normalizeSelection($selection); $formatter = ArrayHelper::remove($options, 'item'); $itemOptions = ArrayHelper::remove($options, 'itemOptions', []); @@ -1069,9 +1068,7 @@ public static function checkboxList($name, $selection = null, $items = [], $opti */ public static function radioList($name, $selection = null, $items = [], $options = []) { - if (ArrayHelper::isTraversable($selection)) { - $selection = array_map('strval', ArrayHelper::toArray($selection)); - } + $selection = self::normalizeSelection($selection); $formatter = ArrayHelper::remove($options, 'item'); $itemOptions = ArrayHelper::remove($options, 'itemOptions', []); @@ -1631,6 +1628,8 @@ protected static function activeBooleanInput($type, $model, $attribute, $options if (!array_key_exists('value', $options)) { $options['value'] = '1'; + } else { + $options['value'] = self::enumToScalar($options['value']); } if (!array_key_exists('uncheck', $options)) { $options['uncheck'] = '0'; @@ -1893,16 +1892,20 @@ public static function renderSelectOptions($selection, $items, &$tagOptions = [] { if (ArrayHelper::isTraversable($selection)) { $normalizedSelection = []; - foreach (ArrayHelper::toArray($selection) as $selectionItem) { + + foreach ($selection as $selectionItem) { if (is_bool($selectionItem)) { $normalizedSelection[] = $selectionItem ? '1' : '0'; } else { - $normalizedSelection[] = (string)$selectionItem; + $normalizedSelection[] = (string) self::enumToScalar($selectionItem); } } + $selection = $normalizedSelection; } elseif (is_bool($selection)) { $selection = $selection ? '1' : '0'; + } else { + $selection = self::enumToScalar($selection); } $lines = []; @@ -2044,7 +2047,7 @@ public static function renderTagAttributes($attributes) $html .= " $name='" . Json::htmlEncode($value) . "'"; } } elseif ($value !== null) { - $html .= " $name=\"" . static::encode($value) . '"'; + $html .= " $name=\"" . static::encode(self::enumToScalar($value)) . '"'; } } @@ -2283,6 +2286,9 @@ public static function getAttributeName($attribute) * If an attribute value is an instance of [[ActiveRecordInterface]] or an array of such instances, * the primary value(s) of the AR instance(s) will be returned instead. * + * If an attribute value is an enum case or an array of enum cases (PHP 8.1+), the backing value + * of a backed enum or the case name of a pure enum will be returned instead. + * * @param Model $model the model object * @param string $attribute the attribute name or expression * @return string|array|null the corresponding attribute value @@ -2311,21 +2317,17 @@ public static function getAttributeValue($model, $attribute) if ($v instanceof ActiveRecordInterface) { $v = $v->getPrimaryKey(false); $value[$i] = is_array($v) ? json_encode($v) : $v; + } else { + $value[$i] = self::enumToScalar($v); } } } elseif ($value instanceof ActiveRecordInterface) { $value = $value->getPrimaryKey(false); return is_array($value) ? json_encode($value) : $value; - } elseif (version_compare(PHP_VERSION, '8.1.0') >= 0) { - if ($value instanceof \BackedEnum) { - $value = $value->value; - } elseif ($value instanceof \UnitEnum) { - $value = $value->name; - } } - return $value; + return self::enumToScalar($value); } /** @@ -2414,4 +2416,51 @@ public static function escapeJsRegularExpression($regexp) return $pattern; } + + /** + * Converts an enum case to its scalar representation. + * + * The backing value of a backed enum or the case name of a pure enum is returned. + * Any other value is returned as is. + * + * @param mixed $value the value to be converted. + * @return mixed the scalar representation of the enum case, or the original value. + */ + private static function enumToScalar($value) + { + if (PHP_VERSION_ID >= 80100) { + if ($value instanceof \BackedEnum) { + return $value->value; + } + if ($value instanceof \UnitEnum) { + return $value->name; + } + } + + return $value; + } + + /** + * Normalizes the selection of a list input so that it can be compared with the item values. + * + * A traversable selection is converted to an array of strings. Enum cases, either as the whole + * selection or as items of a traversable selection, are converted to their scalar representation. + * + * @param mixed $selection the selected value(s). + * @return mixed the normalized selection. + */ + private static function normalizeSelection($selection) + { + if (ArrayHelper::isTraversable($selection)) { + $normalizedSelection = []; + + foreach ($selection as $selectionItem) { + $normalizedSelection[] = (string) self::enumToScalar($selectionItem); + } + + return $normalizedSelection; + } + + return self::enumToScalar($selection); + } } diff --git a/framework/validators/RangeValidator.php b/framework/validators/RangeValidator.php index ede56aba2ef..3e6caa2b1d2 100644 --- a/framework/validators/RangeValidator.php +++ b/framework/validators/RangeValidator.php @@ -35,6 +35,11 @@ class RangeValidator extends Validator * return $range; * } * ``` + * + * The list may contain enum cases (PHP 8.1+), e.g. `Status::cases()`. In this case both the enum case + * itself and its scalar representation (the backing value of a backed enum or the case name of a pure enum) + * are considered valid, so that a value submitted by a form is accepted before it is typecast to the enum. + * The scalar representation is also used for the client-side validation. */ public $range; /** @@ -77,15 +82,17 @@ protected function validateValue($value) { $in = false; + $range = $this->normalizeRange($this->range); + if ( $this->allowArray && ($value instanceof \Traversable || is_array($value)) - && ArrayHelper::isSubset($value, $this->range, $this->strict) + && ArrayHelper::isSubset($value, $range, $this->strict) ) { $in = true; } - if (!$in && ArrayHelper::isIn($value, $this->range, $this->strict)) { + if (!$in && ArrayHelper::isIn($value, $range, $this->strict)) { $in = true; } @@ -124,16 +131,11 @@ public function clientValidateAttribute($model, $attribute, $view) public function getClientOptions($model, $attribute) { $range = []; + foreach ($this->range as $value) { - if (version_compare(PHP_VERSION, '8.1.0') >= 0) { - if ($value instanceof \BackedEnum) { - $value = $value->value; - } elseif ($value instanceof \UnitEnum) { - $value = $value->name; - } - } - $range[] = (string) $value; + $range[] = (string) $this->enumToScalar($value); } + $options = [ 'range' => $range, 'not' => $this->not, @@ -150,4 +152,56 @@ public function getClientOptions($model, $attribute) return $options; } + + /** + * Converts an enum case to its scalar representation. + * + * The backing value of a backed enum or the case name of a pure enum is returned. + * Any other value is returned as is. + * + * @param mixed $value the value to be converted. + * @return mixed the scalar representation of the enum case, or the original value. + */ + private function enumToScalar($value) + { + if (PHP_VERSION_ID >= 80100) { + if ($value instanceof \BackedEnum) { + return $value->value; + } + if ($value instanceof \UnitEnum) { + return $value->name; + } + } + + return $value; + } + + /** + * Adds the scalar representation of each enum case found in the range. + * + * The enum cases are kept in the range, so that an enum case is only matched by itself (not by a case + * of another enum with the same backing value), while its scalar representation matches the value + * submitted by a form. + * + * @param mixed $range the configured range. + * @return mixed the range with the scalar representation of the enum cases added, or the original + * value when it is neither an array nor traversable. + */ + private function normalizeRange($range) + { + if (!is_array($range) && !($range instanceof \Traversable)) { + return $range; + } + + $normalized = []; + + foreach ($range as $value) { + $normalized[] = $value; + if (PHP_VERSION_ID >= 80100 && $value instanceof \UnitEnum) { + $normalized[] = $this->enumToScalar($value); + } + } + + return $normalized; + } } diff --git a/phpstan-baseline-7x.neon b/phpstan-baseline-7x.neon index 432b9255599..372d4130501 100644 --- a/phpstan-baseline-7x.neon +++ b/phpstan-baseline-7x.neon @@ -125,3 +125,129 @@ parameters: identifier: class.notFound count: 1 path: tests/framework/behaviors/AttributeTypecastBehaviorTest.php + + - + message: '#^Access to property \$name on an unknown class UnitEnum\.$#' + identifier: class.notFound + count: 1 + path: framework/helpers/BaseHtml.php + + - + message: '#^Access to property \$value on an unknown class BackedEnum\.$#' + identifier: class.notFound + count: 1 + path: framework/helpers/BaseHtml.php + + - + message: '#^Class BackedEnum not found\.$#' + identifier: class.notFound + count: 1 + path: framework/helpers/BaseHtml.php + + - + message: '#^Class UnitEnum not found\.$#' + identifier: class.notFound + count: 1 + path: framework/helpers/BaseHtml.php + + - + message: '#^Access to property \$name on an unknown class UnitEnum\.$#' + identifier: class.notFound + count: 1 + path: framework/validators/RangeValidator.php + + - + message: '#^Access to property \$value on an unknown class BackedEnum\.$#' + identifier: class.notFound + count: 1 + path: framework/validators/RangeValidator.php + + - + message: '#^Class BackedEnum not found\.$#' + identifier: class.notFound + count: 1 + path: framework/validators/RangeValidator.php + + - + message: '#^Class UnitEnum not found\.$#' + identifier: class.notFound + count: 2 + path: framework/validators/RangeValidator.php + + - + message: '#^Access to constant ACTIVE on an unknown class yiiunit\\data\\enums\\StatusEnum\.$#' + identifier: class.notFound + count: 6 + path: tests/framework/helpers/HtmlTest.php + + - + message: '#^Access to constant BLUE on an unknown class yiiunit\\data\\enums\\ColorEnum\.$#' + identifier: class.notFound + count: 2 + path: tests/framework/helpers/HtmlTest.php + + - + message: '#^Access to constant DELETED on an unknown class yiiunit\\data\\enums\\StatusEnum\.$#' + identifier: class.notFound + count: 3 + path: tests/framework/helpers/HtmlTest.php + + - + message: '#^Access to constant GREEN on an unknown class yiiunit\\data\\enums\\ColorEnum\.$#' + identifier: class.notFound + count: 3 + path: tests/framework/helpers/HtmlTest.php + + - + message: '#^Access to constant INACTIVE on an unknown class yiiunit\\data\\enums\\StatusEnum\.$#' + identifier: class.notFound + count: 1 + path: tests/framework/helpers/HtmlTest.php + + - + message: '#^Access to constant RED on an unknown class yiiunit\\data\\enums\\ColorEnum\.$#' + identifier: class.notFound + count: 6 + path: tests/framework/helpers/HtmlTest.php + + - + message: '#^Access to constant ACTIVE on an unknown class yiiunit\\data\\enums\\StatusEnum\.$#' + identifier: class.notFound + count: 7 + path: tests/framework/validators/RangeValidatorTest.php + + - + message: '#^Access to constant HIGH on an unknown class yiiunit\\data\\enums\\PriorityEnum\.$#' + identifier: class.notFound + count: 1 + path: tests/framework/validators/RangeValidatorTest.php + + - + message: '#^Access to constant INACTIVE on an unknown class yiiunit\\data\\enums\\StatusEnum\.$#' + identifier: class.notFound + count: 1 + path: tests/framework/validators/RangeValidatorTest.php + + - + message: '#^Access to constant LOW on an unknown class yiiunit\\data\\enums\\PriorityEnum\.$#' + identifier: class.notFound + count: 2 + path: tests/framework/validators/RangeValidatorTest.php + + - + message: '#^Access to constant RED on an unknown class yiiunit\\data\\enums\\ColorEnum\.$#' + identifier: class.notFound + count: 1 + path: tests/framework/validators/RangeValidatorTest.php + + - + message: '#^Call to static method cases\(\) on an unknown class yiiunit\\data\\enums\\ColorEnum\.$#' + identifier: class.notFound + count: 2 + path: tests/framework/validators/RangeValidatorTest.php + + - + message: '#^Call to static method cases\(\) on an unknown class yiiunit\\data\\enums\\StatusEnum\.$#' + identifier: class.notFound + count: 6 + path: tests/framework/validators/RangeValidatorTest.php diff --git a/tests/data/enums/ColorEnum.php b/tests/data/enums/ColorEnum.php new file mode 100644 index 00000000000..e886dbea950 --- /dev/null +++ b/tests/data/enums/ColorEnum.php @@ -0,0 +1,16 @@ +assertSame($expected, $actual); } + /** + * @requires PHP >= 8.1 + */ + public function testGetAttributeValueWithBackedEnum(): void + { + $model = new HtmlTestModel(); + $model->types = StatusEnum::ACTIVE; + + $this->assertSame( + 1, + Html::getAttributeValue($model, 'types'), + "Backed enum value should be returned by 'getAttributeValue()' method.", + ); + } + + /** + * @requires PHP >= 8.1 + */ + public function testGetAttributeValueWithUnitEnum(): void + { + $model = new HtmlTestModel(); + $model->types = ColorEnum::RED; + + $this->assertSame( + 'RED', + Html::getAttributeValue($model, 'types'), + "Unit enum name should be returned by 'getAttributeValue()' method.", + ); + } + + /** + * @requires PHP >= 8.1 + */ + public function testGetAttributeValueWithEnumArray(): void + { + $model = new HtmlTestModel(); + $model->types = [StatusEnum::ACTIVE, ColorEnum::GREEN, 'plain']; + + $this->assertSame( + [1, 'GREEN', 'plain'], + Html::getAttributeValue($model, 'types'), + "Enum cases inside an array attribute should be converted by 'getAttributeValue()' method.", + ); + } + public function testGetInputNameInvalidArgumentExceptionAttribute(): void { $model = new HtmlTestModel(); @@ -2181,6 +2228,169 @@ public function testActiveCheckboxListOptions(): void $this->assertEqualsWithoutLE($expected, $actual); } + /** + * @requires PHP >= 8.1 + */ + public function testActiveListInputsWithEnum(): void + { + $items = [1 => 'Active', 2 => 'Deleted', 0 => 'Inactive']; + + $model = new HtmlTestModel(); + + $model->types = StatusEnum::DELETED; + + $this->assertEqualsWithoutLE( + << + + + + + HTML, + Html::activeDropDownList($model, 'types', $items), + 'Enum value must select the matching option.', + ); + $this->assertEqualsWithoutLE( + <<
+ +
+ HTML, + Html::activeRadioList($model, 'types', $items), + 'Enum value must check the matching radio.', + ); + + $model->types = [StatusEnum::ACTIVE, StatusEnum::INACTIVE]; + + $this->assertEqualsWithoutLE( + <<
+ +
+ HTML, + Html::activeCheckboxList($model, 'types', $items), + 'Enum array must check all matching checkboxes.', + ); + $this->assertEqualsWithoutLE( + << + HTML, + Html::activeListBox($model, 'types', $items, ['multiple' => true]), + 'Enum array must select all matching options.', + ); + } + + /** + * @requires PHP >= 8.1 + */ + public function testListInputsWithEnumSelection(): void + { + $items = ['BLUE' => 'Blue', 'GREEN' => 'Green', 'RED' => 'Red']; + + $this->assertEqualsWithoutLE( + << + + + + + HTML, + Html::dropDownList('color', ColorEnum::RED, $items), + 'Enum selection must mark the matching option.', + ); + $this->assertEqualsWithoutLE( + << + + + + + HTML, + Html::listBox('color', [ColorEnum::BLUE, ColorEnum::RED], $items, ['multiple' => true]), + 'Enum array must mark all matching options.', + ); + $this->assertEqualsWithoutLE( + << + + + HTML, + Html::radioList('color', ColorEnum::GREEN, $items), + 'Enum selection must check the matching radio.', + ); + $this->assertEqualsWithoutLE( + << + + + HTML, + Html::checkboxList('color', new ArrayObject([ColorEnum::BLUE, ColorEnum::RED]), $items), + 'Enum collection must check all matching checkboxes.', + ); + } + + /** + * @requires PHP >= 8.1 + */ + public function testBooleanInputsWithEnum(): void + { + $model = new HtmlTestModel(); + + $model->types = StatusEnum::ACTIVE; + + $this->assertEqualsWithoutLE( + << + HTML, + Html::activeCheckbox($model, 'types', ['value' => StatusEnum::ACTIVE]), + 'Enum value must be rendered as the checkbox value.', + ); + $this->assertEqualsWithoutLE( + << + HTML, + Html::activeRadio($model, 'types', ['value' => StatusEnum::DELETED]), + 'Enum value must be rendered as the radio value.', + ); + $this->assertSame( + << + HTML, + Html::checkbox('color', true, ['value' => ColorEnum::RED]), + 'Backed string enum must be rendered as the checkbox value.', + ); + } + + /** + * @requires PHP >= 8.1 + */ + public function testRenderTagAttributesWithEnum(): void + { + $this->assertSame( + ' value="1" data-color="RED"', + Html::renderTagAttributes(['value' => StatusEnum::ACTIVE, 'data-color' => ColorEnum::RED]), + 'Enum attributes must be rendered as their backing values.', + ); + $this->assertSame( + << + HTML, + Html::textInput('status', StatusEnum::DELETED), + 'Enum must be rendered as the input value.', + ); + $this->assertSame( + << + HTML, + Html::hiddenInput('color', ColorEnum::GREEN), + 'Enum must be rendered as the hidden input value.', + ); + } + public function testActiveTextInputPlaceholderFillFromModel(): void { $model = new HtmlTestModel(); diff --git a/tests/framework/validators/RangeValidatorTest.php b/tests/framework/validators/RangeValidatorTest.php index ddf0e79cb49..1e246b55df5 100644 --- a/tests/framework/validators/RangeValidatorTest.php +++ b/tests/framework/validators/RangeValidatorTest.php @@ -13,6 +13,9 @@ use ArrayObject; use yii\validators\RangeValidator; use yii\validators\Validator; +use yiiunit\data\enums\ColorEnum; +use yiiunit\data\enums\PriorityEnum; +use yiiunit\data\enums\StatusEnum; use yiiunit\data\validators\models\FakedValidationModel; use yiiunit\framework\validators\stubs\ViewStub; use yiiunit\TestCase; @@ -216,4 +219,189 @@ public function testClientValidateAttribute(): void 'The computed range must reach the client options.', ); } + + /** + * @requires PHP >= 8.1 + */ + public function testValidateValueWithBackedEnum(): void + { + $val = new RangeValidator(['range' => StatusEnum::cases()]); + + $this->assertTrue( + $val->validate(StatusEnum::ACTIVE), + 'A case of the backed enum must be accepted.', + ); + $this->assertTrue( + $val->validate(StatusEnum::INACTIVE), + 'A case of the backed enum must be accepted.', + ); + $this->assertTrue( + $val->validate(1), + 'The backing value of a case must be accepted.', + ); + $this->assertTrue( + $val->validate('1'), + 'The backing value submitted as a string must be accepted.', + ); + $this->assertFalse( + $val->validate(5), + 'A value not in the range must be rejected.', + ); + $this->assertFalse( + $val->validate('5'), + 'A value not in the range must be rejected.', + ); + $this->assertFalse( + $val->validate('ACTIVE'), + 'The case name of a backed enum is not its scalar representation.', + ); + $this->assertFalse( + $val->validate(PriorityEnum::LOW), + 'A case of another enum must not be accepted, even if it has the same backing value.', + ); + } + + /** + * @requires PHP >= 8.1 + */ + public function testValidateValueWithUnitEnum(): void + { + $val = new RangeValidator(['range' => ColorEnum::cases()]); + + $this->assertTrue( + $val->validate(ColorEnum::RED), + 'The case must be accepted.', + ); + $this->assertTrue( + $val->validate('RED'), + 'The case name must be accepted.', + ); + $this->assertFalse( + $val->validate('PURPLE'), + 'The case name must not be accepted.', + ); + $this->assertFalse( + $val->validate(0), + 'The value must not be accepted.', + ); + $this->assertFalse( + $val->validate(StatusEnum::ACTIVE), + 'The value must not be accepted.', + ); + } + + /** + * @requires PHP >= 8.1 + */ + public function testValidateValueStrictWithBackedEnum(): void + { + $val = new RangeValidator(['range' => StatusEnum::cases(), 'strict' => true]); + + $this->assertTrue( + $val->validate(StatusEnum::ACTIVE), + 'A case of the backed enum must be accepted.', + ); + $this->assertTrue( + $val->validate(1), + 'The backing value of a case must be accepted.', + ); + $this->assertFalse( + $val->validate('1'), + 'Strict comparison must keep rejecting a string for an integer backing value.', + ); + } + + /** + * @requires PHP >= 8.1 + */ + public function testValidateArrayValueWithEnum(): void + { + $val = new RangeValidator(['range' => StatusEnum::cases(), 'allowArray' => true]); + + $this->assertTrue( + $val->validate([StatusEnum::ACTIVE, 2, '0']), + 'All values in the array must be in the range.', + ); + $this->assertFalse( + $val->validate([StatusEnum::ACTIVE, 5]), + 'If any value in the array is not in the range, validation must fail.', + ); + $this->assertFalse( + $val->validate([PriorityEnum::HIGH]), + 'If any value in the array is not in the range, validation must fail.', + ); + } + + /** + * @requires PHP >= 8.1 + */ + public function testValidateValueNotWithEnum(): void + { + $val = new RangeValidator(['range' => StatusEnum::cases(), 'not' => true]); + + $this->assertFalse( + $val->validate(StatusEnum::ACTIVE), + 'The value must not be in the range.', + ); + $this->assertFalse( + $val->validate(1), + 'The value must not be in the range.', + ); + $this->assertTrue( + $val->validate(5), + 'The value must not be in the range.', + ); + $this->assertTrue( + $val->validate(PriorityEnum::LOW), + 'The value must not be in the range.', + ); + } + + /** + * @requires PHP >= 8.1 + */ + public function testValidateAttributeWithEnumRange(): void + { + $val = new RangeValidator(['range' => StatusEnum::cases()]); + + $m = FakedValidationModel::createWithAttributes(['attr_r1' => '2', 'attr_r2' => '9']); + + $val->validateAttribute($m, 'attr_r1'); + + $this->assertFalse( + $m->hasErrors('attr_r1'), + 'A submitted backing value must pass server-side validation.', + ); + + $val->validateAttribute($m, 'attr_r2'); + + $this->assertTrue( + $m->hasErrors('attr_r2'), + 'A submitted backing value must fail server-side validation.', + ); + } + + /** + * @requires PHP >= 8.1 + */ + public function testClientValidateAttributeWithEnumRange(): void + { + $m = FakedValidationModel::createWithAttributes(['attr_range' => StatusEnum::ACTIVE]); + + $val = new RangeValidator(['range' => StatusEnum::cases()]); + + $this->assertSame( + 'yii.validation.range(value, messages, {"range":["1","2","0"],"not":false,"message":"attr_range is invalid.","skipOnEmpty":1});', + $val->clientValidateAttribute($m, 'attr_range', new ViewStub()), + 'The client options must contain the backing values of the cases.', + ); + + $val = new RangeValidator(['range' => ColorEnum::cases()]); + + $this->assertSame( + 'yii.validation.range(value, messages, {"range":["BLUE","GREEN","RED"],"not":false,"message":"attr_range is invalid.","skipOnEmpty":1});', + $val->clientValidateAttribute($m, 'attr_range', new ViewStub()), + 'The client options must contain the names of the cases of a pure enum.', + ); + } } From fa89f9ff764fb1a151c82adf9cd799c0410b6dbd Mon Sep 17 00:00:00 2001 From: Wilmer Arambula Date: Thu, 1 Oct 2026 10:54:48 -0300 Subject: [PATCH 4/5] Apply fixed Coderabbitai review. --- framework/validators/RangeValidator.php | 1 + tests/framework/helpers/HtmlTest.php | 3 ++ .../validators/RangeValidatorTest.php | 36 +++++++++++++++++++ 3 files changed, 40 insertions(+) diff --git a/framework/validators/RangeValidator.php b/framework/validators/RangeValidator.php index 3e6caa2b1d2..802ef5c4cdd 100644 --- a/framework/validators/RangeValidator.php +++ b/framework/validators/RangeValidator.php @@ -143,6 +143,7 @@ public function getClientOptions($model, $attribute) 'attribute' => $model->getAttributeLabel($attribute), ]), ]; + if ($this->skipOnEmpty) { $options['skipOnEmpty'] = 1; } diff --git a/tests/framework/helpers/HtmlTest.php b/tests/framework/helpers/HtmlTest.php index 1dd271baf36..f49f58f05c8 100644 --- a/tests/framework/helpers/HtmlTest.php +++ b/tests/framework/helpers/HtmlTest.php @@ -2072,6 +2072,7 @@ public function testGetAttributeValue(): void public function testGetAttributeValueWithBackedEnum(): void { $model = new HtmlTestModel(); + $model->types = StatusEnum::ACTIVE; $this->assertSame( @@ -2087,6 +2088,7 @@ public function testGetAttributeValueWithBackedEnum(): void public function testGetAttributeValueWithUnitEnum(): void { $model = new HtmlTestModel(); + $model->types = ColorEnum::RED; $this->assertSame( @@ -2102,6 +2104,7 @@ public function testGetAttributeValueWithUnitEnum(): void public function testGetAttributeValueWithEnumArray(): void { $model = new HtmlTestModel(); + $model->types = [StatusEnum::ACTIVE, ColorEnum::GREEN, 'plain']; $this->assertSame( diff --git a/tests/framework/validators/RangeValidatorTest.php b/tests/framework/validators/RangeValidatorTest.php index 1e246b55df5..e58ee0a5ef6 100644 --- a/tests/framework/validators/RangeValidatorTest.php +++ b/tests/framework/validators/RangeValidatorTest.php @@ -167,6 +167,42 @@ public function testValidateSubsetArrayable(): void $this->assertFalse($val->validate('c'), 'A value missing from the traversable range must fail.'); } + public function testValidateValueWithGeneratorRange(): void + { + $val = new RangeValidator([ + 'range' => (static function (): \Generator { + yield 1; + yield 2; + })(), + ]); + + $this->assertTrue( + $val->validate(2), + 'The first validation must consume the generator.', + ); + $this->assertTrue( + $val->validate(1), + 'A second validation must reuse the materialized range instead of the consumed generator.', + ); + $this->assertFalse( + $val->validate(3), + 'A value missing from the materialized range must fail.', + ); + $this->assertSame( + [1, 2], + $val->range, + 'The generator must be materialized into an array.', + ); + + $m = FakedValidationModel::createWithAttributes(['attr_range' => 1]); + + $this->assertSame( + ['1', '2'], + $val->getClientOptions($m, 'attr_range')['range'], + 'The client options must be built from the materialized range.', + ); + } + public function testValidateAttributeWithClosureRange(): void { $val = new RangeValidator([ From 2d389ea9647688c1014ab89e3655c877f91ac70e Mon Sep 17 00:00:00 2001 From: Wilmer Arambula Date: Thu, 1 Oct 2026 11:03:34 -0300 Subject: [PATCH 5/5] Apply fixed Coderabbitai review. --- framework/validators/RangeValidator.php | 28 ++++- phpstan-baseline-7x.neon | 10 +- tests/framework/helpers/HtmlTest.php | 32 +++++ .../validators/RangeValidatorTest.php | 109 ++++++++++++++++++ 4 files changed, 171 insertions(+), 8 deletions(-) diff --git a/framework/validators/RangeValidator.php b/framework/validators/RangeValidator.php index 802ef5c4cdd..d2aa747f706 100644 --- a/framework/validators/RangeValidator.php +++ b/framework/validators/RangeValidator.php @@ -82,7 +82,7 @@ protected function validateValue($value) { $in = false; - $range = $this->normalizeRange($this->range); + $range = $this->normalizeRange($this->materializeRange()); if ( $this->allowArray @@ -132,7 +132,7 @@ public function getClientOptions($model, $attribute) { $range = []; - foreach ($this->range as $value) { + foreach ($this->materializeRange() as $value) { $range[] = (string) $this->enumToScalar($value); } @@ -143,7 +143,6 @@ public function getClientOptions($model, $attribute) 'attribute' => $model->getAttributeLabel($attribute), ]), ]; - if ($this->skipOnEmpty) { $options['skipOnEmpty'] = 1; } @@ -177,6 +176,23 @@ private function enumToScalar($value) return $value; } + /** + * Materializes a traversable [[range]] into an array and returns the resulting range. + * + * The array replaces the traversable in [[range]], so that a one-shot traversable such as a generator + * can be used for more than one validation and for the client options. + * + * @return mixed the materialized range, or the original value of [[range]] when it is not traversable. + */ + private function materializeRange() + { + if ($this->range instanceof \Traversable) { + $this->range = iterator_to_array($this->range, false); + } + + return $this->range; + } + /** * Adds the scalar representation of each enum case found in the range. * @@ -184,13 +200,13 @@ private function enumToScalar($value) * of another enum with the same backing value), while its scalar representation matches the value * submitted by a form. * - * @param mixed $range the configured range. + * @param mixed $range the materialized range, see [[materializeRange()]]. * @return mixed the range with the scalar representation of the enum cases added, or the original - * value when it is neither an array nor traversable. + * value when it is not an array. */ private function normalizeRange($range) { - if (!is_array($range) && !($range instanceof \Traversable)) { + if (!is_array($range)) { return $range; } diff --git a/phpstan-baseline-7x.neon b/phpstan-baseline-7x.neon index 372d4130501..785a44f9182 100644 --- a/phpstan-baseline-7x.neon +++ b/phpstan-baseline-7x.neon @@ -201,7 +201,7 @@ parameters: - message: '#^Access to constant INACTIVE on an unknown class yiiunit\\data\\enums\\StatusEnum\.$#' identifier: class.notFound - count: 1 + count: 3 path: tests/framework/helpers/HtmlTest.php - @@ -216,6 +216,12 @@ parameters: count: 7 path: tests/framework/validators/RangeValidatorTest.php + - + message: '#^Access to constant DELETED on an unknown class yiiunit\\data\\enums\\StatusEnum\.$#' + identifier: class.notFound + count: 1 + path: tests/framework/validators/RangeValidatorTest.php + - message: '#^Access to constant HIGH on an unknown class yiiunit\\data\\enums\\PriorityEnum\.$#' identifier: class.notFound @@ -249,5 +255,5 @@ parameters: - message: '#^Call to static method cases\(\) on an unknown class yiiunit\\data\\enums\\StatusEnum\.$#' identifier: class.notFound - count: 6 + count: 7 path: tests/framework/validators/RangeValidatorTest.php diff --git a/tests/framework/helpers/HtmlTest.php b/tests/framework/helpers/HtmlTest.php index f49f58f05c8..815e8100440 100644 --- a/tests/framework/helpers/HtmlTest.php +++ b/tests/framework/helpers/HtmlTest.php @@ -2336,6 +2336,38 @@ public function testListInputsWithEnumSelection(): void ); } + /** + * @requires PHP >= 8.1 + */ + public function testDropDownListWithFalsyEnumSelection(): void + { + $items = [0 => 'Inactive', 1 => 'Active']; + $options = ['prompt' => 'Any']; + + $this->assertEqualsWithoutLE( + << + + + + + HTML, + Html::dropDownList('status', StatusEnum::INACTIVE, $items, $options), + 'A backed enum with a falsy backing value must select its option, not the prompt.', + ); + $this->assertEqualsWithoutLE( + << + + + + + HTML, + Html::dropDownList('status', StatusEnum::INACTIVE, $items, $options + ['strict' => true]), + 'A backed enum with a falsy backing value must select its option in strict mode.', + ); + } + /** * @requires PHP >= 8.1 */ diff --git a/tests/framework/validators/RangeValidatorTest.php b/tests/framework/validators/RangeValidatorTest.php index e58ee0a5ef6..f12d188010c 100644 --- a/tests/framework/validators/RangeValidatorTest.php +++ b/tests/framework/validators/RangeValidatorTest.php @@ -11,6 +11,7 @@ namespace yiiunit\framework\validators; use ArrayObject; +use yii\base\DynamicModel; use yii\validators\RangeValidator; use yii\validators\Validator; use yiiunit\data\enums\ColorEnum; @@ -203,6 +204,85 @@ public function testValidateValueWithGeneratorRange(): void ); } + public function testClientValidateAttributeWithGeneratorRange(): void + { + $val = new RangeValidator([ + 'range' => (static function (): \Generator { + yield 1; + yield 2; + })(), + ]); + + $m = FakedValidationModel::createWithAttributes(['attr_range' => 1]); + + $this->assertSame( + 'yii.validation.range(value, messages, {"range":["1","2"],"not":false,"message":"attr_range is invalid.","skipOnEmpty":1});', + $val->clientValidateAttribute($m, 'attr_range', new ViewStub()), + 'The client options must consume the generator.', + ); + + $val->validateAttribute($m, 'attr_range'); + + $this->assertFalse( + $m->hasErrors('attr_range'), + 'A validation after the client options must reuse the materialized range instead of the consumed generator.', + ); + } + + public function testValidateAttributeWithClosureRangeReturningGenerator(): void + { + $val = new RangeValidator([ + 'range' => static function ($model, $attribute): \Generator { + yield 1; + yield 2; + }, + ]); + + $m = FakedValidationModel::createWithAttributes(['attr_range' => 2]); + + $val->validateAttribute($m, 'attr_range'); + + $this->assertFalse( + $m->hasErrors('attr_range'), + 'The generator returned by the closure must accept one of its members.', + ); + + $m->attr_range = 1; + + $val->validateAttribute($m, 'attr_range'); + + $this->assertFalse( + $m->hasErrors('attr_range'), + 'A second validation must reuse the materialized range instead of the consumed generator.', + ); + + $m->attr_range = 3; + + $val->validateAttribute($m, 'attr_range'); + + $this->assertTrue( + $m->hasErrors('attr_range'), + 'The materialized range must reject an outsider.', + ); + } + + public function testValidateValueWithConsumedGeneratorRange(): void + { + $range = (static function (): \Generator { + yield 1; + yield 2; + })(); + + iterator_to_array($range, false); + + $val = new RangeValidator(['range' => $range]); + + $this->expectException(\Exception::class); + $this->expectExceptionMessage('Cannot traverse an already closed generator'); + + $val->validate(1); + } + public function testValidateAttributeWithClosureRange(): void { $val = new RangeValidator([ @@ -440,4 +520,33 @@ public function testClientValidateAttributeWithEnumRange(): void 'The client options must contain the names of the cases of a pure enum.', ); } + + /** + * @requires PHP >= 8.1 + */ + public function testValidateDataWithEnumRange(): void + { + $rules = [['status', 'in', 'range' => StatusEnum::cases()]]; + + $model = DynamicModel::validateData(['status' => '2'], $rules); + + $this->assertFalse( + $model->hasErrors('status'), + 'The backing value submitted by a form must pass the same rule that accepts the enum case.', + ); + + $model = DynamicModel::validateData(['status' => StatusEnum::DELETED], $rules); + + $this->assertFalse( + $model->hasErrors('status'), + 'An enum case assigned to the attribute must pass the rule.', + ); + + $model = DynamicModel::validateData(['status' => '9'], $rules); + + $this->assertTrue( + $model->hasErrors('status'), + 'A submitted value outside the range must fail the rule.', + ); + } }