|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace CodeOfDigital\LaravelUrlShortener\Drivers; |
| 4 | + |
| 5 | +use CodeOfDigital\LaravelUrlShortener\Exceptions\BadRequestException; |
| 6 | +use CodeOfDigital\LaravelUrlShortener\Exceptions\InvalidResponseException; |
| 7 | +use CodeOfDigital\LaravelUrlShortener\Exceptions\ShortUrlException; |
| 8 | +use CodeOfDigital\LaravelUrlShortener\Exceptions\TooManyRequestException; |
| 9 | +use GuzzleHttp\ClientInterface; |
| 10 | +use GuzzleHttp\Exception\RequestException; |
| 11 | +use GuzzleHttp\Psr7\Request; |
| 12 | +use Illuminate\Support\Arr; |
| 13 | +use Illuminate\Support\Str; |
| 14 | +use Psr\Http\Message\ResponseInterface; |
| 15 | + |
| 16 | +class FirebaseDriverShortener extends DriverShortener |
| 17 | +{ |
| 18 | + protected $client; |
| 19 | + protected $object; |
| 20 | + |
| 21 | + public function __construct(ClientInterface $client, $token, $domain, $suffix) |
| 22 | + { |
| 23 | + $this->client = $client; |
| 24 | + $this->object = [ |
| 25 | + 'allow_redirects' => false, |
| 26 | + 'base_uri' => 'https://firebasedynamiclinks.googleapis.com', |
| 27 | + 'headers' => [ |
| 28 | + 'Content-Type' => 'application/json', |
| 29 | + 'Accept' => 'application/json' |
| 30 | + ], |
| 31 | + 'query' => [ |
| 32 | + 'key' => $token |
| 33 | + ], |
| 34 | + 'json' => [ |
| 35 | + 'dynamicLinkInfo' => [ |
| 36 | + 'domainUriPrefix' => $domain |
| 37 | + ], |
| 38 | + 'suffix' => [ |
| 39 | + 'option' => $suffix |
| 40 | + ] |
| 41 | + ] |
| 42 | + ]; |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * @inheritDoc |
| 47 | + */ |
| 48 | + public function shortenAsync($url, array $options = []) |
| 49 | + { |
| 50 | + if (!Str::startsWith($url, ['http://', 'https://'])) |
| 51 | + throw new ShortUrlException('The given URL must begin with http/https'); |
| 52 | + |
| 53 | + $options = array_merge_recursive(Arr::add($this->object, 'json.dynamicLinkInfo.link', $url), ['json' => ['dynamicLinkInfo' => $options]]); |
| 54 | + $request = new Request('POST', '/v1/shortLinks'); |
| 55 | + |
| 56 | + return $this->client->sendAsync($request, $options)->then( |
| 57 | + function (ResponseInterface $response) { |
| 58 | + return json_decode($response->getBody()->getContents())->shortLink; |
| 59 | + }, |
| 60 | + function (RequestException $e) { |
| 61 | + $this->getErrorMessage($e->getCode(), json_decode($e->getResponse()->getBody()->getContents())->error->message); |
| 62 | + } |
| 63 | + ); |
| 64 | + } |
| 65 | + |
| 66 | + protected function getErrorMessage($code, $message = null) |
| 67 | + { |
| 68 | + switch ($code) { |
| 69 | + case 400: throw new BadRequestException($message); |
| 70 | + case 429: throw new TooManyRequestException($message); |
| 71 | + default: throw new InvalidResponseException($message); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments