Completed
Push — master ( 7c9327...0eeb7a )
by Dominik
49:52 queued 24:50
created

TestHelper::addMailgunEvent()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 61
Code Lines 55

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 1
Metric Value
cc 1
eloc 55
nc 1
nop 5
dl 0
loc 61
rs 8.9818
c 1
b 1
f 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Azine\MailgunWebhooksBundle\Tests;
4
5
use Azine\MailgunWebhooksBundle\Entity\MailgunAttachment;
6
use Azine\MailgunWebhooksBundle\Entity\MailgunCustomVariable;
7
use Azine\MailgunWebhooksBundle\Entity\MailgunEvent;
8
use Azine\MailgunWebhooksBundle\Entity\MailgunMessageSummary;
9
use Azine\MailgunWebhooksBundle\Entity\Repositories\MailgunMessageSummaryRepository;
10
use Doctrine\ORM\EntityManager;
11
use Symfony\Component\HttpFoundation\File\UploadedFile;
12
13
class TestHelper
14
{
15
    /**
16
     * @param int $count
17
     */
18
    public static function addMailgunEvents(EntityManager $manager, $count, $mailgunApiKey)
19
    {
20
        $eventTypes = array('delivered', 'bounced', 'dropped');
21
        while ($count > 0) {
22
            $eventType = $eventTypes[rand(0, sizeof($eventTypes) - 1)];
23
            $messageId = '<'.md5(time()).$count.'@acme.com>';
24
            $event = self::addMailgunEvent($manager, $mailgunApiKey, $eventType, $messageId, $count);
25
            $messageSummary = $manager->getRepository(MailgunMessageSummary::class)->createOrUpdateMessageSummary($event);
26
27
            // for delivered messages, add some open events
28
            if($eventType == 'delivered'){
29
                $openCount = random_int(0,10);
30
                while($openCount > 0) {
31
                    $openEvent = self::addMailgunEvent($manager, $mailgunApiKey, 'open', $messageId, $openCount);
32
                    $openEvent->setEventSummary($messageSummary);
0 ignored issues
show
Bug introduced by
It seems like $messageSummary can also be of type array; however, parameter $eventSummary of Azine\MailgunWebhooksBun...vent::setEventSummary() does only seem to accept Azine\MailgunWebhooksBun...lgunMessageSummary|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

32
                    $openEvent->setEventSummary(/** @scrutinizer ignore-type */ $messageSummary);
Loading history...
33
34
                    $openCount--;
35
                }
36
            }
37
            $manager->flush();
38
            --$count;
39
        }
40
    }
41
42
    /**
43
     * @param EntityManager $manager
44
     * @param $mailgunApiKey
45
     * @param $eventType
46
     * @param $messageId
47
     * @throws \Exception
48
     */
49
    private static function addMailgunEvent(EntityManager $manager, $mailgunApiKey, $eventType, $messageId, $count){
50
        $mailgunEvent = new MailgunEvent();
51
        $mailgunEvent->setEvent($eventType);
52
        $mailgunEvent->setDomain('acme');
53
        $d = new \DateTime(rand(1, 200).' days '.rand(1, 86400).' seconds ago');
54
        $mailgunEvent->setTimestamp($d->getTimestamp());
55
        $mailgunEvent->setToken(md5(time().$count));
56
        $mailgunEvent->setRecipient('recipient-'.$count.'@email.com');
57
        $mailgunEvent->setSender('some-sender-'.$count.'@email.com');
58
        $mailgunEvent->setMessageHeaders(json_encode(array('some_json' => 'data', 'Subject' => "this mail was sent because it's important.")));
59
        $mailgunEvent->setMessageId($messageId);
60
        $mailgunEvent->setSignature(hash_hmac('SHA256', $mailgunEvent->getTimestamp().$mailgunEvent->getToken(), $mailgunApiKey));
61
        $mailgunEvent->setDescription('some description');
62
        $mailgunEvent->setReason('don\'t know the reason');
63
        $mailgunEvent->setIp('42.42.42.42');
64
        $mailgunEvent->setErrorCode('123');
65
        $mailgunEvent->setCountry('CH');
66
        $mailgunEvent->setCity('Zurich');
67
        $mailgunEvent->setRegion('8000');
68
        $mailgunEvent->setCampaignId('2014-01-01');
69
        $mailgunEvent->setCampaignName('newsletter');
70
        $mailgunEvent->setClientName('some client');
71
        $mailgunEvent->setClientOs('some os');
72
        $mailgunEvent->setClientType('some type');
73
        $mailgunEvent->setDeviceType('some device');
74
        $mailgunEvent->setMailingList('no list');
75
        $mailgunEvent->setTag('hmmm no tag');
76
        $mailgunEvent->setUserAgent('Firefox 42');
77
        $mailgunEvent->setUrl('');
78
        $manager->persist($mailgunEvent);
79
80
        $file = new UploadedFile(realpath(__DIR__.'/testAttachment.small.png'), 'some.real.file.name1.png');
81
        $attachment = new MailgunAttachment($mailgunEvent);
82
        $attachment->setContent(file_get_contents($file->getRealPath()));
83
        $attachment->setName(md5(time() + rand(0, 100)).'.'.$file->getClientOriginalExtension());
84
        $attachment->setSize($file->getSize());
85
        $attachment->setType($file->getType());
86
        $attachment->setCounter(1);
87
        $manager->persist($attachment);
88
89
        $attachment = new MailgunAttachment($mailgunEvent);
90
        $attachment->setContent(file_get_contents($file->getRealPath()));
91
        $attachment->setName(md5(time() + rand(0, 100)).'.'.$file->getClientOriginalExtension());
92
        $attachment->setSize($file->getSize());
93
        $attachment->setType($file->getType());
94
        $attachment->setCounter(2);
95
        $manager->persist($attachment);
96
97
        $variable = new MailgunCustomVariable($mailgunEvent);
98
        $variable->setEventId($mailgunEvent->getId());
99
        $variable->setContent(array('some data1'));
100
        $variable->setVariableName('some custom variable for event'.$mailgunEvent->getId());
0 ignored issues
show
Bug introduced by
'some custom variable fo... $mailgunEvent->getId() of type string is incompatible with the type integer expected by parameter $variableName of Azine\MailgunWebhooksBun...able::setVariableName(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

100
        $variable->setVariableName(/** @scrutinizer ignore-type */ 'some custom variable for event'.$mailgunEvent->getId());
Loading history...
101
        $manager->persist($variable);
102
103
        $variable = new MailgunCustomVariable($mailgunEvent);
104
        $variable->setEventId($mailgunEvent->getId());
105
        $variable->setContent(array('some data2'));
106
        $variable->setVariableName('some custom variable for event'.$mailgunEvent->getId());
107
        $manager->persist($variable);
108
109
        return $mailgunEvent;
110
    }
111
112
    public static function getPostDataWithoutSignature($newApi)
113
    {
114
        if($newApi){
115
            $timestamp = time();
116
            $data = array(
117
                'signature' => array (
118
                    'timestamp' => $timestamp,
119
                    'token' => '50dcec4a2d0ef27036c44ebd9ce9324736fc98ef9405428803',
120
                ),
121
                'event-data' =>
122
                    array(
123
                        'tags' =>
124
                            array(
125
                                0 => 'my_tag_1',
126
                                1 => 'my_tag_2'
127
                            ),
128
                        'timestamp' => $timestamp,
129
                        'storage' =>
130
                            array(
131
                                'url' => 'https://se.api.mailgun.net/v3/domains/acme.com/messages/message_key',
132
                                'key' => 'message_key',
133
                            ),
134
                        'envelope' =>
135
                            array(
136
                                'transport' => 'smtp',
137
                                'sender' => '[email protected]',
138
                                'sending-ip' => '209.61.154.250',
139
                                'targets' => '[email protected]',
140
                            ),
141
                        'recipient-domain' => 'example.com',
142
                        'event' => 'delivered',
143
                        'campaigns' =>
144
                            array(),
145
                        'user-variables' =>
146
                            array(
147
                                'my_var_1' => 'Mailgun Variable #1',
148
                                'my-var-2' => 'awesome',
149
                            ),
150
                        'flags' =>
151
                            array('is-routed' => false, 'is-authenticated' => true, 'is-system-test' => false, 'is-test-mode' => false,
152
                            ),
153
                        'log-level' => 'info',
154
                        'message' =>
155
                            array(
156
                                'headers' =>
157
                                    array(
158
                                        'to' => 'Alice <[email protected]>',
159
                                        'message-id' => '[email protected]',
160
                                        'from' => 'Bob <[email protected]>',
161
                                        'subject' => 'Test delivered webhook',
162
                                    ),
163
                                'attachments' => array(),
164
                                'size' => 111,
165
                            ),
166
                        'recipient' => '[email protected]',
167
                        'id' => 'CPgfbmQMTCKtHW6uIWtuVe',
168
                        'delivery-status' =>
169
                            array(
170
                                'tls' => true,
171
                                'mx-host' => 'smtp-in.example.com',
172
                                'attempt-no' => 1,
173
                                'description' => '',
174
                                'session-seconds' => 0.4331989288330078,
175
                                'utf8' => true,
176
                                'code' => 250,
177
                                'message' => 'OK',
178
                                'certificate-verified' => true,
179
                            ),
180
                    ),
181
            );
182
        } else {
183
            $data = array(
184
                'event' => 'delivered',
185
                'domain' => 'acme',
186
                'timestamp' => time(),
187
                'token' => 'c47468e81de0818af77f3e14a728602a29',
188
                'X-Mailgun-Sid' => 'irrelevant',
189
                'attachment-count' => 'irrelevant',
190
                'recipient' => '[email protected]',
191
                'message-headers' => json_encode(array(
192
                    array('X-Mailgun-Sending-Ip', '198.62.234.37'),
193
                    array('X-Mailgun-Sid', 'WyIwN2U4YyIsICJzdXBwb3J0QGF6aW5lLm1lIiwgIjA2MjkzIl0='),
194
                    array('Received', 'from acme.test (b4.cme.test [194.140.238.63])'),
195
                    array('Sender', '[email protected]'),
196
                    array('Message-Id', '<[email protected]>'),
197
                    array('Date', 'Mon, 07 Sep 2020 14:38:41 +0200'),
198
                    array('Subject', 'Some email message subject'),
199
                    array('From', '\'acme.test sender-name\' <[email protected]>'),
200
                    array('To', '\'acme.test recipient-name\' <[email protected]>'),
201
                    array('Mime-Version', '1.0'),
202
                    array('Content-Transfer-Encoding', '[\'quoted-printable\']')
203
                )),
204
                'Message-Id' => '<[email protected]>',
205
                'description' => 'some description',
206
                'notification' => 'some notification',
207
                'reason' => 'don\'t know the reason',
208
                'code' => 123,
209
                'ip' => '42.42.42.42',
210
                'error' => 'some error',
211
                'country' => 'CH',
212
                'city' => 'Zurich',
213
                'region' => '8000',
214
                'campaign-id' => '2014-01-01',
215
                'campaign-name' => 'newsletter',
216
                'client-name' => 'some client',
217
                'client-os' => 'some os',
218
                'client-type' => 'some type',
219
                'device-type' => 'some device',
220
                'mailing-list' => 'no list',
221
                'tag' => 'hmmm no tag',
222
                'user-agent' => 'Firefox 42',
223
                'url' => '',
224
                'duplicate-key' => 'data1',
225
                'Duplicate-key' => 'data2',
226
                'some-custom-var1' => 'some data1',
227
                'some-custom-var2' => 'some data2',
228
                'some-custom-var3' => 'some data3',
229
            );
230
        }
231
        return $data;
232
    }
233
}
234