-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathImageField.php
More file actions
278 lines (244 loc) · 11.1 KB
/
ImageField.php
File metadata and controls
278 lines (244 loc) · 11.1 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
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
<?php
namespace EasyCorp\Bundle\EasyAdminBundle\Field;
use EasyCorp\Bundle\EasyAdminBundle\Config\Asset;
use EasyCorp\Bundle\EasyAdminBundle\Config\Option\ReplacedFileBehavior;
use EasyCorp\Bundle\EasyAdminBundle\Config\Option\TextAlign;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Field\FieldInterface;
use EasyCorp\Bundle\EasyAdminBundle\Form\Type\FileUploadType;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Image;
use Symfony\Contracts\Translation\TranslatableInterface;
/**
* @author Javier Eguiluz <javier.eguiluz@gmail.com>
*/
final class ImageField implements FieldInterface
{
use FieldTrait;
public const OPTION_BASE_PATH = 'basePath';
public const OPTION_UPLOAD_DIR = 'uploadDir';
public const OPTION_UPLOADED_FILE_NAME_PATTERN = 'uploadedFileNamePattern';
public const OPTION_FILE_CONSTRAINTS = 'fileConstraints';
public const OPTION_REPLACED_FILE_BEHAVIOR = 'replacedFileBehavior';
public const OPTION_DELETABLE = 'deletable';
public const OPTION_VIEWABLE = 'viewable';
public const OPTION_DOWNLOADABLE = 'downloadable';
public const OPTION_MIME_TYPES = 'mimeTypes';
public const OPTION_MIME_TYPES_MESSAGE = 'mimeTypesMessage';
public const OPTION_MAX_SIZE = 'maxSize';
public const OPTION_MAX_SIZE_MESSAGE = 'maxSizeMessage';
public const OPTION_FLYSYSTEM_STORAGE = 'flysystemStorage';
public const OPTION_FLYSYSTEM_URL_PREFIX = 'flysystemUrlPrefix';
public static function new(string $propertyName, TranslatableInterface|string|bool|null $label = null): self
{
return (new self())
->setProperty($propertyName)
->setLabel($label)
->setTemplateName('crud/field/image')
->setFormType(FileUploadType::class)
->addCssClass('field-image')
->addJsFiles(Asset::fromEasyAdminAssetPackage('field-image.js'), Asset::fromEasyAdminAssetPackage('field-file-upload.js'))
->setDefaultColumns('col-md-7 col-xxl-5')
->setTextAlign(TextAlign::CENTER)
->setCustomOption(self::OPTION_BASE_PATH, null)
->setCustomOption(self::OPTION_UPLOAD_DIR, null)
->setCustomOption(self::OPTION_UPLOADED_FILE_NAME_PATTERN, '[name].[extension]')
->setCustomOption(self::OPTION_FILE_CONSTRAINTS, [new Image()])
->setCustomOption(self::OPTION_MIME_TYPES, 'image/*')
->setCustomOption(self::OPTION_REPLACED_FILE_BEHAVIOR, ReplacedFileBehavior::DELETE)
->setCustomOption(self::OPTION_VIEWABLE, true)
->setCustomOption(self::OPTION_DOWNLOADABLE, true)
->setCustomOption(self::OPTION_DELETABLE, true)
->setCustomOption(self::OPTION_MIME_TYPES_MESSAGE, null)
->setCustomOption(self::OPTION_MAX_SIZE, null)
->setCustomOption(self::OPTION_MAX_SIZE_MESSAGE, null)
->setCustomOption(self::OPTION_FLYSYSTEM_STORAGE, null)
->setCustomOption(self::OPTION_FLYSYSTEM_URL_PREFIX, null);
}
/**
* Sets the path prepended to the image name to build the URL used
* to display the image in the detail and index pages (e.g. 'uploads/images/').
*/
public function setBasePath(string $path): self
{
$this->setCustomOption(self::OPTION_BASE_PATH, $path);
return $this;
}
/**
* Relative paths are resolved from the project's root directory (e.g. 'public/uploads/' for `<your-project-dir>/public/uploads/`).
* Absolute filesystem paths are also supported (e.g. '/mnt/data/uploads/'), and so are stream wrappers (e.g. 's3://bucket/path/').
* Default upload dir: `<your-project-dir>/public/uploads/images/`.
*/
public function setUploadDir(string $uploadDirPath): self
{
$this->setCustomOption(self::OPTION_UPLOAD_DIR, $uploadDirPath);
return $this;
}
/**
* @param string|\Closure(UploadedFile, object): string $patternOrCallable
*
* If it's a string, image files will be renamed according to the given pattern.
* The pattern can include the following special values:
*
* [DD] [MM] [YYYY] [YY] [hh] [mm] [ss] [timestamp]
* [name] [slug] [extension] [contenthash]
* [randomhash] [uuid] [ulid]
*
* e.g. [YYYY]/[MM]/[DD]/[slug]-[contenthash].[extension]
*
* Note: [day], [month] and [year] are deprecated since 5.1 (use [DD], [MM], [YYYY] instead).
* They will be removed in 6.0.
*
* If it's a callable, you will be passed the UploadedFile instance and the
* current entity instance, and you must return a string with the new filename
* (which can include subdirectories). On the NEW page, the entity is a fresh
* instance (possibly without an ID). On the EDIT page, it has its current DB values.
* Example:
*
* fn (UploadedFile $image, MyEntity $entity) => sprintf('%s/%s.%s', $entity->getSlug(), $image->getFilename(), $image->guessExtension())
*/
public function setUploadedFileNamePattern(string|\Closure $patternOrCallable): self
{
$this->setCustomOption(self::OPTION_UPLOADED_FILE_NAME_PATTERN, $patternOrCallable);
return $this;
}
/**
* @param Constraint|array<Constraint> $constraints
*
* Define constraints to be validated on the FileType.
* Image constraint is set by default.
*/
public function setFileConstraints(Constraint|array $constraints): self
{
if (\is_array($constraints)) {
foreach ($constraints as $key => $constraint) {
if (!$constraint instanceof Constraint) {
throw new \InvalidArgumentException(sprintf('The "%s" method expects a "%s" instance or an array of them; got "%s" at key "%s".', __METHOD__, Constraint::class, get_debug_type($constraint), $key));
}
}
} else {
$constraints = [$constraints];
}
$this->setCustomOption(self::OPTION_FILE_CONSTRAINTS, $constraints);
return $this;
}
/**
* Defines the allowed MIME types for this image (by default, all image types are accepted).
*
* @param string $mimeTypes a comma-separated list of one or more file types.
* You can use any value considered valid in the HTML `accept` attribute
* https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/accept
* Examples:
*
* '.png' (single extension)
* '.jpg,.jpeg' (multiple extensions)
* 'image/png,image/jpeg' (specific MIME types)
* @param string|null $errorMessage Custom error message shown when the MIME type is invalid.
* Available placeholders:
*
* {{ file }} // absolute file path
* {{ name }} // base file name
* {{ type }} // the MIME type of the given file
* {{ types }} // the list of allowed MIME types
*/
public function mimeTypes(string $mimeTypes, ?string $errorMessage = null): self
{
$this->setCustomOption(self::OPTION_MIME_TYPES, $mimeTypes);
$this->setCustomOption(self::OPTION_MIME_TYPES_MESSAGE, $errorMessage);
return $this;
}
/**
* Sets the maximum allowed size for the uploaded image.
*
* @param int|string $maxSize an integer (bytes) or a suffixed string: `'200k'`, `'2M'`, `'1G'` (SI units) or `'1Ki'`, `'1Mi'` (binary units)
* @param string|null $maxSizeMessage Custom error message shown when the image exceeds the maximum size.
* Available placeholders:
*
* {{ file }} // absolute file path
* {{ limit }} // maximum file size allowed
* {{ name }} // base file name
* {{ size }} // file size of the given file
* {{ suffix }} // suffix for the used file size unit
*/
public function maxSize(int|string $maxSize, ?string $maxSizeMessage = null): self
{
$this->setCustomOption(self::OPTION_MAX_SIZE, $maxSize);
$this->setCustomOption(self::OPTION_MAX_SIZE_MESSAGE, $maxSizeMessage);
return $this;
}
/**
* When an image is replaced by uploading a new one, the old image is deleted
* from the filesystem (this is the default behavior).
*/
public function deleteReplacedFile(): self
{
$this->setCustomOption(self::OPTION_REPLACED_FILE_BEHAVIOR, ReplacedFileBehavior::DELETE);
return $this;
}
/**
* When an image is replaced by uploading a new one, the old image is kept
* in the filesystem (renamed to avoid collisions).
*/
public function keepReplacedFile(): self
{
$this->setCustomOption(self::OPTION_REPLACED_FILE_BEHAVIOR, ReplacedFileBehavior::KEEP);
return $this;
}
/**
* When an image is replaced by uploading a new one, the old image is kept
* and an exception is thrown if the new image name conflicts with an existing one.
*/
public function keepReplacedFileOrFail(): self
{
$this->setCustomOption(self::OPTION_REPLACED_FILE_BEHAVIOR, ReplacedFileBehavior::KEEP_OR_FAIL);
return $this;
}
/**
* If true (default), a link to view the image is displayed next to the form field.
*/
public function isViewable(bool $isViewable = true): self
{
$this->setCustomOption(self::OPTION_VIEWABLE, $isViewable);
return $this;
}
/**
* If true (default), a link to download the image is displayed next to the form field.
*/
public function isDownloadable(bool $isDownloadable = true): self
{
$this->setCustomOption(self::OPTION_DOWNLOADABLE, $isDownloadable);
return $this;
}
/**
* If true (default), a button to delete the image is displayed next to the form field.
*/
public function isDeletable(bool $isDeletable = true): self
{
$this->setCustomOption(self::OPTION_DELETABLE, $isDeletable);
return $this;
}
/**
* Sets the Flysystem storage service ID to use for uploading/deleting images
* (e.g. 'default.storage' as registered by league/flysystem-bundle).
*/
public function setFlysystemStorage(string $storageName): self
{
$this->setCustomOption(self::OPTION_FLYSYSTEM_STORAGE, $storageName);
return $this;
}
/**
* Sets the URL prefix used to generate public URLs for images stored in Flysystem
* (e.g. 'https://cdn.example.com/uploads').
*
* This is optional. When not set, EasyAdmin derives the public URL from the
* Flysystem storage itself (via the 'public_url' or 'public_url_generator'
* configured for that storage in flysystem-bundle). Use this setter to
* override that default, for example when the admin UI serves files from a
* different host than the one configured in Flysystem.
*/
public function setFlysystemUrlPrefix(string $urlPrefix): self
{
$this->setCustomOption(self::OPTION_FLYSYSTEM_URL_PREFIX, $urlPrefix);
return $this;
}
}