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