LiipImagineBundle does not apply filter to SVG file. How to fix it?

LiipImagineBundle does not apply filter to SVG file. How to fix it?

Disclaimer

Maybe it is not the best solution, but this workaround works for me. If you have a better solution, please let me know.

Introduction

LiipImagineBundle (applying filter to a SVG file) still have some issues. If you try to apply a filter to an SVG file, you will get the following error:

Unable to create image for path "X.svg" and filter "XXX".
Message was "An image could not be created from the given input".

Solution:

Quick solution: return the original svg file if the requested file is an svg file.

Step 1:

Create a new controller that extends the Liip\ImagineBundle\Controller\ImagineController and override the filterAction method.

src/Controller/ImagineController.php
<?php

namespace App\Controller;

use Liip\ImagineBundle\Config\Controller\ControllerConfig;
use Liip\ImagineBundle\Imagine\Cache\SignerInterface;
use Liip\ImagineBundle\Imagine\Data\DataManager;
use Liip\ImagineBundle\Service\FilterService;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class ImagineController extends \Liip\ImagineBundle\Controller\ImagineController
{
    public function __construct(
        #[Autowire(service: 'liip_imagine.service.filter')]
        FilterService $filterService,
        #[Autowire(service: 'liip_imagine.data.manager')]
        DataManager $dataManager,
        #[Autowire(service: 'liip_imagine.cache.signer')]
        SignerInterface $signer,
        #[Autowire(service: 'liip_imagine.controller.config')]
        ControllerConfig $controllerConfig = null
    ) {
        parent::__construct($filterService, $dataManager, $signer, $controllerConfig);
    }

    /**
     * @param Request $request
     * @param string $path
     * @param string $filter
     * @Route("/imagine")
     */
    public function filterAction(Request $request, $path, $filter): RedirectResponse
    {
        if (pathinfo($path, PATHINFO_EXTENSION) === 'svg') {
            return new RedirectResponse("/$path");
        }

        return parent::filterAction($request, $path, $filter);
    }
}

Step 2:

Add controller configuration to the liip_imagine.yaml file.

config/packages/liip_imagine.yaml
liip_imagine:
+    controller:
+        filter_action: \App\Controller\ImagineController::filterAction

Step 3:

Waiting for normal support of SVG files in LiipImagineBundle.

That`s it.