/** * @Route("/photo") * @Method({"POST", "OPTIONS"}) */ public function postPhotoAction(Request $request) { $albumId = $request->request->get('albumId'); $dateString = $request->request->get('date'); $files = $request->files->get('photo', array()); try { $date = new \DateTime($dateString); } catch (\Exception $e) { return new JsonResponse(array('message' => 'Invalid arguments', 'list' => array('date: Unable to parse string.')), 422); } // Create an array if only one photo was uploaded if (!is_array($files)) { $files = array($files); } $em = $this->getDoctrine()->getManager(); $album = $em->getRepository('AppBundle:Album')->findOneById($albumId); if (null === $album) { $data = array('message' => 'Invalid parameters', 'list' => array('albumId: no album with such id.')); return new JsonResponse($data, 422); } $this->denyAccessUnlessGranted('edit', $album, 'You cannot add photos to this album.'); foreach ($files as $file) { $photo = new Photo(); $photo->setDate($date)->setUploadDate(new \DateTime())->setAuthor($this->getUser())->setFile($file); $album->addPhoto($photo); } $validator = $this->get('validator'); $errors = $validator->validate($album); if (count($errors) > 0) { return new JsonResponse(Util::violationListToJson($errors), 422); } $em->persist($album); $em->flush(); return new JsonResponse(array('message' => 'Photo added.')); }