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 | 5 | public function init(): void |
|
22 | { |
||
23 | 5 | $this->setAttribute('type', 'file'); |
|
24 | 5 | $this->setRenderer(new FileUploadRender()); |
|
25 | 5 | $this->files = $_FILES; |
|
26 | |||
27 | 5 | if ($this->hasUploadedFile()) { |
|
28 | 3 | $this->setValue($this->files[$this->getName()]['name']); |
|
29 | } |
||
30 | } |
||
31 | |||
32 | 5 | private function hasUploadedFile(): bool |
|
33 | { |
||
34 | 5 | return $this->isFileArraySet() && $this->isTempNameSet(); |
|
35 | } |
||
36 | |||
37 | 5 | private function isFileArraySet(): bool |
|
38 | { |
||
39 | 5 | return isset($this->files[$this->getName()]); |
|
40 | } |
||
41 | |||
42 | 3 | private function isTempNameSet(): bool |
|
43 | { |
||
44 | 3 | return isset($this->files[$this->getName()]['tmp_name']); |
|
45 | } |
||
46 | |||
47 | 2 | public function setUploadDirectory(string $path): void |
|
48 | { |
||
49 | 2 | $path = realpath($path); |
|
50 | |||
51 | 2 | if (!is_dir($path) || !is_writable($path)) { |
|
52 | 1 | throw new InvalidArgumentException('Directory ' . $path . ' does not exist or is not writable.'); |
|
53 | } |
||
54 | |||
55 | 1 | $this->uploadDirectory = $path; |
|
56 | } |
||
57 | |||
58 | 1 | public function getUploadDirectory(): string |
|
59 | { |
||
60 | 1 | return $this->uploadDirectory; |
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
61 | } |
||
62 | |||
63 | 2 | public function hasUploadDirectory(): bool |
|
64 | { |
||
65 | 2 | return $this->uploadDirectory !== null; |
|
66 | } |
||
67 | |||
68 | 2 | public function moveUploadToDestination(): bool |
|
69 | { |
||
70 | 2 | if (!$this->hasUploadDirectory()) { |
|
71 | 1 | throw new LogicException('No destination directory set using setUploadDirectory($path)'); |
|
72 | } |
||
73 | |||
74 | 1 | $tmp = $this->files[$this->getName()]['tmp_name']; |
|
75 | 1 | $destination = $this->getUploadDirectory() . DIRECTORY_SEPARATOR . $this->files[$this->getName()]['name']; |
|
76 | |||
77 | 1 | return \move_uploaded_file($tmp, $destination); |
|
78 | } |
||
79 | } |
||
80 |