You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
97 lines
2.9 KiB
PHP
97 lines
2.9 KiB
PHP
<?php
|
|
namespace App\Controller;
|
|
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
use Symfony\Component\HttpFoundation\Request;
|
|
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
|
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
|
|
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
|
|
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
|
|
|
use App\Entity\Pad;
|
|
use Doctrine\ORM\EntityManagerInterface;
|
|
|
|
|
|
Class PadController extends AbstractController
|
|
{
|
|
private function get_padform(){
|
|
return $this->createFormBuilder()
|
|
->add('content', TextareaType::class)
|
|
->add('save', SubmitType::class, ['label' => 'Enregistrer'])
|
|
->setAction($this->generateUrl('api_post_new'))
|
|
->getForm();
|
|
}
|
|
public function showForm(){
|
|
|
|
return $this->render('pad.html.twig', [
|
|
'head_title' => 'Créer un nouveau PAD',
|
|
'page_title' => 'Simple Pad',
|
|
'form' => $this->get_padform()->createView()
|
|
]);
|
|
}
|
|
public function view($name)
|
|
{
|
|
|
|
$pads = $this->getDoctrine()
|
|
->getRepository(Pad::class)
|
|
->findBy(array('name' => $name));
|
|
|
|
if(count($pads) == 0 )
|
|
{
|
|
throw new NotFoundHttpException('This pad does not exist');
|
|
}
|
|
|
|
$pad = $pads[0];
|
|
|
|
|
|
return $this->render('pad-view.html.twig', [
|
|
'head_title' => 'Pad id: ' . $pad->getName(),
|
|
'page_title' => 'Pad id: ' . $pad->getName(),
|
|
'pad_content' => $pad->getContent()
|
|
]);
|
|
}
|
|
private function get_free_name( $depth = 0, $length=6)
|
|
{
|
|
|
|
|
|
if($depth > 3 ){
|
|
throw new \UnexpectedValueException("I cant generate an unique key");
|
|
}
|
|
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
|
$randstring = '';
|
|
for ($i = 0; $i < $length; $i++) {
|
|
$randstring .= $characters[rand(0, strlen($characters) -1)];
|
|
}
|
|
|
|
$pads = $this->getDoctrine()
|
|
->getRepository(Pad::class)
|
|
->findBy(array('name' => $randstring));
|
|
if(count($pads) > 0){
|
|
return $this->get_free_name( $depth + 1);
|
|
}
|
|
return $randstring;
|
|
|
|
}
|
|
public function post(Request $request)
|
|
{
|
|
|
|
$form = $this->get_padform();
|
|
$form->handleRequest($request);
|
|
if ($form->isSubmitted() && $form->isValid()) {
|
|
$data = $form->getData();
|
|
//save the pad
|
|
$entityManager = $this->getDoctrine()->getManager();
|
|
$pad = new PAD();
|
|
$pad->setContent($data["content"])
|
|
->setName( $this-> get_free_name() );
|
|
$entityManager->persist($pad);
|
|
// actually executes the queries (i.e. the INSERT query)
|
|
$entityManager->flush();
|
|
return $this->redirectToRoute('view',["name" => $pad->getName() ]);
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
} |