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

Upload   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 8
lcom 1
cbo 3
dl 0
loc 49
rs 10
c 2
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A save() 0 16 4
A createUniqueName() 0 9 3
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