Skip to content

Commit

Permalink
Merge tag v2.3.18 into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
roadiz-ci committed Jul 5, 2024
1 parent 81fdcb8 commit 91b0854
Show file tree
Hide file tree
Showing 15 changed files with 311 additions and 147 deletions.
12 changes: 12 additions & 0 deletions config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,18 @@ services:
RZ\Roadiz\CoreBundle\Mailer\EmailManager:
# Recreate manager for each usage
shared: false
deprecated:
message: 'The "%service_id%" service is deprecated and will be removed in Roadiz 3.0. Use RZ\Roadiz\CoreBundle\Mailer\EmailManagerFactory instead.'
package: roadiz/core-bundle
version: '2.3.18'

RZ\Roadiz\CoreBundle\Mailer\ContactFormManager:
# Recreate manager for each usage
shared: false
deprecated:
message: 'The "%service_id%" service is deprecated and will be removed in Roadiz 3.0. Use RZ\Roadiz\CoreBundle\Mailer\ContactFormManagerFactory instead.'
package: roadiz/core-bundle
version: '2.3.18'

RZ\Roadiz\CoreBundle\Doctrine\EventSubscriber\:
resource: '../src/Doctrine/EventSubscriber'
Expand Down
6 changes: 3 additions & 3 deletions src/Console/MailerTestCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace RZ\Roadiz\CoreBundle\Console;

use RZ\Roadiz\CoreBundle\Mailer\EmailManager;
use RZ\Roadiz\CoreBundle\Mailer\EmailManagerFactory;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
Expand All @@ -16,7 +16,7 @@
final class MailerTestCommand extends Command
{
public function __construct(
private readonly EmailManager $emailManager,
private readonly EmailManagerFactory $emailManagerFactory,
?string $name = null
) {
parent::__construct($name);
Expand All @@ -37,7 +37,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$to = Address::create($input->getArgument('email'));
$from = Address::create($input->getOption('from') ?? '[email protected]');

$this->emailManager
$this->emailManagerFactory->create()
->setReceiver($to)
->setSender($from)
// Uses email_sender customizable setting
Expand Down
6 changes: 4 additions & 2 deletions src/Controller/CustomFormController.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,7 @@ public function addAction(Request $request, int $customFormId): Response
);

if ($mixed instanceof Response) {
$mixed->prepare($request);
return $mixed->send();
return $mixed;
} else {
return $this->render('@RoadizCore/customForm/customForm.html.twig', $mixed);
}
Expand Down Expand Up @@ -231,6 +230,9 @@ private function prepareAndHandleCustomFormAssignation(
throw new \RuntimeException('Answer ID is null');
}

if (null === $emailSender || false === filter_var($answer->getEmail(), FILTER_VALIDATE_EMAIL)) {
$emailSender = $answer->getEmail();
}
if (null === $emailSender || false === filter_var($emailSender, FILTER_VALIDATE_EMAIL)) {
$emailSender = $this->settingsBag->get('email_sender');
}
Expand Down
123 changes: 63 additions & 60 deletions src/CustomForm/CustomFormHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,81 +75,84 @@ public function parseAnswerFormData(
CustomFormAnswer $answer = null,
string $ipAddress = ""
): CustomFormAnswer {
if ($form->isSubmitted() && $form->isValid()) {
if (!$form->isSubmitted()) {
throw new \InvalidArgumentException('Form must be submitted before begin parsing.');
}
if (!$form->isValid()) {
throw new \InvalidArgumentException('Form must be validated before begin parsing.');
}

/*
* Create answer if null.
*/
if (null === $answer) {
$answer = new CustomFormAnswer();
$answer->setCustomForm($this->customForm);
$this->em->persist($answer);
}
$answer->setSubmittedAt(new \DateTime());
$answer->setIp($ipAddress);
$documentsUploaded = [];

/** @var CustomFormField $customFormField */
foreach ($this->customForm->getFields() as $customFormField) {
$formField = null;
$fieldAttr = null;

/*
* Create answer if null.
* Get data in form groups
*/
if (null === $answer) {
$answer = new CustomFormAnswer();
$answer->setCustomForm($this->customForm);
$this->em->persist($answer);
if ($customFormField->getGroupName() != '') {
$groupCanonical = StringHandler::slugify($customFormField->getGroupName());
$formGroup = $form->get($groupCanonical);
if ($formGroup->has($customFormField->getName())) {
$formField = $formGroup->get($customFormField->getName());
$fieldAttr = $this->getAttribute($answer, $customFormField);
}
} else {
if ($form->has($customFormField->getName())) {
$formField = $form->get($customFormField->getName());
$fieldAttr = $this->getAttribute($answer, $customFormField);
}
}
$answer->setSubmittedAt(new \DateTime());
$answer->setIp($ipAddress);
$documentsUploaded = [];

/** @var CustomFormField $customFormField */
foreach ($this->customForm->getFields() as $customFormField) {
$formField = null;
$fieldAttr = null;

if (null !== $formField) {
$data = $formField->getData();
/*
* Get data in form groups
*/
if ($customFormField->getGroupName() != '') {
$groupCanonical = StringHandler::slugify($customFormField->getGroupName());
$formGroup = $form->get($groupCanonical);
if ($formGroup->has($customFormField->getName())) {
$formField = $formGroup->get($customFormField->getName());
$fieldAttr = $this->getAttribute($answer, $customFormField);
}
} else {
if ($form->has($customFormField->getName())) {
$formField = $form->get($customFormField->getName());
$fieldAttr = $this->getAttribute($answer, $customFormField);
}
* Create attribute if null.
*/
if (null === $fieldAttr) {
$fieldAttr = new CustomFormFieldAttribute();
$fieldAttr->setCustomFormAnswer($answer);
$fieldAttr->setCustomFormField($customFormField);
$this->em->persist($fieldAttr);
}

if (null !== $formField) {
$data = $formField->getData();
/*
* Create attribute if null.
*/
if (null === $fieldAttr) {
$fieldAttr = new CustomFormFieldAttribute();
$fieldAttr->setCustomFormAnswer($answer);
$fieldAttr->setCustomFormField($customFormField);
$this->em->persist($fieldAttr);
}

if (is_array($data) && isset($data[0]) && $data[0] instanceof UploadedFile) {
/** @var UploadedFile $file */
foreach ($data as $file) {
$documentsUploaded[] = $this->handleUploadedFile($file, $fieldAttr);
}
} elseif ($data instanceof UploadedFile) {
$documentsUploaded[] = $this->handleUploadedFile($data, $fieldAttr);
} else {
$fieldAttr->setValue($this->formValueToString($data));
if (is_array($data) && isset($data[0]) && $data[0] instanceof UploadedFile) {
/** @var UploadedFile $file */
foreach ($data as $file) {
$documentsUploaded[] = $this->handleUploadedFile($file, $fieldAttr);
}
} elseif ($data instanceof UploadedFile) {
$documentsUploaded[] = $this->handleUploadedFile($data, $fieldAttr);
} else {
$fieldAttr->setValue($this->formValueToString($data));
}
}
}

$this->em->flush();
$this->em->flush();

// Dispatch event on document uploaded
foreach ($documentsUploaded as $documentUploaded) {
if ($documentUploaded instanceof DocumentInterface) {
$this->eventDispatcher->dispatch(new DocumentCreatedEvent($documentUploaded));
}
// Dispatch event on document uploaded
foreach ($documentsUploaded as $documentUploaded) {
if ($documentUploaded instanceof DocumentInterface) {
$this->eventDispatcher->dispatch(new DocumentCreatedEvent($documentUploaded));
}

$this->em->refresh($answer);

return $answer;
}

throw new \InvalidArgumentException('Form must be submitted and validated before begin parsing.');
$this->em->refresh($answer);

return $answer;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
use RZ\Roadiz\CoreBundle\Bag\Settings;
use RZ\Roadiz\CoreBundle\CustomForm\Message\CustomFormAnswerNotifyMessage;
use RZ\Roadiz\CoreBundle\Entity\CustomFormAnswer;
use RZ\Roadiz\CoreBundle\Mailer\EmailManager;
use RZ\Roadiz\CoreBundle\Mailer\EmailManagerFactory;
use RZ\Roadiz\Documents\Models\DocumentInterface;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
Expand All @@ -26,10 +26,10 @@ final class CustomFormAnswerNotifyMessageHandler
{
public function __construct(
private readonly ManagerRegistry $managerRegistry,
private readonly EmailManager $emailManager,
private readonly EmailManagerFactory $emailManagerFactory,
private readonly Settings $settingsBag,
private readonly FilesystemOperator $documentsStorage,
private readonly LoggerInterface $logger,
private readonly LoggerInterface $messengerLogger,
) {
}

Expand All @@ -52,12 +52,6 @@ public function __invoke(CustomFormAnswerNotifyMessage $message): void
$answer->toArray(false)
);

$receiver = array_filter(
array_map('trim', explode(',', $answer->getCustomForm()->getEmail() ?? ''))
);
$receiver = array_map(function (string $email) {
return new Address($email);
}, $receiver);
$this->sendAnswer(
$answer,
[
Expand All @@ -66,60 +60,83 @@ public function __invoke(CustomFormAnswerNotifyMessage $message): void
'customForm' => $answer->getCustomForm(),
'title' => $message->getTitle(),
'requestLocale' => $message->getLocale(),
],
$receiver
]
);
}

/**
* @return Address[]
*/
private function getCustomFormReceivers(CustomFormAnswer $answer): array
{
$receiver = array_filter(
array_map('trim', explode(',', $answer->getCustomForm()->getEmail() ?? ''))
);
return array_map(function (string $email) {
return new Address($email);
}, $receiver);
}

/**
* Send an answer form by Email.
*
* @param CustomFormAnswer $answer
* @param array $assignation
* @param string|array|null $receiver
* @throws TransportExceptionInterface
* @throws LoaderError
* @throws RuntimeError
* @throws SyntaxError
*/
private function sendAnswer(
CustomFormAnswer $answer,
array $assignation,
$receiver
array $assignation
): void {
$defaultSender = $this->settingsBag->get('email_sender');
$defaultSender = !empty($defaultSender) ? $defaultSender : '[email protected]';
$this->emailManager->setAssignation($assignation);
$this->emailManager->setEmailTemplate('@RoadizCore/email/forms/answerForm.html.twig');
$this->emailManager->setEmailPlainTextTemplate('@RoadizCore/email/forms/answerForm.txt.twig');
$this->emailManager->setSubject($assignation['title']);
$this->emailManager->setEmailTitle($assignation['title']);
$this->emailManager->setSender($defaultSender);
$defaultSender = filter_var($defaultSender, FILTER_VALIDATE_EMAIL) ? $defaultSender : '[email protected]';
$receivers = $this->getCustomFormReceivers($answer);

$realSender = filter_var($answer->getEmail(), FILTER_VALIDATE_EMAIL) ? $answer->getEmail() : $defaultSender;
$emailManager = $this->emailManagerFactory->create();
$emailManager->setAssignation($assignation);
$emailManager->setEmailTemplate('@RoadizCore/email/forms/answerForm.html.twig');
$emailManager->setEmailPlainTextTemplate('@RoadizCore/email/forms/answerForm.txt.twig');
$emailManager->setSubject($assignation['title']);
$emailManager->setEmailTitle($assignation['title']);
$emailManager->setSender($realSender);

try {
foreach ($answer->getAnswerFields() as $customFormAnswerAttr) {
/** @var DocumentInterface $document */
foreach ($customFormAnswerAttr->getDocuments() as $document) {
$this->emailManager->addResource(
$emailManager->addResource(
$this->documentsStorage->readStream($document->getMountPath()),
$document->getFilename(),
$this->documentsStorage->mimeType($document->getMountPath())
);
$this->messengerLogger->debug(sprintf(
'Joining document %s to email.',
$document->getFilename()
));
}
}
} catch (FilesystemException $exception) {
$this->logger->error($exception->getMessage(), [
$this->messengerLogger->error($exception->getMessage(), [
'entity' => $answer
]);
}

if (empty($receiver)) {
$this->emailManager->setReceiver($defaultSender);
if (empty($receivers)) {
$emailManager->setReceiver($defaultSender);
} else {
$this->emailManager->setReceiver($receiver);
$emailManager->setReceiver($receivers);
}

// Send the message
$this->emailManager->send();
$emailManager->send();
$this->messengerLogger->debug(sprintf(
'CustomForm (%s) answer sent to %s',
$answer->getCustomForm()->getName(),
$realSender
));
}
}
5 changes: 3 additions & 2 deletions src/Document/MessageHandler/DocumentPdfMessageHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,13 @@ protected function extractPdfThumbnail(DocumentInterface $document, string $loca
}
}
} catch (\ImagickException $exception) {
throw new UnrecoverableMessageHandlingException(
// Silent fail to avoid issue with message handling
$this->messengerLogger->warning(
sprintf(
'Cannot extract thumbnail from %s PDF file : %s',
$localPdfPath,
$exception->getMessage()
),
)
);
}
}
Expand Down
1 change: 0 additions & 1 deletion src/Entity/CustomFormAnswer.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,6 @@ public function setSubmittedAt(\DateTime $submittedAt): CustomFormAnswer

/**
* @return string|null
* @throws \Exception
*/
public function getEmail(): ?string
{
Expand Down
3 changes: 1 addition & 2 deletions src/Entity/CustomFormFieldAttribute.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class CustomFormFieldAttribute extends AbstractEntity
* @var Collection<int, Document>
*/
#[
ORM\ManyToMany(targetEntity: "RZ\Roadiz\CoreBundle\Entity\Document", inversedBy: "customFormFieldAttributes"),
ORM\ManyToMany(targetEntity: Document::class, inversedBy: "customFormFieldAttributes"),
ORM\JoinTable(name: "custom_form_answers_documents"),
ORM\JoinColumn(name: "customformfieldattribute_id", onDelete: "CASCADE"),
ORM\InverseJoinColumn(name: "document_id", onDelete: "CASCADE")
Expand Down Expand Up @@ -132,7 +132,6 @@ public function getDocuments(): Collection
public function setDocuments(Collection $documents): CustomFormFieldAttribute
{
$this->documents = $documents;

return $this;
}
}
Loading

0 comments on commit 91b0854

Please sign in to comment.