|
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
|
1 |
|
public function __construct( |
|
27
|
|
|
CacheInterface $cache, |
|
28
|
|
|
DataResponseFactoryInterface $responseFactory, |
|
29
|
|
|
SwaggerService $swaggerService |
|
30
|
|
|
) { |
|
31
|
1 |
|
$this->cache = $cache; |
|
32
|
1 |
|
$this->responseFactory = $responseFactory; |
|
33
|
1 |
|
$this->swaggerService = $swaggerService; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
1 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
|
37
|
|
|
{ |
|
38
|
|
|
/** @var OpenApi $openApi */ |
|
39
|
1 |
|
$openApi = !$this->enableCache ? $this->swaggerService->fetch($this->annotationPaths) : $this->cache->getOrSet( |
|
40
|
|
|
[self::class, $this->annotationPaths], |
|
41
|
|
|
fn () => $this->swaggerService->fetch($this->annotationPaths), |
|
42
|
|
|
$this->cacheTTL, |
|
43
|
|
|
); |
|
44
|
|
|
|
|
45
|
1 |
|
return $this->responseFactory->createResponse($openApi); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* @param string ...$annotationPaths |
|
50
|
|
|
* |
|
51
|
|
|
* @return self |
|
52
|
|
|
*/ |
|
53
|
1 |
|
public function withAnnotationPaths(string ...$annotationPaths): self |
|
54
|
|
|
{ |
|
55
|
1 |
|
$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
|
1 |
|
return $new; |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|