Issues (39)

src/Console/Commands/EmailsSend.php (1 issue)

1
<?php
2
declare(strict_types=1);
3
4
namespace Nip\MailModule\Console\Commands;
5
6
use Exception;
7
use Nip\Records\Collections\Collection as RecordCollection;
8
9
/**
10
 * Class EmailsSend
11
 * @package Nip\MailModule\Console\Commands
12
 */
13
class EmailsSend extends EmailsAbstract
14
{
15
    /**
16
     * @return int
17
     */
18 1
    public function handle()
19
    {
20 1
        $sent = 0;
21 1
        $batchCount = 1;
22 1
        while ($sent < 10) {
23 1
            $sentEmails = $this->sendBatch($batchCount);
24 1
            if ($sentEmails === false) {
25 1
                return $sent;
26
            }
27 1
            $sent += $this->sendBatch($batchCount);
28 1
            $batchCount++;
29
        }
30
        return $sent;
31
    }
32
33
    /**
34
     * @param int $number
35
     * @return int|bool
36
     */
37 1
    protected function sendBatch($number = 1)
38
    {
39 1
        $emailsCount = 10;
40 1
        $emails = $this->getEmailsBatch($emailsCount, $emailsCount * ($number - 1));
41 1
        return $this->sendEmails($emails);
42
    }
43
44
    /**
45
     * @param RecordCollection $emails
46
     * @return int|bool
47
     */
48
    protected function sendEmails($emails)
49
    {
50
        if (count($emails) < 1) {
51
            return false;
52
        }
53
        $sent = 0;
54
        $recipients = 0;
0 ignored issues
show
The assignment to $recipients is dead and can be removed.
Loading history...
55
        foreach ($emails as $email) {
56
            echo 'send email [ID:' . $email->id . '][TO:' . implode(',', array_keys($email->getTos())) . ']';
57
            try {
58
                $recipients = $email->send();
59
                $sent++;
60
            } catch (Exception $exception) {
61
                echo $exception->getMessage();
62
//            die('');
63
            }
64
            echo '[R:' . $recipients . ']<br />' . "\n";
65
        }
66
        return $sent;
67
    }
68
69
    /**
70
     * @param int $count
71
     * @param int $offset
72
     * @return RecordCollection
73
     */
74
    protected function getEmailsBatch($count = 10, $offset = 0)
75
    {
76
        $emailsManager = $this->emailsManager();
77
        return $emailsManager->findByParams(
78
            [
79
                'where' => ['`sent` = \'no\' OR `sent` IS NULL OR `sent` = \'\' '],
80
                'limit' => $offset . ',' . $count,
81
            ]
82
        );
83
    }
84
}
85