Completed
Push — master ( 84a5c5...1bfd40 )
by Tobias
03:27
created

Mailgun::configure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 0
cts 3
cp 0
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 3
crap 2
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\Lists\OptInHandler;
17
use Mailgun\Messages\BatchMessage;
18
use Mailgun\Messages\Exceptions;
19
use Mailgun\Messages\MessageBuilder;
20
use Mailgun\Hydrator\ModelHydrator;
21
use Mailgun\Hydrator\Hydrator;
22
23
/**
24
 * This class is the base class for the Mailgun SDK.
25
 */
26
class Mailgun
27
{
28
    /**
29
     * @var RestClient
30
     *
31
     * @depracated Will be removed in 3.0
32
     */
33
    protected $restClient;
34
35
    /**
36
     * @var null|string
37
     */
38
    protected $apiKey;
39
40
    /**
41
     * @var HttpMethodsClient
42
     */
43
    private $httpClient;
44
45
    /**
46
     * @var Hydrator
47
     */
48
    private $hydrator;
49
50
    /**
51
     * @var RequestBuilder
52
     */
53
    private $requestBuilder;
54
55
    /**
56
     * @param string|null                 $apiKey
57
     * @param HttpClient|null             $httpClient
58
     * @param string                      $apiEndpoint
59
     * @param Hydrator|null               $hydrator
60
     * @param HttpClientConfigurator|null $clientConfigurator
61
     * @param RequestBuilder|null         $requestBuilder
62
     */
63 6
    public function __construct(
64
        $apiKey = null,
65
        HttpClient $httpClient = null, /* Deprecated, will be removed in 3.0 */
66
        $apiEndpoint = 'api.mailgun.net', /* Deprecated, will be removed in 3.0 */
67
        Hydrator $hydrator = null,
68
        HttpClientConfigurator $clientConfigurator = null,
69
        RequestBuilder $requestBuilder = null
70
    ) {
71 6
        $this->apiKey = $apiKey;
72 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...
73
74 6
        if (null === $clientConfigurator) {
75 6
            $clientConfigurator = new HttpClientConfigurator();
76
77
            /*
78
             * To be backward compatible
79
             */
80 6
            if ($apiEndpoint !== 'api.mailgun.net') {
81
                $clientConfigurator->setEndpoint($apiEndpoint);
82
            }
83 6
            if ($httpClient !== null) {
84
                $clientConfigurator->setHttpClient($httpClient);
85
            }
86 6
        }
87
88 6
        $clientConfigurator->setApiKey($apiKey);
89
90 6
        $this->httpClient = $clientConfigurator->createConfiguredClient();
0 ignored issues
show
Documentation Bug introduced by
It seems like $clientConfigurator->createConfiguredClient() of type object<Http\Client\Common\PluginClient> is incompatible with the declared type object<Http\Client\Common\HttpMethodsClient> of property $httpClient.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
91 6
        $this->requestBuilder = $requestBuilder ?: new RequestBuilder();
92 6
        $this->hydrator = $hydrator ?: new ModelHydrator();
93 6
    }
94
95
    /**
96
     * @param HttpClientConfigurator $httpClientConfigurator
97
     * @param Hydrator|null          $hydrator
98
     * @param RequestBuilder|null    $requestBuilder
99
     *
100
     * @return Mailgun
101
     */
102
    public static function configure(
103
        HttpClientConfigurator $httpClientConfigurator,
104
        Hydrator $hydrator = null,
105
        RequestBuilder $requestBuilder = null
106
    ) {
107
        $httpClient = $httpClientConfigurator->createConfiguredClient();
108
109
        return new self($httpClient, $hydrator, $requestBuilder);
0 ignored issues
show
Documentation introduced by
$httpClient is of type object<Http\Client\Common\PluginClient>, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Bug introduced by
It seems like $hydrator defined by parameter $hydrator on line 104 can also be of type object<Mailgun\Hydrator\Hydrator>; however, Mailgun\Mailgun::__construct() does only seem to accept null|object<Http\Client\HttpClient>, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
Documentation introduced by
$requestBuilder is of type null|object<Mailgun\RequestBuilder>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

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