Completed
Push — master ( d50447...91f96b )
by Tobias
07:30 queued 04:39
created

Mailgun::post()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 3
crap 1
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
     * @internal Use Mailgun::configure or Mailgun::create instead.
72
     */
73 30
    public /* private */ function __construct(
74
        $apiKey = null, /* Deprecated, will be removed in 3.0 */
75
        HttpClient $httpClient = null,
76 1
        $apiEndpoint = 'api.mailgun.net', /* Deprecated, will be removed in 3.0 */
77
        Hydrator $hydrator = null,
78
        RequestBuilder $requestBuilder = null
79
    ) {
80 30
        $this->apiKey = $apiKey;
81 30
        $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...
82
83 30
        $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...
84 30
        $this->requestBuilder = $requestBuilder ?: new RequestBuilder();
85 30
        $this->hydrator = $hydrator ?: new ModelHydrator();
86 30
    }
87
88
    /**
89
     * @param HttpClientConfigurator $configurator
90
     * @param Hydrator|null          $hydrator
91
     * @param RequestBuilder|null    $requestBuilder
92
     *
93
     * @return Mailgun
94
     */
95 25
    public static function configure(
96
        HttpClientConfigurator $configurator,
97
        Hydrator $hydrator = null,
98
        RequestBuilder $requestBuilder = null
99
    ) {
100 25
        $httpClient = $configurator->createConfiguredClient();
101
102 25
        return new self($configurator->getApiKey(), $httpClient, 'api.mailgun.net', $hydrator, $requestBuilder);
103
    }
104
105
    /**
106
     * @param string $apiKey
107
     *
108
     * @return Mailgun
109
     */
110 25
    public static function create($apiKey)
111
    {
112 25
        $httpClientConfigurator = (new HttpClientConfigurator())->setApiKey($apiKey);
113
114 25
        return self::configure($httpClientConfigurator);
115
    }
116
117
    /**
118
     *  This function allows the sending of a fully formed message OR a custom
119
     *  MIME string. If sending MIME, the string must be passed in to the 3rd
120
     *  position of the function call.
121
     *
122
     * @param string $workingDomain
123
     * @param array  $postData
124
     * @param array  $postFiles
125
     *
126
     * @throws Exceptions\MissingRequiredMIMEParameters
127
     *
128
     * @return \stdClass
129
     *
130
     * @deprecated Use Mailgun->message() instead. Will be removed in 3.0
131
     */
132 7
    public function sendMessage($workingDomain, $postData, $postFiles = [])
133
    {
134 7
        if (is_array($postFiles)) {
135 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...
136 2
        } elseif (is_string($postFiles)) {
137 1
            $tempFile = tempnam(sys_get_temp_dir(), 'MG_TMP_MIME');
138 1
            $fileHandle = fopen($tempFile, 'w');
139 1
            fwrite($fileHandle, $postFiles);
140
141 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...
142 1
            fclose($fileHandle);
143 1
            unlink($tempFile);
144
145 1
            return $result;
146
        } else {
147 1
            throw new Exceptions\MissingRequiredMIMEParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
148
        }
149
    }
150
151
    /**
152
     * This function checks the signature in a POST request to see if it is
153
     * authentic.
154
     *
155
     * Pass an array of parameters.  If you pass nothing, $_POST will be
156
     * used instead.
157
     *
158
     * If this function returns FALSE, you must not process the request.
159
     * You should reject the request with status code 403 Forbidden.
160
     *
161
     * @param array|null $postData
162
     *
163
     * @return bool
164
     *
165
     * @deprecated Use Mailgun->webhook() instead. Will be removed in 3.0
166
     */
167 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...
168
    {
169 3
        if ($postData === null) {
170
            $postData = $_POST;
171
        }
172 3
        if (!isset($postData['timestamp']) || !isset($postData['token']) || !isset($postData['signature'])) {
173 1
            return false;
174
        }
175 2
        $hmac = hash_hmac('sha256', "{$postData['timestamp']}{$postData['token']}", $this->apiKey);
176 2
        $sig = $postData['signature'];
177 2
        if (function_exists('hash_equals')) {
178
            // hash_equals is constant time, but will not be introduced until PHP 5.6
179
            return hash_equals($hmac, $sig);
180
        } else {
181 2
            return $hmac === $sig;
182
        }
183
    }
184
185
    /**
186
     * @return ResponseInterface|null
187
     */
188
    public function getLastResponse()
189
    {
190
        return $this->responseHistory->getLastResponse();
191
    }
192
193
    /**
194
     * @param string $endpointUrl
195
     * @param array  $postData
196
     * @param array  $files
197
     *
198
     * @return \stdClass
199
     *
200
     * @deprecated Will be removed in 3.0
201
     */
202 7
    public function post($endpointUrl, $postData = [], $files = [])
203
    {
204 7
        return $this->restClient->post($endpointUrl, $postData, $files);
205
    }
206
207
    /**
208
     * @param string $endpointUrl
209
     * @param array  $queryString
210
     *
211
     * @return \stdClass
212
     *
213
     * @deprecated Will be removed in 3.0
214
     */
215
    public function get($endpointUrl, $queryString = [])
216
    {
217
        return $this->restClient->get($endpointUrl, $queryString);
218
    }
219
220
    /**
221
     * @param string $url
222
     *
223
     * @return \stdClass
224
     *
225
     * @deprecated Will be removed in 3.0
226
     */
227 1
    public function getAttachment($url)
228
    {
229 1
        return $this->restClient->getAttachment($url);
230
    }
231
232
    /**
233
     * @param string $endpointUrl
234
     *
235
     * @return \stdClass
236
     *
237
     * @deprecated Will be removed in 3.0
238
     */
239
    public function delete($endpointUrl)
240
    {
241
        return $this->restClient->delete($endpointUrl);
242
    }
243
244
    /**
245
     * @param string $endpointUrl
246
     * @param array  $putData
247
     *
248
     * @return \stdClass
249
     *
250
     * @deprecated Will be removed in 3.0
251
     */
252
    public function put($endpointUrl, $putData)
253
    {
254
        return $this->restClient->put($endpointUrl, $putData);
255
    }
256
257
    /**
258
     * @param string $apiVersion
259
     *
260
     * @return Mailgun
261
     *
262
     * @deprecated Will be removed in 3.0
263
     */
264
    public function setApiVersion($apiVersion)
265
    {
266
        $this->restClient->setApiVersion($apiVersion);
267
268
        return $this;
269
    }
270
271
    /**
272
     * @param bool $sslEnabled
273
     *
274
     * @return Mailgun
275
     *
276
     * @deprecated This will be removed in 3.0. Mailgun does not support non-secure connections to their API.
277
     */
278
    public function setSslEnabled($sslEnabled)
279
    {
280
        $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...
281
282
        return $this;
283
    }
284
285
    /**
286
     * @return MessageBuilder
287
     *
288
     * @deprecated Will be removed in 3.0
289
     */
290 29
    public function MessageBuilder()
291
    {
292 29
        return new MessageBuilder();
293
    }
294
295
    /**
296
     * @return OptInHandler
297
     *
298
     * @deprecated Will be removed in 3.0
299
     */
300 3
    public function OptInHandler()
301
    {
302 3
        return new OptInHandler();
303
    }
304
305
    /**
306
     * @param string $workingDomain
307
     * @param bool   $autoSend
308
     *
309
     * @return BatchMessage
310
     *
311
     * @deprecated Will be removed in 3.0
312
     */
313 15
    public function BatchMessage($workingDomain, $autoSend = true)
314
    {
315 15
        return new BatchMessage($this->restClient, $workingDomain, $autoSend);
316
    }
317
318
    /**
319
     * @return Api\Stats
320
     */
321
    public function stats()
322
    {
323
        return new Api\Stats($this->httpClient, $this->requestBuilder, $this->hydrator);
324
    }
325
326
    /**
327
     * @return Api\Domain
328
     */
329 18
    public function domains()
330
    {
331 18
        return new Api\Domain($this->httpClient, $this->requestBuilder, $this->hydrator);
332
    }
333
334
    /**
335
     * @return Api\Tag
336
     */
337
    public function tags()
338
    {
339
        return new Api\Tag($this->httpClient, $this->requestBuilder, $this->hydrator);
340
    }
341
342
    /**
343
     * @return Api\Event
344
     */
345
    public function events()
346
    {
347
        return new Api\Event($this->httpClient, $this->requestBuilder, $this->hydrator);
348
    }
349
350
    /**
351
     * @return Api\Route
352
     */
353 7
    public function routes()
354
    {
355 7
        return new Api\Route($this->httpClient, $this->requestBuilder, $this->hydrator);
356
    }
357
358
    /**
359
     * @return Api\Webhook
360
     */
361
    public function webhooks()
362
    {
363
        return new Api\Webhook($this->httpClient, $this->requestBuilder, $this->hydrator, $this->apiKey);
364
    }
365
366
    /**
367
     * @return Api\Message
368
     */
369
    public function messages()
370
    {
371
        return new Api\Message($this->httpClient, $this->requestBuilder, $this->hydrator);
372
    }
373
374
    /**
375
     * @return Api\Suppression
376
     */
377
    public function suppressions()
378
    {
379
        return new Api\Suppression($this->httpClient, $this->requestBuilder, $this->hydrator);
380
    }
381
}
382