Completed
Push — master ( 0c70fa...a4aba1 )
by Tobias
22:26
created

Mailgun::attachment()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 0
cts 0
cp 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
/*
4
 * Copyright (C) 2013 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 31
    public 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 31
        $this->apiKey = $apiKey;
81 31
        $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 31
        $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 31
        $this->requestBuilder = $requestBuilder ?: new RequestBuilder();
85 31
        $this->hydrator = $hydrator ?: new ModelHydrator();
86 31
    }
87
88
    /**
89
     * @param HttpClientConfigurator $configurator
90
     * @param Hydrator|null          $hydrator
91
     * @param RequestBuilder|null    $requestBuilder
92
     *
93
     * @return Mailgun
94
     */
95 26
    public static function configure(
96
        HttpClientConfigurator $configurator,
97
        Hydrator $hydrator = null,
98
        RequestBuilder $requestBuilder = null
99
    ) {
100 26
        $httpClient = $configurator->createConfiguredClient();
101
102 26
        return new self($configurator->getApiKey(), $httpClient, 'api.mailgun.net', $hydrator, $requestBuilder);
103
    }
104
105
    /**
106
     * @param string $apiKey
107
     * @param string $endpoint URL to mailgun servers
108
     *
109
     * @return Mailgun
110 26
     */
111
    public static function create($apiKey, $endpoint = 'https://api.mailgun.net')
112 26
    {
113
        $httpClientConfigurator = (new HttpClientConfigurator())
114 26
            ->setApiKey($apiKey)
115
            ->setEndpoint($endpoint);
116
117
        return self::configure($httpClientConfigurator);
118
    }
119
120
    /**
121
     *  This function allows the sending of a fully formed message OR a custom
122
     *  MIME string. If sending MIME, the string must be passed in to the 3rd
123
     *  position of the function call.
124
     *
125
     * @param string $workingDomain
126
     * @param array  $postData
127
     * @param array  $postFiles
128
     *
129
     * @throws Exceptions\MissingRequiredMIMEParameters
130
     *
131
     * @return \stdClass
132 7
     *
133
     * @deprecated Use Mailgun->messages()->send() instead. Will be removed in 3.0
134 7
     */
135 5
    public function sendMessage($workingDomain, $postData, $postFiles = [])
136 2
    {
137 1
        if (is_array($postFiles)) {
138 1
            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...
139 1
        } elseif (is_string($postFiles)) {
140
            $tempFile = tempnam(sys_get_temp_dir(), 'MG_TMP_MIME');
141 1
            $fileHandle = fopen($tempFile, 'w');
142 1
            fwrite($fileHandle, $postFiles);
143 1
144
            $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...
145 1
            fclose($fileHandle);
146
            unlink($tempFile);
147 1
148
            return $result;
149
        } else {
150
            throw new Exceptions\MissingRequiredMIMEParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
151
        }
152
    }
153
154
    /**
155
     * This function checks the signature in a POST request to see if it is
156
     * authentic.
157
     *
158
     * Pass an array of parameters.  If you pass nothing, $_POST will be
159
     * used instead.
160
     *
161
     * If this function returns FALSE, you must not process the request.
162
     * You should reject the request with status code 403 Forbidden.
163
     *
164
     * @param array|null $postData
165
     *
166
     * @return bool
167 3
     *
168
     * @deprecated Use Mailgun->webhook() instead. Will be removed in 3.0
169 3
     */
170
    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...
171
    {
172 3
        if (null === $postData) {
173 1
            $postData = $_POST;
174
        }
175 2
        if (!isset($postData['timestamp']) || !isset($postData['token']) || !isset($postData['signature'])) {
176 2
            return false;
177 2
        }
178
        $hmac = hash_hmac('sha256', "{$postData['timestamp']}{$postData['token']}", $this->apiKey);
179
        $sig = $postData['signature'];
180
        if (function_exists('hash_equals')) {
181 2
            // hash_equals is constant time, but will not be introduced until PHP 5.6
182
            return hash_equals($hmac, $sig);
183
        } else {
184
            return $hmac === $sig;
185
        }
186
    }
187
188
    /**
189
     * @return ResponseInterface|null
190
     */
191
    public function getLastResponse()
192
    {
193
        return $this->responseHistory->getLastResponse();
194
    }
195
196
    /**
197
     * @param string $endpointUrl
198
     * @param array  $postData
199
     * @param array  $files
200
     *
201
     * @return \stdClass
202 7
     *
203
     * @deprecated Will be removed in 3.0
204 7
     */
205
    public function post($endpointUrl, $postData = [], $files = [])
206
    {
207
        return $this->restClient->post($endpointUrl, $postData, $files);
208
    }
209
210
    /**
211
     * @param string $endpointUrl
212
     * @param array  $queryString
213
     *
214
     * @return \stdClass
215
     *
216
     * @deprecated Will be removed in 3.0
217
     */
218
    public function get($endpointUrl, $queryString = [])
219
    {
220
        return $this->restClient->get($endpointUrl, $queryString);
221
    }
222
223
    /**
224
     * @param string $url
225
     *
226
     * @return \stdClass
227 1
     *
228
     * @deprecated Will be removed in 3.0
229 1
     */
230
    public function getAttachment($url)
231
    {
232
        return $this->restClient->getAttachment($url);
233
    }
234
235
    /**
236
     * @param string $endpointUrl
237
     *
238
     * @return \stdClass
239
     *
240
     * @deprecated Will be removed in 3.0
241
     */
242
    public function delete($endpointUrl)
243
    {
244
        return $this->restClient->delete($endpointUrl);
245
    }
246
247
    /**
248
     * @param string $endpointUrl
249
     * @param array  $putData
250
     *
251
     * @return \stdClass
252
     *
253
     * @deprecated Will be removed in 3.0
254
     */
255
    public function put($endpointUrl, $putData)
256
    {
257
        return $this->restClient->put($endpointUrl, $putData);
258
    }
259
260
    /**
261
     * @param string $apiVersion
262
     *
263
     * @return Mailgun
264
     *
265
     * @deprecated Will be removed in 3.0
266
     */
267
    public function setApiVersion($apiVersion)
268
    {
269
        $this->restClient->setApiVersion($apiVersion);
270
271
        return $this;
272
    }
273
274
    /**
275
     * @param bool $sslEnabled
276
     *
277
     * @return Mailgun
278
     *
279
     * @deprecated This will be removed in 3.0. Mailgun does not support non-secure connections to their API.
280
     */
281
    public function setSslEnabled($sslEnabled)
282
    {
283
        $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...
284
285
        return $this;
286
    }
287
288
    /**
289
     * @return MessageBuilder
290 31
     *
291
     * @deprecated Will be removed in 3.0.
292 31
     */
293
    public function MessageBuilder()
294
    {
295
        return new MessageBuilder();
0 ignored issues
show
Deprecated Code introduced by
The class Mailgun\Messages\MessageBuilder has been deprecated with message: Will be removed in 3.0. Use Mailgun\Message\MessageBuilder

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...
296
    }
297
298
    /**
299
     * @return OptInHandler
300 3
     *
301
     * @deprecated Will be removed in 3.0
302 3
     */
303
    public function OptInHandler()
304
    {
305
        return new OptInHandler();
306
    }
307
308
    /**
309
     * @param string $workingDomain
310
     * @param bool   $autoSend
311
     *
312
     * @return BatchMessage
313 15
     *
314
     * @deprecated Will be removed in 3.0. Use Mailgun::messages()::getBatchMessage().
315 15
     */
316
    public function BatchMessage($workingDomain, $autoSend = true)
317
    {
318
        return new BatchMessage($this->restClient, $workingDomain, $autoSend);
0 ignored issues
show
Deprecated Code introduced by
The class Mailgun\Messages\BatchMessage has been deprecated with message: Will be removed in 3.0. Use Mailgun\Message\BatchMessage

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...
319
    }
320
321
    /**
322
     * @return Api\Stats
323
     */
324
    public function stats()
325
    {
326
        return new Api\Stats($this->httpClient, $this->requestBuilder, $this->hydrator);
327
    }
328
329 19
    /**
330
     * @return Api\Attachment
331 19
     */
332
    public function attachment()
333
    {
334
        return new Api\Attachment($this->httpClient, $this->requestBuilder, $this->hydrator);
335
    }
336
337
    /**
338
     * @return Api\Domain
339
     */
340
    public function domains()
341
    {
342
        return new Api\Domain($this->httpClient, $this->requestBuilder, $this->hydrator);
343
    }
344
345
    /**
346
     * @return Api\Tag
347
     */
348
    public function tags()
349
    {
350
        return new Api\Tag($this->httpClient, $this->requestBuilder, $this->hydrator);
351
    }
352
353 7
    /**
354
     * @return Api\Event
355 7
     */
356
    public function events()
357
    {
358
        return new Api\Event($this->httpClient, $this->requestBuilder, $this->hydrator);
359
    }
360
361
    /**
362
     * @return Api\Route
363
     */
364
    public function routes()
365
    {
366
        return new Api\Route($this->httpClient, $this->requestBuilder, $this->hydrator);
367
    }
368
369
    /**
370
     * @return Api\Webhook
371
     */
372
    public function webhooks()
373
    {
374
        return new Api\Webhook($this->httpClient, $this->requestBuilder, $this->hydrator, $this->apiKey);
375
    }
376
377
    /**
378
     * @return Api\Message
379
     */
380
    public function messages()
381
    {
382
        return new Api\Message($this->httpClient, $this->requestBuilder, $this->hydrator);
383
    }
384
385
    /**
386
     * @return Api\Suppression
387
     */
388
    public function suppressions()
389
    {
390
        return new Api\Suppression($this->httpClient, $this->requestBuilder, $this->hydrator);
391
    }
392
}
393