1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace LaraCrafts\UrlShortener\Http; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\ClientInterface; |
6
|
|
|
use GuzzleHttp\Psr7\Request; |
7
|
|
|
use Illuminate\Support\Arr; |
8
|
|
|
use Illuminate\Support\Str; |
9
|
|
|
use Psr\Http\Message\ResponseInterface; |
10
|
|
|
use function GuzzleHttp\json_decode; |
11
|
|
|
|
12
|
|
|
class FirebaseShortener extends RemoteShortener |
13
|
|
|
{ |
14
|
|
|
private static $SUFFIXES = ['UNGUESSABLE', 'SHORT']; |
15
|
|
|
|
16
|
|
|
protected $client; |
17
|
|
|
protected $defaults; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Create a new Shorte.st shortener. |
21
|
|
|
* |
22
|
|
|
* @param \GuzzleHttp\ClientInterface $client |
23
|
|
|
* @param string $token |
24
|
|
|
* @param string $domain |
25
|
|
|
* @param string $suffix |
26
|
|
|
*/ |
27
|
|
|
public function __construct(ClientInterface $client, string $token, string $domain, string $suffix) |
28
|
|
|
{ |
29
|
|
|
if (!Arr::has(self::$SUFFIXES, Str::upper($suffix))) { |
30
|
|
|
$suffix = self::$SUFFIXES[0]; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
$this->client = $client; |
34
|
|
|
$this->defaults = [ |
35
|
|
|
'allow_redirects' => false, |
36
|
|
|
'base_uri' => 'https://firebasedynamiclinks.googleapis.com', |
37
|
|
|
'headers' => [ |
38
|
|
|
'Content-Type' => 'application/json', |
39
|
|
|
'Accept' => 'application/json', |
40
|
|
|
], |
41
|
|
|
'query' => [ |
42
|
|
|
'key' => $token, |
43
|
|
|
], |
44
|
|
|
'json' => [ |
45
|
|
|
'dynamicLinkInfo' => [ |
46
|
|
|
'domainUriPrefix' => $domain, |
47
|
|
|
], |
48
|
|
|
'suffix' => [ |
49
|
|
|
"option" => $suffix, |
50
|
|
|
], |
51
|
|
|
], |
52
|
|
|
]; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Shorten the given URL asynchronously. |
57
|
|
|
* |
58
|
|
|
* @param \Psr\Http\Message\UriInterface|string $url |
59
|
|
|
* @param array $options |
60
|
|
|
* @return \GuzzleHttp\Promise\PromiseInterface |
61
|
|
|
*/ |
62
|
|
|
public function shortenAsync($url, array $options = []) |
63
|
|
|
{ |
64
|
|
|
$options = array_merge(Arr::add($this->defaults, 'json.dynamicLinkInfo.link', $url), $options); |
65
|
|
|
$request = new Request('POST', '/v1/shortLinks'); |
66
|
|
|
|
67
|
|
|
return $this->client->sendAsync($request, $options)->then(function (ResponseInterface $response) { |
68
|
|
|
return json_decode($response->getBody()->getContents())->shortLink; |
69
|
|
|
}); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|