diff --git a/lib/mail/Personalization.php b/lib/mail/Personalization.php index 020e8245..7fb57e9d 100644 --- a/lib/mail/Personalization.php +++ b/lib/mail/Personalization.php @@ -43,11 +43,24 @@ class Personalization implements \JsonSerializable /** * Add a To object to a Personalization object + * If there are substitutions in the To object preserve them + * by transferring them to the Personalization object. + * If a substitution with the same key already exists + * that takes precedence, and we don't overwrite * * @param To $email To object */ public function addTo($email) { + if ($subs = $email->getSubstitutions()) { + $existing_subs = $this->getSubstitutions(); + foreach ($subs as $key => $value) { + if (!array_key_exists($key, $existing_subs)) { + $this->addSubstitution($key, $value); + } + } + } + $this->tos[] = $email; } diff --git a/test/unit/PersonalizationTest.php b/test/unit/PersonalizationTest.php index 9bd35ba4..f4417e95 100644 --- a/test/unit/PersonalizationTest.php +++ b/test/unit/PersonalizationTest.php @@ -16,6 +16,7 @@ use SendGrid\Mail\Subject; use SendGrid\Mail\To; use SendGrid\Mail\TypeException; +use SendGrid\Mail\Substitution; /** * This class tests Personalization. @@ -32,6 +33,32 @@ public function testAddTo() $this->assertSame('dx@sendgrid.com', $personalization->getTos()[0]->getEmail()); } + public function testAddToWithSubstitution() + { + $personalization = new Personalization(); + $personalization->addTo(new To('dx@sendgrid.com', 'Test with sub', + [ + '-name-' => 'Example User' + ] + )); + + $this->assertArrayHasKey('-name-', $personalization->getSubstitutions()); + } + + public function testAddSubstitutionHasPrecedence() + { + $personalization = new Personalization(); + $personalization->addSubstitution(new Substitution('-name-', 'Example User 2')); + $personalization->addTo(new To('dx@sendgrid.com', 'Test with sub', + [ + '-name-' => 'Example User' + ] + )); + + $this->assertArrayHasKey('-name-', $personalization->getSubstitutions()); + $this->assertSame('Example User 2', $personalization->getSubstitutions()['-name-']); + } + public function testAddFrom() { $personalization = new Personalization();