File size: 7,336 Bytes
d2897cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
<?php

namespace Mautic\EmailBundle\Tests\Model;

use Mautic\CoreBundle\Event\TokenReplacementEvent;
use Mautic\CoreBundle\Exception\RecordNotPublishedException;
use Mautic\EmailBundle\EmailEvents;
use Mautic\EmailBundle\Entity\Email;
use Mautic\EmailBundle\Event\EmailSendEvent;
use Mautic\EmailBundle\Exception\EmailCouldNotBeSentException;
use Mautic\EmailBundle\Exception\InvalidEmailException;
use Mautic\EmailBundle\Helper\EmailValidator;
use Mautic\EmailBundle\Model\EmailModel;
use Mautic\EmailBundle\Model\SendEmailToUser;
use Mautic\LeadBundle\Entity\Lead;
use Mautic\LeadBundle\Validator\CustomFieldValidator;
use Mautic\UserBundle\Entity\User;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class SendEmailToUserTest extends \PHPUnit\Framework\TestCase
{
    /**
     * @var MockObject|EmailModel
     */
    private MockObject $emailModel;

    /**
     * @var MockObject|EventDispatcherInterface
     */
    private MockObject $dispatcher;

    /**
     * @var MockObject|CustomFieldValidator
     */
    private MockObject $customFieldValidator;

    /**
     * @var MockObject|EmailValidator
     */
    private MockObject $emailValidator;

    private SendEmailToUser $sendEmailToUser;

    protected function setUp(): void
    {
        parent::setUp();
        $this->emailModel           = $this->createMock(EmailModel::class);
        $this->dispatcher           = $this->createMock(EventDispatcherInterface::class);
        $this->customFieldValidator = $this->createMock(CustomFieldValidator::class);
        $this->emailValidator       = $this->createMock(EmailValidator::class);
        $this->sendEmailToUser      = new SendEmailToUser(
            $this->emailModel,
            $this->dispatcher,
            $this->customFieldValidator,
            $this->emailValidator
        );
    }

    public function testEmailNotFound(): void
    {
        $lead = new Lead();

        $this->emailModel->expects($this->once())
            ->method('getEntity')
            ->with(100)
            ->willReturn(null);

        $config                       = [];
        $config['useremail']['email'] = 100;

        $this->expectException(EmailCouldNotBeSentException::class);

        $this->sendEmailToUser->sendEmailToUsers($config, $lead);
    }

    public function testEmailNotPublished(): void
    {
        $lead  = new Lead();
        $email = new Email();
        $email->setIsPublished(false);

        $this->emailModel->expects($this->once())
            ->method('getEntity')
            ->with(100)
            ->willREturn($email);

        $config                       = [];
        $config['useremail']['email'] = 100;

        $this->expectException(EmailCouldNotBeSentException::class);

        $this->sendEmailToUser->sendEmailToUsers($config, $lead);
    }

    public function testSendEmailWithNoError(): void
    {
        $lead  = new Lead();
        $owner = new class() extends User {
            public function getId()
            {
                return 10;
            }
        };

        $lead->setOwner($owner);

        $email = new Email();
        $email->setIsPublished(true);

        $this->emailModel->expects($this->once())
            ->method('getEntity')
            ->with(33)
            ->willReturn($email);

        $emailSendEvent                           = new class() extends EmailSendEvent {
            public int $getTokenMethodCallCounter = 0;

            public function __construct()
            {
            }

            /**
             * @param bool $includeGlobal
             *
             * @return string[]
             */
            public function getTokens($includeGlobal = true): array
            {
                ++$this->getTokenMethodCallCounter;

                return [];
            }
        };

        // Global token for Email
        $this->emailModel->expects($this->once())
            ->method('dispatchEmailSendEvent')
            ->willReturn($emailSendEvent);

        // Different handling of tokens in the To, BC, BCC fields.
        $this->customFieldValidator->expects($this->exactly(3))
            ->method('validateFieldType')
            ->withConsecutive(
                ['unpublished-field', 'email'],
                ['unpublished-field', 'email'],
                ['active-field', 'email']
            )
            ->willReturnOnConsecutiveCalls(
                $this->throwException(new RecordNotPublishedException()),
                $this->throwException(new RecordNotPublishedException()),
                null
            );

        // The event is dispatched only for valid tokens.
        $this->dispatcher->expects($this->once())
            ->method('dispatch')
            ->with(
                $this->callback(
                    function (TokenReplacementEvent $event) use ($lead) {
                        Assert::assertSame('{contactfield=active-field}', $event->getContent());
                        Assert::assertSame($lead, $event->getLead());

                        // Emulate a subscriber.
                        $event->setContent('[email protected]');

                        return true;
                    }
                ),
                EmailEvents::ON_EMAIL_ADDRESS_TOKEN_REPLACEMENT,
            );

        $this->emailValidator->expects($this->exactly(4))
            ->method('validate')
            ->withConsecutive(
                ['[email protected]'],
                ['[email protected]'],
                ['[email protected]'],
                ['{invalid-token}']
            )
            ->willReturnOnConsecutiveCalls(
                null,
                null,
                null,
                $this->throwException(new InvalidEmailException('{invalid-token}'))
            );
        // Send email method

        $this->emailModel
            ->expects($this->once())
            ->method('sendEmailToUser')
            ->will($this->returnCallback(function ($email, $users, $leadCredentials, $tokens, $assetAttachments, $saveStat, $to, $cc, $bcc): void {
                $expectedUsers = [
                    ['id' => 6],
                    ['id' => 7],
                    ['id' => 10], // owner ID
                ];
                $this->assertInstanceOf(Email::class, $email);
                $this->assertEquals($expectedUsers, $users);
                $this->assertFalse($saveStat);
                $this->assertEquals(['[email protected]', '[email protected]', '[email protected]'], $to);
                $this->assertEquals([], $cc);
                $this->assertEquals([0 => '[email protected]', 2 => '[email protected]'], $bcc);
            }));

        $config = [
            'useremail' => [
                'email' => 33,
            ],
            'user_id'  => [6, 7],
            'to_owner' => true,
            'to'       => '[email protected], [email protected], {contactfield=unpublished-field|[email protected]}, {contactfield=unpublished-field}',
            'bcc'      => '[email protected],{invalid-token}, {contactfield=active-field}',
        ];

        $this->sendEmailToUser->sendEmailToUsers($config, $lead);

        Assert::assertSame(1, $emailSendEvent->getTokenMethodCallCounter);
    }
}