<?php
namespace App\Ox\HoardBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\ButtonType;
use App\Ox\HoardBundle\Entity\Container;
use App\Ox\HoardBundle\Entity\ContainerImage;
use App\Ox\HoardBundle\Entity\Image;
use App\Ox\HoardBundle\Form\ContainerType;
/**
* Container controller
*
* @Route("/container")
*/
class ContainerController extends AbstractController
{
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* @Route("/{id}/edit", name="container_edit", methods={"GET"})
* @Template()
*/
public function editAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$em->getFilters()->enable('softdeleteable');
$container = $em->getRepository('OxHoardBundle:Container')->find($id);
if(!$container) {
throw $this->createNotFoundException('Unable to find container entity.');
}
// $deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($container);
$isAjax = $request->isXmlHttpRequest();
$template = ($isAjax ? '@OxHoardBundle/container/edit_form.html.twig' : '@OxHoardBundle/container/edit.html.twig');
return $this->render($template, array(
'ajax' => $request->isXmlHttpRequest(),
'container' => $container,
'edit_form' => $editForm->createView(),
// 'delete_form' => $deleteForm->createView(),
));
}
/**
* Creates a form to delete an Container entity by id.
*
* @param mixed $id The entity id
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('container_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', ButtonType::class, array(
'label' => 'Delete',
'attr' => array(
'class' => 'delete-button btn-danger'
)))
->getForm()
;
}
/**
* Creates a form to edit an Container entity.
*
* @param Container $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Container $entity)
{
$form = $this->createForm(ContainerType::class, $entity, array(
'action' => $this->generateUrl('container_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', SubmitType::class, array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Container entity.
*
* @Route("/{id}", name="container_update", methods={"PUT"}) PUT doesn't seem to work...
* @Template("@OxHoardBundle/container/edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$em->getFilters()->enable('softdeleteable');
$container = $em->getRepository('OxHoardBundle:Container')->find($id);
if (!$container) {
throw $this->createNotFoundException('Unable to find Container entity.');
}
// $deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($container);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
//persist the containers
foreach($container->getLayers() as $layer)
{
$layer->setContainer($container);
$em->persist($layer);
}
//mark as unvalidated since it has changed
if(!$this->userIsAdmin())
{
$container->getHoard()->markUnvalidatedByAdmin();
}
$em->flush();
return $this->redirect($this->generateUrl('container_edit', array('id' => $id)));
}
return array(
'container' => $container,
'edit_form' => $editForm->createView(),
// 'delete_form' => $deleteForm->createView(),
);
}
/**
* Container root placeholder.
*
* @Route("/", name="container", methods={"GET"})
* @Template()
*/
public function indexAction(Request $request)
{
// $limit = 20;
// $em = $this->getDoctrine()->getManager();
// $em->getFilters()->enable('softdeleteable');
//
// $dql = 'SELECT c FROM OxHoardBundle:Container c';
// $query = $em->createQuery($dql)
// ->setFirstResult(0)
// ->setMaxResults($limit);
//
// $paginator = $this->get('knp_paginator');
//
// $pagination = $paginator->paginate(
// $query,
// $request->query->getInt('page', 1)/*page number*/,
// $limit/*limit per page*/
// );
// parameters to template
// return $this->render('@OxHoardBundle/container/index.html.twig', array('pagination' => $pagination));
return $this->render('@OxHoardBundle/container/index.html.twig');
}
/**
* Finds and displays a container entity.
*
* @Route("/{id}", name="container_show", methods={"GET"})
* @Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$container = $em->getRepository('OxHoardBundle:Container')->find($id);
$this->checkAccess($container, 'view');
if (!$container) {
throw $this->createNotFoundException('Unable to find container entity.');
}
$objects = $em->getRepository('OxHoardBundle:HObject')->findBy(array(
'container' => $id,
));
return array(
'container' => $container,
'objects' => $objects,
);
}
/**
* Adds a new image file, creating an Image entity, and a ContainerImage entity
*
* @Route("/{id}/ajax_add_image", methods={"POST"})
*/
public function ajaxAddImage(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$file = $request->files->get('image');
$container = $em->getRepository('OxHoardBundle:Container')->find($id);
//validate the file - TODO
$this->checkAccess($container, 'edit');
//move to desired location/name
$count = $container->getContainerImages()->count();
$fileName = $id.$count.'.'.$file->guessExtension();
$file = $file->move($this->getPermanentContainerImageUploadDir(), $fileName);
//create Image entity
$image = new Image();
$image->setFileName($fileName);
$em->persist($image);
//create ContainerImage entity
$containerImage = new ContainerImage();
$containerImage->setContainer($container);
$containerImage->setImage($image);
$em->persist($containerImage);
//mark as unvalidated since it has changed
if(!$this->userIsAdmin())
{
if($container->getHoard())
{
$container->getHoard()->markUnvalidatedByAdmin();
}
}
$em->persist($container);
$em->flush();
return new JsonResponse(array(
'fileName'=>$fileName,
'container_image_id'=>$containerImage->getId()
));
}
private function removeImageFailed($reason)
{
return new JsonResponse( array(
'removedImage'=>null,
'error'=> $reason
));
}
/**
* checks permission of user's current request
*
* @param mixed $entity The entity being validated
*
* @param string $attribute - 'view' or 'edit' or 'delete'
* @return boolean
*
* @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
*/
private function checkAccess($entity, $attribute) {
// call security voter(s)
if (false === $this->security->isGranted($attribute, $entity->getHoard())) {
throw new AccessDeniedException('Unauthorised access!');
}
return true;
}
private function userIsAdmin() {
if($this->getUser() && ($this->getUser()->hasRole('ROLE_ADMIN') || $this->getUser()->hasRole('ROLE_SUPER_ADMIN')))
{
return true;
}
return false;
}
private function getPermanentContainerImageUploadDir() {
return '/srv/hoards_container_images';
}
}