Skip to content

Commit

Permalink
[ImageField] Support constraint validation
Browse files Browse the repository at this point in the history
  • Loading branch information
Seb33300 authored and javiereguiluz committed May 21, 2024
1 parent ecfb473 commit 76a9e9d
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 2 deletions.
10 changes: 10 additions & 0 deletions doc/fields/ImageField.rst
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ change that location. The argument is the directory relative to your project roo

yield ImageField::new('...')->setUploadDir('assets/images/');

setFileConstraints
~~~~~~~~~~~~~~~~~~

By default, the uploaded file is validated using the `Image`_ constraint.
Use this option to change constraints applied to the uploaded file::

yield ImageField::new('...')->setFileConstraints(new Image(maxSize: '100k'));

setUploadedFileNamePattern
~~~~~~~~~~~~~~~~~~~~~~~~~~

Expand Down Expand Up @@ -74,3 +82,5 @@ argument the Symfony's UploadedFile instance::
yield ImageField::new('...')->setUploadedFileNamePattern(
fn (UploadedFile $file): string => sprintf('upload_%d_%s.%s', random_int(1, 999), $file->getFilename(), $file->guessExtension()))
);

.. _`Image`: https://symfony.com/doc/current/reference/constraints/Image.html
2 changes: 2 additions & 0 deletions src/Field/Configurator/ImageConfigurator.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ public function configure(FieldDto $field, EntityDto $entityDto, AdminContext $c
$absoluteUploadDir = u($relativeUploadDir)->ensureStart($this->projectDir.\DIRECTORY_SEPARATOR)->toString();
}
$field->setFormTypeOption('upload_dir', $absoluteUploadDir);

$field->setFormTypeOption('file_constraints', $field->getCustomOption(ImageField::OPTION_FILE_CONSTRAINTS));
}

private function getImagesPaths(?array $images, ?string $basePath): array
Expand Down
19 changes: 18 additions & 1 deletion src/Field/ImageField.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
use EasyCorp\Bundle\EasyAdminBundle\Config\Option\TextAlign;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Field\FieldInterface;
use EasyCorp\Bundle\EasyAdminBundle\Form\Type\FileUploadType;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Image;
use Symfony\Contracts\Translation\TranslatableInterface;

/**
Expand All @@ -18,6 +20,7 @@ final class ImageField implements FieldInterface
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';

/**
* @param TranslatableInterface|string|false|null $label
Expand All @@ -35,7 +38,8 @@ public static function new(string $propertyName, $label = null): self
->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_UPLOADED_FILE_NAME_PATTERN, '[name].[extension]')
->setCustomOption(self::OPTION_FILE_CONSTRAINTS, [new Image()]);
}

public function setBasePath(string $path): self
Expand Down Expand Up @@ -76,4 +80,17 @@ public function setUploadedFileNamePattern($patternOrCallable): self

return $this;
}

/**
* @param Constraint|array<Constraint> $constraints
*
* Define constraints to be validated on the FileType.
* Image constraint is set by default.
*/
public function setFileConstraints($constraints): self
{
$this->setCustomOption(self::OPTION_FILE_CONSTRAINTS, $constraints);

return $this;
}
}
9 changes: 8 additions & 1 deletion src/Form/Type/FileUploadType.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Symfony\Component\String\Slugger\AsciiSlugger;
use Symfony\Component\Uid\Ulid;
use Symfony\Component\Uid\Uuid;
use Symfony\Component\Validator\Constraint;

/**
* @author Yonel Ceruto <yonelceruto@gmail.com>
Expand All @@ -38,7 +39,8 @@ public function buildForm(FormBuilderInterface $builder, array $options): void
$uploadFilename = $options['upload_filename'];
$uploadValidate = $options['upload_validate'];
$allowAdd = $options['allow_add'];
unset($options['upload_dir'], $options['upload_new'], $options['upload_delete'], $options['upload_filename'], $options['upload_validate'], $options['download_path'], $options['allow_add'], $options['allow_delete'], $options['compound']);
$options['constraints'] = $options['file_constraints'];
unset($options['upload_dir'], $options['upload_new'], $options['upload_delete'], $options['upload_filename'], $options['upload_validate'], $options['download_path'], $options['allow_add'], $options['allow_delete'], $options['compound'], $options['file_constraints']);

$builder->add('file', FileType::class, $options);
$builder->add('delete', CheckboxType::class, ['required' => false]);
Expand Down Expand Up @@ -123,6 +125,7 @@ public function configureOptions(OptionsResolver $resolver): void
'required' => false,
'error_bubbling' => false,
'allow_file_upload' => true,
'file_constraints' => [],
]);

$resolver->setAllowedTypes('upload_dir', 'string');
Expand All @@ -133,6 +136,7 @@ public function configureOptions(OptionsResolver $resolver): void
$resolver->setAllowedTypes('download_path', ['null', 'string']);
$resolver->setAllowedTypes('allow_add', 'bool');
$resolver->setAllowedTypes('allow_delete', 'bool');
$resolver->setAllowedTypes('file_constraints', [Constraint::class, Constraint::class.'[]']);

$resolver->setNormalizer('upload_dir', function (Options $options, string $value): string {
if (\DIRECTORY_SEPARATOR !== mb_substr($value, -1)) {
Expand Down Expand Up @@ -181,6 +185,9 @@ public function configureOptions(OptionsResolver $resolver): void

return (bool) $value;
});
$resolver->setNormalizer('file_constraints', static function (Options $options, $constraints) {
return \is_object($constraints) ? [$constraints] : (array) $constraints;
});
}

public function getBlockPrefix(): string
Expand Down

0 comments on commit 76a9e9d

Please sign in to comment.