1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Log\Target\Email; |
6
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use RuntimeException; |
9
|
|
|
use Throwable; |
10
|
|
|
use Yiisoft\Log\Target; |
11
|
|
|
use Yiisoft\Mailer\MailerInterface; |
12
|
|
|
|
13
|
|
|
use function wordwrap; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* EmailTarget sends selected log messages to the specified email addresses. |
17
|
|
|
* |
18
|
|
|
* {@see EmailTarget::$mailer} is instance of {@see MailerInterface} that sends email and should be already configured. |
19
|
|
|
*/ |
20
|
|
|
final class EmailTarget extends Target |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* @var string|string[] The receiver email address. |
24
|
|
|
* You may pass an array of addresses if multiple recipients should receive this message. |
25
|
|
|
* You may also specify receiver name in addition to email address using format: `[email => name]`. |
26
|
|
|
*/ |
27
|
|
|
private array|string $emailTo; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var string The email message subject. |
31
|
|
|
*/ |
32
|
|
|
private string $subjectEmail; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param MailerInterface $mailer The mailer instance. |
36
|
|
|
* @param string|string[] $emailTo The receiver email address. |
37
|
|
|
* You may pass an array of addresses if multiple recipients should receive this message. |
38
|
|
|
* You may also specify receiver name in addition to email address using format: `[email => name]`. |
39
|
|
|
* @param string $subjectEmail The email message subject. |
40
|
|
|
* |
41
|
|
|
* @throws InvalidArgumentException If the "to" email message argument is invalid. |
42
|
|
|
*/ |
43
|
|
|
public function __construct( |
44
|
|
|
private MailerInterface $mailer, |
45
|
|
|
array|string $emailTo, |
46
|
|
|
string $subjectEmail = '' |
47
|
|
|
) { |
48
|
|
|
if (empty($emailTo)) { |
49
|
|
|
throw new InvalidArgumentException('The "to" argument must be an array or string and must not be empty.'); |
50
|
|
|
} |
51
|
|
|
$this->emailTo = $emailTo; |
52
|
|
|
$this->subjectEmail = $subjectEmail ?: 'Application Log'; |
53
|
|
|
parent::__construct(); |
54
|
|
|
} |
55
|
11 |
|
|
56
|
|
|
/** |
57
|
|
|
* Sends log messages to specified email addresses. |
58
|
11 |
|
* |
59
|
7 |
|
* @throws RuntimeException If the log cannot be exported. |
60
|
|
|
*/ |
61
|
|
|
protected function export(): void |
62
|
4 |
|
{ |
63
|
4 |
|
$message = $this->mailer |
64
|
4 |
|
->compose() |
65
|
4 |
|
->withTo($this->emailTo) |
66
|
|
|
->withSubject($this->subjectEmail) |
67
|
|
|
->withTextBody(wordwrap($this->formatMessages("\n"), 70)) |
68
|
|
|
; |
69
|
|
|
|
70
|
|
|
try { |
71
|
|
|
$this->mailer->send($message); |
72
|
|
|
} catch (Throwable $e) { |
73
|
4 |
|
throw new RuntimeException('Unable to export log through email.', 0, $e); |
74
|
|
|
} |
75
|
4 |
|
} |
76
|
|
|
} |
77
|
|
|
|