4

I just want to validate the extension of image that I upload in Sonata Admin (v3.28.0) with Sonata Media Bundle (v3.10.0) in Symfony (v2.8.32) application.

I've read all similar questions and Sonata documentations, but still don't have a success.

I tried to add constraints to config.yml

sonata_media:
    providers:
        image:
            allowed_extensions:
                - 'jpg'
                - 'png'

I wonder that it doesn't work as is, because standard FileProvider (that is extended by ImageProvider) has extension check in validate method. But the method is not being called.

So I also tried to create custom provider:

services.yml:

sonata.media.provider.custom:
    class: Application\Sonata\MediaBundle\Provider\CustomImageProvider
    tags:
        - { name: sonata.media.provider }
    arguments:
        - sonata.media.provider.custom
        - @sonata.media.filesystem.local
        - @sonata.media.cdn.server
        - @sonata.media.generator.default
        - @sonata.media.thumbnail.format
        - ['jpg', 'png']
        - ['image/pjpeg', 'image/jpeg', 'image/png', 'image/x-png']
        - @sonata.media.adapter.image.imagick
        - @sonata.media.metadata.proxy
    calls:
      - [ setTemplates, [{helper_view:SonataMediaBundle:Provider:view_image.html.twig,helper_thumbnail:SonataMediaBundle:Provider:thumbnail.html.twig}]]

Application\Sonata\MediaBundle\Provider\CustomImageProvider.php:

<?php

namespace Application\Sonata\MediaBundle\Provider;

use Sonata\CoreBundle\Validator\ErrorElement;
use Sonata\MediaBundle\Model\MediaInterface;
use Sonata\MediaBundle\Provider\ImageProvider;

class CustomImageProvider extends ImageProvider
{
    public function validate(ErrorElement $errorElement, MediaInterface $media)
    {
        throw new \Exception();
    }
}

config.yml:

sonata_media:
    contexts:
        image:
            providers:
                - sonata.media.provider.custom
            formats:
                small: { width: 100 , quality: 70}
                big:   { width: 500 , quality: 70}

But the validate method is still not being called.

So when I try to load GIF image I get an error:

Length of either side cannot be 0 or negative, current size is x

Do I miss something?

UPDATE

Simple validation can be added right in SomeEntityAdmin class like this:

public function validate(ErrorElement $errorElement, $object)
{
    /** @var Media $image */
    $image = $object->getImage();

    if (!in_array($video->getContentType(), ['image/pjpeg', 'image/jpeg', 'image/png', 'image/x-png'])) {
        $errorElement
            ->with('image')
            ->addViolation('Invalid file type')
            ->end()
        ;
    };
}

But it's not a good solution if you want to validate a batch of uploaded images.

cezar
  • 11,616
  • 6
  • 48
  • 84
Pavel Alazankin
  • 1,325
  • 1
  • 12
  • 22

0 Answers0