Snips/src/Controller/SnipController.php

78 lines
2.3 KiB
PHP

<?php
namespace App\Controller;
use App\Entity\Snip;
use App\Form\SnipType;
use App\Repository\SnipRepository;
use App\Service\SnipServiceFactory;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
#[Route('/snip', name: 'snip')]
class SnipController extends AbstractController
{
public function __construct(
private readonly SnipRepository $repository,
private readonly SnipServiceFactory $snipServiceFactory,
)
{
}
#[Route('/', name: '_index')]
public function index(): Response
{
return $this->render('snip/index.html.twig', [
'snips' => $this->repository->findByUser($this->getUser()),
]);
}
#[Route('/single/{snip}', name: '_single')]
public function single(Snip $snip): Response
{
return $this->render('snip/single.html.twig', [
'snip' => $snip,
'content' => $this->snipServiceFactory->create($snip)->get(),
]);
}
#[Route('/edit/{snip}', name: '_edit')]
public function edit(Snip $snip, Request $request): Response
{
$snipService = $this->snipServiceFactory->create($snip);
$form = $this->createForm(SnipType::class, $snip);
$form->get('content')->setData($snipService->get());
$form->add('Save', SubmitType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$snip->setCreatedAtTodayNoSeconds()
->setCreatedBy($this->getUser());
$this->repository->save($snip);
$snipService->update($form->get('content')->getData());
$this->addFlash('success', sprintf('Snip "%s" saved successfully', $snip));
return $this->redirectToRoute('snip_single', [
'snip' => $snip->getId(),
]);
}
return $this->render('snip/edit.html.twig', [
'snip' => $snip,
'form' => $form->createView(),
]);
}
#[Route('/new', name: '_new')]
public function new(Request $request): Response
{
$snip = new Snip();
return $this->edit($snip, $request);
}
}