EmailCount.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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\Mailer\Test\Constraint;
  11. use PHPUnit\Framework\Constraint\Constraint;
  12. use Symfony\Component\Mailer\Event\MessageEvents;
  13. final class EmailCount extends Constraint
  14. {
  15. public function __construct(
  16. private int $expectedValue,
  17. private ?string $transport = null,
  18. private bool $queued = false,
  19. ) {
  20. }
  21. public function toString(): string
  22. {
  23. return \sprintf('%shas %s "%d" emails', $this->transport ? $this->transport.' ' : '', $this->queued ? 'queued' : 'sent', $this->expectedValue);
  24. }
  25. /**
  26. * @param MessageEvents $events
  27. */
  28. protected function matches($events): bool
  29. {
  30. return $this->expectedValue === $this->countEmails($events);
  31. }
  32. /**
  33. * @param MessageEvents $events
  34. */
  35. protected function failureDescription($events): string
  36. {
  37. return \sprintf('the Transport %s (%d %s)', $this->toString(), $this->countEmails($events), $this->queued ? 'queued' : 'sent');
  38. }
  39. private function countEmails(MessageEvents $events): int
  40. {
  41. $count = 0;
  42. foreach ($events->getEvents($this->transport) as $event) {
  43. if (
  44. ($this->queued && $event->isQueued())
  45. || (!$this->queued && !$event->isQueued())
  46. ) {
  47. ++$count;
  48. }
  49. }
  50. return $count;
  51. }
  52. }