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