Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
85.71% covered (warning)
85.71%
24 / 28
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
SwaggerUIController
85.71% covered (warning)
85.71%
24 / 28
50.00% covered (danger)
50.00%
1 / 2
5.07
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 __invoke
85.19% covered (warning)
85.19%
23 / 27
0.00% covered (danger)
0.00%
0 / 1
3.03
1<?php
2namespace Apie\RestApi\Controllers;
3
4use Apie\Core\BoundedContext\BoundedContextHashmap;
5use Nyholm\Psr7\Factory\Psr17Factory;
6use Psr\Http\Message\ResponseInterface;
7use Psr\Http\Message\ServerRequestInterface;
8
9class SwaggerUIController
10{
11    private readonly string $htmlPath;
12
13    public function __construct(
14        private readonly string $baseUrl,
15        private readonly BoundedContextHashmap $boundedContextHashmap,
16        ?string $htmlPath = null
17    ) {
18        $this->htmlPath = null === $htmlPath ? __DIR__ . '/../../resources/swagger-ui/index.html' : $htmlPath;
19    }
20
21    public function __invoke(ServerRequestInterface $request): ResponseInterface
22    {
23        $boundedContextId = $request->getAttribute('boundedContextId');
24        $search = [
25            '%%OPENAPI_YAML%%',
26            '%%OPENAPIS_AVAILABLE%%',
27        ];
28        $boundedContext = $this->boundedContextHashmap[$boundedContextId];
29        $urls = [
30            [
31                'url' => '/' . trim($this->baseUrl, '/') . '/' . $boundedContextId . '/openapi.yaml',
32                'name' => $boundedContextId . '(' . $boundedContext->actions->count() . ' actions, ' . $boundedContext->resources->count() . ' resources)',
33            ]
34        ];
35        
36        foreach ($this->boundedContextHashmap as $availableBoundedContextId => $boundedContext) {
37            if ($boundedContextId !== $availableBoundedContextId) {
38                $urls[] = [
39                    'url' => '/' . trim($this->baseUrl, '/') . '/' . $availableBoundedContextId . '/openapi.yaml',
40                    'name' => $availableBoundedContextId . '(' . $boundedContext->actions->count() . ' actions, ' . $boundedContext->resources->count() . ' resources)',
41                ];
42            }
43        }
44        $replace = [
45            '/' . trim($this->baseUrl, '/') . '/' . $boundedContextId . '/openapi.yaml',
46            json_encode($urls),
47        ];
48
49        $responseBody = str_replace($search, $replace, file_get_contents($this->htmlPath));
50        $psr17Factory = new Psr17Factory();
51        return $psr17Factory->createResponse(200)
52            ->withBody($psr17Factory->createStream($responseBody))
53            ->withHeader('Content-Type', 'text/html');
54    }
55}