Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
41.18% |
7 / 17 |
|
66.67% |
2 / 3 |
CRAP | |
0.00% |
0 / 1 |
| DownloadFileController | |
41.18% |
7 / 17 |
|
66.67% |
2 / 3 |
10.09 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| __invoke | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
1 | |||
| createResponse | |
16.67% |
2 / 12 |
|
0.00% |
0 / 1 |
8.21 | |||
| 1 | <?php |
| 2 | namespace Apie\Graphql\Controllers; |
| 3 | |
| 4 | use Apie\Common\ApieFacade; |
| 5 | use Apie\Common\Events\ResponseDispatcher; |
| 6 | use Apie\Core\Actions\ActionResponse; |
| 7 | use Apie\Core\ContextBuilders\ContextBuilderFactory; |
| 8 | use Apie\Core\ContextConstants; |
| 9 | use Apie\Serializer\EncoderHashmap; |
| 10 | use Nyholm\Psr7\Factory\Psr17Factory; |
| 11 | use Psr\Http\Message\ResponseInterface; |
| 12 | use Psr\Http\Message\ServerRequestInterface; |
| 13 | |
| 14 | /** |
| 15 | * Copy of RestApiController for handling file downloads. Maybe move some code to apie/common? |
| 16 | */ |
| 17 | class DownloadFileController |
| 18 | { |
| 19 | public function __construct( |
| 20 | private readonly ContextBuilderFactory $contextBuilderFactory, |
| 21 | private readonly ApieFacade $apieFacade, |
| 22 | private readonly EncoderHashmap $encoderHashmap, |
| 23 | private readonly ResponseDispatcher $responseDispatcher |
| 24 | ) { |
| 25 | } |
| 26 | |
| 27 | public function __invoke(ServerRequestInterface $request): ResponseInterface |
| 28 | { |
| 29 | $context = $this->contextBuilderFactory->createFromRequest($request, [ContextConstants::REST_API => true]); |
| 30 | |
| 31 | $action = $this->apieFacade->createAction($context); |
| 32 | $data = ($action)($context, $context->getContext(ContextConstants::RAW_CONTENTS)); |
| 33 | |
| 34 | return $this->createResponse($request, $data); |
| 35 | } |
| 36 | |
| 37 | private function createResponse(ServerRequestInterface $request, ActionResponse $output): ResponseInterface |
| 38 | { |
| 39 | if ($output->result instanceof ResponseInterface) { |
| 40 | return $output->result; |
| 41 | } |
| 42 | $contentType = $this->encoderHashmap->getAcceptedContentTypeForRequest($request); |
| 43 | $encoder = $this->encoderHashmap[$contentType]; |
| 44 | |
| 45 | $psr17Factory = new Psr17Factory(); |
| 46 | $statusCode = $output->getStatusCode(); |
| 47 | |
| 48 | $responseBody = $psr17Factory->createStream($statusCode === 204 ? '' : $encoder->encode($output->getResultAsNativeData())); |
| 49 | |
| 50 | $response = $psr17Factory->createResponse($statusCode) |
| 51 | ->withBody($responseBody) |
| 52 | ->withHeader('Content-Type', $contentType); |
| 53 | $response = $this->responseDispatcher->triggerResponseCreated($response, $output->apieContext); |
| 54 | |
| 55 | return $response; |
| 56 | } |
| 57 | } |