<?php

namespace Application\Service\Extension\Uploader\adapter;

use Application\Service\Extension\Uploader\Image;
use Application\Service\Extension\Uploader\ImageUploader;
use Application\Service\Extension\Uploader\UploadAdapterAbstract;
use Application\Service\Extension\Uploader\UploadException;
use League\Flysystem\Filesystem;
use League\Flysystem\FilesystemException;
use League\Flysystem\Local\LocalFilesystemAdapter;

class Local extends UploadAdapterAbstract
{
    /**
     * @param Image $file
     * @return array
     * @throws FilesystemException|UploadException
     */
    public function upload(Image $file): array
    {
        $savePath = $this->config['savePath'] . $this->getSaveDir();
        $fileSystem = new Filesystem(new LocalFilesystemAdapter($savePath));
        $fileName = "{$file->baseName}.{$file->extension}";
        if ($fileSystem->fileExists($fileName)) {
            throw new UploadException("{$fileName}已存在。");
        }
        $stream = fopen($file->tmpName, 'r+');
        $fileSystem->writeStream($fileName, $stream);
        if (is_resource($stream)) {
            fclose($stream);
        }

        return [
            'name' => $file->baseName,
            'extension' => $file->extension,
            'dir' => $this->getSaveDir(),
            'size' => $file->size,
            'driver' => ImageUploader::DRIVER_LOCAL,
            'path' => $this->getSaveDir() . "/{$file->baseName}.{$file->extension}"
        ];
    }
}