Passed
Push — master ( 784a2f...45100f )
by Thomas
13:34
created

SparkPostTest::testSendAllTo()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 32
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 2
eloc 17
c 3
b 1
f 0
nc 2
nop 0
dl 0
loc 32
rs 9.7
1
<?php
2
3
namespace LeKoala\SparkPost\Test;
4
5
use SilverStripe\Core\Environment;
6
use SilverStripe\Dev\SapphireTest;
7
use SilverStripe\Control\Email\Email;
8
use LeKoala\SparkPost\SparkPostHelper;
9
use SilverStripe\Core\Injector\Injector;
10
use Symfony\Component\Mailer\Envelope;
11
use Symfony\Component\Mailer\MailerInterface;
12
use Symfony\Component\Mime\Address;
13
14
/**
15
 * Test for SparkPost
16
 *
17
 * @group SparkPost
18
 */
19
class SparkPostTest extends SapphireTest
20
{
21
    /**
22
     * @var MailerInterface
23
     */
24
    protected $testMailer;
25
    protected bool $isDummy = false;
26
27
    protected function setUp(): void
28
    {
29
        parent::setUp();
30
31
        // add dummy api key
32
        if (!SparkPostHelper::getAPIKey()) {
33
            $this->isDummy = true;
34
            SparkPostHelper::config()->api_key = "dummy";
35
        }
36
37
        $this->testMailer = Injector::inst()->get(MailerInterface::class);
38
    }
39
40
    protected function tearDown(): void
41
    {
42
        parent::tearDown();
43
44
        Injector::inst()->registerService($this->testMailer, MailerInterface::class);
45
    }
46
47
    public function testSetup(): void
48
    {
49
        $inst = SparkPostHelper::registerTransport();
50
        $mailer = SparkPostHelper::getMailer();
51
        $instClass = get_class($inst);
52
        $instMailer = get_class($mailer);
53
        $this->assertEquals($instClass, $instMailer);
54
    }
55
56
    public function testClient(): void
57
    {
58
        $client = SparkPostHelper::getClient();
59
60
        if ($this->isDummy) {
61
            $this->assertTrue(true);
62
        } else {
63
            $result = $client->listAllSendingDomains();
64
            $this->assertTrue(is_array($result));
65
        }
66
    }
67
68
    public function testTLSVersion(): void
69
    {
70
        $ch = curl_init();
71
        // This fixes ca cert issues if server is not configured properly
72
        $cainfo = ini_get('curl.cainfo');
73
        if (is_string($cainfo) && strlen($cainfo) === 0) {
74
            curl_setopt($ch, CURLOPT_CAINFO, \Composer\CaBundle\CaBundle::getBundledCaBundlePath());
75
        }
76
        curl_setopt($ch, CURLOPT_URL, 'https://www.howsmyssl.com/a/check');
77
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
78
        $data = curl_exec($ch);
79
        if (!$data) {
80
            $this->markTestIncomplete('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
81
        }
82
        curl_close($ch);
83
        if (is_string($data)) {
84
            $json = json_decode($data);
85
            $this->assertNotEquals("TLS 1.0", $json->tls_version);
86
        }
87
    }
88
89
    public function testSendAllTo(): void
90
    {
91
        $sendAllTo = Environment::getEnv('SS_SEND_ALL_EMAILS_TO');
92
93
        $mailer = SparkPostHelper::registerTransport();
94
95
        $email = new Email();
96
        $email->setSubject('Test email');
97
        $email->setBody("Body of my email");
98
        $email->getHeaders()->addTextHeader('X-SendingDisabled', "true");
99
        $email->setTo("[email protected]");
100
101
        // This is async, therefore it does not return anything anymore
102
        $email->send();
103
104
        /** @var \LeKoala\SparkPost\SparkPostApiTransport $transport */
105
        $transport = SparkPostHelper::getTransportFromMailer($mailer);
106
        $result = $transport->getApiResult();
107
108
        // if we have a send all to, it should match
109
        $realRecipient = $sendAllTo ? $sendAllTo : "[email protected]";
110
        $this->assertEquals($realRecipient, $result["email"]);
111
112
        Environment::setEnv("SS_SEND_ALL_EMAILS_TO", "[email protected]");
113
114
        $email->send();
115
        $result = $transport->getApiResult();
116
117
        $this->assertEquals("[email protected]", $result["email"]);
118
119
        // reset env
120
        Environment::setEnv("SS_SEND_ALL_EMAILS_TO", $sendAllTo);
121
    }
122
123
    public function testSending(): void
124
    {
125
        $test_to = Environment::getEnv('SPARKPOST_TEST_TO');
126
        $test_from = Environment::getEnv('SPARKPOST_TEST_FROM');
127
128
        $mailer = SparkPostHelper::registerTransport();
129
130
        $email = new Email();
131
        $email->setSubject('Test email');
132
        $email->setBody("Body of my email");
133
134
        if (!$test_from || !$test_to || $this->isDummy) {
135
            $test_to = "example@localhost";
136
            $test_from =  "sender@localhost";
137
            // don't try to send it for real
138
            $email->getHeaders()->addTextHeader('X-SendingDisabled', "true");
139
        }
140
        $email->setTo($test_to);
141
        $email->setFrom($test_from);
142
143
        // This is async, therefore it does not return anything anymore
144
        $email->send();
145
146
        /** @var \LeKoala\SparkPost\SparkPostApiTransport $transport */
147
        $transport = SparkPostHelper::getTransportFromMailer($mailer);
148
        $result = $transport->getApiResult();
149
150
        $this->assertEquals(1, $result['total_accepted_recipients']);
151
    }
152
153
    public function testPayload(): void
154
    {
155
        $mailer = SparkPostHelper::registerTransport();
156
        /** @var \LeKoala\SparkPost\SparkPostApiTransport $transport */
157
        $transport = SparkPostHelper::getTransportFromMailer($mailer);
158
159
160
        $html = <<<HTML
161
<!DOCTYPE html>
162
<html>
163
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><style type="text/css">.red {color:red;}</style></head>
164
<body><span class="red">red</span></body>
165
</html>
166
HTML;
167
        $result = <<<HTML
168
<!DOCTYPE html>
169
<html>
170
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head>
171
<body><span class="red" style="color: red;">red</span></body>
172
</html>
173
174
HTML;
175
176
        $sender = new Address('[email protected]', "testman");
177
        $recipients = [
178
            new Address('[email protected]', "testrec"),
179
        ];
180
        $email = new Email();
181
        $email->setBody($html);
182
        $envelope = new Envelope($sender, $recipients);
183
        $payload = $transport->getPayload($email, $envelope);
184
        $content = $payload['content'];
185
186
        $payloadRecipients = $payload['recipients'][0];
187
        $this->assertEquals("testrec", $recipients[0]->getName());
188
        $this->assertEquals(
189
            [
190
                'address' => [
191
                    'email' => '[email protected]',
192
                    'name' => 'rec' // extracted from email due to how recipients work
193
                ]
194
            ],
195
            $payloadRecipients
196
        );
197
        $payloadSender = $content['from'];
198
        $this->assertEquals([
199
            'email' => '[email protected]',
200
            'name' => 'testman'
201
        ], $payloadSender);
202
203
        // Make sure our styles are properly inlined
204
        $this->assertEquals('red', $content['text']);
205
        $this->assertEquals($result, $content['html']);
206
    }
207
}
208