|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace SimpleCrud\Fields; |
|
4
|
|
|
|
|
5
|
|
|
use Psr\Http\Message\UploadedFileInterface; |
|
6
|
|
|
use SimpleCrud\SimpleCrud; |
|
7
|
|
|
use SimpleCrud\SimpleCrudException; |
|
8
|
|
|
use RuntimeException; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* To save files. |
|
12
|
|
|
*/ |
|
13
|
|
|
class File extends Field |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* {@inheritdoc} |
|
17
|
|
|
*/ |
|
18
|
|
|
public function dataToDatabase($data) |
|
19
|
|
|
{ |
|
20
|
|
|
if ($data instanceof UploadedFileInterface) { |
|
21
|
|
|
return $this->upload($data); |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
return $data; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* {@inheritdoc} |
|
29
|
|
|
*/ |
|
30
|
|
|
public function dataFromDatabase($data) |
|
31
|
|
|
{ |
|
32
|
|
|
if (!empty($data)) { |
|
33
|
|
|
return sprintf('/%s/%s/%s', $this->table->name, $this->name, $data); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
return $data; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* Upload the file and return the value. |
|
41
|
|
|
* |
|
42
|
|
|
* @param UploadedFileInterface $file |
|
43
|
|
|
* |
|
44
|
|
|
* @return string |
|
45
|
|
|
*/ |
|
46
|
|
|
private function upload(UploadedFileInterface $file) |
|
47
|
|
|
{ |
|
48
|
|
|
$root = $this->table->getDatabase()->getAttribute(SimpleCrud::ATTR_UPLOADS); |
|
49
|
|
|
|
|
50
|
|
|
if (empty($root)) { |
|
51
|
|
|
throw new SimpleCrudException('No ATTR_UPLOADS attribute found to upload files'); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
$filename = $this->getFilename($file); |
|
55
|
|
|
$targetPath = sprintf('%s/%s/%s/', $root, $this->table->name, $this->name); |
|
56
|
|
|
|
|
57
|
|
|
if (!is_dir($targetPath)) { |
|
58
|
|
|
mkdir($targetPath, 0777, true); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
$file->moveTo($targetPath.$filename); |
|
62
|
|
|
|
|
63
|
|
|
return $filename; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* Get the name used to save the file in lowercase and without spaces. |
|
68
|
|
|
* |
|
69
|
|
|
* @param UploadedFilenameInterface $file |
|
70
|
|
|
* |
|
71
|
|
|
* @return string |
|
72
|
|
|
*/ |
|
73
|
|
|
protected function getFilename(UploadedFileInterface $file) |
|
74
|
|
|
{ |
|
75
|
|
|
$name = $file->getClientFilename(); |
|
76
|
|
|
|
|
77
|
|
|
if ($name === '') { |
|
78
|
|
|
return uniqid(); |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
|
|
$name = preg_replace('/[^\w\.]/', '-', strtolower($name)); |
|
82
|
|
|
return preg_replace('/[\-]{2,}/', '-', $name); |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|