PageRenderTime 61ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/symfony/src/ApiBundle/Controller/ImagesController.php

https://gitlab.com/jensdwul1/nmdad3.local
PHP | 362 lines | 137 code | 43 blank | 182 comment | 9 complexity | 300b578210e08fcf6d4be4e23227a5d3 MD5 | raw file
  1. <?php
  2. namespace ApiBundle\Controller;
  3. use ApiBundle\Form\ImageType;
  4. use AppBundle\Entity\Image;
  5. use AppBundle\Entity\User;
  6. use FOS\RestBundle\Controller\Annotations as FOSRest;
  7. use FOS\RestBundle\Controller\FOSRestController;
  8. use FOS\RestBundle\Request\ParamFetcher;
  9. use FOS\RestBundle\View\View;
  10. use Nelmio\ApiDocBundle\Annotation as Nelmio;
  11. use Symfony\Component\HttpFoundation\File\UploadedFile;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  15. /**
  16. * Class ImagesController.
  17. */
  18. class ImagesController extends FOSRestController
  19. {
  20. /**
  21. * Test API options and requirements.
  22. *
  23. * @return Response
  24. *
  25. * @Nelmio\ApiDoc(
  26. * resource = true,
  27. * statusCodes = {
  28. * Response::HTTP_OK: "OK"
  29. * }
  30. * )
  31. */
  32. public function optionsImagesAction() : Response
  33. {
  34. $response = new Response();
  35. $response->headers->set('Allow', 'OPTIONS, GET, POST, PUT');
  36. return $response;
  37. }
  38. /**
  39. * Returns all images of a user.
  40. *
  41. * @param ParamFetcher $paramFetcher
  42. * @param $user_id
  43. *
  44. * @return mixed
  45. *
  46. * @FOSRest\View(serializerGroups={"Default", "Images_getImages"})
  47. * @FOSRest\Get(
  48. * requirements = {
  49. * "_format" : "json|jsonp|xml"
  50. * }
  51. * )
  52. * @FOSRest\QueryParam(
  53. * name = "sort",
  54. * requirements = "id|title",
  55. * default = "id",
  56. * description = "Order by Image id or Image title."
  57. * )
  58. * @FOSRest\QueryParam(
  59. * name = "order",
  60. * requirements = "asc|desc",
  61. * default = "asc",
  62. * description = "Order result ascending or descending."
  63. * )
  64. * @Nelmio\ApiDoc(
  65. * resource = true,
  66. * statusCodes = {
  67. * Response::HTTP_OK : "OK"
  68. * }
  69. * )
  70. */
  71. public function getImagesAction(ParamFetcher $paramFetcher, $user_id)
  72. {
  73. # HTTP method: GET
  74. # Host/port : http://www.nmdad3.local
  75. #
  76. # Path : /api/v1/users/1/images.json
  77. # Path : /api/v1/users/1/images.xml
  78. # Path : /api/v1/users/1/images.xml?sort=title&amp;order=desc
  79. // dump([
  80. // $paramFetcher->get('sort'),
  81. // $paramFetcher->get('order'),
  82. // $paramFetcher->all(),
  83. // ]);
  84. $em = $this->getDoctrine()->getManager();
  85. $user = $em
  86. ->getRepository(User::class)
  87. ->find($user_id);
  88. if (!$user instanceof User) {
  89. throw new NotFoundHttpException('Not found');
  90. }
  91. $posts = $user->getPosts();
  92. $images = $posts
  93. ->filter(
  94. function ($post) {
  95. return $post instanceof Image;
  96. }
  97. )->getValues();
  98. return $images;
  99. }
  100. /**
  101. * Returns an image of a user.
  102. *
  103. * @param $user_id
  104. * @param $image_id
  105. *
  106. * @return object
  107. *
  108. * @FOSRest\Get(
  109. * requirements = {
  110. * "image_id": "\d+",
  111. * "_format" : "json|xml"
  112. * }
  113. * )
  114. * @Nelmio\ApiDoc(
  115. * resource = true,
  116. * statusCodes = {
  117. * Response::HTTP_OK : "OK",
  118. * Response::HTTP_NO_CONTENT : "No Content",
  119. * Response::HTTP_NOT_FOUND : "Not Found"
  120. * }
  121. * )
  122. */
  123. public function getImageAction($user_id, $image_id)
  124. {
  125. # HTTP method: GET
  126. # Host/port : http://www.nmdad3.local
  127. #
  128. # Path : /api/v1/users/1/images/1.json
  129. $em = $this->getDoctrine()->getManager();
  130. $image = $em
  131. ->getRepository(Image::class)
  132. ->find($image_id);
  133. if (!$image instanceof Image) {
  134. throw new NotFoundHttpException('Not found');
  135. }
  136. if ($image->getUser()->getId() === (int) $user_id) {
  137. return $image;
  138. }
  139. }
  140. /**
  141. * Post a new image of a user.
  142. *
  143. * { "image": { "title": "Lorem" } }
  144. *
  145. * @param Request $request
  146. * @param $user_id
  147. *
  148. * @return View|Response
  149. *
  150. * @FOSRest\View()
  151. * @FOSRest\Post(
  152. * "/users/{user_id}/images/",
  153. * requirements = {
  154. * "user_id" : "\d+"
  155. * }
  156. * )
  157. * @Nelmio\ApiDoc(
  158. * input = ApiBundle\Form\ImageType::class,
  159. * statusCodes = {
  160. * Response::HTTP_CREATED : "Created"
  161. * }
  162. * )
  163. */
  164. public function postImageAction(Request $request, $user_id)
  165. {
  166. $em = $this->getDoctrine()->getManager();
  167. $user = $em
  168. ->getRepository(User::class)
  169. ->find($user_id);
  170. if (!$user instanceof User) {
  171. throw new NotFoundHttpException();
  172. }
  173. $image = new Image();
  174. $image->setUser($user);
  175. $logger = $this->get('logger');
  176. $logger->info($request);
  177. return $this->processImageForm($request, $image);
  178. }
  179. /**
  180. * @param Request $request
  181. * @param $user_id
  182. * @param $image_id
  183. *
  184. * @return \Symfony\Component\HttpFoundation\RedirectResponse
  185. * @FOSRest\View()
  186. * @FOSRest\Post(
  187. * "/users/{user_id}/images/{image_id}/file/",
  188. * requirements = {
  189. * "user_id" : "\d+"
  190. * }
  191. * )
  192. */
  193. public function postImageFileAction(Request $request, $user_id, $image_id)
  194. {
  195. $em = $this->getDoctrine()->getManager();
  196. $image = $em->getRepository(Image::class)->find($image_id);
  197. $data = $_FILES['imageFile'];
  198. $file = new UploadedFile($data['tmp_name'], $data['name'], $data['type'], $data['size'], $data['error']);
  199. $uploadDirectory = 'uploads';
  200. $fileName = sha1_file($file->getRealPath()).'.'.$file->guessExtension();
  201. $fileLocator = realpath($this->getParameter('kernel.root_dir').DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'web').DIRECTORY_SEPARATOR.$uploadDirectory;
  202. $file->move($fileLocator, $fileName);
  203. $image->setUri($request->getScheme().'://'.$request->getHttpHost().'/'.$uploadDirectory.'/'.$fileName);
  204. $em = $this->getDoctrine()->getManager();
  205. $em->persist($image);
  206. $em->flush();
  207. $response = new Response();
  208. return $response->setStatusCode(Response::HTTP_CREATED);
  209. }
  210. /**
  211. * Update an image of a user.
  212. *
  213. * @param Request $request
  214. * @param $user_id
  215. * @param $image_id
  216. *
  217. * @return Response
  218. *
  219. * @FOSRest\View()
  220. * @FOSRest\Put(
  221. * requirements = {
  222. * "user_id" : "\d+",
  223. * "image_id": "\d+",
  224. * "_format" : "json|xml"
  225. * }
  226. * )
  227. * @Nelmio\ApiDoc(
  228. * input = AppBundle\Form\ImageType::class,
  229. * statusCodes = {
  230. * Response::HTTP_NO_CONTENT: "No Content"
  231. * }
  232. * )
  233. */
  234. public function putImageAction(Request $request, $user_id, $image_id)
  235. {
  236. $em = $this->getDoctrine()->getManager();
  237. $image = $em
  238. ->getRepository(Image::class)
  239. ->find($image_id);
  240. if (!$image instanceof Image) {
  241. throw new NotFoundHttpException();
  242. }
  243. if ($image->getUser()->getId() === (int) $user_id) {
  244. return $this->processImageForm($request, $image);
  245. }
  246. }
  247. /**
  248. * Delete an image of a user.
  249. *
  250. * @param $user_id
  251. * @param $image_id
  252. *
  253. * @throws NotFoundHttpException
  254. * @FOSRest\View(statusCode = 204)
  255. * @FOSRest\Delete(
  256. * requirements = {
  257. * "user_id" : "\d+",
  258. * "image_id" : "\d+",
  259. * "_format" : "json|xml"
  260. * },
  261. * defaults = {"_format": "json"}
  262. * )
  263. * @Nelmio\ApiDoc(
  264. * statusCodes = {
  265. * Response::HTTP_NO_CONTENT: "No Content",
  266. * Response::HTTP_NOT_FOUND : "Not Found"
  267. * }
  268. * )
  269. */
  270. public function deleteImageAction($user_id, $image_id)
  271. {
  272. $em = $this->getDoctrine()->getManager();
  273. $image = $em
  274. ->getRepository(Image::class)
  275. ->find($image_id);
  276. if (!$image instanceof Image) {
  277. throw new NotFoundHttpException();
  278. }
  279. if ($image->getUser()->getId() === (int) $user_id) {
  280. $em->remove($image);
  281. $em->flush();
  282. }
  283. }
  284. // Convenience methods
  285. // -------------------
  286. /**
  287. * Process ImageType Form.
  288. *
  289. * @param Request $request
  290. * @param Image $image
  291. *
  292. * @return View|Response
  293. */
  294. private function processImageForm(Request $request, Image $image)
  295. {
  296. $form = $this->createForm(ImageType::class, $image, ['method' => $request->getMethod()]);
  297. $form->handleRequest($request);
  298. if ($form->isValid()) {
  299. $statusCode = is_null($image->getId()) ? Response::HTTP_CREATED : Response::HTTP_NO_CONTENT;
  300. $em = $this->getDoctrine()->getManager();
  301. $em->persist($image); // Manage entity Image for persistence.
  302. $em->flush(); // Persist to database.
  303. $response = new Response();
  304. $response->setStatusCode($statusCode);
  305. // Redirect to the URI of the resource.
  306. $response->headers->set('Location',
  307. $this->generateUrl('api_v1_get_user_image', [
  308. 'user_id' => $image->getUser()->getId(),
  309. 'image_id' => $image->getId(),
  310. ], /* absolute path = */true)
  311. );
  312. $response->setContent(json_encode([
  313. 'image' => ['id' => $image->getId()],
  314. ]));
  315. return $response;
  316. }
  317. return View::create($form, Response::HTTP_BAD_REQUEST);
  318. }
  319. }