EmailHeaderSame.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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) ?? 'null');
  50. }
  51. private function getHeaderValue($message): ?string
  52. {
  53. if (null === $header = $message->getHeaders()->get($this->headerName)) {
  54. return null;
  55. }
  56. return $header instanceof UnstructuredHeader ? $header->getValue() : $header->getBodyAsString();
  57. }
  58. }