Completed
Push — master ( 054527...be0150 )
by Milan
01:52
created

Upload::createUniqueName()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 3
eloc 6
nc 2
nop 1
1
<?php
2
3
namespace h4kuna\Upload;
4
5
use h4kuna\Upload\Store,
6
	Nette\Http;
7
8
class Upload
9
{
10
	/** @var string */
11
	private $name;
12
13
	/** @var IDriver */
14
	private $driver;
15
16
	/** @var Store\Filename */
17
	private $filename;
18
19
	public function __construct($name, IDriver $driver, Store\Filename $filename)
20
	{
21
		$this->name = $name;
22
		$this->driver = $driver;
23
		$this->filename = $filename;
24
	}
25
26
	/**
27
	 * Output object save to database.
28
	 * Don't forget use nette rule Form::MIME_TYPE and Form::IMAGE.
29
	 * $fileUpload->isOk() nette call automaticaly.
30
	 *
31
	 * @param Http\FileUpload $fileUpload
32
	 * @param string $path
33
	 * @param callable|NULL $extendStoredFile - If you need special rules then return false if is not valid.
34
	 * @return Store\File
35
	 *
36
	 * @throws FileUploadFailedException
37
	 */
38
	public function save(Http\FileUpload $fileUpload, $path = '', callable $extendStoredFile = null)
39
	{
40
		if ($path) {
41
			$path = trim($path, '\/') . DIRECTORY_SEPARATOR;
42
		}
43
44
		do {
45
			$relativePath = $path . $this->filename->createUniqueName($fileUpload, $this->name);
46
		} while ($this->driver->isFileExists($relativePath));
47
48
		$storeFile = new Store\File($relativePath, $fileUpload->getName(), $fileUpload->getContentType());
49
50
		if ($extendStoredFile !== null && $extendStoredFile($storeFile, $fileUpload) === false) {
51
			throw new FileUploadFailedException($fileUpload->getName());
52
		}
53
54
		try {
55
			$this->driver->save($fileUpload, $relativePath);
56
		} catch (\Exception $e) {
57
			throw new FileUploadFailedException('Driver "' . get_class($this->driver) . '" failed.', null, $e);
58
		}
59
60
		return $storeFile;
61
	}
62
}
63