src/Ox/HoardBundle/Controller/ObjectController.php line 201

Open in your IDE?
  1. <?php
  2.     
  3. namespace App\Ox\HoardBundle\Controller;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  9. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  10. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  11. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  12. use Symfony\Component\Security\Core\Security;
  13. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  14. use Symfony\Component\Form\Extension\Core\Type\ButtonType;
  15. use App\Ox\HoardBundle\Entity\HObject;
  16. use App\Ox\HoardBundle\Entity\ObjectImage;
  17. use App\Ox\HoardBundle\Entity\Image;
  18. use App\Ox\HoardBundle\Form\ObjectType;
  19. /**
  20.  * Object controller
  21.  *
  22.  * @Route("/object")
  23.  */
  24.  class ObjectController extends AbstractController
  25.  {
  26.     private $security;
  27.     public function __construct(Security $security)
  28.     {
  29.         $this->security $security;
  30.     }
  31.      /**
  32.       * @Route("/{id}/edit", name="object_edit", methods={"GET"})
  33.      * @Template("@OxHoardBundle/hObject/edit.html.twig")
  34.       */
  35.       public function editAction(Request $request$id)
  36.       {
  37.           $em $this->getDoctrine()->getManager();
  38.           
  39.           $object $em->getRepository('OxHoardBundle:HObject')->find($id);
  40.           
  41.           $this->checkAccess($object'edit');
  42.           if(!$object) {
  43.               throw $this->createNotFoundException('Unable to find object entity.');
  44.           }
  45.           
  46.           // $deleteForm = $this->createDeleteForm($id);
  47.           $editForm $this->createEditForm($object);
  48.           
  49.           $isAjax $request->isXmlHttpRequest();
  50.           
  51.           $template = ($isAjax '@OxHoardBundle/hObject/edit_form.html.twig' '@OxHoardBundle/hObject/edit.html.twig');
  52.           $referenceTypes $em->createQuery('SELECT rt FROM OxHoardBundle:ReferenceType rt ORDER BY rt.referenceType')->getResult();
  53.           return $this->render($template, array(
  54.               'ajax' => $request->isXmlHttpRequest(),
  55.               'object' => $object,
  56.               'edit_form' => $editForm->createView(),
  57.               // 'delete_form' => $deleteForm->createView(),
  58.               'reference_types' => $referenceTypes
  59.           ));
  60.       }
  61.       
  62.     /**
  63.      * Creates a form to delete an Object entity by id.
  64.      *
  65.      * @param mixed $id The entity id
  66.      *
  67.      * @return \Symfony\Component\Form\Form The form
  68.      */
  69.     private function createDeleteForm($id)
  70.     {
  71.         return $this->createFormBuilder()
  72.             ->setAction($this->generateUrl('object_delete', array('id' => $id)))
  73.             ->setMethod('DELETE')
  74.             ->add('submit'ButtonType::class, array(
  75.                 'label' => 'Delete this object',
  76.                 'attr' => array(
  77.                     'class' => 'delete-button btn-danger'
  78.                 )
  79.             ))
  80.             ->getForm()
  81.             ;
  82.     }
  83.       
  84.     /**
  85.      * Creates a form to edit an Object entity.
  86.      *
  87.      * @param HObject $entity The entity
  88.      *
  89.      * @return \Symfony\Component\Form\Form The form
  90.      */
  91.     private function createEditForm(HObject $entity)
  92.     {
  93.         $form $this->createForm(ObjectType::class, $entity, array(
  94.             'action' => $this->generateUrl('object_update', array('id' => $entity->getId())),
  95.             'method' => 'PUT',
  96.             'hoard' => $entity->getHoard()
  97.         ));
  98.         $form->add('submit'SubmitType::class, array('label' => 'Update'));
  99.         return $form;
  100.     }
  101.     
  102.     /**
  103.      * Edits an existing Object entity.
  104.      *
  105.      * @Route("/{id}", name="object_update", methods={"PUT"}) PUT doesn't seem to work...
  106.      * @Template("@OxHoardBundle/hObject/edit.html.twig")
  107.      */
  108.     public function updateAction(Request $request$id)
  109.     {
  110.         $em $this->getDoctrine()->getManager();
  111.         $object $em->getRepository('OxHoardBundle:HObject')->find($id);
  112.         $this->checkAccess($object'edit');
  113.         if (!$object) {
  114.             throw $this->createNotFoundException('Unable to find Object entity.');
  115.         }
  116.         // $deleteForm = $this->createDeleteForm($id);
  117.         $editForm $this->createEditForm($object);
  118.         $editForm->handleRequest($request);
  119.         if ($editForm->isValid()) {
  120.             //mark as unvalidated since it has changed
  121.             if(!$this->userIsAdmin())
  122.             {
  123.                 if($object->getHoard())
  124.                 {
  125.                     $object->getHoard()->markUnvalidatedByAdmin();
  126.                 }
  127.             }
  128.             
  129.             //persist object references
  130.             $objectReferences $object->getObjectReferences();
  131.             foreach($objectReferences as $ref)
  132.             {
  133.                 if($ref->getDeleted())
  134.                 {
  135.                     //do soft delete
  136.                     //persist deleted flag
  137.                     $em->persist($ref);
  138.                     //clear link to object
  139.                     $ref->setObject(null);
  140.                     //flush before removing;
  141.                     $em->flush();
  142.                     $em->remove($ref);
  143.                 }
  144.                 else
  145.                 {
  146.                     $ref->setObject($object);
  147.                     $em->persist($ref);
  148.                 }
  149.             }
  150.             
  151.             $em->flush();
  152.             
  153.             return $this->redirect($this->generateUrl('object_show', array('id' => $id)));
  154.         } else {
  155.             $referenceTypes $em->createQuery('SELECT rt FROM OxHoardBundle:ReferenceType rt ORDER BY rt.referenceType')->getResult();
  156.             return $this->render('@OxHoardBundle/hObject/edit_form.html.twig', array(
  157.                 'object' => $object,
  158.                 'edit_form' => $editForm->createView(),
  159.                 'reference_types' => $referenceTypes
  160.             ));
  161.         }
  162.         $referenceTypes $em->createQuery('SELECT rt FROM OxHoardBundle:ReferenceType rt ORDER BY rt.referenceType')->getResult();
  163.         return array(
  164.             'object'      => $object,
  165.             'edit_form'   => $editForm->createView(),
  166.             // 'delete_form' => $deleteForm->createView(),
  167.             'reference_types' => $referenceTypes
  168.         );
  169.     }
  170.     
  171.     /**
  172.      * Finds and displays an object entity.
  173.      *
  174.      * @Route("/{id}", name="object_show", methods={"GET"})
  175.      * @Template("@OxHoardBundle/hObject/show.html.twig")
  176.      */
  177.     public function showAction(Request $request$id)
  178.     {
  179.         $em $this->getDoctrine()->getManager();
  180.         $object $em->getRepository('OxHoardBundle:HObject')->find($id);
  181.         $this->checkAccess($object'view');
  182.         if (!$object) {
  183.             throw $this->createNotFoundException('Unable to find Object entity.');
  184.         }
  185.         $isAjax $request->isXmlHttpRequest();
  186.         $template = ($isAjax '@OxHoardBundle/hObject/show_modal.html.twig' '@OxHoardBundle/hObject/show.html.twig');
  187.         return $this->render($template, array(
  188.             'object'      => $object,
  189.         ));
  190.     }
  191.     
  192.     /**
  193.      * Adds a new image file, creating an Image entity, and an ObjectImage entity
  194.      *
  195.      * @Route("/{id}/ajax_add_image", methods={"POST"})
  196.      */
  197.      public function ajaxAddImage(Request $request$id)
  198.      {
  199.          $em $this->getDoctrine()->getManager();
  200.          
  201.          $file $request->files->get('image');
  202.          $object $em->getRepository('OxHoardBundle:HObject')->find($id);
  203.          
  204.          //validate the file - TODO
  205.          
  206.          $this->checkAccess($object'edit');
  207.          
  208.          //move to desired location/name
  209.          $count $object->getObjectImages()->count();
  210.          $fileName $id.$count.'.'.$file->guessExtension();
  211.          $file $file->move($this->getPermanentObjectImageUploadDir(), $fileName);
  212.          
  213.          //create Image entity
  214.          $image = new Image();
  215.          $image->setFileName($fileName);
  216.          $em->persist($image);
  217.          
  218.          //create ObjectImage entity
  219.          $objectImage = new ObjectImage();
  220.          $objectImage->setObject($object);
  221.          $objectImage->setImage($image);
  222.          $em->persist($objectImage);
  223.          
  224.            //mark as unvalidated since it has changed
  225.             if(!$this->userIsAdmin())
  226.             {
  227.              if($object->getHoard())
  228.              {
  229.                    $object->getHoard()->markUnvalidatedByAdmin();
  230.              }
  231.          }
  232.          $em->persist($object);
  233.          $em->flush();
  234.          
  235.          return new JsonResponse(array(
  236.              'fileName'=>$fileName,
  237.              'object_image_id'=>$objectImage->getId()
  238.          ));
  239.      }
  240.      
  241.      /**
  242.       * soft-delete the given object image from the object
  243.       *
  244.       * @Route("/{id}/ajax_remove_image/{objectImage_id}", methods={"POST"})
  245.       */
  246.       public function ajaxRemoveImage(Request $request$id$objectImage_id)
  247.       {
  248.           $em $this->getDoctrine()->getManager();
  249.           
  250.           $object $em->getRepository('OxHoardBundle:HObject')->find($id);
  251.           
  252.           $this->checkAccess($object'edit');
  253.           
  254.           if(!$object)
  255.           {
  256.             return $this->removeImageFailed('Object not found');
  257.           }
  258.           $objectImage $em->getRepository('OxHoardBundle:ObjectImage')->find($objectImage_id);
  259.           if(!$objectImage)
  260.           {
  261.             return $this->removeImageFailed('Object Image not found');
  262.           }
  263.           
  264.           if($objectImage->getObject() != $object)
  265.           {
  266.               return $this->removeImageFailed('Image does not belong to specified object');
  267.           }
  268.           
  269.           //Remove the objectImage (performs soft delete)
  270.           $em->remove($objectImage);
  271.           
  272.           //mark as unvalidated since it has changed
  273.           if(!$this->userIsAdmin())
  274.           {
  275.               if($object->getHoard())
  276.               {
  277.                   $object->getHoard()->markUnvalidatedByAdmin();
  278.               }
  279.           }
  280.           $em->flush();
  281.           
  282.           return new JsonResponse( array(
  283.               'removedImage'=>$objectImage_id,
  284.           ));
  285.       }
  286.       
  287.       private function removeImageFailed($reason)
  288.       {
  289.         return new JsonResponse( array(
  290.           'removedImage'=>null,
  291.           'error'=> $reason
  292.         ));
  293.       }
  294.       
  295.       /**
  296.        * checks permission of user's current request
  297.        *
  298.        * @param mixed $entity The entity being validated
  299.        *
  300.        * @param string $attribute - 'view' or 'edit' or 'delete'
  301.        * @return boolean
  302.        *
  303.        * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  304.        */
  305.       private function checkAccess($entity$attribute) {
  306.           // call security voter(s)
  307.           if (false === $this->security->isGranted($attribute$entity->getHoard())) {
  308.               throw new AccessDeniedException('Unauthorised access!');
  309.           }
  310.           return true;
  311.       }
  312.       
  313.       private function userIsAdmin() {
  314.           if($this->getUser() && ($this->getUser()->hasRole('ROLE_ADMIN') || $this->getUser()->hasRole('ROLE_SUPER_ADMIN')))
  315.           {
  316.               return true;
  317.           }
  318.           return false;
  319.       }
  320.      private function getPermanentObjectImageUploadDir() {
  321.          return '/srv/hoards_object_images';
  322.      }
  323.  }