N°7157 - Add support for backed-enum in \ValueSetEnum constructor

This commit is contained in:
Molkobain
2024-03-07 11:02:23 +01:00
parent e05b4e772c
commit 8e8d586dcc
4 changed files with 116 additions and 27 deletions

View File

@@ -471,34 +471,12 @@ class ValueSetEnum extends ValueSetDefinition
*/
protected bool $bSortByValues;
/**
* @param string $sBackedEnumFQCN FQCN of the backed enum to use
* @param bool $bSortValues {@see static::$bSortValues}
*
* @return \ValueSetEnum ValueSetEnum based on the values of the $sBackedEnumFQCN backed enum
* @throws \CoreException
* @since 3.2.0
*/
public static function FromBackedEnum(string $sBackedEnumFQCN, bool $bSortValues = false): ValueSetEnum
{
// First, check that we pass an enum as there is no generic type hint for that yet
if (false === enum_exists($sBackedEnumFQCN)) {
throw new CoreException("Can't instantiate " . __CLASS__ . "::" . __METHOD__ . " from a non-enum argument", [
"argument" => $sBackedEnumFQCN
]);
}
// Implode cases
$sJoinedValues = implode(",", array_map(fn($case) => $case->value, $sBackedEnumFQCN::cases()));
return new ValueSetEnum($sJoinedValues, $bSortValues);
}
/**
* @param array|string $Values
* @param bool $bLocalizedSort
*
* @since 3.1.0 N°1646 Add $bLocalizedSort parameter
* @since 3.2.0 N°7157 $Values can be an array of backed-enum cases
*/
public function __construct($Values, bool $bSortByValues = false)
{
@@ -546,13 +524,21 @@ class ValueSetEnum extends ValueSetDefinition
*/
protected function LoadValues($aArgs)
{
$aValues = [];
if (is_array($this->m_values))
{
$aValues = $this->m_values;
foreach ($this->m_values as $value) {
// Handle backed-enum case
if (is_object($value) && enum_exists(get_class($value))) {
$aValues[] = $value->value;
continue;
}
$aValues[] = $value;
}
}
elseif (is_string($this->m_values) && strlen($this->m_values) > 0)
{
$aValues = array();
foreach (explode(",", $this->m_values) as $sVal)
{
$sVal = trim($sVal);
@@ -562,7 +548,7 @@ class ValueSetEnum extends ValueSetDefinition
}
else
{
$aValues = array();
$aValues = [];
}
$this->m_aValues = $aValues;
return true;