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

SwaggerService   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Test Coverage

Coverage 83.33%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 22
dl 0
loc 57
ccs 20
cts 24
cp 0.8333
rs 10
c 3
b 0
f 0
wmc 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getViewName() 0 3 1
A getViewPath() 0 3 1
A withOptions() 0 5 1
A fetch() 0 18 3
A __construct() 0 5 1
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