From f4a97f93d727ac3d380f18f25db0315fbc44a29d Mon Sep 17 00:00:00 2001 From: Oleg Poludnenko Date: Mon, 6 Nov 2023 12:51:13 +0200 Subject: [PATCH 1/2] Enum support for ArrayHelper::toArray() --- framework/helpers/BaseArrayHelper.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/framework/helpers/BaseArrayHelper.php b/framework/helpers/BaseArrayHelper.php index 56411163e1e..abb73556d46 100644 --- a/framework/helpers/BaseArrayHelper.php +++ b/framework/helpers/BaseArrayHelper.php @@ -63,7 +63,9 @@ public static function toArray($object, $properties = [], $recursive = true) if (is_array($object)) { if ($recursive) { foreach ($object as $key => $value) { - if (is_array($value) || is_object($value)) { + if ($value instanceof \UnitEnum) { + $object[$key] = $value->value; + } elseif (is_array($value) || is_object($value)) { $object[$key] = static::toArray($value, $properties, true); } } From 38a2c50d7deeb025ee3346e98c3a0ca358d81617 Mon Sep 17 00:00:00 2001 From: Wilmer Arambula Date: Tue, 29 Sep 2026 20:09:14 -0300 Subject: [PATCH 2/2] Apply fixed Coderabbitai review. --- framework/CHANGELOG.md | 1 + framework/UPGRADE.md | 4 + framework/helpers/BaseArrayHelper.php | 10 +- phpstan-baseline-7x.neon | 90 ++++++++++++++ tests/data/helpers/enums/IntBackedStatus.php | 21 ++++ tests/data/helpers/enums/Status.php | 21 ++++ .../data/helpers/enums/StringBackedStatus.php | 26 ++++ tests/framework/helpers/ArrayHelperTest.php | 113 ++++++++++++++++++ 8 files changed, 284 insertions(+), 2 deletions(-) create mode 100644 tests/data/helpers/enums/IntBackedStatus.php create mode 100644 tests/data/helpers/enums/Status.php create mode 100644 tests/data/helpers/enums/StringBackedStatus.php diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 657ed1169e8..e684702d6c7 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 #20065: Convert enum cases to scalar values in `yii\helpers\ArrayHelper::toArray()`: backed enums to their value and pure enums to their name (uaoleg, terabytesoftw) 2.0.55 May 09, 2026 ------------------- diff --git a/framework/UPGRADE.md b/framework/UPGRADE.md index e882e151e11..4bb04d49ade 100644 --- a/framework/UPGRADE.md +++ b/framework/UPGRADE.md @@ -65,6 +65,10 @@ Upgrade from Yii 2.0.55 The detection result is composed once per owner class, so such a condition can not be resolved there, and an attribute covered by conditional rules only is now left out of the map instead of being type-casted according to the first matching rule. Set `attributeTypes` explicitly if you rely on those attributes being type-casted. +* `yii\helpers\ArrayHelper::toArray()` now treats enum cases as scalar values: a backed enum case is converted to + its value and a pure enum case to its name, instead of an array with the `name` and `value` keys. This also affects + `yii\base\Arrayable::toArray()` of models with enum attributes and therefore the REST output of such models. + Specify a mapping for the enum class in `$properties` if you rely on the previous representation. Upgrade from Yii 2.0.53 ----------------------- diff --git a/framework/helpers/BaseArrayHelper.php b/framework/helpers/BaseArrayHelper.php index 775926d985b..5fc037362ec 100644 --- a/framework/helpers/BaseArrayHelper.php +++ b/framework/helpers/BaseArrayHelper.php @@ -56,6 +56,9 @@ class BaseArrayHelper * ] * ``` * + * Enum cases are treated as scalar values: a backed enum case is converted to its value and a pure enum case + * to its name, unless a mapping for the enum class is specified in `$properties`. + * * @param bool $recursive whether to recursively converts properties which are objects into arrays. * @return array the array representation of the object */ @@ -64,8 +67,8 @@ public static function toArray($object, $properties = [], $recursive = true) if (is_array($object)) { if ($recursive) { foreach ($object as $key => $value) { - if ($value instanceof \UnitEnum) { - $object[$key] = $value->value; + if ($value instanceof \UnitEnum && empty($properties[get_class($value)])) { + $object[$key] = $value instanceof \BackedEnum ? $value->value : $value->name; } elseif (is_array($value) || is_object($value)) { $object[$key] = static::toArray($value, $properties, true); } @@ -91,6 +94,9 @@ public static function toArray($object, $properties = [], $recursive = true) return $recursive ? static::toArray($result, $properties) : $result; } } + if ($object instanceof \UnitEnum) { + return [$object instanceof \BackedEnum ? $object->value : $object->name]; + } if ($object instanceof Arrayable) { $result = $object->toArray([], [], $recursive); } else { diff --git a/phpstan-baseline-7x.neon b/phpstan-baseline-7x.neon index 432b9255599..1eef0535f80 100644 --- a/phpstan-baseline-7x.neon +++ b/phpstan-baseline-7x.neon @@ -54,6 +54,36 @@ parameters: count: 1 path: framework/db/QueryBuilder.php + - + message: '#^Access to property \$name on an unknown class UnitEnum\.$#' + identifier: class.notFound + count: 2 + path: framework/helpers/BaseArrayHelper.php + + - + message: '#^Access to property \$value on an unknown class BackedEnum\.$#' + identifier: class.notFound + count: 2 + path: framework/helpers/BaseArrayHelper.php + + - + message: '#^Access to property \$value on an unknown class UnitEnum\.$#' + identifier: class.notFound + count: 2 + path: framework/helpers/BaseArrayHelper.php + + - + message: '#^Class BackedEnum not found\.$#' + identifier: class.notFound + count: 2 + path: framework/helpers/BaseArrayHelper.php + + - + message: '#^Class UnitEnum not found\.$#' + identifier: class.notFound + count: 2 + path: framework/helpers/BaseArrayHelper.php + - message: '#^Call to an undefined method ReflectionType\:\:getName\(\)\.$#' identifier: method.notFound @@ -114,6 +144,66 @@ parameters: count: 1 path: tests/framework/db/CommandTest.php + - + message: '#^Access to constant Active on an unknown class yiiunit\\data\\helpers\\enums\\IntBackedStatus\.$#' + identifier: class.notFound + count: 1 + path: tests/framework/helpers/ArrayHelperTest.php + + - + message: '#^Access to constant Active on an unknown class yiiunit\\data\\helpers\\enums\\Status\.$#' + identifier: class.notFound + count: 4 + path: tests/framework/helpers/ArrayHelperTest.php + + - + message: '#^Access to constant Active on an unknown class yiiunit\\data\\helpers\\enums\\StringBackedStatus\.$#' + identifier: class.notFound + count: 8 + path: tests/framework/helpers/ArrayHelperTest.php + + - + message: '#^Access to constant Inactive on an unknown class yiiunit\\data\\helpers\\enums\\IntBackedStatus\.$#' + identifier: class.notFound + count: 1 + path: tests/framework/helpers/ArrayHelperTest.php + + - + message: '#^Access to constant Inactive on an unknown class yiiunit\\data\\helpers\\enums\\Status\.$#' + identifier: class.notFound + count: 2 + path: tests/framework/helpers/ArrayHelperTest.php + + - + message: '#^Access to constant Inactive on an unknown class yiiunit\\data\\helpers\\enums\\StringBackedStatus\.$#' + identifier: class.notFound + count: 1 + path: tests/framework/helpers/ArrayHelperTest.php + + - + message: '#^Call to method label\(\) on an unknown class yiiunit\\data\\helpers\\enums\\StringBackedStatus\.$#' + identifier: class.notFound + count: 1 + path: tests/framework/helpers/ArrayHelperTest.php + + - + message: '#^Call to static method cases\(\) on an unknown class yiiunit\\data\\helpers\\enums\\StringBackedStatus\.$#' + identifier: class.notFound + count: 1 + path: tests/framework/helpers/ArrayHelperTest.php + + - + message: '#^Class yiiunit\\data\\helpers\\enums\\StringBackedStatus not found\.$#' + identifier: class.notFound + count: 1 + path: tests/framework/helpers/ArrayHelperTest.php + + - + message: '#^Parameter \$status of anonymous function has invalid type yiiunit\\data\\helpers\\enums\\StringBackedStatus\.$#' + identifier: class.notFound + count: 1 + path: tests/framework/helpers/ArrayHelperTest.php + - message: '#^Function str_contains not found\.$#' identifier: function.notFound diff --git a/tests/data/helpers/enums/IntBackedStatus.php b/tests/data/helpers/enums/IntBackedStatus.php new file mode 100644 index 00000000000..3e7ca307490 --- /dev/null +++ b/tests/data/helpers/enums/IntBackedStatus.php @@ -0,0 +1,21 @@ + + */ +enum IntBackedStatus: int +{ + case Active = 1; + case Inactive = 0; +} diff --git a/tests/data/helpers/enums/Status.php b/tests/data/helpers/enums/Status.php new file mode 100644 index 00000000000..05f8e5ad6e9 --- /dev/null +++ b/tests/data/helpers/enums/Status.php @@ -0,0 +1,21 @@ + + */ +enum Status +{ + case Active; + case Inactive; +} diff --git a/tests/data/helpers/enums/StringBackedStatus.php b/tests/data/helpers/enums/StringBackedStatus.php new file mode 100644 index 00000000000..98ff30045be --- /dev/null +++ b/tests/data/helpers/enums/StringBackedStatus.php @@ -0,0 +1,26 @@ + + */ +enum StringBackedStatus: string +{ + case Active = 'active'; + case Inactive = 'inactive'; + + public function label(): string + { + return ucfirst($this->value); + } +} diff --git a/tests/framework/helpers/ArrayHelperTest.php b/tests/framework/helpers/ArrayHelperTest.php index 47d3d62d953..e95d6f7625b 100644 --- a/tests/framework/helpers/ArrayHelperTest.php +++ b/tests/framework/helpers/ArrayHelperTest.php @@ -19,9 +19,13 @@ use ArrayAccess; use Iterator; use yii\base\BaseObject; +use yii\base\DynamicModel; use yii\base\Model; use yii\data\Sort; use yii\helpers\ArrayHelper; +use yiiunit\data\helpers\enums\IntBackedStatus; +use yiiunit\data\helpers\enums\Status; +use yiiunit\data\helpers\enums\StringBackedStatus; use yiiunit\TestCase; /** @@ -132,6 +136,115 @@ public function testToArray(): void ], ArrayHelper::toArray(new DateTime('2021-09-13 15:16:17', new DateTimeZone('UTC')))); } + /** + * @requires PHP >= 8.1 + */ + public function testToArrayWithEnums(): void + { + $this->assertSame( + ['string' => 'active', 'int' => 0, 'pure' => 'Inactive'], + ArrayHelper::toArray([ + 'string' => StringBackedStatus::Active, + 'int' => IntBackedStatus::Inactive, + 'pure' => Status::Inactive, + ]), + 'Backed enum cases should be converted to their value and pure enum cases to their name, preserving the keys.', + ); + $this->assertSame( + ['active', 'inactive'], + ArrayHelper::toArray(StringBackedStatus::cases()), + 'A list of enum cases should be converted to a list of their values.', + ); + $this->assertSame( + ['id' => 1, 'status' => 'active', 'tags' => ['status' => 1]], + ArrayHelper::toArray([ + 'id' => 1, + 'status' => StringBackedStatus::Active, + 'tags' => ['status' => IntBackedStatus::Active], + ]), + 'Enum cases nested in sub-arrays should be converted when converting recursively.', + ); + $this->assertSame( + ['active'], + ArrayHelper::toArray(StringBackedStatus::Active), + 'A backed enum case passed directly should be converted like a scalar value.', + ); + $this->assertSame( + ['Active'], + ArrayHelper::toArray(Status::Active), + 'A pure enum case passed directly should be converted like a scalar value.', + ); + } + + /** + * @requires PHP >= 8.1 + */ + public function testToArrayWithEnumsNonRecursive(): void + { + $this->assertSame( + ['status' => StringBackedStatus::Active, 'nested' => ['status' => Status::Active]], + ArrayHelper::toArray( + ['status' => StringBackedStatus::Active, 'nested' => ['status' => Status::Active]], + [], + false, + ), + 'Enum cases should not be converted when converting an array non-recursively, like any other object.', + ); + $this->assertSame( + ['active'], + ArrayHelper::toArray(StringBackedStatus::Active, [], false), + 'An enum case passed directly should be converted even when converting non-recursively.', + ); + } + + /** + * @requires PHP >= 8.1 + */ + public function testToArrayWithEnumsAndProperties(): void + { + $properties = [ + StringBackedStatus::class => [ + 'value', + 'label' => function (StringBackedStatus $status) { + return $status->label(); + }, + ], + ]; + + $this->assertSame( + ['value' => 'active', 'label' => 'Active'], + ArrayHelper::toArray(StringBackedStatus::Active, $properties), + 'A mapping specified for the enum class should take precedence over the scalar conversion.', + ); + $this->assertSame( + [ + 'status' => ['value' => 'inactive', 'label' => 'Inactive'], + 'other' => 'Active', + ], + ArrayHelper::toArray(['status' => StringBackedStatus::Inactive, 'other' => Status::Active], $properties), + 'A mapping specified for the enum class should also take precedence for nested enum cases, while enum classes without a mapping are converted to scalar values.', + ); + } + + /** + * @requires PHP >= 8.1 + */ + public function testToArrayWithEnumsInArrayable(): void + { + $model = new DynamicModel(['status' => StringBackedStatus::Active, 'flag' => Status::Inactive]); + + $this->assertSame( + ['status' => 'active', 'flag' => 'Inactive'], + $model->toArray(), + 'Enum attributes of an `Arrayable` object should be converted to scalar values.', + ); + $this->assertSame( + [['status' => 'active', 'flag' => 'Inactive']], + ArrayHelper::toArray([$model]), + 'Enum attributes of an `Arrayable` object nested in an array should be converted to scalar values.', + ); + } + public function testRemove(): void { $array = ['name' => 'b', 'age' => 3];