Merge pull request #2981 from frankforte/custom-headers

Add methods to update or clear custom headers by name.
This commit is contained in:
Marcus Bointon 2023-11-22 18:25:52 +01:00 committed by GitHub
commit f2798a387d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 68 additions and 0 deletions

View File

@ -4058,6 +4058,39 @@ class PHPMailer
$this->CustomHeader = [];
}
/**
* Clear a specific custom header.
*/
public function clearCustomHeader($name)
{
foreach ($this->CustomHeader as $k => $pair) {
if ($pair[0] == $name) {
unset($this->CustomHeader[$k]);
}
}
}
/**
* Replace a custom header.
*/
public function replaceCustomHeader($name, $value)
{
foreach ($this->CustomHeader as $k => $pair) {
if ($pair[0] == $name) {
if (strpbrk($name . $value, "\r\n") !== false) {
if ($this->exceptions) {
throw new Exception($this->lang('invalid_header'));
}
return false;
}
$this->CustomHeader[$k] = [$name, $value];
}
}
return true;
}
/**
* Add an error message to the error container.
*

View File

@ -190,6 +190,23 @@ final class CustomHeaderTest extends TestCase
];
}
/**
* Test removing previously set custom header.
*
* @covers \PHPMailer\PHPMailer\PHPMailer::clearCustomHeader
*/
public function testClearCustomHeader()
{
$this->Mail->addCustomHeader('foo', 'bar');
self::assertSame([['foo', 'bar']], $this->Mail->getCustomHeaders());
$this->Mail->clearCustomHeader('foo');
$cleared = $this->Mail->getCustomHeaders();
self::assertIsArray($cleared);
self::assertEmpty($cleared);
}
/**
* Test removing previously set custom headers.
*
@ -222,4 +239,22 @@ final class CustomHeaderTest extends TestCase
$mail = new PHPMailer(true);
$mail->addCustomHeader('SomeHeader', "Some\n Value");
}
/**
* Test replacing a previously set custom header.
*
* @covers \PHPMailer\PHPMailer\PHPMailer::replaceCustomHeader
*/
public function testReplaceCustomHeader()
{
$this->Mail->addCustomHeader('foo', 'bar');
$this->Mail->replaceCustomHeader('foo', 'baz');
// Test retrieving the custom header(s) and verify the updated value is seet.
self::assertSame(
[['foo', 'baz']],
$this->Mail->getCustomHeaders(),
'Custom header does not contain expected update'
);
}
}