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