Last active
October 14, 2020 09:52
-
-
Save dawidgora-old-account/f721247fe24c85f66942b59e2818a398 to your computer and use it in GitHub Desktop.
base64 converter for Symfony
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace AppBundle\Service; | |
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser; | |
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser; | |
/** | |
* @author Dawid Góra | |
*/ | |
class Base64Service | |
{ | |
/** @var string */ | |
private $filePrefix; | |
/** | |
* @param string $base64 | |
* @param string $targetPath | |
* @param string $filePrefix | |
* @return string name of converted file | |
*/ | |
public function convertToFile(string $base64, string $targetPath, $filePrefix = 'file_'): string | |
{ | |
$this->filePrefix = $filePrefix; | |
$fileName = $this->generateFileName(); | |
$filePath = $this->generateFilePath($targetPath, $fileName); | |
$file = fopen($filePath, 'wb'); | |
$data = explode(',', $base64); | |
fwrite($file, base64_decode($data[1])); | |
fclose($file); | |
$fileExt = $this->getFileExt($filePath); | |
rename($filePath, $filePath . '.' . $fileExt); | |
return $fileName . '.' . $fileExt; | |
} | |
/** | |
* @param string $targetPath | |
* @param string $fileName | |
* @return string | |
*/ | |
private function generateFilePath(string $targetPath, string $fileName): string | |
{ | |
return $targetPath . '/' . $fileName; | |
} | |
/** | |
* @return string | |
*/ | |
private function generateFileName(): string | |
{ | |
return uniqid($this->filePrefix, true); | |
} | |
/** | |
* @param string $filePath | |
* @return string | |
*/ | |
private function getFileExt(string $filePath): string | |
{ | |
$guesser = MimeTypeGuesser::getInstance(); | |
$extensionGuesser = new MimeTypeExtensionGuesser(); | |
return $extensionGuesser->guess( | |
$guesser->guess($filePath) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment