AgentContextService.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. <?php
  2. namespace App\Services\Agent;
  3. use Illuminate\Http\Request;
  4. class AgentContextService
  5. {
  6. public function device(Request $request): string
  7. {
  8. $ua = strtolower((string) $request->userAgent());
  9. return preg_match('/mobile|android|iphone|ipad|ipod|windows phone|harmonyos/', $ua)
  10. ? 'mobile'
  11. : 'pc';
  12. }
  13. public function domain(Request $request): string
  14. {
  15. foreach ([(string) $request->header('Origin'), (string) $request->header('Referer')] as $url) {
  16. $host = parse_url($url, PHP_URL_HOST);
  17. if (is_string($host) && $host !== '') {
  18. return strtolower($host);
  19. }
  20. }
  21. return strtolower((string) $request->getHost());
  22. }
  23. public function location(Request $request): array
  24. {
  25. // 优先读取 CDN/网关在边缘完成的 IP 归属地;没有时保留空值,避免登录依赖外部接口。
  26. return [
  27. 'country' => mb_substr((string) ($request->header('CF-IPCountry') ?: $request->header('X-IP-Country', '')), 0, 128),
  28. 'region' => mb_substr((string) $request->header('X-IP-Region', ''), 0, 128),
  29. 'city' => mb_substr((string) $request->header('X-IP-City', ''), 0, 128),
  30. ];
  31. }
  32. }