|
| 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\InvalidDataException; |
| 8 | +use CodeOfDigital\LaravelUrlShortener\Exceptions\InvalidResponseException; |
| 9 | +use GuzzleHttp\ClientInterface; |
| 10 | +use GuzzleHttp\Exception\RequestException; |
| 11 | +use GuzzleHttp\Psr7\Request; |
| 12 | +use Illuminate\Support\Arr; |
| 13 | +use Psr\Http\Message\ResponseInterface; |
| 14 | + |
| 15 | +class CuttLyDriverShortener extends DriverShortener |
| 16 | +{ |
| 17 | + protected $client; |
| 18 | + protected $object; |
| 19 | + |
| 20 | + public function __construct(ClientInterface $client, $token) |
| 21 | + { |
| 22 | + $this->client = $client; |
| 23 | + $this->object = [ |
| 24 | + 'allow_redirects' => false, |
| 25 | + 'base_uri' => 'https://cutt.ly', |
| 26 | + 'query' => [ |
| 27 | + 'key' => $token |
| 28 | + ] |
| 29 | + ]; |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * @inheritDoc |
| 34 | + */ |
| 35 | + public function shortenAsync($url, array $options = []) |
| 36 | + { |
| 37 | + $options = array_merge_recursive(Arr::add($this->object, 'query.short', urlencode($url)), ['query' => $options]); |
| 38 | + $request = new Request('GET', '/api/api.php'); |
| 39 | + |
| 40 | + return $this->client->sendAsync($request, $options)->then( |
| 41 | + function (ResponseInterface $response) { |
| 42 | + $statusCode = json_decode($response->getBody()->getContents())->url->status; |
| 43 | + if ($statusCode != 7) $this->getErrorMessage($statusCode); |
| 44 | + return str_replace('http://', 'https://', json_decode($response->getBody()->getContents())->url->shortLink); |
| 45 | + }, |
| 46 | + function (RequestException $e) { |
| 47 | + $this->getErrorMessage($e->getCode(), $e->getMessage()); |
| 48 | + } |
| 49 | + ); |
| 50 | + } |
| 51 | + |
| 52 | + protected function getErrorMessage($code, $message = null) |
| 53 | + { |
| 54 | + switch ($code) { |
| 55 | + case 1: |
| 56 | + throw new BadRequestException("The link has already been shortened."); |
| 57 | + case 2: |
| 58 | + throw new InvalidDataException("The entered link is not a link."); |
| 59 | + case 3: |
| 60 | + throw new InvalidDataException("The preferred link name is already taken."); |
| 61 | + case 4: |
| 62 | + case 401: |
| 63 | + throw new InvalidApiTokenException("Your API Key is invalid and incorrect."); |
| 64 | + case 5: |
| 65 | + throw new InvalidDataException("The link has not passed validated. There is invalid characters."); |
| 66 | + case 6: |
| 67 | + throw new InvalidDataException("The link provided is from a blocked domain."); |
| 68 | + default: |
| 69 | + throw new InvalidResponseException($message); |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments