Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: preserve substitutions from To in Personalization #1101

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions lib/mail/Personalization.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
27 changes: 27 additions & 0 deletions test/unit/PersonalizationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use SendGrid\Mail\Subject;
use SendGrid\Mail\To;
use SendGrid\Mail\TypeException;
use SendGrid\Mail\Substitution;

/**
* This class tests Personalization.
Expand All @@ -32,6 +33,32 @@ public function testAddTo()
$this->assertSame('[email protected]', $personalization->getTos()[0]->getEmail());
}

public function testAddToWithSubstitution()
{
$personalization = new Personalization();
$personalization->addTo(new To('[email protected]', '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('[email protected]', '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();
Expand Down
Loading