EmailCount.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. private $expectedValue;
  16. private $transport;
  17. private $queued;
  18. public function __construct(int $expectedValue, string $transport = null, bool $queued = false)
  19. {
  20. $this->expectedValue = $expectedValue;
  21. $this->transport = $transport;
  22. $this->queued = $queued;
  23. }
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function toString(): string
  28. {
  29. return sprintf('%shas %s "%d" emails', $this->transport ? $this->transport.' ' : '', $this->queued ? 'queued' : 'sent', $this->expectedValue);
  30. }
  31. /**
  32. * @param MessageEvents $events
  33. *
  34. * {@inheritdoc}
  35. */
  36. protected function matches($events): bool
  37. {
  38. return $this->expectedValue === $this->countEmails($events);
  39. }
  40. /**
  41. * @param MessageEvents $events
  42. *
  43. * {@inheritdoc}
  44. */
  45. protected function failureDescription($events): string
  46. {
  47. return sprintf('the Transport %s (%d %s)', $this->toString(), $this->countEmails($events), $this->queued ? 'queued' : 'sent');
  48. }
  49. private function countEmails(MessageEvents $events): int
  50. {
  51. $count = 0;
  52. foreach ($events->getEvents($this->transport) as $event) {
  53. if (
  54. ($this->queued && $event->isQueued())
  55. ||
  56. (!$this->queued && !$event->isQueued())
  57. ) {
  58. ++$count;
  59. }
  60. }
  61. return $count;
  62. }
  63. }