-
Notifications
You must be signed in to change notification settings - Fork 2
/
EmailTarget.php
94 lines (85 loc) · 2.59 KB
/
EmailTarget.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
/**
* Created by PhpStorm.
* User: zura
* Date: 3/28/18
* Time: 11:28 AM
*/
namespace apollo11\logger;
use Yii;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\di\Instance;
use yii\mail\MailerInterface;
/**
* 'components' => [
* 'log' => [
* 'targets' => [
* [
* 'class' => apollo11\logger\EmailTarget::class,
* 'levels' => ['error'],
* 'excludeKeys' => [],
* 'message' => [
* 'to' => '[email protected]',
* 'from' => '[email protected]',
* 'subject' => 'Apollo11 Error Logger',
* ]
* ],
* ],
* ],
* ],
*
*/
class EmailTarget extends Target
{
/**
* @var array
*/
public $message = [];
/**
* @var MailerInterface|array|string the mailer object or the application component ID of the mailer object.
* After the EmailTarget object is created, if you want to change this property, you should only assign it
* with a mailer object.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $mailer = 'mailer';
/**
* {@inheritdoc}
* @throws InvalidConfigException
*/
public function init()
{
parent::init();
if (empty($this->message['to'])) {
throw new InvalidConfigException('The "to" option must be set for EmailTarget::message.');
}
$this->mailer = Instance::ensure($this->mailer, 'yii\mail\MailerInterface');
}
/**
*
*
* @author Zura Sekhniashvili <[email protected]>
* @throws InvalidConfigException
* @throws Exception
*/
public function sendMessage()
{
if (!isset($this->config['formattedMessage'])){
throw new InvalidConfigException('`formattedMessage` was not found in $config object. Maybe you forgot to call ->prepareConfig() method?');
}
// https://github.com/yiisoft/yii2/issues/1446
if (empty($this->message['subject'])) {
$this->message['subject'] = 'Application Log';
}
$message = Yii::$app->mailer->compose();
Yii::configure($message, $this->message);
$message->setTextBody($this->config['formattedMessage']);
if (!$message->send($this->mailer)) {
throw new Exception('Unable to export log through email!');
}
}
protected function prepareConfig()
{
$this->config['formattedMessage'] = $this->getFormatMessage();
}
}