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

SwaggerJson::handle()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 2
rs 10
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