68 lines
2.4 KiB
PHP
68 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Lib;
|
|
|
|
use Exception;
|
|
use Illuminate\Http\UploadedFile;
|
|
use Illuminate\Support\Facades\File;
|
|
use Illuminate\Support\Str;
|
|
use SplFileInfo;
|
|
|
|
/**
|
|
* Some utilities methods
|
|
*
|
|
* @author Jérémy Munsch <jeremy.munsch@ldc.fr>
|
|
*/
|
|
// phpcs:disable Generic.Files.LineLength.TooLong
|
|
class Utils
|
|
{
|
|
/**
|
|
* Store an image for a model
|
|
* if a string is passed then the store action is ignored and the strieng is returned
|
|
*
|
|
* @param \Illuminate\Http\UploadedFile|\SplFileInfo|string $image
|
|
* @param string $folderName
|
|
* @return string The storage path
|
|
*/
|
|
public static function storeImage($image, string $folderName): string
|
|
{
|
|
if (\is_object($image) and get_class($image) === UploadedFile::class) {
|
|
/** @var UploadedFile */
|
|
$image = $image;
|
|
$newPath = self::prepareMoveFile($image->getClientOriginalName(), $folderName);
|
|
$newPath = str_replace(storage_path('app'), '', $newPath);
|
|
$image->storePubliclyAs(pathinfo($newPath, \PATHINFO_DIRNAME), pathinfo($newPath, \PATHINFO_BASENAME));
|
|
return '/storage' . str_replace('/public', '', $newPath);
|
|
}
|
|
if (\is_object($image) and get_class($image) === SplFileInfo::class) {
|
|
/** @var SplFileInfo */
|
|
$image = $image;
|
|
$newPath = self::prepareMoveFile($image->getBaseName(), $folderName);
|
|
if (!File::copy($image->getRealPath(), $newPath)) {
|
|
throw new \Exception(sprintf(
|
|
'Failed to copy file %s to %s',
|
|
$image->getRealPath(),
|
|
$newPath
|
|
));
|
|
}
|
|
return str_replace(\storage_path('app/public'), '/storage', $newPath);
|
|
}
|
|
if (\is_string($image)) {
|
|
return $image;
|
|
}
|
|
throw new Exception(sprintf('Cannot handle image %s', \gettype($image)));
|
|
}
|
|
private static function prepareMoveFile(string $filename, string $folderName): string
|
|
{
|
|
$pathFolder = \storage_path("app/public/images/$folderName");
|
|
if (!File::exists($pathFolder)) {
|
|
File::makeDirectory($pathFolder, 0755, true);
|
|
}
|
|
$filename = sprintf('%s-%s', Str::uuid(), $filename);
|
|
$fullPath = sprintf('%s/%s', $pathFolder, $filename);
|
|
if (File::exists($fullPath)) {
|
|
File::delete($fullPath);
|
|
}
|
|
return $fullPath;
|
|
}
|
|
}
|