ApiService.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace App\Api\Services;
  3. use App\Base\Library\Shorty;
  4. use App\Base\Services\ApiBaseService;
  5. use App\Basic\Facades\UrlsFacade;
  6. use Illuminate\Support\Facades\Cache;
  7. class ApiService extends ApiBaseService
  8. {
  9. private $shorty;// 短地址服务
  10. public function __construct()
  11. {
  12. $this->shorty = new Shorty(config("app.domain"));
  13. }
  14. /**
  15. * 获取短地址
  16. */
  17. public function getShortUrl($urls)
  18. {
  19. $isArray = 0;
  20. if (is_array($urls)) {
  21. $isArray = 1;
  22. }
  23. $urls = is_array($urls) ? $urls : [$urls];
  24. $list = [];
  25. foreach ($urls as $url) {
  26. $key = "shortUrl_" . md5($url);
  27. $value = Cache::get($key, '');
  28. if ($value) {
  29. $list[$url] = $value;
  30. continue;
  31. }
  32. try {
  33. $list[$url] = $this->shorty->run($url);
  34. Cache::put($key, $list[$url], 86400 * 7);
  35. } catch (\Exception $e) {
  36. \Log::info($e->getMessage());
  37. //continue;
  38. }
  39. }
  40. if ($isArray == 0) {
  41. return $list[$urls[0]] ?? '';
  42. } else {
  43. return $list;
  44. }
  45. }
  46. /**
  47. * 获取短地址访问量
  48. */
  49. public function getShortUrlHits($urls)
  50. {
  51. return UrlsFacade::getShortUrlHits($urls);
  52. }
  53. }