EmailHeaderSame.php 1.6 KB

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