Test Failed
Push — master ( ff4390...71c56c )
by Alexander
03:31 queued 01:52
created

SwaggerJson::getCacheKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
cc 1
nc 1
nop 0
crap 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 CacheInterface $cache;
22
    private DataResponseFactoryInterface $responseFactory;
23
    private SwaggerService $swaggerService;
24
    private DateInterval|int|null $cacheTTL = null;
25
26
    public function __construct(
27
        CacheInterface $cache,
28
        DataResponseFactoryInterface $responseFactory,
29
        SwaggerService $swaggerService
30 1
    ) {
31
        $this->cache = $cache;
32
        $this->responseFactory = $responseFactory;
33
        $this->swaggerService = $swaggerService;
34
    }
35 1
36 1
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
37 1
    {
38 1
        /** @var OpenApi $openApi */
39
        $openApi = !$this->enableCache ? $this->swaggerService->fetch($this->annotationPaths) : $this->cache->getOrSet(
40 1
            [self::class, $this->annotationPaths],
41
            static fn () => $this->swaggerService->fetch($this->annotationPaths),
42 1
            $this->cacheTTL,
43
        );
44 1
45
        return $this->responseFactory->createResponse($openApi);
46
    }
47
48
    /**
49 1
     * @param string[] $annotationPaths
50 1
     *
51
     * @return self
52 1
     */
53
    public function withAnnotationPaths(array $annotationPaths): self
54
    {
55
        $new = clone $this;
56 1
        $new->annotationPaths = $annotationPaths;
57 1
        return $new;
58
    }
59
60
    /**
61
     * @param DateInterval|int|null $cacheTTL
62
     *
63
     * @return self
64
     */
65 1
    public function withCache(DateInterval|int $cacheTTL = null): self
66
    {
67 1
        $new = clone $this;
68 1
        $new->enableCache = true;
69 1
        $new->cacheTTL = $cacheTTL;
70
        return $new;
71
    }
72
}
73