Completed
Push — master ( c383ac...a7fbb8 )
by Milan
01:52 queued 01:52
created

Upload::setDestination()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
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
10
	/** @var DocumentRoot */
11
	private $documentRoot;
12
13
	public function __construct(DocumentRoot $documentRoot)
14
	{
15
		$this->documentRoot = $documentRoot;
16
	}
17
18
	/**
19
	 * Output path save to databese.
20
	 * @param Http\FileUpload $fileUpload
21
	 * @param string $path
22
	 * @param string|NULL $destinationAlias
23
	 * @throws FileUploadFaildException
24
	 * @return string
25
	 */
26
	public function save(Http\FileUpload $fileUpload, $path = '', $destinationAlias = NULL)
27
	{
28
		if (!$fileUpload->isOk()) {
29
			throw new FileUploadFaildException($fileUpload->getName(), $fileUpload->getError());
30
		} elseif ($path) {
31
			$path = trim($path, '\/') . DIRECTORY_SEPARATOR;
32
		}
33
34
		do {
35
			$relativePath = $path . $this->createName($fileUpload);
36
			$pathname = $this->documentRoot->createAbsolutePath($relativePath, $destinationAlias);
37
		} while (is_file($pathname));
38
39
		$fileUpload->move($pathname);
40
		return $relativePath;
41
	}
42
43
	/**
44
	 * Prepare file name for save to file system.
45
	 * @param Http\FileUpload $fileUpload
46
	 * @return string
47
	 */
48
	protected function createName(Http\FileUpload $fileUpload)
49
	{
50
		$ext = pathinfo($fileUpload->getName(), PATHINFO_EXTENSION);
51
		return sha1(microtime(TRUE) . '.' . $fileUpload->getName()) . '.' . $ext;
52
	}
53
54
}
55