Completed
Push — master ( 7d2771...0f5440 )
by Sean
03:41
created

Mailgun::__construct()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 14
ccs 7
cts 7
cp 1
rs 9.4285
cc 3
eloc 11
nc 4
nop 5
crap 3
1
<?PHP
2
3
/*
4
 * Copyright (C) 2013-2016 Mailgun
5
 *
6
 * This software may be modified and distributed under the terms
7
 * of the MIT license. See the LICENSE file for details.
8
 */
9
10
namespace Mailgun;
11
12
use Http\Client\Common\HttpMethodsClient;
13
use Http\Client\HttpClient;
14
use Mailgun\Connection\RestClient;
15
use Mailgun\Constants\ExceptionMessages;
16
use Mailgun\HttpClient\Plugin\History;
17
use Mailgun\Lists\OptInHandler;
18
use Mailgun\Messages\BatchMessage;
19
use Mailgun\Messages\Exceptions;
20
use Mailgun\Messages\MessageBuilder;
21
use Mailgun\Hydrator\ModelHydrator;
22
use Mailgun\Hydrator\Hydrator;
23
use Psr\Http\Message\ResponseInterface;
24
25
/**
26
 * This class is the base class for the Mailgun SDK.
27
 */
28
class Mailgun
29
{
30
    /**
31
     * @var RestClient
32
     *
33
     * @depracated Will be removed in 3.0
34
     */
35
    protected $restClient;
36
37
    /**
38
     * @var null|string
39
     */
40
    protected $apiKey;
41
42
    /**
43
     * @var HttpMethodsClient
44
     */
45
    private $httpClient;
46
47
    /**
48
     * @var Hydrator
49
     */
50
    private $hydrator;
51
52
    /**
53
     * @var RequestBuilder
54
     */
55
    private $requestBuilder;
56
57
    /**
58
     * This is a object that holds the last response from the API.
59
     *
60
     * @var History
61
     */
62
    private $responseHistory = null;
63
64
    /**
65
     * @param string|null         $apiKey
66
     * @param HttpClient|null     $httpClient
67
     * @param string              $apiEndpoint
68
     * @param Hydrator|null       $hydrator
69
     * @param RequestBuilder|null $requestBuilder
70
     */
71 6
    public function __construct(
72
        $apiKey = null, /* Deprecated, will be removed in 3.0 */
73
        HttpClient $httpClient = null,
74
        $apiEndpoint = 'api.mailgun.net', /* Deprecated, will be removed in 3.0 */
75
        Hydrator $hydrator = null,
76
        RequestBuilder $requestBuilder = null
77
    ) {
78 6
        $this->apiKey = $apiKey;
79 6
        $this->restClient = new RestClient($apiKey, $apiEndpoint, $httpClient);
0 ignored issues
show
Deprecated Code introduced by
The class Mailgun\Connection\RestClient has been deprecated with message: Will be removed in 3.0

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
80
81 6
        $this->httpClient = $httpClient;
0 ignored issues
show
Documentation Bug introduced by
It seems like $httpClient can also be of type object<Http\Client\HttpClient>. However, the property $httpClient is declared as type object<Http\Client\Common\HttpMethodsClient>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
82 6
        $this->requestBuilder = $requestBuilder ?: new RequestBuilder();
83 6
        $this->hydrator = $hydrator ?: new ModelHydrator();
84 6
    }
85
86
    /**
87
     * @param HttpClientConfigurator $httpClientConfigurator
88
     * @param Hydrator|null          $hydrator
89
     * @param RequestBuilder|null    $requestBuilder
90
     *
91
     * @return Mailgun
92
     */
93
    public static function configure(
94
        HttpClientConfigurator $httpClientConfigurator,
95
        Hydrator $hydrator = null,
96
        RequestBuilder $requestBuilder = null
97
    ) {
98
        $httpClient = $httpClientConfigurator->createConfiguredClient();
99
100
        return new self(null, $httpClient, 'api.mailgun.net', $hydrator, $requestBuilder);
101
    }
102
103
    /**
104
     * @param string $apiKey
105
     *
106
     * @return Mailgun
107
     */
108
    public static function create($apiKey)
109
    {
110
        $httpClientConfigurator = (new HttpClientConfigurator())->setApiKey($apiKey);
111
112
        return self::configure($httpClientConfigurator);
113
    }
114
115
    /**
116
     *  This function allows the sending of a fully formed message OR a custom
117
     *  MIME string. If sending MIME, the string must be passed in to the 3rd
118
     *  position of the function call.
119
     *
120
     * @param string $workingDomain
121
     * @param array  $postData
122
     * @param array  $postFiles
123
     *
124
     * @throws Exceptions\MissingRequiredMIMEParameters
125
     *
126
     * @return \stdClass
127
     *
128
     * @deprecated Use Mailgun->message() instead. Will be removed in 3.0
129
     */
130 7
    public function sendMessage($workingDomain, $postData, $postFiles = [])
131
    {
132 7
        if (is_array($postFiles)) {
133 5
            return $this->post("$workingDomain/messages", $postData, $postFiles);
0 ignored issues
show
Deprecated Code introduced by
The method Mailgun\Mailgun::post() has been deprecated with message: Will be removed in 3.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
134 2
        } elseif (is_string($postFiles)) {
135 1
            $tempFile = tempnam(sys_get_temp_dir(), 'MG_TMP_MIME');
136 1
            $fileHandle = fopen($tempFile, 'w');
137 1
            fwrite($fileHandle, $postFiles);
138
139 1
            $result = $this->post("$workingDomain/messages.mime", $postData, ['message' => $tempFile]);
0 ignored issues
show
Deprecated Code introduced by
The method Mailgun\Mailgun::post() has been deprecated with message: Will be removed in 3.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
140 1
            fclose($fileHandle);
141 1
            unlink($tempFile);
142
143 1
            return $result;
144
        } else {
145 1
            throw new Exceptions\MissingRequiredMIMEParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
146
        }
147
    }
148
149
    /**
150
     * This function checks the signature in a POST request to see if it is
151
     * authentic.
152
     *
153
     * Pass an array of parameters.  If you pass nothing, $_POST will be
154
     * used instead.
155
     *
156
     * If this function returns FALSE, you must not process the request.
157
     * You should reject the request with status code 403 Forbidden.
158
     *
159
     * @param array|null $postData
160
     *
161
     * @return bool
162
     *
163
     * @deprecated Use Mailgun->webhook() instead. Will be removed in 3.0
164
     */
165 3
    public function verifyWebhookSignature($postData = null)
0 ignored issues
show
Coding Style introduced by
verifyWebhookSignature uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
166
    {
167 3
        if ($postData === null) {
168
            $postData = $_POST;
169
        }
170 3
        if (!isset($postData['timestamp']) || !isset($postData['token']) || !isset($postData['signature'])) {
171 1
            return false;
172
        }
173 2
        $hmac = hash_hmac('sha256', "{$postData['timestamp']}{$postData['token']}", $this->apiKey);
174 2
        $sig = $postData['signature'];
175 2
        if (function_exists('hash_equals')) {
176
            // hash_equals is constant time, but will not be introduced until PHP 5.6
177
            return hash_equals($hmac, $sig);
178
        } else {
179 2
            return $hmac === $sig;
180
        }
181
    }
182
183
    /**
184
     * @return ResponseInterface|null
185
     */
186
    public function getLastResponse()
187
    {
188
        return $this->responseHistory->getLastResponse();
189
    }
190
191
    /**
192
     * @param string $endpointUrl
193
     * @param array  $postData
194
     * @param array  $files
195
     *
196
     * @return \stdClass
197
     *
198
     * @deprecated Will be removed in 3.0
199
     */
200 8
    public function post($endpointUrl, $postData = [], $files = [])
201
    {
202 8
        return $this->restClient->post($endpointUrl, $postData, $files);
203
    }
204
205
    /**
206
     * @param string $endpointUrl
207
     * @param array  $queryString
208
     *
209
     * @return \stdClass
210
     *
211
     * @deprecated Will be removed in 3.0
212
     */
213
    public function get($endpointUrl, $queryString = [])
214
    {
215
        return $this->restClient->get($endpointUrl, $queryString);
216
    }
217
218
    /**
219
     * @param string $url
220
     *
221
     * @return \stdClass
222
     *
223
     * @deprecated Will be removed in 3.0
224
     */
225 2
    public function getAttachment($url)
226
    {
227 2
        return $this->restClient->getAttachment($url);
228
    }
229
230
    /**
231
     * @param string $endpointUrl
232
     *
233
     * @return \stdClass
234
     *
235
     * @deprecated Will be removed in 3.0
236
     */
237
    public function delete($endpointUrl)
238
    {
239
        return $this->restClient->delete($endpointUrl);
240
    }
241
242
    /**
243
     * @param string $endpointUrl
244
     * @param array  $putData
245
     *
246
     * @return \stdClass
247
     *
248
     * @deprecated Will be removed in 3.0
249
     */
250
    public function put($endpointUrl, $putData)
251
    {
252
        return $this->restClient->put($endpointUrl, $putData);
253
    }
254
255
    /**
256
     * @param string $apiVersion
257
     *
258
     * @return Mailgun
259
     *
260
     * @deprecated Will be removed in 3.0
261
     */
262
    public function setApiVersion($apiVersion)
263
    {
264
        $this->restClient->setApiVersion($apiVersion);
265
266
        return $this;
267
    }
268
269
    /**
270
     * @param bool $sslEnabled
271
     *
272
     * @return Mailgun
273
     *
274
     * @deprecated This will be removed in 3.0. Mailgun does not support non-secure connections to their API.
275
     */
276
    public function setSslEnabled($sslEnabled)
277
    {
278
        $this->restClient->setSslEnabled($sslEnabled);
0 ignored issues
show
Deprecated Code introduced by
The method Mailgun\Connection\RestClient::setSslEnabled() has been deprecated with message: To be removed in 3.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
279
280
        return $this;
281
    }
282
283
    /**
284
     * @return MessageBuilder
285
     *
286
     * @deprecated Will be removed in 3.0
287
     */
288 30
    public function MessageBuilder()
289
    {
290 30
        return new MessageBuilder();
291
    }
292
293
    /**
294
     * @return OptInHandler
295
     *
296
     * @deprecated Will be removed in 3.0
297
     */
298 3
    public function OptInHandler()
299
    {
300 3
        return new OptInHandler();
301
    }
302
303
    /**
304
     * @param string $workingDomain
305
     * @param bool   $autoSend
306
     *
307
     * @return BatchMessage
308
     *
309
     * @deprecated Will be removed in 3.0
310
     */
311 15
    public function BatchMessage($workingDomain, $autoSend = true)
312
    {
313 15
        return new BatchMessage($this->restClient, $workingDomain, $autoSend);
314
    }
315
316
    /**
317
     * @return Api\Stats
318
     */
319
    public function stats()
320
    {
321
        return new Api\Stats($this->httpClient, $this->requestBuilder, $this->hydrator);
322
    }
323
324
    /**
325
     * @return Api\Domain
326
     */
327
    public function domains()
328
    {
329
        return new Api\Domain($this->httpClient, $this->requestBuilder, $this->hydrator);
330
    }
331
332
    /**
333
     * @return Api\Tag
334
     */
335
    public function tags()
336
    {
337
        return new Api\Tag($this->httpClient, $this->requestBuilder, $this->hydrator);
338
    }
339
340
    /**
341
     * @return Api\Event
342
     */
343
    public function events()
344
    {
345
        return new Api\Event($this->httpClient, $this->requestBuilder, $this->hydrator);
346
    }
347
348
    /**
349
     * @return Api\Route
350
     */
351
    public function routes()
352
    {
353
        return new Api\Route($this->httpClient, $this->requestBuilder, $this->hydrator);
354
    }
355
356
    /**
357
     * @return Api\Webhook
358
     */
359
    public function webhooks()
360
    {
361
        return new Api\Webhook($this->httpClient, $this->requestBuilder, $this->hydrator);
362
    }
363
364
    /**
365
     * @return Api\Message
366
     */
367
    public function messages()
368
    {
369
        return new Api\Message($this->httpClient, $this->requestBuilder, $this->hydrator);
370
    }
371
372
    /**
373
     * @return Api\Suppression
374
     */
375
    public function suppressions()
376
    {
377
        return new Api\Suppression($this->httpClient, $this->requestBuilder, $this->hydrator);
378
    }
379
}
380