Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions framework/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
-------------------
Expand Down
77 changes: 66 additions & 11 deletions framework/helpers/BaseHtml.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down Expand Up @@ -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', []);
Expand Down Expand Up @@ -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', []);
Expand Down Expand Up @@ -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';
Expand Down Expand Up @@ -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 = [];
Expand Down Expand Up @@ -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)) . '"';
}
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -2311,6 +2317,8 @@ 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) {
Expand All @@ -2319,7 +2327,7 @@ public static function getAttributeValue($model, $attribute)
return is_array($value) ? json_encode($value) : $value;
}

return $value;
return self::enumToScalar($value);
}

/**
Expand Down Expand Up @@ -2408,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);
}
}
67 changes: 64 additions & 3 deletions framework/validators/RangeValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
/**
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -124,9 +131,11 @@ public function clientValidateAttribute($model, $attribute, $view)
public function getClientOptions($model, $attribute)
{
$range = [];

foreach ($this->range as $value) {
$range[] = (string) $value;
$range[] = (string) $this->enumToScalar($value);
}

$options = [
'range' => $range,
'not' => $this->not,
Expand All @@ -143,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) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
$normalized[] = $value;
if (PHP_VERSION_ID >= 80100 && $value instanceof \UnitEnum) {
$normalized[] = $this->enumToScalar($value);
}
}

return $normalized;
}
}
126 changes: 126 additions & 0 deletions phpstan-baseline-7x.neon
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading
Loading