GenericMail.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace App\Mail;
  3. use Illuminate\Bus\Queueable;
  4. use Illuminate\Mail\Mailable;
  5. use Illuminate\Queue\SerializesModels;
  6. use Illuminate\Support\Collection;
  7. class GenericMail extends Mailable
  8. {
  9. use Queueable, SerializesModels;
  10. protected array $filesData = [];
  11. public function __construct(string $subjectLine, string $html, iterable $attachments = [])
  12. {
  13. $this->subject = $subjectLine;
  14. $this->html = $html;
  15. $items = $attachments instanceof Collection ? $attachments->all()
  16. : (is_array($attachments) ? $attachments : []);
  17. $this->filesData = array_values(array_map(function ($a) {
  18. if (is_object($a)) {
  19. $disk = $a->disk ?? null;
  20. $path = $a->path ?? null;
  21. $name = $a->name ?? null;
  22. } else {
  23. $disk = $a['disk'] ?? null;
  24. $path = $a['path'] ?? null;
  25. $name = $a['name'] ?? null;
  26. }
  27. return [
  28. 'disk' => $disk,
  29. 'path' => $path,
  30. 'name' => $name ?? ($path ? basename($path) : null),
  31. ];
  32. }, $items));
  33. }
  34. public function build()
  35. {
  36. $mail = $this->subject($this->subject)
  37. ->html($this->html);
  38. foreach ($this->filesData as $att) {
  39. $disk = $att['disk'] ?? null;
  40. $path = $att['path'] ?? null;
  41. $name = $att['name'] ?? ($path ? basename($path) : null);
  42. if ($disk && $path) {
  43. $mail->attachFromStorageDisk($disk, $path, $name);
  44. }
  45. }
  46. return $mail;
  47. }
  48. }