src/Controller/UploadController.php line 18

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Service\ServiceflowApi;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\Filesystem\Filesystem;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\Routing\Annotation\Route;
  9. use Symfony\Component\String\Slugger\AsciiSlugger;
  10. class UploadController extends AbstractController
  11. {
  12. /**
  13. * @Route("/upload/new_file/{mode}/{uuid}/{dir}", name="file_upload")
  14. */
  15. public function uploadFile($mode, $uuid, $dir, ServiceflowApi $serviceflowApi, Request $request): JsonResponse
  16. {
  17. if ($request->isMethod('POST')) {
  18. if ($mode === 'update' && !$this->checkSketch($uuid, $serviceflowApi)) {
  19. return new JsonResponse(array('status' => false));
  20. }
  21. if (empty($_FILES['file']) || $_FILES['file']['error']) {
  22. return new JsonResponse(array('status' => false));
  23. }
  24. // create directory if no exist
  25. $filesystem = new Filesystem();
  26. $path = 'upload/' . $uuid . '/' . $dir;
  27. if (!$filesystem->exists($path)) {
  28. $filesystem->mkdir($path);
  29. }
  30. // define path
  31. $file = $_FILES['file'];
  32. $source = $file['tmp_name'];
  33. // get file info
  34. $fileInfo = pathinfo($file['name']);
  35. // slugify name
  36. $slugger = new AsciiSlugger();
  37. $filename = $slugger->slug($fileInfo['filename']);
  38. $destination = $path . '/' . $filename . '.' . $fileInfo['extension'];
  39. // move
  40. move_uploaded_file($source, $destination);
  41. return new JsonResponse(array('status' => true));
  42. }
  43. return new JsonResponse(array('status' => false));
  44. }
  45. private function checkSketch(?string $uuid, ServiceflowApi $serviceflowApi): bool
  46. {
  47. $sketch = $serviceflowApi->getSketch((string)$uuid);
  48. return $sketch && (int)$sketch['drp_status'] === 3;
  49. }
  50. /**
  51. * @Route("/upload/remove_file/{mode}/{uuid}/{dir}", name="file_upload_remove")
  52. */
  53. public function removeFile($mode, $uuid, $dir, ServiceflowApi $serviceflowApi, Request $request): JsonResponse
  54. {
  55. if ($request->isMethod('POST')) {
  56. if ($mode === 'upload' && !$this->checkSketch($uuid, $serviceflowApi)) {
  57. return new JsonResponse(array('status' => false));
  58. }
  59. $file = $request->request->get('file');
  60. $filesystem = new Filesystem();
  61. $path = 'upload/' . $uuid . '/' . $dir;
  62. if (!$filesystem->exists($path)) {
  63. return new JsonResponse(array('status' => false));
  64. }
  65. @unlink($path . '/' . $file);
  66. return new JsonResponse(array('status' => true));
  67. }
  68. return new JsonResponse(array('status' => true));
  69. }
  70. }