1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ffcms\Core\Helper; |
4
|
|
|
use Ffcms\Core\App; |
5
|
|
|
use Ffcms\Core\Exception\SyntaxException; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Class Mailer. Email send overlay over swiftmailer instance |
9
|
|
|
* @package Ffcms\Core\Helper |
10
|
|
|
*/ |
11
|
|
|
class Mailer |
12
|
|
|
{ |
13
|
|
|
/** @var \Swift_Mailer */ |
14
|
|
|
private $swift; |
15
|
|
|
private $from; |
16
|
|
|
|
17
|
|
|
private $message; |
18
|
|
|
private $tpl; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Mailer constructor. Construct object with ref to swiftmailer and sender info |
22
|
|
|
* @param \Swift_Mailer $instance |
23
|
|
|
* @param string $from |
24
|
|
|
*/ |
25
|
|
|
public function __construct(\Swift_Mailer $instance, string $from) |
26
|
|
|
{ |
27
|
|
|
$this->swift = $instance; |
28
|
|
|
$this->from = $from; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Factory constructor |
33
|
|
|
* @param \Swift_Mailer $instance |
34
|
|
|
* @param string $from |
35
|
|
|
* @return Mailer |
36
|
|
|
*/ |
37
|
|
|
public static function factory(\Swift_Mailer $instance, string $from) |
38
|
|
|
{ |
39
|
|
|
return new self($instance, $from); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* |
44
|
|
|
* @param string $tpl |
45
|
|
|
* @param array|null $params |
46
|
|
|
* @param null|string $dir |
47
|
|
|
* @return $this |
48
|
|
|
*/ |
49
|
|
|
public function tpl(string $tpl, ?array $params = [], ?string $dir = null) |
50
|
|
|
{ |
51
|
|
|
try { |
52
|
|
|
$this->message = App::$View->render($tpl, $params, $dir); |
53
|
|
|
} catch (SyntaxException $e){} |
|
|
|
|
54
|
|
|
return $this; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function send(string $to, string $subject, ?string $message = null) |
58
|
|
|
{ |
59
|
|
|
// try to get message from global if not passed direct |
60
|
|
|
if ($message === null) |
61
|
|
|
$message = $this->message; |
62
|
|
|
|
63
|
|
|
try { |
64
|
|
|
if ($message === null) |
65
|
|
|
throw new \Exception('Message body is empty!'); |
66
|
|
|
|
67
|
|
|
// try to build message and send it |
68
|
|
|
$message = (new \Swift_Message($subject)) |
69
|
|
|
->setFrom($this->from) |
70
|
|
|
->setTo($to) |
71
|
|
|
->setBody($message); |
72
|
|
|
$this->swift->send($message); |
73
|
|
|
} catch (\Exception $e) { |
74
|
|
|
if (App::$Debug) { |
75
|
|
|
App::$Debug->addException($e); |
76
|
|
|
App::$Debug->addMessage('Send mail failed! Info: ' . $e->getMessage(), 'error'); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
} |