<?php
namespace App\Controller;
use App\Service\ServiceflowApi;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\String\Slugger\AsciiSlugger;
class UploadController extends AbstractController
{
/**
* @Route("/upload/new_file/{mode}/{uuid}/{dir}", name="file_upload")
*/
public function uploadFile($mode, $uuid, $dir, ServiceflowApi $serviceflowApi, Request $request): JsonResponse
{
if ($request->isMethod('POST')) {
if ($mode === 'update' && !$this->checkSketch($uuid, $serviceflowApi)) {
return new JsonResponse(array('status' => false));
}
if (empty($_FILES['file']) || $_FILES['file']['error']) {
return new JsonResponse(array('status' => false));
}
// create directory if no exist
$filesystem = new Filesystem();
$path = 'upload/' . $uuid . '/' . $dir;
if (!$filesystem->exists($path)) {
$filesystem->mkdir($path);
}
// define path
$file = $_FILES['file'];
$source = $file['tmp_name'];
// get file info
$fileInfo = pathinfo($file['name']);
// slugify name
$slugger = new AsciiSlugger();
$filename = $slugger->slug($fileInfo['filename']);
$destination = $path . '/' . $filename . '.' . $fileInfo['extension'];
// move
move_uploaded_file($source, $destination);
return new JsonResponse(array('status' => true));
}
return new JsonResponse(array('status' => false));
}
private function checkSketch(?string $uuid, ServiceflowApi $serviceflowApi): bool
{
$sketch = $serviceflowApi->getSketch((string)$uuid);
return $sketch && (int)$sketch['drp_status'] === 3;
}
/**
* @Route("/upload/remove_file/{mode}/{uuid}/{dir}", name="file_upload_remove")
*/
public function removeFile($mode, $uuid, $dir, ServiceflowApi $serviceflowApi, Request $request): JsonResponse
{
if ($request->isMethod('POST')) {
if ($mode === 'upload' && !$this->checkSketch($uuid, $serviceflowApi)) {
return new JsonResponse(array('status' => false));
}
$file = $request->request->get('file');
$filesystem = new Filesystem();
$path = 'upload/' . $uuid . '/' . $dir;
if (!$filesystem->exists($path)) {
return new JsonResponse(array('status' => false));
}
@unlink($path . '/' . $file);
return new JsonResponse(array('status' => true));
}
return new JsonResponse(array('status' => true));
}
}