Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
64.29% |
9 / 14 |
|
66.67% |
2 / 3 |
CRAP | |
0.00% |
0 / 1 |
| RestApiController | |
64.29% |
9 / 14 |
|
66.67% |
2 / 3 |
4.73 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| __invoke | |
50.00% |
5 / 10 |
|
0.00% |
0 / 1 |
2.50 | |||
| createResponse | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | namespace Apie\RestApi\Controllers; |
| 3 | |
| 4 | use Apie\Common\ApieFacade; |
| 5 | use Apie\Common\Events\ResponseDispatcher; |
| 6 | use Apie\Common\Exceptions\EntityNotModifiedException; |
| 7 | use Apie\Common\StreamFactory\StreamFactoryInterface; |
| 8 | use Apie\Core\Actions\ActionResponse; |
| 9 | use Apie\Core\ContextBuilders\ContextBuilderFactory; |
| 10 | use Apie\Core\ContextConstants; |
| 11 | use Nyholm\Psr7\Response; |
| 12 | use Psr\Http\Message\ResponseInterface; |
| 13 | use Psr\Http\Message\ServerRequestInterface; |
| 14 | |
| 15 | class RestApiController |
| 16 | { |
| 17 | public function __construct( |
| 18 | private readonly ContextBuilderFactory $contextBuilderFactory, |
| 19 | private readonly ApieFacade $apieFacade, |
| 20 | private readonly StreamFactoryInterface $streamFactory, |
| 21 | private readonly ResponseDispatcher $responseDispatcher |
| 22 | ) { |
| 23 | } |
| 24 | |
| 25 | public function __invoke(ServerRequestInterface $request): ResponseInterface |
| 26 | { |
| 27 | $context = $this->contextBuilderFactory->createFromRequest($request, [ContextConstants::REST_API => true]); |
| 28 | |
| 29 | $action = $this->apieFacade->createAction($context); |
| 30 | try { |
| 31 | $data = ($action)($context, $context->getContext(ContextConstants::RAW_CONTENTS)); |
| 32 | } catch (EntityNotModifiedException $exception) { |
| 33 | $response = new Response(304, [ |
| 34 | 'ETag' => $exception->etag, |
| 35 | 'Cache-Control' => 'no-cache', |
| 36 | ]); |
| 37 | return $this->responseDispatcher->triggerResponseCreated($response, $context); |
| 38 | } |
| 39 | |
| 40 | return $this->createResponse($request, $data); |
| 41 | } |
| 42 | |
| 43 | private function createResponse(ServerRequestInterface $request, ActionResponse $output): ResponseInterface |
| 44 | { |
| 45 | $response = $this->streamFactory->createStream($request, $output) ?? new Response(); |
| 46 | $response = $this->responseDispatcher->triggerResponseCreated($response, $output->apieContext); |
| 47 | |
| 48 | return $response; |
| 49 | } |
| 50 | } |