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
|
|
|
/** |
18
|
|
|
* @deprecated Use {@see \Yiisoft\Swagger\Action\SwaggerJson} instead. Will be removed in next major version. |
19
|
|
|
*/ |
20
|
|
|
final class SwaggerJson implements MiddlewareInterface |
21
|
|
|
{ |
22
|
|
|
private array $annotationPaths = []; |
23
|
|
|
private bool $enableCache = false; |
24
|
|
|
private DateInterval|int|null $cacheTTL = null; |
25
|
|
|
|
26
|
1 |
|
public function __construct( |
27
|
|
|
private CacheInterface $cache, |
28
|
|
|
private DataResponseFactoryInterface $responseFactory, |
29
|
|
|
private SwaggerService $swaggerService |
30
|
|
|
) { |
31
|
1 |
|
} |
32
|
|
|
|
33
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
34
|
|
|
{ |
35
|
|
|
/** @var OpenApi $openApi */ |
36
|
|
|
$openApi = !$this->enableCache ? $this->swaggerService->fetch($this->annotationPaths) : $this->cache->getOrSet( |
37
|
|
|
[self::class, $this->annotationPaths], |
38
|
|
|
fn () => $this->swaggerService->fetch($this->annotationPaths), |
39
|
|
|
$this->cacheTTL, |
40
|
|
|
); |
41
|
|
|
|
42
|
|
|
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
|
|
|
public function withCache(DateInterval|int $cacheTTL = null): self |
56
|
|
|
{ |
57
|
|
|
$new = clone $this; |
58
|
|
|
$new->enableCache = true; |
59
|
|
|
$new->cacheTTL = $cacheTTL; |
60
|
|
|
return $new; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|