-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
FileType.php
243 lines (206 loc) · 7.97 KB
/
FileType.php
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form\Extension\Core\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Event\PreSubmitEvent;
use Symfony\Component\Form\FileUploadError;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Contracts\Translation\TranslatorInterface;
class FileType extends AbstractType
{
public const KIB_BYTES = 1024;
public const MIB_BYTES = 1048576;
private const SUFFIXES = [
1 => 'bytes',
self::KIB_BYTES => 'KiB',
self::MIB_BYTES => 'MiB',
];
private ?TranslatorInterface $translator;
public function __construct(?TranslatorInterface $translator = null)
{
$this->translator = $translator;
}
/**
* @return void
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
// Ensure that submitted data is always an uploaded file or an array of some
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($options) {
/** @var PreSubmitEvent $event */
$form = $event->getForm();
$requestHandler = $form->getConfig()->getRequestHandler();
if ($options['multiple']) {
$data = [];
$files = $event->getData();
if (!\is_array($files)) {
$files = [];
}
foreach ($files as $file) {
if ($requestHandler->isFileUpload($file)) {
$data[] = $file;
if (method_exists($requestHandler, 'getUploadFileError') && null !== $errorCode = $requestHandler->getUploadFileError($file)) {
$form->addError($this->getFileUploadError($errorCode));
}
}
}
// Since the array is never considered empty in the view data format
// on submission, we need to evaluate the configured empty data here
if ([] === $data) {
$emptyData = $form->getConfig()->getEmptyData();
$data = $emptyData instanceof \Closure ? $emptyData($form, $data) : $emptyData;
}
$event->setData($data);
} elseif ($requestHandler->isFileUpload($event->getData()) && method_exists($requestHandler, 'getUploadFileError') && null !== $errorCode = $requestHandler->getUploadFileError($event->getData())) {
$form->addError($this->getFileUploadError($errorCode));
} elseif (!$requestHandler->isFileUpload($event->getData())) {
$event->setData(null);
}
});
}
/**
* @return void
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
if ($options['multiple']) {
$view->vars['full_name'] .= '[]';
$view->vars['attr']['multiple'] = 'multiple';
}
$view->vars = array_replace($view->vars, [
'type' => 'file',
'value' => '',
]);
}
/**
* @return void
*/
public function finishView(FormView $view, FormInterface $form, array $options)
{
$view->vars['multipart'] = true;
}
/**
* @return void
*/
public function configureOptions(OptionsResolver $resolver)
{
$dataClass = null;
if (class_exists(File::class)) {
$dataClass = static fn (Options $options) => $options['multiple'] ? null : File::class;
}
$emptyData = static fn (Options $options) => $options['multiple'] ? [] : null;
$resolver->setDefaults([
'compound' => false,
'data_class' => $dataClass,
'empty_data' => $emptyData,
'multiple' => false,
'allow_file_upload' => true,
'invalid_message' => 'Please select a valid file.',
]);
}
public function getBlockPrefix(): string
{
return 'file';
}
private function getFileUploadError(int $errorCode): FileUploadError
{
$messageParameters = [];
if (\UPLOAD_ERR_INI_SIZE === $errorCode) {
[$limitAsString, $suffix] = $this->factorizeSizes(0, self::getMaxFilesize());
$messageTemplate = 'The file is too large. Allowed maximum size is {{ limit }} {{ suffix }}.';
$messageParameters = [
'{{ limit }}' => $limitAsString,
'{{ suffix }}' => $suffix,
];
} elseif (\UPLOAD_ERR_FORM_SIZE === $errorCode) {
$messageTemplate = 'The file is too large.';
} else {
$messageTemplate = 'The file could not be uploaded.';
}
if (null !== $this->translator) {
$message = $this->translator->trans($messageTemplate, $messageParameters, 'validators');
} else {
$message = strtr($messageTemplate, $messageParameters);
}
return new FileUploadError($message, $messageTemplate, $messageParameters);
}
/**
* Returns the maximum size of an uploaded file as configured in php.ini.
*
* This method should be kept in sync with Symfony\Component\HttpFoundation\File\UploadedFile::getMaxFilesize().
*/
private static function getMaxFilesize(): int|float
{
$iniMax = strtolower(\ini_get('upload_max_filesize'));
if ('' === $iniMax) {
return \PHP_INT_MAX;
}
$max = ltrim($iniMax, '+');
if (str_starts_with($max, '0x')) {
$max = \intval($max, 16);
} elseif (str_starts_with($max, '0')) {
$max = \intval($max, 8);
} else {
$max = (int) $max;
}
switch (substr($iniMax, -1)) {
case 't': $max *= 1024;
// no break
case 'g': $max *= 1024;
// no break
case 'm': $max *= 1024;
// no break
case 'k': $max *= 1024;
}
return $max;
}
/**
* Converts the limit to the smallest possible number
* (i.e. try "MB", then "kB", then "bytes").
*
* This method should be kept in sync with Symfony\Component\Validator\Constraints\FileValidator::factorizeSizes().
*/
private function factorizeSizes(int $size, int|float $limit): array
{
$coef = self::MIB_BYTES;
$coefFactor = self::KIB_BYTES;
$limitAsString = (string) ($limit / $coef);
// Restrict the limit to 2 decimals (without rounding! we
// need the precise value)
while (self::moreDecimalsThan($limitAsString, 2)) {
$coef /= $coefFactor;
$limitAsString = (string) ($limit / $coef);
}
// Convert size to the same measure, but round to 2 decimals
$sizeAsString = (string) round($size / $coef, 2);
// If the size and limit produce the same string output
// (due to rounding), reduce the coefficient
while ($sizeAsString === $limitAsString) {
$coef /= $coefFactor;
$limitAsString = (string) ($limit / $coef);
$sizeAsString = (string) round($size / $coef, 2);
}
return [$limitAsString, self::SUFFIXES[$coef]];
}
/**
* This method should be kept in sync with Symfony\Component\Validator\Constraints\FileValidator::moreDecimalsThan().
*/
private static function moreDecimalsThan(string $double, int $numberOfDecimals): bool
{
return \strlen($double) > \strlen(round($double, $numberOfDecimals));
}
}