BaseEnum.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace addons\exam\enum;
  3. use ReflectionClassConstant;
  4. class BaseEnum
  5. {
  6. /**
  7. * 获取所有常量
  8. * @return array
  9. */
  10. public static function getConst(): array
  11. {
  12. $objClass = new \ReflectionClass(get_called_class());
  13. return $objClass->getConstants();
  14. }
  15. /**
  16. * 获取所有常量名
  17. * @return array
  18. */
  19. public static function getConstantsKeys(): array
  20. {
  21. return array_keys(self::getConst());
  22. }
  23. /**
  24. * 获取所有常量值
  25. * @return array
  26. */
  27. public static function getConstantsValues(): array
  28. {
  29. return array_values(self::getConst());
  30. }
  31. /**
  32. * 获取常量注释
  33. * @param string $key 常量名
  34. * @return string
  35. */
  36. public static function getDescription(string $key): string
  37. {
  38. return preg_replace('#[\*\s]*(^/|/$)[\*\s]*#', '', (new ReflectionClassConstant(static::class, $key))->getDocComment());
  39. }
  40. /**
  41. * 获取常量名和注释列表
  42. * @return array
  43. */
  44. public static function getKeyDescription(): array
  45. {
  46. $keys = self::getConstantsKeys();
  47. $result = [];
  48. foreach ($keys as $key => $key_name) {
  49. $result[$key_name] = self::getDescription($key_name);
  50. }
  51. return $result;
  52. }
  53. /**
  54. * 获取常量值和注释列表
  55. * @return array
  56. */
  57. public static function getValueDescription(): array
  58. {
  59. $const = self::getConst();
  60. $result = [];
  61. foreach ($const as $key => $value) {
  62. $result[$value] = self::getDescription($key);
  63. }
  64. return $result;
  65. }
  66. }