EmailHeaderSame.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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\UnstructuredHeader;
  13. use Symfony\Component\Mime\RawMessage;
  14. final class EmailHeaderSame extends Constraint
  15. {
  16. private $headerName;
  17. private $expectedValue;
  18. public function __construct(string $headerName, string $expectedValue)
  19. {
  20. $this->headerName = $headerName;
  21. $this->expectedValue = $expectedValue;
  22. }
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function toString(): string
  27. {
  28. return sprintf('has header "%s" with value "%s"', $this->headerName, $this->expectedValue);
  29. }
  30. /**
  31. * @param RawMessage $message
  32. *
  33. * {@inheritdoc}
  34. */
  35. protected function matches($message): bool
  36. {
  37. if (RawMessage::class === \get_class($message)) {
  38. throw new \LogicException('Unable to test a message header on a RawMessage instance.');
  39. }
  40. return $this->expectedValue === $this->getHeaderValue($message);
  41. }
  42. /**
  43. * @param RawMessage $message
  44. *
  45. * {@inheritdoc}
  46. */
  47. protected function failureDescription($message): string
  48. {
  49. return sprintf('the Email %s (value is %s)', $this->toString(), $this->getHeaderValue($message));
  50. }
  51. private function getHeaderValue($message): string
  52. {
  53. $header = $message->getHeaders()->get($this->headerName);
  54. return $header instanceof UnstructuredHeader ? $header->getValue() : $header->getBodyAsString();
  55. }
  56. }