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