|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Del\Form\Field; |
|
6
|
|
|
|
|
7
|
|
|
use Del\Form\Renderer\Field\FileUploadRender; |
|
8
|
|
|
use InvalidArgumentException; |
|
9
|
|
|
use LogicException; |
|
10
|
|
|
|
|
11
|
|
|
class FileUpload extends FieldAbstract |
|
12
|
|
|
{ |
|
13
|
|
|
private ?string $uploadDirectory = null; |
|
14
|
|
|
private array $files = []; |
|
15
|
|
|
|
|
16
|
2 |
|
public function getTag(): string |
|
17
|
|
|
{ |
|
18
|
2 |
|
return 'input'; |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
6 |
|
public function init(): void |
|
22
|
|
|
{ |
|
23
|
6 |
|
$this->setAttribute('type', 'file'); |
|
24
|
6 |
|
$this->setRenderer(new FileUploadRender()); |
|
25
|
6 |
|
$this->files = $_FILES; |
|
26
|
|
|
|
|
27
|
6 |
|
if ($this->hasUploadedFile()) { |
|
28
|
4 |
|
$this->setValue($this->files[$this->getName()]['name']); |
|
29
|
|
|
} |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
6 |
|
private function hasUploadedFile(): bool |
|
33
|
|
|
{ |
|
34
|
6 |
|
return $this->isFileArraySet() && $this->isTempNameSet(); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
6 |
|
private function isFileArraySet(): bool |
|
38
|
|
|
{ |
|
39
|
6 |
|
return isset($this->files[$this->getName()]); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
4 |
|
private function isTempNameSet(): bool |
|
43
|
|
|
{ |
|
44
|
4 |
|
return isset($this->files[$this->getName()]['tmp_name']); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
3 |
|
public function setUploadDirectory(string $path): void |
|
48
|
|
|
{ |
|
49
|
3 |
|
$path = realpath($path); |
|
50
|
|
|
|
|
51
|
3 |
|
if (!is_dir($path) || !is_writable($path)) { |
|
52
|
1 |
|
throw new InvalidArgumentException('Directory ' . $path . ' does not exist or is not writable.'); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
2 |
|
$this->uploadDirectory = $path; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
2 |
|
public function getUploadDirectory(): string |
|
59
|
|
|
{ |
|
60
|
2 |
|
return $this->uploadDirectory; |
|
|
|
|
|
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
3 |
|
public function hasUploadDirectory(): bool |
|
64
|
|
|
{ |
|
65
|
3 |
|
return $this->uploadDirectory !== null; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
3 |
|
public function moveUploadToDestination(): bool |
|
69
|
|
|
{ |
|
70
|
3 |
|
if (!$this->hasUploadDirectory()) { |
|
71
|
1 |
|
throw new LogicException('No destination directory set using setUploadDirectory($path)'); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
2 |
|
$tmp = $this->files[$this->getName()]['tmp_name']; |
|
75
|
2 |
|
$destination = $this->getUploadDirectory() . DIRECTORY_SEPARATOR . $this->files[$this->getName()]['name']; |
|
76
|
|
|
|
|
77
|
2 |
|
return \move_uploaded_file($tmp, $destination); |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|