Completed
Push — master ( 3f6851...6e71e0 )
by Milan
03:43
created

Upload::createName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 5
rs 9.4285
c 1
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace h4kuna\Upload;
4
5
use Nette\Http;
6
7
class Upload
8
{
9
	/** @var IDriver */
10
	private $driver;
11
12
	public function __construct(IDriver $driver)
13
	{
14
		$this->driver = $driver;
15
	}
16
17
	/**
18
	 * Output path save to database.
19
	 * @param Http\FileUpload $fileUpload
20
	 * @param string $path
21
	 * @return string
22
	 *
23
	 * @throws FileUploadFailedException
24
	 */
25
	public function save(Http\FileUpload $fileUpload, $path = '')
26
	{
27
		if (!$fileUpload->isOk()) {
28
			throw new FileUploadFailedException($fileUpload->getName(), $fileUpload->getError());
29
		} elseif ($path) {
30
			$path = trim($path, '\/') . DIRECTORY_SEPARATOR;
31
		}
32
33
		do {
34
			$relativePath = $path . $this->createUniqueName($fileUpload);
35
		} while ($this->driver->isFileExists($relativePath));
36
37
		$this->driver->save($fileUpload, $relativePath);
38
39
		return $relativePath;
40
	}
41
42
	/**
43
	 * @param Http\FileUpload $fileUpload
44
	 * @return FileName
45
	 */
46
	private function createUniqueName(Http\FileUpload $fileUpload)
47
	{
48
		$fileName = $this->driver->createName($fileUpload);
49
		if ($fileName !== NULL && is_string($fileName)) {
50
			return $fileName;
51
		}
52
		$ext = pathinfo($fileUpload->getName(), PATHINFO_EXTENSION);
53
		return sha1(microtime(TRUE) . '.' . $fileUpload->getName()) . '.' . $ext;
54
	}
55
}
56