BatchIterator.php
71 lines
| 1 | <?php // phpcs:ignore SlevomatCodingStandard.TypeHints.DeclareStrictTypes.DeclareStrictTypesMissing |
| 2 | |
| 3 | namespace MailPoet\Tasks\Subscribers; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use MailPoet\DI\ContainerWrapper; |
| 9 | use MailPoet\Newsletter\Sending\ScheduledTaskSubscribersRepository; |
| 10 | |
| 11 | /** |
| 12 | * @implements \Iterator<null, array> |
| 13 | */ |
| 14 | class BatchIterator implements \Iterator, \Countable { |
| 15 | private $taskId; |
| 16 | private $batchSize; |
| 17 | private $lastProcessedId = 0; |
| 18 | private $batchLastId; |
| 19 | |
| 20 | /** @var ScheduledTaskSubscribersRepository */ |
| 21 | private $scheduledTaskSubscribersRepository; |
| 22 | |
| 23 | public function __construct( |
| 24 | $taskId, |
| 25 | $batchSize |
| 26 | ) { |
| 27 | if ($taskId <= 0) { |
| 28 | throw new \Exception('Task ID must be greater than zero'); |
| 29 | } elseif ($batchSize <= 0) { |
| 30 | throw new \Exception('Batch size must be greater than zero'); |
| 31 | } |
| 32 | $this->taskId = (int)$taskId; |
| 33 | $this->batchSize = (int)$batchSize; |
| 34 | $this->scheduledTaskSubscribersRepository = ContainerWrapper::getInstance()->get(ScheduledTaskSubscribersRepository::class); |
| 35 | } |
| 36 | |
| 37 | public function rewind(): void { |
| 38 | $this->lastProcessedId = 0; |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * @return mixed - it's required for PHP8.1 to prevent using ReturnTypeWillChange that cause an error in PHPStan with PHP7 |
| 43 | */ |
| 44 | #[\ReturnTypeWillChange] |
| 45 | public function current() { |
| 46 | $subscribers = $this->scheduledTaskSubscribersRepository->getSubscriberIdsBatchForTask($this->taskId, $this->lastProcessedId, $this->batchSize); |
| 47 | $this->batchLastId = end($subscribers); |
| 48 | return $subscribers; |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * @return string|float|int|bool|null - it's required for PHP8.1 to prevent using ReturnTypeWillChange that cause an error in PHPStan with PHP7 |
| 53 | */ |
| 54 | #[\ReturnTypeWillChange] |
| 55 | public function key() { |
| 56 | return null; |
| 57 | } |
| 58 | |
| 59 | public function next(): void { |
| 60 | $this->lastProcessedId = $this->batchLastId; |
| 61 | } |
| 62 | |
| 63 | public function valid(): bool { |
| 64 | return $this->count() > 0; |
| 65 | } |
| 66 | |
| 67 | public function count(): int { |
| 68 | return max(0, $this->scheduledTaskSubscribersRepository->countSubscriberIdsBatchForTask($this->taskId, $this->lastProcessedId)); |
| 69 | } |
| 70 | } |
| 71 |