Created
April 13, 2020 23:26
-
-
Save lpj145/2bf153568ac93ae4152cfc13c8987776 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
| declare(strict_types=1); | |
| namespace App\Actions; | |
| use Psr\Http\Message\ServerRequestInterface; | |
| use Psr\Http\Message\UploadedFileInterface; | |
| class Upload | |
| { | |
| /** | |
| * @var ServerRequestInterface | |
| */ | |
| private $request; | |
| /** | |
| * @var string | |
| */ | |
| private $nomeCampoUpload; | |
| public function __construct(ServerRequestInterface $request, string $nomeCampoUpload) | |
| { | |
| $this->request = $request; | |
| $this->nomeCampoUpload = $nomeCampoUpload; | |
| } | |
| public function salvarArquivosOuFalhar(string $caminho, int $quantidadeMax = 10, string $prefixoArquivo = '') | |
| { | |
| $qntArquivosSalvos = 0; | |
| $this->criarDiretorioSeNaoExistir($caminho); | |
| $arquivos = $this->request->getUploadedFiles()[$this->nomeCampoUpload]; | |
| if (empty($arquivos)) { | |
| return false; | |
| } | |
| if (!is_dir($caminho)) { | |
| throw new \Exception(sprintf('O Caminho: %s não existe.', $caminho)); | |
| } | |
| foreach ($arquivos as $arquivo) { | |
| if ($qntArquivosSalvos > $quantidadeMax) { | |
| break; | |
| } | |
| if (!($arquivo instanceof UploadedFileInterface)) { | |
| throw new \Exception(sprintf('O campo: %s parece vazio ou inválido.', $caminho)); | |
| } | |
| $nomeArquivo = $this->gerarNomeArquivo($prefixoArquivo, $arquivo); | |
| $arquivo->moveTo($caminho.DIRECTORY_SEPARATOR.$nomeArquivo); | |
| $qntArquivosSalvos += 1; | |
| } | |
| return true; | |
| } | |
| private function criarDiretorioSeNaoExistir(string $caminho) | |
| { | |
| if (!is_dir($caminho)) { | |
| mkdir($caminho); | |
| } | |
| } | |
| private function gerarNomeArquivo(string $prefixo, UploadedFileInterface $file) | |
| { | |
| return sprintf('%s%s.%s', uniqid(), $prefixo, $file->getClientMediaType()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment