how to properly add a view handler to fosrestbundle to return file

1.3k views Asked by At

Checking this post and this other post, also I checked the bundle RssExample I came up with this config:

Under fos_rest

format_listener:
    enabled: true
    rules:
        - { path: ^/service/export-to-csv, priorities: [ csv,json ], fallback_format: json, prefer_extension: false }
        - { path: ^/, priorities: [ json ], fallback_format: json, prefer_extension: true }
exception:
    enabled: true
serializer:
    serialize_null: true
service:
    view_handler: app.view_handler.csv

Under services

app.view_handler.csv:
    class: AppBundle\View\CsvViewHandler

app.view_handler:
    parent: fos_rest.view_handler.default
    public: true
    autowire: true
    autoconfigure: false
    calls:
        - ['registerHandler', ['csv', ["@app.view_handler.csv",'createResponse'] ] ]

The Handler Class

namespace AppBundle\View;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\View\View;
use FOS\RestBundle\View\ViewHandler;


class CsvViewHandler
{

    public function createResponse(ViewHandler $handler, View $view, Request $request, $format)
    {
        $spreadSheet = new Spreadsheet();

        $spreadSheet->getActiveSheet()->getCell('A1')->setValue('CSV DOWNLOAD EXAMPLE');

        $csv = new Csv($spreadSheet);


        return new Response($csv, 200, $view->getHeaders());
    }
}

The idea is that every data sended in the request to /service/export-to-csv be procesed and returned as a .csv file. But the problem is that I still getting this FatalThrowableError:

Type error: Argument 1 passed to FOS\RestBundle\Controller\TemplatingExceptionController::__construct() must implement interface FOS\RestBundle\View\ViewHandlerInterface, instance of AppBundle\View\CsvViewHandler given, called in /var/www/sicocme-emed-api/var/cache/dev/ContainerDztemfl/getFosRest_Exception_TwigControllerService.php on line 14

0

There are 0 answers