1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @author Rizart Dokollari <[email protected]> |
4
|
|
|
* @author Jeroen Derks <[email protected]> |
5
|
|
|
* @since 12/24/17 |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace ElasticEmail; |
9
|
|
|
|
10
|
|
|
use GuzzleHttp\HandlerStack; |
11
|
|
|
use GuzzleHttp\Middleware; |
12
|
|
|
use GuzzleHttp\Psr7\Uri; |
13
|
|
|
use Psr\Http\Message\RequestInterface; |
14
|
|
|
use Psr\Http\Message\ResponseInterface; |
15
|
|
|
|
16
|
|
|
/** HTTP client: sets correct base URI & api key and other middlewares. */ |
17
|
|
|
class Client extends \GuzzleHttp\Client |
18
|
|
|
{ |
19
|
|
|
public static $baseUri = 'https://api.elasticemail.com/v2/'; |
20
|
|
|
|
21
|
|
|
public function __construct(string $apiKey, array $middlewares = []) |
22
|
|
|
{ |
23
|
|
|
if (empty($apiKey)) { |
24
|
|
|
throw new ElasticEmailException('ElasticEmail API key is missing.'); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
parent::__construct([ |
28
|
|
|
'base_uri' => self::$baseUri, |
29
|
|
|
'handler' => $this->handler($apiKey, $middlewares), |
30
|
|
|
]); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function handler($apikey, array $externalMiddlewares = []) |
34
|
|
|
{ |
35
|
|
|
$stack = HandlerStack::create(); |
36
|
|
|
|
37
|
|
|
$stack->push(Middleware::mapRequest( |
38
|
|
|
function (RequestInterface $request) use ($apikey) { |
39
|
|
|
return $request->withUri( |
40
|
|
|
Uri::withQueryValue( |
41
|
|
|
$request->getUri(), 'apikey', $apikey |
42
|
|
|
) |
43
|
|
|
); |
44
|
|
|
} |
45
|
|
|
), 'apikey'); |
46
|
|
|
|
47
|
|
|
$stack->push(Middleware::mapResponse( |
48
|
|
|
function (ResponseInterface $response) { |
49
|
|
|
$body = json_decode((string)$response->getBody(), true); |
50
|
|
|
|
51
|
|
|
if (! $body['success']) { |
52
|
|
|
throw new ElasticEmailException($body['error']); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return $response; |
56
|
|
|
} |
57
|
|
|
), 'api_error'); |
58
|
|
|
|
59
|
|
|
foreach ($externalMiddlewares as $middleware) { |
60
|
|
|
$stack->push($middleware); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return $stack; |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|