12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- <?php
- namespace app\admin\service;
- use app\common\constants\ShortUrl;
- use app\common\library\Redis;
- use think\Config;
- class ShortUrlService
- {
- /**
- * @var \app\common\model\ShortUrl
- */
- private $_shortUrl;
- public function __construct()
- {
- $this->_shortUrl = model('ShortUrl');
- }
- /**
- * 获取短链接
- * @param $id 短链接id
- * @return bool|string
- * @throws \Exception
- */
- public function getShortUrl($id)
- {
- $redisService = new RedisService();
- $url = $redisService->getShortUrl($id);
- if (empty($url)) {
- $urlInfo = $this->_shortUrl->getInfo($id);
- if (empty($urlInfo)) {
- //todo: 这里需要记日志
- } else {
- $url = $urlInfo->url;
- $redisService->setShortUrl($id, $url);
- }
- }
- return $url;
- }
- /**
- * 创建短链接
- * @param string $url 长链接
- * @return string
- * @throws \Exception
- */
- public function create($url, $channelId)
- {
- $redisService = new RedisService();
- $urlData = [
- 'url' => $url,
- 'createtime' => time(),
- 'updatetime' => time(),
- ];
- $id = $this->_shortUrl->allowField(true)->insertGetId($urlData);
- $redisService->setShortUrl($id, $url);
- $shortUrlHost = Config::get("site.short_url_host");
- if (preg_match('/ext=({.*?})/', $url, $match_ext)) {
- $ext = $match_ext[1];
- preg_match('/\/t\/(\d+)/', $url, $match_short_referral_id);
- preg_match('/referral_id=(\d+)/', $url, $match_referral_id);
- $referral_id = 0;
- if ($match_short_referral_id) {
- $referral_id = $match_short_referral_id[1];
- }
- if ($match_referral_id) {
- $referral_id = $match_referral_id[1];
- }
- if ($referral_id) {
- $cacheExt = 'RefExt:' . md5($ext);
- Redis::instance()->set($cacheExt, $referral_id);
- }
- }
- if (empty($shortUrlHost)) {
- //取渠道业务域名
- $shortUrlHost = trim(getCurrentDomain($channelId, null, [], true),'/');
- }
- $shortUrl = sprintf('%s/%s/%s', $shortUrlHost, ShortUrl::SHORT_URL_PATH, $id);
- return $shortUrl;
- }
- }
|