1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace h4kuna\Upload; |
4
|
|
|
|
5
|
|
|
use h4kuna\Upload\Store, |
6
|
|
|
Nette\Http; |
7
|
|
|
|
8
|
|
|
class Upload |
9
|
|
|
{ |
10
|
|
|
/** @var IDriver */ |
11
|
|
|
private $driver; |
12
|
|
|
|
13
|
|
|
public function __construct(IDriver $driver) |
14
|
|
|
{ |
15
|
|
|
$this->driver = $driver; |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Output object save to database. |
20
|
|
|
* Don't forget use nette rule Form::MIME_TYPE and Form::IMAGE. |
21
|
|
|
* $fileUpload->isOk() nette call automaticaly. |
22
|
|
|
* |
23
|
|
|
* @param Http\FileUpload $fileUpload |
24
|
|
|
* @param string $path |
25
|
|
|
* @param callable|NULL $extendStoredFile - If you need special rules then return false if is not valid. |
26
|
|
|
* @return Store\File |
27
|
|
|
* |
28
|
|
|
* @throws FileUploadFailedException |
29
|
|
|
*/ |
30
|
|
|
public function save(Http\FileUpload $fileUpload, $path = '', callable $extendStoredFile = null) |
31
|
|
|
{ |
32
|
|
|
if ($path) { |
33
|
|
|
$path = trim($path, '\/') . DIRECTORY_SEPARATOR; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
do { |
37
|
|
|
$relativePath = $path . $this->createUniqueName($fileUpload); |
38
|
|
|
} while ($this->driver->isFileExists($relativePath)); |
39
|
|
|
|
40
|
|
|
$storeFile = new Store\File($relativePath, $fileUpload->getName(), $fileUpload->getContentType()); |
41
|
|
|
|
42
|
|
|
if ($extendStoredFile !== null && $extendStoredFile($storeFile, $fileUpload) === false) { |
43
|
|
|
throw new FileUploadFailedException($fileUpload->getName()); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
try { |
47
|
|
|
$this->driver->save($fileUpload, $relativePath); |
48
|
|
|
} catch (\Exception $e) { |
49
|
|
|
throw new FileUploadFailedException('Driver "' . get_class($this->driver) . '" failed.', null, $e); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return $storeFile; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param Http\FileUpload $fileUpload |
57
|
|
|
* @return string |
58
|
|
|
*/ |
59
|
|
|
private function createUniqueName(Http\FileUpload $fileUpload) |
60
|
|
|
{ |
61
|
|
|
$fileName = $this->driver->createName($fileUpload); |
62
|
|
|
if ($fileName !== null && is_string($fileName)) { |
63
|
|
|
return $fileName; |
64
|
|
|
} |
65
|
|
|
$ext = pathinfo($fileUpload->getName(), PATHINFO_EXTENSION); |
66
|
|
|
|
67
|
|
|
return sha1(microtime(true) . '.' . $fileUpload->getName()) . '.' . $ext; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|