<?php
namespace App\Controller;
use App\Form\ContactType;
use App\Entity\Contact;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\EmailValidator;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Validation;
#[Route('/')]
class HomeController extends AbstractController
{
#[Route('/', name: 'app_home', methods: ['GET'])]
public function index(EntityManagerInterface $em): Response
{
return $this->redirectToRoute("app_dashboard");
}
#[Route('/contact', name: 'app_home_contact', methods: ['POST'])]
public function contact(EntityManagerInterface $em, Request $request, MailerInterface $mailer): Response
{
return $this->json(false);
$payload = json_decode($request->getContent(), true);
// check payload data
$valuesSet = isset($payload['name']) &&
isset($payload['email']) &&
isset($payload['message']);
if (!$valuesSet) {
return $this->json([
'error' => 'Invalid payload.'
]);
}
// check if values are valid
$validator = Validation::createValidator();
$nameValidator = $validator->validate($payload['name'], [
new NotBlank(),
]);
$emailValidator = $validator->validate($payload['email'], [
new Email(),
]);
$messageValidator = $validator->validate($payload['message'], [
new NotBlank(),
]);
if ($nameValidator->count() > 0 ||
$emailValidator->count() > 0 ||
$messageValidator->count() > 0
) {
return $this->json([
'error' => 'Invalid payload'
]);
}
$email = (new TemplatedEmail())
->from('btwebadmin@smart-device.ch')
->to('aris.konstantinidis@smart-advice.ch')
->subject('New bodytrip.app message')
->htmlTemplate('contact/contact.html.twig')
->context([
'name' => $payload['name'],
'message' => $payload['message'],
'emailAddress' => $payload['email'],
]);
try {
$mailer->send($email);
} catch (TransportExceptionInterface $e) {
return $this->json([
'error' => 'Something went wrong. Please contact us directly at aris.konstantinidis@smart-advice.ch.'
]);
}
return $this->json([
'success' => 'Thank you for your message. We will contact you asap'
]);
}
}