ShortUrlService.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace app\admin\service;
  3. use app\common\constants\ShortUrl;
  4. use app\common\library\Redis;
  5. use think\Config;
  6. class ShortUrlService
  7. {
  8. /**
  9. * @var \app\common\model\ShortUrl
  10. */
  11. private $_shortUrl;
  12. public function __construct()
  13. {
  14. $this->_shortUrl = model('ShortUrl');
  15. }
  16. /**
  17. * 获取短链接
  18. * @param $id 短链接id
  19. * @return bool|string
  20. * @throws \Exception
  21. */
  22. public function getShortUrl($id)
  23. {
  24. $redisService = new RedisService();
  25. $url = $redisService->getShortUrl($id);
  26. if (empty($url)) {
  27. $urlInfo = $this->_shortUrl->getInfo($id);
  28. if (empty($urlInfo)) {
  29. //todo: 这里需要记日志
  30. } else {
  31. $url = $urlInfo->url;
  32. $redisService->setShortUrl($id, $url);
  33. }
  34. }
  35. return $url;
  36. }
  37. /**
  38. * 创建短链接
  39. * @param string $url 长链接
  40. * @return string
  41. * @throws \Exception
  42. */
  43. public function create($url, $channelId)
  44. {
  45. $redisService = new RedisService();
  46. $urlData = [
  47. 'url' => $url,
  48. 'createtime' => time(),
  49. 'updatetime' => time(),
  50. ];
  51. $id = $this->_shortUrl->allowField(true)->insertGetId($urlData);
  52. $redisService->setShortUrl($id, $url);
  53. $shortUrlHost = Config::get("site.short_url_host");
  54. if (preg_match('/ext=({.*?})/', $url, $match_ext)) {
  55. $ext = $match_ext[1];
  56. preg_match('/\/t\/(\d+)/', $url, $match_short_referral_id);
  57. preg_match('/referral_id=(\d+)/', $url, $match_referral_id);
  58. $referral_id = 0;
  59. if ($match_short_referral_id) {
  60. $referral_id = $match_short_referral_id[1];
  61. }
  62. if ($match_referral_id) {
  63. $referral_id = $match_referral_id[1];
  64. }
  65. if ($referral_id) {
  66. $cacheExt = 'RefExt:' . md5($ext);
  67. Redis::instance()->set($cacheExt, $referral_id);
  68. }
  69. }
  70. if (empty($shortUrlHost)) {
  71. //取渠道业务域名
  72. $shortUrlHost = trim(getCurrentDomain($channelId, null, [], true),'/');
  73. }
  74. $shortUrl = sprintf('%s/%s/%s', $shortUrlHost, ShortUrl::SHORT_URL_PATH, $id);
  75. return $shortUrl;
  76. }
  77. }