before switch to turbo

This commit is contained in:
2022-11-10 13:48:29 +01:00
parent 219f4097ff
commit 23139a5835
35 changed files with 731 additions and 139 deletions

View File

@@ -6,13 +6,18 @@ use App\Entity\User;
use App\Form\EditProfileFormType;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Sunrise\Slugger\Slugger;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Validator\Constraints\File;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* Class UserController.
@@ -56,10 +61,6 @@ class UserController extends BaseController
return $this->redirectToRoute(route: 'app_main');
};
$user = $form->getData();
// hash the plain password
return $this->renderForm(view: '@default/user/edit_profile.html.twig', parameters: [
'user' => $user,
'userForm' => $form
@@ -93,4 +94,48 @@ class UserController extends BaseController
'users' => $users,
]);
}
// TODO move to a helper class
function humanFilesize($bytes, $decimals = 2)
{
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
#[Route(path: '/user/upload/avatar/{id}', name: 'user_upload_avatar')]
public function uploadAvatar(
Request $request,
UserRepository $userRepository,
EntityManagerInterface $entityManager,
ValidatorInterface $validator,
int $id)
{
$user = $userRepository->find($id);
if (!$user) {
return $this->json('User not found.', 404);
}
$postMaxSize = UploadedFile::getMaxFilesize();
$contentLength = $request->headers->get('Content-length');
if ($contentLength > $postMaxSize) {
return $this->json('File is bigger than the allowed ' . $this->humanFilesize($postMaxSize) . ' Bytes.', 400);
}
$uploadedAvatar = $request->files->get('file');
$destination = $this->getParameter(name: 'kernel.project_dir') . '/public/uploads/avatars';
$originalFilename = pathinfo($uploadedAvatar->getClientOriginalName(), PATHINFO_FILENAME);
$slugger = new Slugger();
$cleanFilename = $slugger->slugify($originalFilename);
$newFilename = $cleanFilename . '-' . uniqid() . '.' . $uploadedAvatar->guessExtension();
$uploadedAvatar->move($destination, $newFilename);
$user->setAvatar($newFilename);
$entityManager->persist(entity: $user);
$entityManager->flush();
return $this->json(data: 'OK', status: 201);
}
}