-
Notifications
You must be signed in to change notification settings - Fork 78
/
AttachmentType.php
92 lines (76 loc) · 2.79 KB
/
AttachmentType.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
<?php
/*
* This file is part of Sulu.
*
* (c) Sulu GmbH
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Sulu\Bundle\FormBundle\Dynamic\Types;
use Sulu\Bundle\FormBundle\Dynamic\FormFieldTypeConfiguration;
use Sulu\Bundle\FormBundle\Dynamic\FormFieldTypeInterface;
use Sulu\Bundle\FormBundle\Entity\FormField;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\All;
use Symfony\Component\Validator\Constraints\Count;
use Symfony\Component\Validator\Constraints\File;
use Symfony\Component\Validator\Constraints\Image;
use Symfony\Component\Validator\Constraints\NotBlank;
/**
* The Attachment form field type.
*/
class AttachmentType implements FormFieldTypeInterface
{
use SimpleTypeTrait;
public function getConfiguration(): FormFieldTypeConfiguration
{
return new FormFieldTypeConfiguration(
'sulu_form.type.attachment',
__DIR__ . '/../../Resources/config/form-fields/field_attachment.xml',
'special'
);
}
public function build(FormBuilderInterface $builder, FormField $field, string $locale, array $options): void
{
$type = FileType::class;
$options['mapped'] = false;
$allConstraints = [];
// Mime Types Filter.
$mimeTypes = [];
$translation = $field->getTranslation($locale);
if (\is_array($translation->getOption('type'))) {
foreach ($translation->getOption('type') as $attachmentType) {
$mimeTypes[] = $attachmentType . '/*';
}
}
if (!empty($mimeTypes)) {
$options['attr']['accept'] = \implode(',', $mimeTypes);
}
// File Constraint.
if ($translation->getOption('type') === ['image']) {
$fileConstraint = new Image();
} else {
$fileConstraint = new File(['mimeTypes' => $mimeTypes]);
}
$allConstraints[] = $fileConstraint;
// Required for Files.
if ($field->getRequired()) {
$allConstraints[] = new NotBlank();
}
// File Constraint.
$options['constraints'][] = new All(['constraints' => $allConstraints]);
// Max File Constraint.
if ($fileMax = (int) $translation->getOption('max')) {
$options['constraints'][] = new Count([
'max' => $fileMax,
]);
// @deprecated remove when a new major is release as max is not supported by input[type=file]
$options['attr']['max'] = $fileMax;
$options['attr']['data-max'] = $fileMax;
}
$options['multiple'] = true;
$builder->add($field->getKey(), $type, $options);
}
}