Completed
Push — master ( 3cea42...86bc77 )
by Milan
06:50
created

Upload::save()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 22
rs 8.6737
cc 5
eloc 13
nc 5
nop 3
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 path save to database.
20
	 * @param Http\FileUpload $fileUpload
21
	 * @param string $path
22
	 * @param callable|NULL $extendStoredFile
23
	 * @return Store\File
24
	 *
25
	 * @throws FileUploadFailedException
26
	 */
27
	public function save(Http\FileUpload $fileUpload, $path = '', callable $extendStoredFile = NULL)
28
	{
29
		if (!$fileUpload->isOk()) {
30
			throw new FileUploadFailedException($fileUpload->getName(), $fileUpload->getError());
31
		} elseif ($path) {
32
			$path = trim($path, '\/') . DIRECTORY_SEPARATOR;
33
		}
34
35
		do {
36
			$relativePath = $path . $this->createUniqueName($fileUpload);
37
		} while ($this->driver->isFileExists($relativePath));
38
39
		$storeFile = new Store\File($relativePath, $fileUpload->getName(), $fileUpload->getContentType());
40
41
		if($extendStoredFile !== NULL) {
42
			$extendStoredFile($storeFile, $fileUpload);
43
		}
44
45
		$this->driver->save($fileUpload, $relativePath);
46
47
		return $storeFile;
48
	}
49
50
	/**
51
	 * @param Http\FileUpload $fileUpload
52
	 * @return string
53
	 */
54
	private function createUniqueName(Http\FileUpload $fileUpload)
55
	{
56
		$fileName = $this->driver->createName($fileUpload);
57
		if ($fileName !== null && is_string($fileName)) {
58
			return $fileName;
59
		}
60
		$ext = pathinfo($fileUpload->getName(), PATHINFO_EXTENSION);
61
62
		return sha1(microtime(true) . '.' . $fileUpload->getName()) . '.' . $ext;
63
	}
64
}
65