pflaenz.li-Symfony/src/Controller/AppController.php
2021-04-30 19:23:01 +02:00

86 lines
2.7 KiB
PHP

<?php
namespace App\Controller;
use App\Entity\Offering;
use App\Form\OfferingFormType;
use App\Repository\OfferingRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Twig\Environment;
class AppController extends AbstractController
{
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
#[Route('/', name: 'homepage')]
public function index(Environment $twig, OfferingRepository $offeringRepository): Response
{
return new Response($twig->render('app/index.html.twig', [
'offerings' => $offeringRepository->findAll(),
]));
}
#[Route('/user', name: 'user_page')]
public function user(): Response
{
return $this->render('app/user.html.twig', [
'user' => $this->getUser(),
]);
}
#[Route('/new', name: 'new_listing')]
public function new_listing(Request $request, string $photoDir): Response
{
$offering = new Offering();
$form = $this->createForm(OfferingFormType::class, $offering);
$user = $this->getUser();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$offering->setByUser($user);
$offering->setCreatedAt(new \DateTime());
if ($photo = $form['photo']->getData()) {
$filename = bin2hex(random_bytes(6)).'.'.$photo->guessExtension();
try {
$photo->move($photoDir, $filename);
} catch (FileException $e) {
// unable to upload the photo, give up
$this->addFlash("error", "There was an error uploading the photo: ".$e);
return $this->redirectToRoute('new_listing');
}
$offering->setPhotoFilename($filename);
}
$this->entityManager->persist($offering);
$this->entityManager->flush();
$this->addFlash("success", "Successfully added the new offering!");
return $this->redirectToRoute('homepage');
}
return $this->render('app/new_listing.html.twig', [
'user' => $this->getUser(),
'offering_form' => $form->createView(),
]);
}
#[Route('/offer/{id}', name: 'show_offer')]
public function offer(): Response
{
return $this->render('app/offer.html.twig', [
'offer' => $this->getOffering(),
]);
}
}