1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ffcms\Core\Helper; |
4
|
|
|
|
5
|
|
|
use Ffcms\Core\App; |
6
|
|
|
use Ffcms\Core\Exception\SyntaxException; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class Mailer. Email send overlay over swiftmailer instance |
10
|
|
|
* @package Ffcms\Core\Helper |
11
|
|
|
*/ |
12
|
|
|
class Mailer |
13
|
|
|
{ |
14
|
|
|
/** @var \Swift_Mailer */ |
15
|
|
|
private $swift; |
16
|
|
|
private $from; |
17
|
|
|
|
18
|
|
|
private $message; |
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
|
|
|
* Set tpl file |
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
|
|
|
} |
55
|
|
|
return $this; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* Set mail to address |
60
|
|
|
* @param string $address |
61
|
|
|
* @param string $subject |
62
|
|
|
* @param null|string $message |
63
|
|
|
* @return bool |
64
|
|
|
*/ |
65
|
|
|
public function send(string $address, string $subject, ?string $message = null): bool |
66
|
|
|
{ |
67
|
|
|
// try to get message from global if not passed direct |
68
|
|
|
if ($message === null) { |
69
|
|
|
$message = $this->message; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
try { |
73
|
|
|
if ($message === null) { |
74
|
|
|
throw new \Exception('Message body is empty!'); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
// try to build message and send it |
78
|
|
|
$message = (new \Swift_Message($subject)) |
79
|
|
|
->setFrom($this->from) |
80
|
|
|
->setTo($address) |
81
|
|
|
->setBody($message, 'text/html'); |
82
|
|
|
$this->swift->send($message); |
83
|
|
|
return true; |
84
|
|
|
} catch (\Exception $e) { |
85
|
|
|
if (App::$Debug) { |
86
|
|
|
App::$Debug->addException($e); |
87
|
|
|
App::$Debug->addMessage('Send mail failed! Info: ' . $e->getMessage(), 'error'); |
88
|
|
|
} |
89
|
|
|
return false; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|