ActionUtil.php 1.6 KB

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