|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* @author Rizart Dokollari <[email protected]> |
|
4
|
|
|
* @since 12/24/17 |
|
5
|
|
|
*/ |
|
6
|
|
|
|
|
7
|
|
|
namespace ElasticEmail; |
|
8
|
|
|
|
|
9
|
|
|
use GuzzleHttp\HandlerStack; |
|
10
|
|
|
use GuzzleHttp\Middleware; |
|
11
|
|
|
use GuzzleHttp\Psr7\Uri; |
|
12
|
|
|
use Psr\Http\Message\RequestInterface; |
|
13
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
14
|
|
|
|
|
15
|
|
|
|
|
16
|
|
|
/** HTTP client: sets correct base URI & api key. */ |
|
17
|
|
|
class Client extends \GuzzleHttp\Client |
|
18
|
|
|
{ |
|
19
|
|
|
static $baseUri = 'https://api.elasticemail.com/v2/'; |
|
|
|
|
|
|
20
|
|
|
|
|
21
|
|
|
public function __construct($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( |
|
38
|
|
|
Middleware::mapRequest( |
|
39
|
|
|
function (RequestInterface $request) use ($apikey) { |
|
40
|
|
|
return $request->withUri( |
|
41
|
|
|
Uri::withQueryValue( |
|
42
|
|
|
$request->getUri(), 'apikey', $apikey |
|
43
|
|
|
) |
|
44
|
|
|
); |
|
45
|
|
|
} |
|
46
|
|
|
) |
|
47
|
|
|
); |
|
48
|
|
|
|
|
49
|
|
|
$stack->push(Middleware::mapResponse( |
|
50
|
|
|
function (ResponseInterface $response) { |
|
51
|
|
|
|
|
52
|
|
|
$body = json_decode((string)$response->getBody(), true); |
|
53
|
|
|
|
|
54
|
|
|
if ( ! $body['success']) { |
|
55
|
|
|
throw new ElasticEmailException($body['error']); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
return $response; |
|
59
|
|
|
} |
|
60
|
|
|
)); |
|
61
|
|
|
|
|
62
|
|
|
foreach ($externalMiddlewares as $middleware) { |
|
63
|
|
|
$stack->push($middleware); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
return $stack; |
|
67
|
|
|
} |
|
68
|
|
|
} |
The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using
the property is implicitly global.
To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.