我遇到了Fos Rest Bundle的问题 - 一切都适用于jsons(响应始终采用这种格式,包括错误)。现在我坚持使用PDF下载。我有两个问题:
我必须使用" application / pdf"发送Accept标头。要获取pdf文件,如果我使用其他类型,我将收到错误,它无法序列化为json。
Uncaught PHP Exception RuntimeException: "Your data could not be encoded because it contains invalid UTF8 characters."
我想强制端点始终使用pdf格式,无论Accept标头中是什么。
如果在生成PDF时出现错误,则响应应采用json格式,并包含错误详细信息(适用于其他端点)。现在,错误以html格式返回。
请记住,我现在正在使用开发环境,因此,config.yml中的异常部分已被注释掉。
我的路线:
我现在拥有的:
config.yml
fos_rest:
access_denied_listener:
html: true
twig: true
body_converter:
enabled: true
view:
default_engine: json
view_response_listener: force
templating_formats:
html: true
twig: false
mime_types:
pdf: ['application/pdf']
formats:
json: true
pdf: false
routing_loader:
default_format: json
include_format: false
format_listener:
rules:
- { path: '^/pdf', priorities: ['pdf'], fallback_format: json, prefer_extension: false }
# /doc is nelmio api doc, so html is correct here
- { path: '^/doc', priorities: ['html'], fallback_format: ~, prefer_extension: false }
- { path: '^/', priorities: ['json'], fallback_format: json, prefer_extension: false }
#exception:
#codes:
# 'ApiBundle\Exception\InvalidArgumentException': 400
# 'ApiBundle\Exception\Exception': true
serializer:
serialize_null: true
service:
view_handler: api.fos_rest.view_handler
services.yml
api.fos_rest.view_handler:
parent: fos_rest.view_handler.default
calls:
- ['registerHandler', ['pdf', ["@api.fos_rest.view_handler.pdf", 'createResponse']]]
api.fos_rest.view_handler.pdf:
class: ApiBundle\View\PdfViewHandler
PdfViewHandler.php
<?php
namespace ApiBundle\View;
use FOS\RestBundle\View\View;
use FOS\RestBundle\View\ViewHandler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class PdfViewHandler
{
public function createResponse(ViewHandler $handler, View $view, Request $request, $format)
{
return new Response($view->getData(), 200, $view->getHeaders());
}
}
DocumentController.php
<?php
namespace ApiBundle\Controller;
use ApiBundle\Document\FilledSurvey;
use FOS\RestBundle\Controller\Annotations as Rest;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
/**
* Class DocumentController
* @package ApiBundle\Controller
*
* @Rest\Route("/pdf")
*/
class DocumentController extends AbstractController
{
/**
* @param FilledSurvey $filledSurvey
* @return mixed
*
* @ApiDoc(
* section = "Document",
* description = "Get document",
* statusCodes = {
* 200 = "Document returned",
* }
* )
*
* @Rest\Get("/{id}", requirements={"id": "[a-zA-Z0-9]+"}, name="document_get")
* @Rest\View(serializerGroups={"???"})
*/
public function getAction(FilledSurvey $filledSurvey)
{
$path = $this->get('api.pdf.generator')->generate($filledSurvey);
return file_get_contents($path);
}
}