src/Controller/ShopController.php line 36
<?php
namespace App\Controller;
use App\Entity\Shop;
use App\Entity\User;
use App\Form\ShopType;
use App\Form\AdditionalShopType;
use App\Repository\ShopRepository;
use Symfony\Component\Mime\Address;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
#[Route('/shop')]
class ShopController extends AbstractController
{
#[Route('/', name: 'app_shop_index', methods: ['GET'])]
public function index(ShopRepository $shopRepository): Response
{
return $this->render('shop/index.html.twig', [
'shops' => $shopRepository->findAll(),
]);
}
#[Route('/new', name: 'app_shop_new', methods: ['GET', 'POST'])]
public function new(
Request $request,
ShopRepository $shopRepository,
ValidatorInterface $validator,
EntityManagerInterface $entityManager,
MailerInterface $mailer,
UserPasswordHasherInterface $passwordHasher
): Response {
$shop = new Shop();
$user = new User();
$shop->setUsers($user); // Lie les deux entités ensemble
$form = $this->createForm(ShopType::class, $shop);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$plaintextPassword = $user->getPassword();
$hashedPassword = $passwordHasher->hashPassword($user, $plaintextPassword);
$user->setPassword($hashedPassword);
// Récupérer les coordonnées géographiques
if ($shop->getMyBusiness() !== null) {
$apiKey = 'AIzaSyCM1n8TZCulTKvvFnaznr_sEodEXxrL44A'; // Clé API Google Places
// Récupération de l'ID du commerce
$placeId = $shop->getMyBusiness(); // Assurez-vous d'avoir la méthode getMyBusiness() dans l'entité Shop
// Construction de l'URL de l'API Google Places
$apiUrl = "https://maps.googleapis.com/maps/api/place/details/json?place_id=$placeId&key=$apiKey&language=fr";
//dd($apiUrl);
// Utilisation de cURL pour effectuer la requête HTTP
$httpClient = HttpClient::create();
$response = $httpClient->request('GET', $apiUrl);
if ($response->getStatusCode() === 200) {
$data = json_decode($response->getContent(), true);
$latitude = $data['result']['geometry']['location']['lat'];
$longitude = $data['result']['geometry']['location']['lng'];
$phoneNumber = $data['result']['formatted_phone_number'];
$website = $data['result']['website'];
// Pour la mise en place du persist de l'adresse
$addressComponents = $data['result']['address_components'];
$address_street = '';
$address_postal_code = '';
$address_city = '';
if (in_array("street_number", $addressComponents[0]['types'])) {
$address_street = $addressComponents[0]['long_name'] . " " . $addressComponents[1]['long_name'];
} else {
$address_street = $addressComponents[0]['long_name'];
}
foreach ($addressComponents as $component) {
$types = $component['types'];
if (in_array('postal_code', $types)) {
$address_postal_code = $component['long_name'];
} elseif (in_array('locality', $types)) {
$address_city = $component['long_name'];
}
}
// Persistez dans l'entité Shop
$shop->setLatitude($latitude);
$shop->setLongitude($longitude);
$shop->setPhoneNumber($phoneNumber);
$shop->setWebsite($website);
$shop->setAdressStreet($address_street);
$shop->setAddressPostalCode($address_postal_code);
$shop->setAddressCity($address_city);
}
$shopRepository->save($shop, true);
// début de l'envoi de l'email de confirmation
$email = (new TemplatedEmail())
->from(new Address('contact@bestof.ovh', 'Bestof contact'))
->to($user->getEmail())
->subject('Bienvenue sur Best of Sarlat')
->htmlTemplate('shop/emailInscription.html.twig')
->context(['user' => $user]);
$mailer->send($email);
// fin de l'envoi de l'email de confirmation
// Afficher le message de confirmation
$this->addFlash('success', 'Merci pour votre inscription !');
return $this->redirectToRoute('app_home_list', [], Response::HTTP_SEE_OTHER);
}
}
return $this->render('shop/new.html.twig', [
'shop' => $shop,
'form' => $form->createView(),
'user' => $user,
]);
}
#[Route('/nouveau-commerce', name: 'app_shop_additional', methods: ['GET', 'POST'])]
public function newAdditional(
Request $request,
ShopRepository $shopRepository,
): Response {
$shop = new Shop();
$form = $this->createForm(AdditionalShopType::class, $shop);
$form->handleRequest($request);
// Récupérer les coordonnées géographiques
if ($shop->getMyBusiness() !== null) {
$apiKey = 'AIzaSyCM1n8TZCulTKvvFnaznr_sEodEXxrL44A'; // Clé API Google Places
// Récupération de l'ID du commerce
$placeId = $shop->getMyBusiness(); // Assurez-vous d'avoir la méthode getMyBusiness() dans l'entité Shop
// Construction de l'URL de l'API Google Places
$apiUrl = "https://maps.googleapis.com/maps/api/place/details/json?place_id=$placeId&key=$apiKey&language=fr";
//dd($apiUrl);
// Utilisation de cURL pour effectuer la requête HTTP
$httpClient = HttpClient::create();
$response = $httpClient->request('GET', $apiUrl);
if ($response->getStatusCode() === 200) {
$data = json_decode($response->getContent(), true);
$latitude = $data['result']['geometry']['location']['lat'];
$longitude = $data['result']['geometry']['location']['lng'];
$phoneNumber = $data['result']['formatted_phone_number'];
$website = $data['result']['website'];
// Pour la mise en place du persist de l'adresse
$addressComponents = $data['result']['address_components'];
$address_street = '';
$address_postal_code = '';
$address_city = '';
if (in_array("street_number", $addressComponents[0]['types'])) {
$address_street = $addressComponents[0]['long_name'] . " " . $addressComponents[1]['long_name'];
} else {
$address_street = $addressComponents[0]['long_name'];
}
foreach ($addressComponents as $component) {
$types = $component['types'];
if (in_array('postal_code', $types)) {
$address_postal_code = $component['long_name'];
} elseif (in_array('locality', $types)) {
$address_city = $component['long_name'];
}
}
// Persistez dans l'entité Shop
$shop->setLatitude($latitude);
$shop->setLongitude($longitude);
$shop->setPhoneNumber($phoneNumber);
$shop->setWebsite($website);
$shop->setAdressStreet($address_street);
$shop->setAddressPostalCode($address_postal_code);
$shop->setAddressCity($address_city);
}
$shopRepository->save($shop, true);
// Afficher le message de confirmation
$this->addFlash('success', 'Merci pour votre ajout de commerce !');
return $this->redirectToRoute('app_home_list', [], Response::HTTP_SEE_OTHER);
}
return $this->render('shop/newShopOnly.html.twig', [
'shop' => $shop,
'form' => $form->createView(),
]);
}
#[Route('/{id}', name: 'app_shop_show', methods: ['GET'])]
public function show(Shop $shop): Response
{
return $this->render('shop/show.html.twig', [
'shop' => $shop,
]);
}
#[Route('/{id}/edit', name: 'app_shop_edit', methods: ['GET', 'POST'])]
public function edit(Request $request, Shop $shop, ShopRepository $shopRepository): Response
{
$form = $this->createForm(ShopType::class, $shop);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$shopRepository->save($shop, true);
return $this->redirectToRoute('app_shop_index', [], Response::HTTP_SEE_OTHER);
}
return $this->render('shop/edit.html.twig', [
'shop' => $shop,
'form' => $form,
]);
}
#[Route('/{id}', name: 'app_shop_delete', methods: ['POST'])]
public function delete(Request $request, Shop $shop, ShopRepository $shopRepository): Response
{
if ($this->isCsrfTokenValid('delete'.$shop->getId(), $request->request->get('_token'))) {
$shopRepository->remove($shop, true);
}
return $this->redirectToRoute('app_shop_index', [], Response::HTTP_SEE_OTHER);
}
}