Test Failed
Pull Request — master (#79)
by Dmitriy
12:15
created

SwaggerJson   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 41
ccs 17
cts 17
cp 1
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 handle() 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\RequestHandlerInterface;
12
use Yiisoft\Cache\CacheInterface;
13
use Yiisoft\DataResponse\DataResponseFactoryInterface;
14
use Yiisoft\Swagger\Service\SwaggerService;
15
16
final class SwaggerJson implements RequestHandlerInterface
17
{
18
    private array $annotationPaths = [];
19
    private bool $enableCache = false;
20
    private DateInterval|int|null $cacheTTL = null;
21
22
    public function __construct(
23 2
        private CacheInterface $cache,
24
        private DataResponseFactoryInterface $responseFactory,
25
        private SwaggerService $swaggerService
26
    ) {
27
    }
28 2
29
    public function handle(ServerRequestInterface $request): ResponseInterface
30 1
    {
31
        /** @var OpenApi $openApi */
32
        $openApi = !$this->enableCache ? $this->swaggerService->fetch($this->annotationPaths) : $this->cache->getOrSet(
33 1
            [self::class, $this->annotationPaths],
34 1
            fn () => $this->swaggerService->fetch($this->annotationPaths),
35 1
            $this->cacheTTL,
36 1
        );
37 1
38
        return $this->responseFactory->createResponse($openApi);
39 1
    }
40
41
    public function withAnnotationPaths(string ...$annotationPaths): self
42 2
    {
43
        $new = clone $this;
44 2
        $new->annotationPaths = $annotationPaths;
45 2
        return $new;
46 2
    }
47
48
    /**
49
     * @param DateInterval|int|null $cacheTTL
50
     */
51
    public function withCache(DateInterval|int $cacheTTL = null): self
52 1
    {
53
        $new = clone $this;
54 1
        $new->enableCache = true;
55 1
        $new->cacheTTL = $cacheTTL;
56 1
        return $new;
57 1
    }
58
}
59