1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Swagger\Service; |
6
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use OpenApi\Generator; |
9
|
|
|
use OpenApi\Processors\MergeIntoOpenApi; |
10
|
|
|
use OpenApi\Util; |
11
|
|
|
use OpenApi\Annotations\OpenApi; |
12
|
|
|
use RuntimeException; |
13
|
|
|
use Yiisoft\Aliases\Aliases; |
14
|
|
|
|
15
|
|
|
use function array_map; |
16
|
|
|
use function dirname; |
17
|
|
|
use function sprintf; |
18
|
|
|
|
19
|
|
|
final class SwaggerService |
20
|
|
|
{ |
21
|
|
|
private string $viewPath; |
22
|
|
|
private string $viewName = 'swagger-ui'; |
23
|
|
|
private array $options = []; |
24
|
|
|
|
25
|
6 |
|
public function __construct(private Aliases $aliases) |
26
|
|
|
{ |
27
|
6 |
|
$this->viewPath = dirname(__DIR__, 2) . '/views'; |
28
|
|
|
} |
29
|
|
|
|
30
|
2 |
|
public function getViewPath(): string |
31
|
|
|
{ |
32
|
2 |
|
return $this->aliases->get($this->viewPath); |
33
|
|
|
} |
34
|
|
|
|
35
|
2 |
|
public function getViewName(): string |
36
|
|
|
{ |
37
|
2 |
|
return $this->viewName; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Returns a new instance with the specified options for {@see OpenApi} generation. |
42
|
|
|
* |
43
|
|
|
* @param array $options For {@see Generator::scan()}. |
44
|
|
|
*/ |
45
|
1 |
|
public function withOptions(array $options): self |
46
|
|
|
{ |
47
|
1 |
|
$new = clone $this; |
48
|
1 |
|
$new->options = $options; |
49
|
1 |
|
return $new; |
50
|
|
|
} |
51
|
|
|
|
52
|
2 |
|
public function fetch(array $annotationPaths): OpenApi |
53
|
|
|
{ |
54
|
2 |
|
if ($annotationPaths === []) { |
55
|
1 |
|
throw new InvalidArgumentException('Annotation paths cannot be empty array.'); |
56
|
|
|
} |
57
|
|
|
|
58
|
1 |
|
$directories = array_map(fn (string $path): string => $this->aliases->get($path), $annotationPaths); |
59
|
1 |
|
$openApi = Generator::scan(Util::finder($directories), $this->options); |
60
|
|
|
|
61
|
1 |
|
if ($openApi === null) { |
62
|
|
|
throw new RuntimeException(sprintf( |
63
|
|
|
'No OpenApi target set. Run the "%s" processor before "%s::fetch()".', |
64
|
|
|
MergeIntoOpenApi::class, |
65
|
|
|
self::class, |
66
|
|
|
)); |
67
|
|
|
} |
68
|
|
|
|
69
|
1 |
|
return $openApi; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|