SwaggerService::withOptions()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
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 7
    public function __construct(private Aliases $aliases)
26
    {
27 7
        $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 2
    public function withOptions(array $options): self
46
    {
47 2
        $new = clone $this;
48 2
        $new->options = $options;
49 2
        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