1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Win\Repositories\Filesystem; |
4
|
|
|
|
5
|
|
|
use Win\Repositories\Filesystem\File; |
6
|
|
|
use Win\Repositories\Filesystem; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Auxilia fazer upload de Arquivos |
10
|
|
|
*/ |
11
|
|
|
class Uploader |
12
|
|
|
{ |
13
|
|
|
/** @var string[] */ |
14
|
|
|
protected static $validExtensions = [ |
15
|
|
|
'csv', 'doc', 'docx', 'gif', 'jpeg', 'jpg', 'md', 'mp3', |
16
|
|
|
'mp4', 'mpeg', 'pdf', 'png', 'svg', 'txt', 'wav', 'xls', 'xlsx', 'zip', |
17
|
|
|
]; |
18
|
|
|
|
19
|
|
|
/** @var string */ |
20
|
|
|
protected $path; |
21
|
|
|
|
22
|
|
|
/** @var Filesystem */ |
23
|
|
|
protected $fs; |
24
|
|
|
|
25
|
|
|
/** @var string[]|null */ |
26
|
|
|
protected $temp; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Inicializa o upload para o diretório de destino |
30
|
|
|
* @param string $path |
31
|
|
|
*/ |
32
|
|
|
public function __construct($path) |
33
|
|
|
{ |
34
|
|
|
$this->path = $path . '/'; |
35
|
|
|
$this->fs = new Filesystem(); |
36
|
|
|
$this->fs->create($path); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Prepara o upload |
41
|
|
|
* @param string[] $temp |
42
|
|
|
*/ |
43
|
|
|
public function prepare($tempFile) |
44
|
|
|
{ |
45
|
|
|
if (is_null($tempFile) || $tempFile['error']) { |
46
|
|
|
throw new \Exception('Error during upload'); |
47
|
|
|
} |
48
|
|
|
$this->temp = $tempFile; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Faz o upload para o diretório final |
53
|
|
|
* @param string $name |
54
|
|
|
*/ |
55
|
|
|
public function upload($name = '') |
56
|
|
|
{ |
57
|
|
|
if (!is_null($this->temp)) { |
58
|
|
|
$name = $this->generateName($name); |
59
|
|
|
\move_uploaded_file( |
60
|
|
|
$this->temp['tmp_name'], |
61
|
|
|
$this->path . $name |
62
|
|
|
); |
63
|
|
|
|
64
|
|
|
return new File($this->path . $name); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return null; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
protected function generateName($name) |
71
|
|
|
{ |
72
|
|
|
$info = pathinfo($this->temp['name']); |
73
|
|
|
|
74
|
|
|
return ($name ? $name : md5(time())) . '.' . $info['extension']; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|