From b25a9a4f513635a195241fd3d024de61d8146868 Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Mon, 23 Mar 2020 16:22:18 -0400 Subject: [PATCH] using slugger for file uploading, instead of long transliterator code --- controller/upload_file.rst | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/controller/upload_file.rst b/controller/upload_file.rst index 5211907fa86..18d0fee4be8 100644 --- a/controller/upload_file.rst +++ b/controller/upload_file.rst @@ -129,13 +129,14 @@ Finally, you need to update the code of the controller that handles the form:: use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; + use Symfony\Component\String\Slugger\SluggerInterface; class ProductController extends AbstractController { /** * @Route("/product/new", name="app_product_new") */ - public function new(Request $request) + public function new(Request $request, SluggerInterface $slugger) { $product = new Product(); $form = $this->createForm(ProductType::class, $product); @@ -150,7 +151,7 @@ Finally, you need to update the code of the controller that handles the form:: if ($brochureFile) { $originalFilename = pathinfo($brochureFile->getClientOriginalName(), PATHINFO_FILENAME); // this is needed to safely include the file name as part of the URL - $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename); + $safeFilename = $slugger->slug($originalFilename); $newFilename = $safeFilename.'-'.uniqid().'.'.$brochureFile->guessExtension(); // Move the file to the directory where brochures are stored @@ -238,20 +239,23 @@ logic to a separate service:: use Symfony\Component\HttpFoundation\File\Exception\FileException; use Symfony\Component\HttpFoundation\File\UploadedFile; + use Symfony\Component\String\Slugger\SluggerInterface; class FileUploader { private $targetDirectory; + private $slugger; - public function __construct($targetDirectory) + public function __construct($targetDirectory, SluggerInterface $slugger) { $this->targetDirectory = $targetDirectory; + $this->slugger = $slugger; } public function upload(UploadedFile $file) { $originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME); - $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename); + $safeFilename = $slugger->slug($originalFilename); $fileName = $safeFilename.'-'.uniqid().'.'.$file->guessExtension(); try {