uxf/storage

Maintainers

Details

gitlab.com/uxf/storage

3.1.3 2022-06-23 16:37 UTC

README

Install

$ composer req uxf/storage

Config

// config/packages/uxf.php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $containerConfigurator): void {
    $containerConfigurator->extension('uxf_storage', [
        'dsn' => '%env(STORAGE_DSN)%', // default local
    ]);
};
  • Local: local://default/%kernel.project_dir%/public/upload
  • S3: s3://key:secret@domain.com/bucket

Usage

FileCreatorInterface

use Ramsey\Uuid\Uuid;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use UXF\Storage\Entity\File;
use UXF\Storage\Utils\MimeTypeHelper;

class UploadedFileCreator implements FileCreatorInterface
{
    /**
     * @param UploadedFile $uploadedFile
     * @param Closure(string $uuid, ?string $namespace): string $dirPathFn
     */
    public function createFile($uploadedFile, ?string $namespace, Closure $dirPathFn): File
    {
        $uuid = Uuid::uuid4()->toString();

        $destDir = $dirPathFn($uuid, $namespace);

        $type = $uploadedFile->getClientMimeType() ?? 'image/jpeg';
        $ext = $uploadedFile->getClientOriginalExtension() ?: MimeTypeHelper::convertToExtension($type) ?? 'jpg';
        $size = $uploadedFile->getSize();
        $uploadedFile->move($destDir, "$uuid.$ext");

        return new File(
            $uuid,
            $ext,
            $type,
            $uploadedFile->getClientOriginalName() ?? '',
            $namespace,
            $size
        );
    }

    public function supports($uploadedFile, ?string $namespace): bool
    {
        return $uploadedFile instanceof UploadedFile;
    }
}