1

How do you count the cases in an enum like this one? I have functions getRandomDataTypeName() and getRandomDataTypeValue() with for($i = 0; $i < DataType::count(); $i++) that should dynamically learn about this public static method count():int .

<?php

enum DataType: string {

    case ACCEPTED = "accepted";
    case WITH_ERRORS = "with errore";
    case DONE = "done";
    case FAILED ='failed';


    public static function getRandomDataTypeName(): string {
      $arr =  array();
      $arrDT = DataType::cases();

      for($i = 0; $i < DataType::count(); $i++)
        $arr[$i] = $arrDT[$i]->name;

      $i = array_rand($arr, 1);

      return $arrDT[$i]->name;
    }

    public static function getRandomDataTypeValue(): string {
      $arr =  array();
      $arrDT = DataType::cases();

      for($i = 0; $i < DataType::count(); $i++)
        $arr[$i] = $arrDT[$i]->value;

      $i = array_rand($arr, 1);

      return $arrDT[$i]->value;
    }
    
    public static function count(): int {
      return count(DataType::cases());
    }
}
?>
Toni Zeidler
  • 163
  • 1
  • 11

1 Answers1

4

Add this method to your enum and get random case

public static function random(): self
{
    $count = count(self::cases()) - 1;

    return self::cases()[rand(0, $count)];
}

Then simply get name or value

DataType::random()->name // return random name
DataType::random()->value // return random value