sendgrid / sendgrid-php

The Official Twilio SendGrid PHP API Library
https://sendgrid.com
MIT License
1.49k stars 624 forks source link

fix: preserve substitutions from To in Personalization #1101

Open toleabivol opened 2 years ago

toleabivol commented 2 years ago

If there are substitutions in the To object preserve them by transfering them to the Personalization object.

Currently this does not work (we loose all substitutions from the To):

$personalization0 = new Personalization();
$personalization0->addTo(new To(
        "test+test2@example.com",
        "Example User2",
        [
            '-name-' => 'Example User 2'   // <--this is lost and not sent to sendgrid API
        ],
        "Example User2 -name-"
));
$email->addPersonalization($personalization0);

We can either add the substitution during addTo method (as current PR is proposing) or parse all Tos during getSubstitutions method and add them to the substitution property. I propose the first way because it is similar to what we have in https://github.com/sendgrid/sendgrid-php/blob/main/lib/mail/Mail.php#L205

We have to also think about implementations that worked around this issue (like myself) and not break them, so the following must still be working :

$personalization0 = new Personalization();
personalization->addSubstitution(new Substitution('-name-', 'Example User 1')); // <- we want this preserved even if added first
$personalization0->addTo(new To(
        "test+test2@example.com",
        "Example User2",
        [
            '-name-' => 'Example User 2' // <- we want this to not be applied in this case as addSubstitution takes precedence
        ],
        "Example User2 -name-"
));

$email->addPersonalization($personalization0);

OR we don't but we risk to break some implementations. Are there means of communicating the change in this case ?

Checklist