1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Swagger\Action; |
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
|
1 |
|
public function __construct( |
23
|
|
|
private CacheInterface $cache, |
24
|
|
|
private DataResponseFactoryInterface $responseFactory, |
25
|
|
|
private SwaggerService $swaggerService |
26
|
|
|
) { |
27
|
1 |
|
} |
28
|
|
|
|
29
|
1 |
|
public function handle(ServerRequestInterface $request): ResponseInterface |
30
|
|
|
{ |
31
|
1 |
|
if (!$this->enableCache) { |
32
|
1 |
|
$openApi = $this->swaggerService->fetch($this->annotationPaths); |
33
|
|
|
} else { |
34
|
|
|
/** @var OpenApi $openApi */ |
35
|
|
|
$openApi = $this->cache->getOrSet( |
36
|
|
|
[self::class, $this->annotationPaths], |
37
|
|
|
fn () => $this->swaggerService->fetch($this->annotationPaths), |
38
|
|
|
$this->cacheTTL, |
39
|
|
|
); |
40
|
|
|
} |
41
|
|
|
|
42
|
1 |
|
return $this->responseFactory->createResponse($openApi); |
43
|
|
|
} |
44
|
|
|
|
45
|
1 |
|
public function withAnnotationPaths(string ...$annotationPaths): self |
46
|
|
|
{ |
47
|
1 |
|
$new = clone $this; |
48
|
1 |
|
$new->annotationPaths = $annotationPaths; |
49
|
1 |
|
return $new; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param DateInterval|int|null $cacheTTL |
54
|
|
|
*/ |
55
|
1 |
|
public function withCache(DateInterval|int $cacheTTL = null): self |
56
|
|
|
{ |
57
|
1 |
|
$new = clone $this; |
58
|
1 |
|
$new->enableCache = true; |
59
|
1 |
|
$new->cacheTTL = $cacheTTL; |
60
|
1 |
|
return $new; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|