0

I receive as input an array of values. Example : [3,2,3,1] I need as output an array of enums like this : [Fruits::Banana, Fruits::Pear, Fruits::Banana, Fruits::Apple ]

I Try to do a generic function to do this but I got an error because $enumClassName::class does not work...

function get_ennum_array_from_values( array $values, string $enumClassName ){
  $array_of_enum = [];
  foreach ( $values as $value ){
    if( is_numeric( $value ) ){
      $fvalue = (int) $value;
    }else{
      $fvalue = $value;
    }
    $enum = new ReflectionEnum($enumClassName::class);

    if (enum_exists($enum)) {
      $array_of_enum[] = $enum::tryFrom($fvalue);
    }
  }
  return $array_of_enum;
}

This how I would like to use it :

enum Fruits: int {
  case Apple = 1;
  case Pear = 2;
  case Banana = 3;
}

$array_of_enums = get_ennum_array_from_values( [3,2,3,1], 'Fruits' );

How can I do this or fix this function please ?

1

2 Answers 2

0

Can you put class name (with ::class) as second argument? If yes, than

function get_ennum_array_from_values(array $values, string $enumClassName) {
  if (!enum_exists($enumClassName)) {
    return [];
  }

  $array_of_enum = [];

  foreach ($values as $value) {
    $fvalue = is_numeric($value) ? (int)$value : $value;
    $array_of_enum[] = $enumClassName::tryFrom($fvalue);
  }

  return $array_of_enum;
}

and call it like

$array_of_enums = get_ennum_array_from_values([3,2,3,1], Fruits::class);
Sign up to request clarification or add additional context in comments.

Comments

0

Perhaps you don't need a function?

$array_of_enums = array_map(fn ($case) => Fruits::tryFrom($case), [3,2,3,1]);

Or can I suggest a trait?

which you can use on enums where you are wanting to get an array of enums from an array of values. You could even add a second function to the trait tryFromArrayNames if it is not a backed enum.

trait EnumsFromArray
{
    public static function tryFromArrayValues(array $array): array
    {
        return array_map(fn ($case) => self::tryFrom($case), $array);
    }
}

But if you really want a function:

function get_ennum_array_from_values(array $values, string $enumClassName) {
  if (!enum_exists($enumClassName)) {
    // Or perhaps throw an exception, this would obscure coding errors?
    return [];
  }

  return array_map(fn ($case) => $enumClassName::tryFrom($case), $values);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.