-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathFileField.php
More file actions
144 lines (121 loc) · 3.06 KB
/
FileField.php
File metadata and controls
144 lines (121 loc) · 3.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
<?php
namespace Gregwar\Formidable\Fields;
/**
* File field type
*
* @author Grégoire Passault <g.passault@gmail.com>
*/
class FileField extends Field
{
/**
* File data
*/
protected $datas;
/**
* Maximum file size
*/
protected $maxsize;
/**
* File type
*/
protected $filetype;
/**
* Field type
*/
protected $type = 'file';
public function __sleep()
{
return array_merge(parent::__sleep(), array(
'datas', 'filetype', 'maxsize'
));
}
public function push($var, $value = null)
{
switch ($var) {
case 'maxsize':
$this->maxsize = $value;
break;
case 'filetype':
$this->filetype = $value;
break;
default:
parent::push($var, $value);
break;
}
}
public function setValue($value, $default = false)
{
if (!is_array($value)) {
return;
}
$this->datas = $value;
}
public function check()
{
if ($this->hasData()) {
if (null !== $this->maxsize && $this->datas['size'] > $this->maxsize) {
return array('file_size_too_big', $this->printName(), $this->sizePrettyize($this->maxsize));
}
if (null !== $this->filetype) {
switch ($this->filetype) {
case 'image':
$size = @getimagesize($this->datas['tmp_name']);
if (!$size || !$size[0] || !$size[1]) {
return array('file_image', $this->printName());
}
default:
break;
}
}
} else {
if ($this->required) {
return array('file_required', $this->printName());
}
}
// Custom constraints
foreach ($this->constraints as $constraint) {
$error = $constraint($this->value);
if ($error) {
return $error;
}
}
return;
}
public function hasData()
{
return (null !== $this->datas && isset($this->datas['size']) && $this->datas['size'] != 0);
}
public function save($filename)
{
if (null === $this->datas) {
return;
}
@move_uploaded_file($this->datas['tmp_name'], $filename);
}
public function tmpName() {
return $this->datas['tmp_name'];
}
public function size()
{
return $this->datas['size'];
}
public function prettySize()
{
return $this->sizePrettyize($this->datas['size']);
}
public function sizePrettyize($size)
{
$unites = array('o', 'Ko', 'Mo', 'Go', 'To', 'Po');
$n = floor(log($size)/log(1024));
$t = round($size/pow(1024,$n),1);
return $t.' '.$unites[$n];
}
public function fileName()
{
return $this->datas['name'];
}
public function getValue()
{
return $this->hasData() ? $this : null;
}
}