Skip to content

Instantly share code, notes, and snippets.

@kunicmarko20
Last active May 22, 2024 12:30
Show Gist options
  • Save kunicmarko20/0af5e61510a68706ecbf658c0c690b8a to your computer and use it in GitHub Desktop.
Save kunicmarko20/0af5e61510a68706ecbf658c0c690b8a to your computer and use it in GitHub Desktop.
Sonata Media SVG Provider

Sonata Media SVG Provider

This example will help you create custom provider for Sonata Media that will allowe you to upload svg.

Adapted solution from here.

sonata_media:
db_driver: doctrine_orm
default_context: default
contexts:
default:
providers:
- admin.provider.image
#...
<?php
namespace YourBundle\Provider;
use Sonata\MediaBundle\Provider\FileProvider;
class ImageProvider extends FileProvider
{
}
services:
admin.provider.image:
class: YourBundle\Provider\ImageProvider
tags:
- { name: sonata.media.provider }
arguments:
- "admin.provider.image"
- "@sonata.media.filesystem.local"
- "@sonata.media.cdn.server"
- "@sonata.media.generator.default"
- "@sonata.media.thumbnail.format"
- ['gif', 'svg', 'jpg', 'jpeg', 'png']
- ['image/svg+xml', 'image/gif', 'image/jpeg', 'image/pjpeg', 'image/png']
calls:
- [ setTemplates, [{ helper_thumbnail : 'YourBundle:Provider:thumbnail.html.twig', helper_view : 'YourBundle:Provider:view_image.html.twig' }]]
<img src="/uploads/media/{{ options.file }}" {% for name, value in options %}{{name}}="{{value}}" {% endfor %} />
<img src="/uploads/media/{{ options.file }}" {% for name, value in options %}{{ name }}="{{ value }}" {% endfor %} />
<?php
namespace YourBundle\Admin;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
class YourAdmin extends AbstractAdmin
{
/**
* @param FormMapper $formMapper
*/
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('icon', 'sonata_type_model_list', ['required' => false], [
'link_parameters' => ['context' => 'default', 'provider' => 'admin.provider.image']]);
}
}
@vprohorov
Copy link

This will add svg extension to files instead of empty. Also i've added ability to show referenced svg in admin panel.

<?php

namespace YourBundle\Provider;

use RuntimeException;
use Sonata\MediaBundle\Model\MediaInterface;
use Sonata\MediaBundle\Provider\FileProvider;
use Sonata\MediaBundle\Provider\MediaProviderInterface;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class ImageProvider extends FileProvider
{
    /** @var string */
    private $svgContentType = 'image/svg';

    /**
     * {@inheritdoc}
     */
    protected function generateReferenceName(MediaInterface $media): string
    {
        if ($media->getBinaryContent() instanceof UploadedFile) {
            $fileName = $media->getBinaryContent()->getClientOriginalName();
        } elseif ($media->getBinaryContent() instanceof File) {
            $fileName = $media->getBinaryContent()->getFilename();
        } else {
            throw new RuntimeException(sprintf('Invalid binary content type: %s', get_class($media->getBinaryContent())));
        }
        $extension = $media->getBinaryContent()->guessExtension() ?: strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        return $this->generateMediaUniqId($media) . '.' . $extension;
    }

    /**
     * {@inheritdoc}
     */
    public function generatePublicUrl(MediaInterface $media, $format): string
    {
        if (MediaProviderInterface::FORMAT_REFERENCE === $format || $media->getContentType() === $this->svgContentType) {
            $path = $this->getReferenceImage($media);
        } else {
            $path = sprintf('sonatamedia/files/%s/file.png', $format);
        }
        return $this->getCdn()->getPath($path, $media->getCdnIsFlushable());
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment