Passed
Push — master ( 8124c9...ed94cb )
by
unknown
12:35
created

SwaggerJson   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 81.25%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 41
ccs 13
cts 16
cp 0.8125
rs 10
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A withAnnotationPaths() 0 5 1
A withCache() 0 6 1
A process() 0 10 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Swagger\Middleware;
6
7
use DateInterval;
8
use OpenApi\Annotations\OpenApi;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
use Psr\Http\Server\MiddlewareInterface;
12
use Psr\Http\Server\RequestHandlerInterface;
13
use Yiisoft\Cache\CacheInterface;
14
use Yiisoft\DataResponse\DataResponseFactoryInterface;
15
use Yiisoft\Swagger\Service\SwaggerService;
16
17
final class SwaggerJson implements MiddlewareInterface
18
{
19
    private array $annotationPaths = [];
20
    private bool $enableCache = false;
21
    private DateInterval|int|null $cacheTTL = null;
22
23 1
    public function __construct(
24
        private CacheInterface $cache,
25
        private DataResponseFactoryInterface $responseFactory,
26
        private SwaggerService $swaggerService
27
    ) {
28
    }
29
30 1
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
31
    {
32
        /** @var OpenApi $openApi */
33 1
        $openApi = !$this->enableCache ? $this->swaggerService->fetch($this->annotationPaths) : $this->cache->getOrSet(
34
            [self::class, $this->annotationPaths],
35
            fn () => $this->swaggerService->fetch($this->annotationPaths),
36
            $this->cacheTTL,
37
        );
38
39 1
        return $this->responseFactory->createResponse($openApi);
40
    }
41
42 1
    public function withAnnotationPaths(string ...$annotationPaths): self
43
    {
44 1
        $new = clone $this;
45 1
        $new->annotationPaths = $annotationPaths;
46 1
        return $new;
47
    }
48
49
    /**
50
     * @param DateInterval|int|null $cacheTTL
51
     */
52 1
    public function withCache(DateInterval|int $cacheTTL = null): self
53
    {
54 1
        $new = clone $this;
55 1
        $new->enableCache = true;
56 1
        $new->cacheTTL = $cacheTTL;
57 1
        return $new;
58
    }
59
}
60