| 1 | <?php |
||
| 2 | |||
| 3 | namespace NotificationChannels\Unisender; |
||
| 4 | |||
| 5 | use GuzzleHttp\Client; |
||
| 6 | use GuzzleHttp\Exception\RequestException; |
||
| 7 | use Illuminate\Support\Str; |
||
| 8 | use NotificationChannels\Unisender\Exceptions\ApiRequestFailedException; |
||
| 9 | |||
| 10 | class UnisenderApi |
||
| 11 | { |
||
| 12 | const BASE_URI = 'https://api.unisender.com/ru/api/'; |
||
| 13 | |||
| 14 | protected $token; |
||
| 15 | protected $client; |
||
| 16 | |||
| 17 | public function __construct(string $token = null) |
||
| 18 | { |
||
| 19 | $this->token = $token; |
||
| 20 | $this->client = null; |
||
| 21 | } |
||
| 22 | |||
| 23 | public function setToken(string $token) |
||
| 24 | { |
||
| 25 | $this->token = $token; |
||
| 26 | $this->client = null; |
||
| 27 | } |
||
| 28 | |||
| 29 | public function getClient() |
||
| 30 | { |
||
| 31 | if (!is_null($this->client)) { |
||
| 32 | return $this->client; |
||
| 33 | } |
||
| 34 | |||
| 35 | return $this->client = new Client([ |
||
| 36 | 'base_uri' => static::BASE_URI, |
||
| 37 | ]); |
||
| 38 | } |
||
| 39 | |||
| 40 | public function performRequest(string $method, string $url, array $options = []) |
||
| 41 | { |
||
| 42 | $response = null; |
||
|
0 ignored issues
–
show
Unused Code
introduced
by
Loading history...
|
|||
| 43 | $method = Str::upper($method); |
||
| 44 | $options = $this->withDefaultOptions($method, $options); |
||
| 45 | |||
| 46 | try { |
||
| 47 | $response = $this->getClient()->request($method, $url, $options); |
||
| 48 | } catch (RequestException $e) { |
||
| 49 | throw new ApiRequestFailedException($e, $e->getResponse()); |
||
| 50 | } |
||
| 51 | |||
| 52 | return json_decode((string) $response->getBody(), true); |
||
| 53 | } |
||
| 54 | |||
| 55 | protected function withDefaultOptions(string $method, array $options = []) |
||
| 56 | { |
||
| 57 | $parametersBag = ''; |
||
| 58 | |||
| 59 | switch ($method) { |
||
| 60 | case 'GET': |
||
| 61 | $parametersBag = 'query'; |
||
| 62 | break; |
||
| 63 | case 'POST': |
||
| 64 | $parametersBag = 'form_params'; |
||
| 65 | break; |
||
| 66 | } |
||
| 67 | |||
| 68 | if (!isset($options[$parametersBag])) { |
||
| 69 | $options[$parametersBag] = []; |
||
| 70 | } |
||
| 71 | |||
| 72 | $options[$parametersBag]['format'] = 'json'; |
||
| 73 | $options[$parametersBag]['api_key'] = $this->token; |
||
| 74 | |||
| 75 | return $options; |
||
| 76 | } |
||
| 77 | |||
| 78 | public function sendSms(UnisenderMessage $message) |
||
| 79 | { |
||
| 80 | return $this->performRequest('POST', 'sendSms', [ |
||
| 81 | 'form_params' => [ |
||
| 82 | 'phone' => $message->to, |
||
| 83 | 'sender' => $message->from, |
||
| 84 | 'text' => $message->content, |
||
| 85 | ] |
||
| 86 | ]); |
||
| 87 | } |
||
| 88 | } |
||
| 89 |