You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

27 lines
897 B

  1. <?php
  2. use Illuminate\Support\Arr;
  3. use Illuminate\Support\Str;
  4. if (! function_exists('enum')) {
  5. function enum($key)
  6. {
  7. // add a dot at the end of string to prevent undefined offset
  8. $key .= Str::of($key)->contains(".") ? "" : ".";
  9. // the first parameter of all enum keys are its filename
  10. [$filename, $key] = explode(".", $key, 2);
  11. // because we do not want to load the file every time use require
  12. $enums = require app_path("Enums/$filename.php");
  13. // if the key that user provided not exists then null return
  14. $enums = Arr::get($enums, $key, null);
  15. // if enum null means that key not found
  16. throw_if($enums === null, 'Exception', "Undefined enum '{$key}'");
  17. // if enum value is array its mean that user want to use it as collection
  18. return is_array($enums) ? collect($enums) : $enums;
  19. }
  20. }