TestHelper::addMailgunEvents()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 6 Features 3
Metric Value
cc 4
eloc 14
nc 3
nop 3
dl 0
loc 21
rs 9.7998
c 8
b 6
f 3
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 Doctrine\ORM\EntityManager;
10
use Symfony\Component\HttpFoundation\File\UploadedFile;
11
12
class TestHelper
13
{
14
    /**
15
     * @param int $count
16
     */
17
    public static function addMailgunEvents(EntityManager $manager, $count, $mailgunApiKey)
18
    {
19
        $eventTypes = array('delivered', 'bounced', 'dropped');
20
        while ($count > 0) {
21
            $eventType = $eventTypes[rand(0, sizeof($eventTypes) - 1)];
22
            $messageId = '<'.md5(time()).$count.'@acme.com>';
23
            $event = self::addMailgunEvent($manager, $mailgunApiKey, $eventType, $messageId, $count);
24
            $messageSummary = $manager->getRepository(MailgunMessageSummary::class)->createOrUpdateMessageSummary($event);
25
26
            // for delivered messages, add some open events
27
            if ('delivered' == $eventType) {
28
                $openCount = random_int(0, 10);
29
                while ($openCount > 0) {
30
                    $openEvent = self::addMailgunEvent($manager, $mailgunApiKey, 'open', $messageId, $openCount);
31
                    $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

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

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