ReflectionCache.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | saiadmin [ saiadmin快速开发框架 ]
  4. // +----------------------------------------------------------------------
  5. // | Author: sai <1430792918@qq.com>
  6. // +----------------------------------------------------------------------
  7. declare(strict_types=1);
  8. namespace plugin\saiadmin\app\cache;
  9. use ReflectionClass;
  10. use ReflectionMethod;
  11. use plugin\saiadmin\service\Permission;
  12. use support\think\Cache;
  13. /**
  14. * 反射文件缓存
  15. */
  16. class ReflectionCache
  17. {
  18. /**
  19. * 读取缓存配置
  20. * @return array
  21. */
  22. public static function cacheConfig(): array
  23. {
  24. return config('plugin.saiadmin.saithink.reflection_cache', [
  25. 'tag' => 'saiadmin:reflection',
  26. 'expire' => 60 * 60 * 24 * 365,
  27. 'no_need' => 'saiadmin:reflection_cache:no_need_',
  28. 'attr' => 'saiadmin:reflection_cache:attr_',
  29. ]);
  30. }
  31. /**
  32. * 获取控制器中无需登录的方法列表
  33. */
  34. public static function getNoNeedLogin(string $controller): array
  35. {
  36. $cache = static::cacheConfig();
  37. $tag = [];
  38. $tag[] = $cache['tag'];
  39. $key = $cache['no_need'] . md5($controller);
  40. $data = Cache::get($key);
  41. if ($data !== null) {
  42. return $data;
  43. }
  44. // 反射逻辑
  45. if (class_exists($controller)) {
  46. $ref = new ReflectionClass($controller);
  47. $data = $ref->getDefaultProperties()['noNeedLogin'] ?? [];
  48. } else {
  49. $data = [];
  50. }
  51. Cache::tag($tag)->set($key, $data, $cache['expire']);
  52. return $data;
  53. }
  54. /**
  55. * 获取方法上的权限属性
  56. */
  57. public static function getPermissionAttributes(string $controller, string $action): array
  58. {
  59. $cache = static::cacheConfig();
  60. $tag = [];
  61. $tag[] = $cache['tag'];
  62. $key = $cache['attr'] . md5($controller . '::' . $action);
  63. $data = Cache::get($key);
  64. if ($data) {
  65. return $data;
  66. }
  67. $data = [];
  68. if (method_exists($controller, $action)) {
  69. $refMethod = new ReflectionMethod($controller, $action);
  70. $attributes = $refMethod->getAttributes(Permission::class);
  71. if (!empty($attributes)) {
  72. $attr = $attributes[0]->newInstance();
  73. $data = [
  74. 'title' => $attr->getTitle(),
  75. 'slug' => $attr->getSlug(),
  76. ];
  77. }
  78. }
  79. Cache::tag($tag)->set($key, $data, $cache['expire']);
  80. return $data;
  81. }
  82. /**
  83. * 清理所有反射缓存
  84. * @return bool
  85. */
  86. public static function clear(): bool
  87. {
  88. $cache = static::cacheConfig();
  89. return Cache::tag($cache['tag'])->clear();
  90. }
  91. }