This repository has been archived by the owner on Jan 18, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
YoGateway.php
122 lines (108 loc) · 2.92 KB
/
YoGateway.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
<?php
/*
* This file is part of NotifyMe.
*
* (c) Alt Three Services Limited
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace NotifyMeHQ\Adapters\Yo;
use GuzzleHttp\Client;
use NotifyMeHQ\Contracts\GatewayInterface;
use NotifyMeHQ\Http\GatewayTrait;
use NotifyMeHQ\Http\Response;
use NotifyMeHQ\Support\Arr;
class YoGateway implements GatewayInterface
{
use GatewayTrait;
/**
* The api endpoint.
*
* @var string
*/
protected $endpoint = 'https://api.justyo.co';
/**
* Create a new yo gateway instance.
*
* @param \GuzzleHttp\Client $client
* @param string[] $config
*
* @return void
*/
public function __construct(Client $client, array $config)
{
$this->client = $client;
$this->config = $config;
}
/**
* Send a notification.
*
* @param string $to
* @param string $message
*
* @return \NotifyMeHQ\Contracts\ResponseInterface
*/
public function notify($to, $message)
{
$params = [
'username' => strtoupper($to),
'api_token' => $this->config['token'],
'location' => Arr::get($this->config, 'location'),
'link' => Arr::get($this->config, 'link'),
];
return $this->send($this->buildUrlFromString('yo'), $params);
}
/**
* Send the notification over the wire.
*
* @param string $url
* @param string[] $params
*
* @return \NotifyMeHQ\Contracts\ResponseInterface
*/
protected function send($url, array $params)
{
$success = false;
$rawResponse = $this->client->post($url, [
'exceptions' => false,
'timeout' => '80',
'connect_timeout' => '30',
'headers' => [
'Accept' => 'application/json',
],
'body' => $params,
]);
if (substr((string) $rawResponse->getStatusCode(), 0, 1) === '2') {
$response = json_decode($rawResponse->getBody(), true);
$success = $response['success'];
} else {
$response = $this->responseError($rawResponse);
}
return $this->mapResponse($success, $response);
}
/**
* Map the raw response to our response object.
*
* @param bool $success
* @param array $response
*
* @return \NotifyMeHQ\Contracts\ResponseInterface
*/
protected function mapResponse($success, array $response)
{
return (new Response())->setRaw($response)->map([
'success' => $success,
'message' => $success ? 'Message sent' : $response['error'],
]);
}
/**
* Get the request url.
*
* @return string
*/
protected function getRequestUrl()
{
return $this->endpoint;
}
}