ldc-legaulois/app/Mail/Contact.php
2021-02-15 17:48:49 +01:00

112 lines
2.9 KiB
PHP

<?php
namespace App\Mail;
use App\Exceptions\AbortContactMailer;
use App\Models\MailContactData;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\File;
use League\Csv\Writer;
use SplTempFileObject;
class Contact extends Mailable
{
use Queueable;
use SerializesModels;
/**
* The order instance.
*
* @var MailContactData
*/
protected $data;
/**
* Where to store CSV FilePath
*
* @var string
*/
protected $csvFilePath;
/**
* The joined file name
*
* @var string
*/
protected $joinedFileName;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct(MailContactData $data, string $csvFilePath)
{
$this->data = $data;
$this->csvFilePath = $csvFilePath;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
$this->joinFileIfProvided();
$this->makeCsvFile();
return $this
->subject(sprintf('Nouveau message consommateur Le Gaulois (%s)', $this->data->type->label))
->view('emails.contact')
->text('emails.contact-plain')
->with('data', $this->data)
->attach($this->csvFilePath, [
'as' => sprintf('contact_le_gaulois_%d.csv', time()),
'mime' => 'text/csv',
]);
}
/**
* Attach a joined file if given in data
*
* @return void
*/
protected function joinFileIfProvided()
{
if ($this->data->joinFile) {
$this->joinedFileName = sprintf(
'LEGAULOIS_PASS_MESSAGE-PJ-%s.%s',
date("YmdHis"),
$this->data->joinFile->extension()
);
$this->attach($this->data->joinFile, [
'as' => $this->joinedFileName,
'mime' => $this->data->joinFile->getMimeType()
]);
$this->data->joinFile = $this->joinedFileName;
}
}
protected function makeCsvFile()
{
//we create the CSV into memory
// FILENAME
$csv = Writer::createFromFileObject(new SplTempFileObject());
$csv->setDelimiter(';');
//we insert the CSV header
$csv->insertOne([
'EMETTEUR_DATE', 'EMETTEUR_HEURE', 'EMETTEUR_CIVILITE', 'EMETTEUR_NOM', 'EMETTEUR_PRENOM',
'EMETTEUR_ADRESSE', 'EMETTEUR_CP', 'EMETTEUR_VILLE', 'EMETTEUR_EMAIL', 'EMETTEUR_OBJETDEMANDE',
'EMETTEUR_MESSAGE', 'EMETTEUR_CATEGORIE', 'EMETTEUR_ACTIVITE', 'REPONSE_ETAT', 'TYPE_REPONSE'
]);
$csv->insertOne($this->data->exportToArcadiaDataArray());
if (!File::put($this->csvFilePath, $csv->getContent())) {
throw new AbortContactMailer(sprintf('Could save create %s', $this->csvFilePath));
}
}
}