|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace CodeOfDigital\LaravelUrlShortener\Drivers; |
| 4 | + |
| 5 | +use CodeOfDigital\LaravelUrlShortener\Exceptions\BadRequestException; |
| 6 | +use CodeOfDigital\LaravelUrlShortener\Exceptions\InvalidApiTokenException; |
| 7 | +use CodeOfDigital\LaravelUrlShortener\Exceptions\InvalidResponseException; |
| 8 | +use CodeOfDigital\LaravelUrlShortener\Exceptions\ShortUrlException; |
| 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 OuoIoDriverShortener extends DriverShortener |
| 17 | +{ |
| 18 | + protected $client; |
| 19 | + protected $object; |
| 20 | + protected $token; |
| 21 | + |
| 22 | + public function __construct(ClientInterface $client, $token) |
| 23 | + { |
| 24 | + $this->client = $client; |
| 25 | + $this->token = $token; |
| 26 | + $this->object = [ |
| 27 | + 'allow_redirects' => false, |
| 28 | + 'base_uri' => 'https://ouo.io', |
| 29 | + ]; |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * @inheritDoc |
| 34 | + */ |
| 35 | + public function shortenAsync($url, array $options = []) |
| 36 | + { |
| 37 | + if (!Str::startsWith($url, ['http://', 'https://'])) |
| 38 | + throw new ShortUrlException('The given URL must begin with http/https'); |
| 39 | + |
| 40 | + $options = array_merge_recursive(Arr::add($this->object, 'query.s', urlencode($url)), ['query' => $options]); |
| 41 | + $request = new Request('GET', "/api/{$this->token}"); |
| 42 | + |
| 43 | + return $this->client->sendAsync($request, $options)->then( |
| 44 | + function (ResponseInterface $response) { |
| 45 | + if ($response->getStatusCode() == 302) |
| 46 | + $this->getErrorMessage($response->getStatusCode(), "Your API Token is invalid. Please try a new API Token."); |
| 47 | + |
| 48 | + return $response->getBody()->getContents(); |
| 49 | + }, |
| 50 | + function (RequestException $e) { |
| 51 | + $this->getErrorMessage($e->getCode(), $e->getResponse()->getBody()->getContents()); |
| 52 | + } |
| 53 | + ); |
| 54 | + } |
| 55 | + |
| 56 | + protected function getErrorMessage($code, $message = null) |
| 57 | + { |
| 58 | + switch ($code) { |
| 59 | + case 302: throw new InvalidApiTokenException($message); |
| 60 | + case 400: throw new BadRequestException($message); |
| 61 | + default: throw new InvalidResponseException($message); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments