-
Notifications
You must be signed in to change notification settings - Fork 0
/
OpenAPIRenderer.php
executable file
·100 lines (85 loc) · 2.57 KB
/
OpenAPIRenderer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
namespace globalart\swagger;
use Swagger\Annotations\Swagger;
use Yii;
use yii\base\Action;
use yii\caching\Cache;
use yii\di\Instance;
use yii\web\Response;
/**
* Class OpenAPIRenderer is responsible for generating the JSON spec.
*
* @package globalart\swagger\actions
*/
class OpenAPIRenderer extends Action
{
/**
* @var string|array|\Symfony\Component\Finder\Finder The directory(s) or filename(s).
* If you configured the directory must be full path of the directory.
*/
public $scanDir;
/**
* @var array the options passed to `Swagger`, Please refer the `Swagger\scan` function for more information
*/
public $scanOptions = [];
/**
* @var Cache|array|string the cache used to improve generating api documentation performance. This can be one of the followings:
*
* - an application component ID (e.g. `cache`)
* - a configuration array
* - a [[yii\caching\Cache]] object
*
* When this is not set, it means caching is not enabled
*/
public $cache = 'cache';
/**
* @var int default duration in seconds before the cache will expire
*/
public $cacheDuration = 360;
/**
* @var string the key used to store swagger data in cache
*/
public $cacheKey = 'api-swagger-cache';
/**
* @inheritdoc
*/
public function init(): void
{
parent::init();
if ($this->cache !== null) {
$this->cache = Instance::ensure($this->cache, Cache::class);
}
}
/**
* @inheritdoc
*/
public function run(): Response
{
$this->enableCORS();
return $this->controller->asJson($this->getSwaggerDocumentation());
}
/**
* Scan the filesystem for swagger annotations and build swagger-documentation.
*
* @return Swagger
*/
protected function getSwaggerDocumentation()
{
if (!$this->cache instanceof Cache) {
return \OpenApi\Generator::scan($this->scanDir, $this->scanOptions);
}
return $this->cache->getOrSet($this->cacheKey, function () {
return \OpenApi\Generator::scan($this->scanDir, $this->scanOptions);
}, $this->cacheDuration);
}
/**
* Enable CORS
*/
protected function enableCORS(): void
{
$headers = Yii::$app->getResponse()->getHeaders();
$headers->set('Access-Control-Allow-Headers', 'Content-Type, api_key, Authorization');
$headers->set('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT');
$headers->set('Access-Control-Allow-Origin', '*');
}
}