You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.1 KiB

3 years ago
  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. private $headerName;
  18. private $expectedValue;
  19. public function __construct(string $headerName, string $expectedValue)
  20. {
  21. $this->headerName = $headerName;
  22. $this->expectedValue = $expectedValue;
  23. }
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function toString(): string
  28. {
  29. return sprintf('contains address "%s" with value "%s"', $this->headerName, $this->expectedValue);
  30. }
  31. /**
  32. * @param RawMessage $message
  33. *
  34. * {@inheritdoc}
  35. */
  36. protected function matches($message): bool
  37. {
  38. if (RawMessage::class === \get_class($message)) {
  39. throw new \LogicException('Unable to test a message address on a RawMessage instance.');
  40. }
  41. $header = $message->getHeaders()->get($this->headerName);
  42. if ($header instanceof MailboxHeader) {
  43. return $this->expectedValue === $header->getAddress()->getAddress();
  44. } elseif ($header instanceof MailboxListHeader) {
  45. foreach ($header->getAddresses() as $address) {
  46. if ($this->expectedValue === $address->getAddress()) {
  47. return true;
  48. }
  49. }
  50. return false;
  51. }
  52. throw new \LogicException('Unable to test a message address on a non-address header.');
  53. }
  54. /**
  55. * @param RawMessage $message
  56. *
  57. * {@inheritdoc}
  58. */
  59. protected function failureDescription($message): string
  60. {
  61. return sprintf('the Email %s (value is %s)', $this->toString(), $message->getHeaders()->get($this->headerName)->getBodyAsString());
  62. }
  63. }