1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace App\Contact; |
6
|
|
|
|
7
|
|
|
use Exception; |
8
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
9
|
|
|
use Psr\Log\LoggerInterface; |
10
|
|
|
use Yiisoft\Form\FormModelInterface; |
11
|
|
|
use Yiisoft\Mailer\MailerInterface; |
12
|
|
|
use Yiisoft\Session\Flash\FlashInterface; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* ContactMailer sends an email from the contact form |
16
|
|
|
*/ |
17
|
|
|
class ContactMailer |
18
|
|
|
{ |
19
|
6 |
|
private FlashInterface $flash; |
20
|
|
|
private LoggerInterface $logger; |
21
|
6 |
|
private MailerInterface $mailer; |
22
|
6 |
|
private string $to; |
23
|
6 |
|
|
24
|
|
|
public function __construct( |
25
|
2 |
|
FlashInterface $flash, |
26
|
|
|
LoggerInterface $logger, |
27
|
2 |
|
MailerInterface $mailer, |
28
|
2 |
|
string $to |
29
|
|
|
) { |
30
|
2 |
|
$this->flash = $flash; |
31
|
2 |
|
$this->logger = $logger; |
32
|
|
|
$this->mailer = $mailer; |
33
|
|
|
$this->to = $to; |
34
|
2 |
|
} |
35
|
2 |
|
|
36
|
2 |
|
public function send(FormModelInterface $form, ServerRequestInterface $request) |
37
|
|
|
{ |
38
|
2 |
|
$message = $this->mailer->compose( |
39
|
2 |
|
'contact', |
40
|
|
|
[ |
41
|
|
|
'content' => $form->getAttributeValue('body'), |
42
|
|
|
] |
43
|
|
|
) |
44
|
|
|
->setSubject($form->getAttributeValue('subject')) |
45
|
|
|
->setFrom([$form->getAttributeValue('email') => $form->getAttributeValue('name')]) |
46
|
|
|
->setTo($this->to); |
47
|
|
|
|
48
|
|
|
$attachFiles = $request->getUploadedFiles(); |
49
|
|
|
foreach ($attachFiles as $attachFile) { |
50
|
|
|
foreach ($attachFile as $file) { |
51
|
|
|
if ($file->getError() === UPLOAD_ERR_OK) { |
52
|
|
|
$message->attachContent( |
53
|
2 |
|
(string) $file->getStream(), |
54
|
2 |
|
[ |
55
|
|
|
'fileName' => $file->getClientFilename(), |
56
|
|
|
'contentType' => $file->getClientMediaType(), |
57
|
|
|
] |
58
|
|
|
); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
try { |
64
|
|
|
$message->send(); |
65
|
|
|
$flashMsg = 'Thanks to contact us, we\'ll get in touch with you as soon as possible.'; |
66
|
|
|
} catch (Exception $e) { |
67
|
|
|
$flashMsg = $e->getMessage(); |
68
|
|
|
$this->logger->error($flashMsg); |
69
|
|
|
} finally { |
70
|
|
|
$this->flash->add( |
71
|
|
|
isset($e) ? 'danger' : 'success', |
72
|
|
|
[ |
73
|
|
|
'body' => $flashMsg, |
|
|
|
|
74
|
|
|
], |
75
|
|
|
true |
76
|
|
|
); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|