yiisoft /
yii-demo
| 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\File; |
||
| 12 | use Yiisoft\Mailer\MailerInterface; |
||
| 13 | use Yiisoft\Mailer\MessageBodyTemplate; |
||
| 14 | use Yiisoft\Session\Flash\FlashInterface; |
||
| 15 | |||
| 16 | /** |
||
| 17 | * ContactMailer sends an email from the contact form |
||
| 18 | */ |
||
| 19 | class ContactMailer |
||
| 20 | { |
||
| 21 | private FlashInterface $flash; |
||
| 22 | private LoggerInterface $logger; |
||
| 23 | private MailerInterface $mailer; |
||
| 24 | private string $to; |
||
| 25 | |||
| 26 | 6 | public function __construct( |
|
| 27 | FlashInterface $flash, |
||
| 28 | LoggerInterface $logger, |
||
| 29 | MailerInterface $mailer, |
||
| 30 | string $to |
||
| 31 | ) { |
||
| 32 | 6 | $this->flash = $flash; |
|
| 33 | 6 | $this->logger = $logger; |
|
| 34 | 6 | $this->mailer = $mailer->withTemplate(new MessageBodyTemplate(__DIR__ . '/mail/')); |
|
| 35 | 6 | $this->to = $to; |
|
| 36 | 6 | } |
|
| 37 | |||
| 38 | 2 | public function send(FormModelInterface $form, ServerRequestInterface $request) |
|
| 39 | { |
||
| 40 | 2 | $message = $this->mailer->compose( |
|
| 41 | 2 | 'contact-email', |
|
| 42 | [ |
||
| 43 | 2 | 'content' => $form->getAttributeValue('body'), |
|
| 44 | ] |
||
| 45 | ) |
||
| 46 | 2 | ->withSubject($form->getAttributeValue('subject')) |
|
| 47 | 2 | ->withFrom([$form->getAttributeValue('email') => $form->getAttributeValue('name')]) |
|
| 48 | 2 | ->withTo($this->to); |
|
| 49 | |||
| 50 | 2 | $attachFiles = $request->getUploadedFiles(); |
|
| 51 | 2 | foreach ($attachFiles as $attachFile) { |
|
| 52 | foreach ($attachFile as $file) { |
||
| 53 | if ($file->getError() === UPLOAD_ERR_OK) { |
||
| 54 | $message = $message->withAttached( |
||
| 55 | File::fromContent( |
||
| 56 | (string)$file->getStream(), |
||
| 57 | $file->getClientFilename(), |
||
| 58 | $file->getClientMediaType() |
||
| 59 | ), |
||
| 60 | ); |
||
| 61 | } |
||
| 62 | } |
||
| 63 | } |
||
| 64 | |||
| 65 | try { |
||
| 66 | 2 | $this->mailer->send($message); |
|
| 67 | 2 | $flashMsg = 'Thank you for contacting us, we\'ll get in touch with you as soon as possible.'; |
|
| 68 | } catch (Exception $e) { |
||
| 69 | $flashMsg = $e->getMessage(); |
||
| 70 | $this->logger->error($flashMsg); |
||
| 71 | 2 | } finally { |
|
| 72 | 2 | $this->flash->add( |
|
| 73 | 2 | isset($e) ? 'danger' : 'success', |
|
| 74 | [ |
||
| 75 | 2 | 'body' => $flashMsg, |
|
|
0 ignored issues
–
show
Comprehensibility
Best Practice
introduced
by
Loading history...
|
|||
| 76 | ], |
||
| 77 | 2 | true |
|
| 78 | ); |
||
| 79 | } |
||
| 80 | 2 | } |
|
| 81 | } |
||
| 82 |