Passed
Push — master ( 374698...e16807 )
by Milan
01:50
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
	 * @param string $alias
20
	 * @return self
21
	 */
22
	public function setDestination($alias)
23
	{
24
		$this->documentRoot->setDestination($alias);
25
		return $this;
26
	}
27
28
	/**
29
	 * Output path save to databese.
30
	 * @param Http\FileUpload $fileUpload
31
	 * @param string $destination
32
	 * @throws FileUploadFaildException
33
	 * @return string
34
	 */
35
	public function save(Http\FileUpload $fileUpload, $destination = '')
36
	{
37
		if (!$fileUpload->isOk()) {
38
			throw new FileUploadFaildException($fileUpload->getName(), $fileUpload->getError());
39
		} elseif ($destination) {
40
			$destination = trim($destination, '\/') . DIRECTORY_SEPARATOR;
41
		}
42
43
		do {
44
			$relativePath = $destination . $this->createName($fileUpload);
45
			$pathname = $this->documentRoot->createAbsolutePath($relativePath);
46
		} while (is_file($pathname));
47
48
		$fileUpload->move($pathname);
49
		return $relativePath;
50
	}
51
52
	/**
53
	 * Prepare file name for save to file system.
54
	 * @param Http\FileUpload $fileUpload
55
	 * @return string
56
	 */
57
	protected function createName(Http\FileUpload $fileUpload)
58
	{
59
		$ext = pathinfo($fileUpload->getName(), PATHINFO_EXTENSION);
60
		return sha1(microtime(TRUE) . '.' . $fileUpload->getName()) . '.' . $ext;
61
	}
62
63
}
64