EmailAddressContains.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Mime\Test\Constraint;
  11. use PHPUnit\Framework\Constraint\Constraint;
  12. use Symfony\Component\Mime\Header\MailboxHeader;
  13. use Symfony\Component\Mime\Header\MailboxListHeader;
  14. use Symfony\Component\Mime\RawMessage;
  15. final class EmailAddressContains extends Constraint
  16. {
  17. public function __construct(
  18. private string $headerName,
  19. private string $expectedValue,
  20. ) {
  21. }
  22. public function toString(): string
  23. {
  24. return sprintf('contains address "%s" with value "%s"', $this->headerName, $this->expectedValue);
  25. }
  26. /**
  27. * @param RawMessage $message
  28. */
  29. protected function matches($message): bool
  30. {
  31. if (RawMessage::class === $message::class) {
  32. throw new \LogicException('Unable to test a message address on a RawMessage instance.');
  33. }
  34. $header = $message->getHeaders()->get($this->headerName);
  35. if ($header instanceof MailboxHeader) {
  36. return $this->expectedValue === $header->getAddress()->getAddress();
  37. } elseif ($header instanceof MailboxListHeader) {
  38. foreach ($header->getAddresses() as $address) {
  39. if ($this->expectedValue === $address->getAddress()) {
  40. return true;
  41. }
  42. }
  43. return false;
  44. }
  45. throw new \LogicException('Unable to test a message address on a non-address header.');
  46. }
  47. /**
  48. * @param RawMessage $message
  49. */
  50. protected function failureDescription($message): string
  51. {
  52. return sprintf('the Email %s (value is %s)', $this->toString(), $message->getHeaders()->get($this->headerName)->getBodyAsString());
  53. }
  54. }