|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace LeadThread\Shortener; |
|
4
|
|
|
|
|
5
|
|
|
use Exception; |
|
6
|
|
|
use Illuminate\Support\Facades\Cache; |
|
7
|
|
|
use LeadThread\Shortener\Drivers\Bitly; |
|
8
|
|
|
use LeadThread\Shortener\Interfaces\UrlShortener; |
|
9
|
|
|
use LeadThread\Shortener\Exceptions\ShortenerException; |
|
10
|
|
|
use LeadThread\Shortener\Rotators\Service\Rotator as ServiceRotator; |
|
11
|
|
|
use Illuminate\Cache\TaggableStore; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* The master class |
|
15
|
|
|
*/ |
|
16
|
|
|
class Shortener |
|
17
|
|
|
{ |
|
18
|
|
|
protected $config; |
|
19
|
|
|
protected $rotator; |
|
20
|
|
|
|
|
21
|
30 |
|
public function __construct(ServiceRotator $rotator = null) |
|
22
|
|
|
{ |
|
23
|
30 |
|
$this->config = config('shortener'); |
|
24
|
|
|
|
|
25
|
30 |
|
if (!$rotator instanceof ServiceRotator) { |
|
26
|
9 |
|
$rotator = $this->getRotator(); |
|
27
|
6 |
|
} |
|
28
|
|
|
|
|
29
|
27 |
|
$this->rotator = $rotator; |
|
30
|
27 |
|
} |
|
31
|
|
|
|
|
32
|
9 |
|
protected function getRotator() |
|
33
|
|
|
{ |
|
34
|
9 |
|
$service = $this->config['driver']; |
|
35
|
|
|
|
|
36
|
|
|
|
|
37
|
9 |
|
if ($service === null) { |
|
38
|
6 |
|
$services = array_keys($this->config['accounts']); |
|
39
|
9 |
|
} else if (is_string($service)) { |
|
40
|
3 |
|
$services = [$service]; |
|
41
|
3 |
|
} else { |
|
42
|
|
|
throw new Exception("Could not determine which services to use."); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
9 |
|
$rotatorInstance = new ServiceRotator($services); |
|
46
|
|
|
|
|
47
|
6 |
|
return $rotatorInstance; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
21 |
|
public function shorten($url, $encode = true) |
|
51
|
|
|
{ |
|
52
|
21 |
|
$rotator = $this->rotator; |
|
53
|
21 |
|
if ($this->config['cache']['enabled'] === true) { |
|
54
|
18 |
|
return $this->getFromCache($url, $this->config['cache']['duration'], function () use ($rotator, $url, $encode) { |
|
55
|
18 |
|
return $rotator->shorten($url, $encode); |
|
56
|
18 |
|
}); |
|
57
|
|
|
} else { |
|
58
|
3 |
|
return $rotator->shorten($url, $encode); |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
18 |
|
protected function getFromCache($key, $time, $fn) |
|
63
|
|
|
{ |
|
64
|
18 |
|
$cache = Cache::driver(Cache::getDefaultDriver()); |
|
65
|
18 |
|
if ($cache instanceof TaggableStore) { |
|
66
|
|
|
$cache->tags('shortener'); |
|
67
|
|
|
} |
|
68
|
18 |
|
return $cache->remember($key, $time, $fn); |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|