Skip to content
Open
Show file tree
Hide file tree
Changes from all 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 @@ -41,6 +41,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)
- Bug #20344: Fix `yii\helpers\VarDumper::dumpAsString()` leaving the `<?php` open tag in highlighted output on PHP 8.3+ (mixxael, terabytesoftw)
- Bug #21115: Fix PHPStan 2.3.0 `parameterByRef.type` error in `yii\db\QueryBuilder::getTableUniqueColumnNames()` (theluckystrike)
- Enh #20681: Add `yii\base\ErrorHandler::fallbackExceptionMessage()` to customize the message shown by `handleFallbackExceptionMessage()` when `YII_DEBUG` is disabled (ZhandosKz, terabytesoftw)
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 @@ -2423,4 +2431,51 @@ function ($matches) {

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);
}
}
86 changes: 82 additions & 4 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->materializeRange());

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;

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

$options = [
'range' => $range,
'not' => $this->not,
Expand All @@ -143,4 +152,73 @@ 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;
}

/**
* 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.
*
* 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 materialized range, see [[materializeRange()]].
* @return mixed the range with the scalar representation of the enum cases added, or the original
* value when it is not an array.
*/
private function normalizeRange($range)
{
if (!is_array($range)) {
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;
}
}
Loading
Loading