1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Swagger\Middleware; |
6
|
|
|
|
7
|
|
|
use DateInterval; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
10
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
11
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
12
|
|
|
use Psr\SimpleCache\CacheInterface; |
13
|
|
|
use Yiisoft\DataResponse\DataResponseFactoryInterface; |
14
|
|
|
use Yiisoft\Swagger\Service\SwaggerService; |
15
|
|
|
|
16
|
|
|
use function md5; |
17
|
|
|
use function var_export; |
18
|
|
|
|
19
|
|
|
final class SwaggerJson implements MiddlewareInterface |
20
|
|
|
{ |
21
|
|
|
private array $annotationPaths = []; |
22
|
|
|
private bool $enableCache = false; |
23
|
|
|
private CacheInterface $cache; |
24
|
|
|
private DataResponseFactoryInterface $responseFactory; |
25
|
|
|
private SwaggerService $swaggerService; |
26
|
|
|
|
27
|
|
|
/** @var DateInterval|int|null $cacheTTL */ |
28
|
|
|
private $cacheTTL; |
29
|
|
|
|
30
|
1 |
|
public function __construct( |
31
|
|
|
CacheInterface $cache, |
32
|
|
|
DataResponseFactoryInterface $responseFactory, |
33
|
|
|
SwaggerService $swaggerService |
34
|
|
|
) { |
35
|
1 |
|
$this->cache = $cache; |
36
|
1 |
|
$this->responseFactory = $responseFactory; |
37
|
1 |
|
$this->swaggerService = $swaggerService; |
38
|
1 |
|
} |
39
|
|
|
|
40
|
1 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
41
|
|
|
{ |
42
|
1 |
|
$cacheKey = $this->enableCache ? $this->getCacheKey() : false; |
43
|
|
|
|
44
|
1 |
|
if ($cacheKey && $this->cache->has($cacheKey)) { |
45
|
|
|
return $this->responseFactory |
46
|
|
|
->createResponse($this->cache->get($cacheKey)); |
47
|
|
|
} |
48
|
|
|
|
49
|
1 |
|
$openApi = $this->swaggerService |
50
|
1 |
|
->fetch($this->annotationPaths); |
51
|
|
|
|
52
|
1 |
|
if ($cacheKey) { |
53
|
|
|
$this->cache->set($cacheKey, $openApi, $this->cacheTTL); |
54
|
|
|
} |
55
|
|
|
|
56
|
1 |
|
return $this->responseFactory |
57
|
1 |
|
->createResponse($openApi); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
private function getCacheKey(): string |
61
|
|
|
{ |
62
|
|
|
return md5(var_export([self::class, $this->annotationPaths], true)); |
63
|
|
|
} |
64
|
|
|
|
65
|
1 |
|
public function withAnnotationPaths(array $annotationPaths): self |
66
|
|
|
{ |
67
|
1 |
|
$new = clone $this; |
68
|
1 |
|
$new->annotationPaths = $annotationPaths; |
69
|
1 |
|
return $new; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @param DateInterval|int|null $cacheTTL |
74
|
|
|
* @return SwaggerJson |
75
|
|
|
*/ |
76
|
1 |
|
public function withCache($cacheTTL = null): self |
77
|
|
|
{ |
78
|
1 |
|
$new = clone $this; |
79
|
1 |
|
$new->enableCache = true; |
80
|
1 |
|
$new->cacheTTL = $cacheTTL; |
81
|
1 |
|
return $new; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
} |
85
|
|
|
|