1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Class DataArchiveFileField |
5
|
|
|
* |
6
|
|
|
* Overwrite field to save into a {@link DataArchive}, using generateFilepath(). |
7
|
|
|
* This mainly just works around the limitation |
8
|
|
|
* of FileField to set the folder path *before* uploading the file, |
9
|
|
|
* at which point we don't have a {@link DataTransfer} ID yet, so can't generate the path. |
10
|
|
|
*/ |
11
|
|
|
class DataArchiveFileField extends FileField { |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* @param DataObjectInterface $record |
15
|
|
|
* @return bool|DataArchiveFileField |
16
|
|
|
*/ |
17
|
|
|
public function saveInto(DataObjectInterface $record) { |
|
|
|
|
18
|
|
|
if(!isset($_FILES[$this->name])) { |
19
|
|
|
return false; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
if(!($record instanceof DNDataArchive)) { |
23
|
|
|
throw new LogicException('Saving into wrong type, expected DNDataArchive'); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
$dataArchive = $record; |
27
|
|
|
|
28
|
|
|
/** @var DNDataTransfer $dataTransfer */ |
29
|
|
|
$dataTransfer = $dataArchive->DataTransfers()->First(); |
30
|
|
|
if(!$dataTransfer) { |
31
|
|
|
throw new LogicException('No transfer found'); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
$fileClass = File::get_class_for_file_extension(pathinfo($_FILES[$this->name]['name'], PATHINFO_EXTENSION)); |
35
|
|
|
$file = new $fileClass(); |
36
|
|
|
// Hack: loadIntoFile assumes paths relative to assets, |
37
|
|
|
// otherwise it creates the whole structure *within* that folder |
38
|
|
|
$absolutePath = $dataArchive->generateFilepath($dataTransfer); |
39
|
|
|
$relativePath = preg_replace('#^' . preg_quote(ASSETS_PATH) . '/#', '', $absolutePath); |
40
|
|
|
$this->upload->loadIntoFile($_FILES[$this->name], $file, $relativePath); |
|
|
|
|
41
|
|
|
if($this->upload->isError()) { |
42
|
|
|
return false; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
$file = $this->upload->getFile(); |
46
|
|
|
if($this->relationAutoSetting) { |
47
|
|
|
// save to record |
48
|
|
|
$record->{$this->name . 'ID'} = $file->ID; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return $this; |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: