ActionUtil.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace App\Utils\Control;
  3. use Hyperf\Coroutine\Coroutine;
  4. use Hyperf\HttpServer\Router\Dispatched;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. class ActionUtil
  7. {
  8. private static string $prefix = 'App\Controller\\';
  9. protected array $actions = [];// 控制器信息
  10. protected static array $instance = [];
  11. public static function getInstance(): ActionUtil
  12. {
  13. //协程id
  14. $coroutine_id = Coroutine::id();
  15. if (empty(self::$instance[$coroutine_id])) {
  16. self::$instance[$coroutine_id] = new self();
  17. Coroutine::defer(function () use ($coroutine_id) {
  18. unset(self::$instance[$coroutine_id]);
  19. });
  20. }
  21. return self::$instance[$coroutine_id];
  22. }
  23. /**
  24. * 获取当前路由地址
  25. * @param ServerRequestInterface $request
  26. * @param string $project
  27. * @return array
  28. */
  29. public function actions(ServerRequestInterface $request, string $project = 'Api'): array
  30. {
  31. $action = $request->getAttribute(Dispatched::class)->handler->callback ?? [];
  32. $controller = str_replace(self::$prefix.$project . '\\', '', $action[0] ?? '');
  33. $controller = str_replace('\\', '/', $controller);
  34. if (!empty($action[1])) {
  35. $this->actions['controller'] = $controller ?? 'CommonController';
  36. $this->actions['action'] = $action[1];
  37. } else {
  38. $this->actions['controller'] = 'CommonController';
  39. $this->actions['action'] = 'common';
  40. }
  41. return $this->actions;
  42. }
  43. public function get()
  44. {
  45. return $this->actions;
  46. }
  47. }