summaryrefslogtreecommitdiffstats
path: root/lib/SparkPost/Transmission.php
blob: 8efc934ca01d787fbeb9c2a006058c5f40e1505b (plain)
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
<?php

namespace SparkPost;

class Transmission extends ResourceBase
{
    public function __construct(SparkPost $sparkpost)
    {
        parent::__construct($sparkpost, 'transmissions');
    }

    /**
     * Send post request to transmission endpoint after formatting cc, bcc, and expanding the shorthand emails.
     *
     * @return SparkPostPromise or SparkPostResponse depending on sync or async request
     */
    public function post($payload = [], $headers = [])
    {
        if (isset($payload['recipients']) && !isset($payload['recipients']['list_id'])) {
            $payload = $this->formatPayload($payload);
        }

        return parent::post($payload, $headers);
    }

    /**
     * Runs the given payload through the formatting functions.
     *
     * @param array $payload - the request body
     *
     * @return array - the modified request body
     */
    public function formatPayload($payload)
    {
        $payload = $this->formatBlindCarbonCopy($payload); //Fixes BCCs into payload
        $payload = $this->formatCarbonCopy($payload); //Fixes CCs into payload
        $payload = $this->formatShorthandRecipients($payload); //Fixes shorthand recipients format

        return $payload;
    }

    /**
     * Formats bcc list into recipients list.
     *
     * @param array $payload - the request body
     *
     * @return array - the modified request body
     */
    private function formatBlindCarbonCopy($payload)
    {

        //If there's a list of BCC recipients, move them into the correct format
        if (isset($payload['bcc'])) {
            $payload = $this->addListToRecipients($payload, 'bcc');
        }

        return $payload;
    }

    /**
     * Formats cc list into recipients list and adds the CC header to the content.
     *
     * @param array $payload - the request body
     *
     * @return array - the modified request body
     */
    private function formatCarbonCopy($payload)
    {
        if (isset($payload['cc'])) {
            $ccAddresses = [];
            for ($i = 0; $i < count($payload['cc']); ++$i) {
                array_push($ccAddresses, $this->toAddressString($payload['cc'][$i]['address']));
            }

            // set up the content headers as either what it was before or an empty array
            $payload['content']['headers'] = isset($payload['content']['headers']) ? $payload['content']['headers'] : [];
            // add cc header
            $payload['content']['headers']['CC'] = implode(',', $ccAddresses);

            $payload = $this->addListToRecipients($payload, 'cc');
        }

        return $payload;
    }

    /**
     * Formats all recipients into the long form of [ "name" => "John", "email" => "john@exmmple.com" ].
     *
     * @param array $payload - the request body
     *
     * @return array - the modified request body
     */
    private function formatShorthandRecipients($payload)
    {
        if (isset($payload['content']['from'])) {
            $payload['content']['from'] = $this->toAddressObject($payload['content']['from']);
        }

        for ($i = 0; $i < count($payload['recipients']); ++$i) {
            $payload['recipients'][$i]['address'] = $this->toAddressObject($payload['recipients'][$i]['address']);
        }

        return $payload;
    }

    /**
     * Loops through the given listName in the payload and adds all the recipients to the recipients list after removing their names.
     *
     * @param array $payload  - the request body
     * @param array $listName - the name of the array in the payload to be moved to the recipients list
     *
     * @return array - the modified request body
     */
    private function addListToRecipients($payload, $listName)
    {
        $originalAddress = $this->toAddressString($payload['recipients'][0]['address']);
        foreach ($payload[$listName] as $recipient) {
            $recipient['address'] = $this->toAddressObject($recipient['address']);
            $recipient['address']['header_to'] = $originalAddress;

            // remove name from address - name is only put in the header for cc and not at all for bcc
            if (isset($recipient['address']['name'])) {
                unset($recipient['address']['name']);
            }

            array_push($payload['recipients'], $recipient);
        }

        //Delete the original object from the payload.
        unset($payload[$listName]);

        return $payload;
    }

    /**
     * Takes the shorthand form of an email address and converts it to the long form.
     *
     * @param $address - the shorthand form of an email address "Name <Email address>"
     *
     * @return array - the longhand form of an email address [ "name" => "John", "email" => "john@exmmple.com" ]
     */
    private function toAddressObject($address)
    {
        $formatted = $address;
        if (is_string($formatted)) {
            $formatted = [];

            if ($this->isEmail($address)) {
                $formatted['email'] = $address;
            } elseif (preg_match('/"?(.[^"]*)?"?\s*<(.+)>/', $address, $matches)) {
                $name = trim($matches[1]);
                $formatted['name'] = $matches[1];
                $formatted['email'] = $matches[2];
            } else {
                throw new \Exception('Invalid address format: '.$address);
            }
        }

        return $formatted;
    }

    /**
     * Takes the longhand form of an email address and converts it to the shorthand form.
     *
     * @param $address - the longhand form of an email address [ "name" => "John", "email" => "john@exmmple.com" ]
     * @param string - the shorthand form of an email address "Name <Email address>"
     */
    private function toAddressString($address)
    {
        // convert object to string
        if (!is_string($address)) {
            if (isset($address['name'])) {
                $address = '"'.$address['name'].'" <'.$address['email'].'>';
            } else {
                $address = $address['email'];
            }
        }

        return $address;
    }

    /**
     * Checks if a string is an email.
     *
     * @param string $email - a string that might be an email address
     * @param bool - true if the given string is an email
     */
    private function isEmail($email)
    {
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return true;
        } else {
            return false;
        }
    }
}