Passed
Push — master ( 773117...ee5c62 )
by Alexander
02:08
created

SwaggerService::withOptions()   A

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 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 Aliases $aliases;
22
23
    private string $viewPath;
24
    private string $viewName;
25
    private array $options = [];
26
27 6
    public function __construct(Aliases $aliases)
28
    {
29 6
        $this->aliases = $aliases;
30 6
        $this->viewPath = dirname(__DIR__, 2) . '/views';
31 6
        $this->viewName = 'swagger-ui';
32 6
    }
33
34 2
    public function getViewPath(): string
35
    {
36 2
        return $this->aliases->get($this->viewPath);
37
    }
38
39 2
    public function getViewName(): string
40
    {
41 2
        return $this->viewName;
42
    }
43
44
    /**
45
     * Returns a new instance with the specified swagger options.
46
     *
47
     * @param array $options For {@see Generator::scan()}.
48
     *
49
     * @return self
50
     */
51 1
    public function withOptions(array $options): self
52
    {
53 1
        $new = clone $this;
54 1
        $new->options = $options;
55 1
        return $new;
56
    }
57
58 2
    public function fetch(array $annotationPaths): OpenApi
59
    {
60 2
        if ($annotationPaths === []) {
61 1
            throw new InvalidArgumentException('Annotation paths cannot be empty array.');
62
        }
63
64 1
        $directories = array_map(fn (string $path): string => $this->aliases->get($path), $annotationPaths);
65 1
        $openApi = Generator::scan(Util::finder($directories), $this->options);
66
67 1
        if ($openApi === null) {
68
            throw new RuntimeException(sprintf(
69
                'No OpenApi target set. Run the "%s" processor before "%s::fetch()".',
70
                MergeIntoOpenApi::class,
71
                self::class,
72
            ));
73
        }
74
75 1
        return $openApi;
76
    }
77
}
78