Completed
Pull Request — master (#20)
by Woody
02:36 queued 41s
created

SwaggerSchemaFactory::resolveSchemaFile()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 41
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 5

Importance

Changes 0
Metric Value
eloc 23
dl 0
loc 41
ccs 21
cts 21
cp 1
rs 9.2408
c 0
b 0
f 0
cc 5
nc 6
nop 1
crap 5
1
<?php
2
namespace ElevenLabs\Api\Factory;
3
4
use ElevenLabs\Api\Definition\RequestDefinition;
5
use ElevenLabs\Api\Definition\Parameter;
6
use ElevenLabs\Api\Definition\Parameters;
7
use ElevenLabs\Api\Definition\RequestDefinitions;
8
use ElevenLabs\Api\Definition\ResponseDefinition;
9
use ElevenLabs\Api\Schema;
10
use ElevenLabs\Api\JsonSchema\Uri\YamlUriRetriever;
11
use JsonSchema\SchemaStorage;
12
use JsonSchema\Uri\UriResolver;
13
use JsonSchema\Uri\UriRetriever;
14
use stdClass;
15
use Symfony\Component\Yaml\Yaml;
16
17
/**
18
 * Create a schema definition from a Swagger file
19
 */
20
class SwaggerSchemaFactory implements SchemaFactory
21
{
22 17
    public function createSchema(string $schemaFile): Schema
23
    {
24 17
        $schema = $this->resolveSchemaFile($schemaFile);
25
26 16
        $host = isset($schema->host) ? $schema->host : null;
27 16
        $basePath = isset($schema->basePath) ? $schema->basePath : '';
28 16
        $schemes = isset($schema->schemes) ? $schema->schemes : ['http'];
29
30 16
        return new Schema(
31 16
            $this->createRequestDefinitions($schema),
32 13
            $basePath,
33 13
            $host,
0 ignored issues
show
Bug introduced by
It seems like $host can also be of type null; however, parameter $host of ElevenLabs\Api\Schema::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

33
            /** @scrutinizer ignore-type */ $host,
Loading history...
34 13
            $schemes
35
        );
36
    }
37
38 17
    protected function resolveSchemaFile($schemaFile): stdClass
39
    {
40 17
        $extension = pathinfo($schemaFile, PATHINFO_EXTENSION);
41 17
        switch ($extension) {
42 17
            case 'yml':
43 17
            case 'yaml':
44 1
                if (!class_exists(Yaml::class)) {
45
                    // @codeCoverageIgnoreStart
46
                    throw new \InvalidArgumentException(
47
                        'You need to require the "symfony/yaml" component in order to parse yml files'
48
                    );
49
                    // @codeCoverageIgnoreEnd
50
                }
51
52 1
                $uriRetriever = new YamlUriRetriever();
53 1
                break;
54 16
            case 'json':
55 15
                $uriRetriever = new UriRetriever();
56 15
                break;
57
            default:
58 1
                throw new \InvalidArgumentException(
59 1
                    sprintf(
60 1
                        'file "%s" does not provide a supported extension choose either json, yml or yaml',
61 1
                        $schemaFile
62
                    )
63
                );
64
        }
65
66 16
        $schemaStorage = new SchemaStorage(
67 16
            $uriRetriever,
68 16
            new UriResolver()
69
        );
70
71 16
        $schema = $schemaStorage->getSchema($schemaFile);
72
73
        // JsonSchema normally defers resolution of $ref values until validation.
74
        // That does not work for us, because we need to have the complete schema
75
        // to build definitions.
76 16
        $this->expandSchemaReferences($schema, $schemaStorage);
77
78 16
        return $schema;
79
    }
80
81 16
    private function expandSchemaReferences(&$schema, SchemaStorage $schemaStorage): void
82
    {
83 16
        foreach ($schema as &$member) {
84 16
            if (is_object($member) && property_exists($member, '$ref') && is_string($member->{'$ref'})) {
85 9
                $member = $schemaStorage->resolveRef($member->{'$ref'});
86
            }
87 16
            if (is_object($member) || is_array($member)) {
88 16
                $this->expandSchemaReferences($member, $schemaStorage);
89
            }
90
        }
91 16
    }
92
93 16
    protected function createRequestDefinitions(stdClass $schema): RequestDefinitions
94
    {
95 16
        $definitions = [];
96 16
        $defaultConsumedContentTypes = [];
97 16
        $defaultProducedContentTypes = [];
98
99 16
        if (isset($schema->consumes)) {
100 1
            $defaultConsumedContentTypes = $schema->consumes;
101
        }
102 16
        if (isset($schema->produces)) {
103 1
            $defaultProducedContentTypes = $schema->produces;
104
        }
105
106 16
        $basePath = isset($schema->basePath) ? $schema->basePath : '';
107
108 16
        foreach ($schema->paths as $pathTemplate => $methods) {
109 16
            foreach ($methods as $method => $definition) {
110 16
                $method = strtoupper($method);
111 16
                $contentTypes = $defaultConsumedContentTypes;
112 16
                if (isset($definition->consumes)) {
113 9
                    $contentTypes = $definition->consumes;
114
                }
115
116 16
                if (!isset($definition->operationId)) {
117 1
                    throw new \LogicException(
118 1
                        sprintf(
119 1
                            'You need to provide an operationId for %s %s',
120 1
                            $method,
121 1
                            $pathTemplate
122
                        )
123
                    );
124
                }
125
126 15
                if (empty($contentTypes) && $this->containsBodyParametersLocations($definition)) {
127 12
                    $contentTypes = $this->guessSupportedContentTypes($definition, $pathTemplate);
128
                }
129
130 14
                if (!isset($definition->responses)) {
131 1
                    throw new \LogicException(
132 1
                        sprintf(
133 1
                            'You need to specify at least one response for %s %s',
134 1
                            $method,
135 1
                            $pathTemplate
136
                        )
137
                    );
138
                }
139
140 13
                if (!isset($definition->parameters)) {
141 2
                    $definition->parameters = [];
142
                }
143
144 13
                $requestParameters = [];
145 13
                foreach ($definition->parameters as $parameter) {
146 11
                    $requestParameters[] = $this->createParameter($parameter);
147
                }
148
149 13
                $responseContentTypes = $defaultProducedContentTypes;
150 13
                if (isset($definition->produces)) {
151 11
                    $responseContentTypes = $definition->produces;
152
                }
153
154 13
                $responseDefinitions = [];
155 13
                foreach ($definition->responses as $statusCode => $response) {
156 13
                    $responseDefinitions[] = $this->createResponseDefinition(
157 13
                        $statusCode,
158 13
                        $responseContentTypes,
159 13
                        $response
160
                    );
161
                }
162
163 13
                $definitions[] = new RequestDefinition(
164 13
                    $method,
165 13
                    $definition->operationId,
166 13
                    $basePath.$pathTemplate,
167 13
                    new Parameters($requestParameters),
168 13
                    $contentTypes,
169 13
                    $responseDefinitions
170
                );
171
            }
172
        }
173
174 13
        return new RequestDefinitions($definitions);
175
    }
176
177 14
    private function containsBodyParametersLocations(stdClass $definition): bool
178
    {
179 14
        if (!isset($definition->parameters)) {
180 2
            return false;
181
        }
182
183 12
        foreach ($definition->parameters as $parameter) {
184 12
            if (isset($parameter->in) && \in_array($parameter->in, Parameter::BODY_LOCATIONS, true)) {
185 12
                return true;
186
            }
187
        }
188
189 9
        return false;
190
    }
191
192
    /**
193
     * @return string[]
194
     */
195 12
    private function guessSupportedContentTypes(stdClass $definition, string $pathTemplate): array
196
    {
197 12
        if (!isset($definition->parameters)) {
198
            return [];
199
        }
200
201 12
        $bodyLocations = [];
202 12
        foreach ($definition->parameters as $parameter) {
203 12
            if (isset($parameter->in) && \in_array($parameter->in, Parameter::BODY_LOCATIONS, true)) {
204 12
                $bodyLocations[] = $parameter->in;
205
            }
206
        }
207
208 12
        if (count($bodyLocations) > 1) {
209 1
            throw new \LogicException(
210 1
                sprintf(
211 1
                    'Parameters cannot have %s locations at the same time in %s',
212 1
                    implode(' and ', $bodyLocations),
213 1
                    $pathTemplate
214
                )
215
            );
216
        }
217
218 11
        if (count($bodyLocations) === 1) {
219 11
            return [Parameter::BODY_LOCATIONS_TYPES[current($bodyLocations)]];
220
        }
221
222
        return [];
223
    }
224
225
    /**
226
     * @param string|int $statusCode
227
     * @param string[] $allowedContentTypes
228
     */
229 13
    protected function createResponseDefinition($statusCode, array $allowedContentTypes, stdClass $response): ResponseDefinition
230
    {
231 13
        $parameters = [];
232 13
        if (isset($response->schema)) {
233 9
            $parameters[] = $this->createParameter((object) [
234 9
                'in' => 'body',
235 9
                'name' => 'body',
236
                'required' => true,
237 9
                'schema' => $response->schema
238
            ]);
239
        }
240
241 13
        if (isset($response->headers)) {
242 9
            foreach ($response->headers as $headerName => $schema) {
243 9
                $schema->in = 'header';
244 9
                $schema->name = $headerName;
245 9
                $schema->required = true;
246 9
                $parameters[] = $this->createParameter($schema);
247
            }
248
        }
249
250 13
        return new ResponseDefinition($statusCode, $allowedContentTypes, new Parameters($parameters));
251
    }
252
253 11
    protected function createParameter(stdClass $parameter): Parameter
254
    {
255 11
        $parameter = get_object_vars($parameter);
256 11
        $location = $parameter['in'];
257 11
        $name = $parameter['name'];
258 11
        $schema = isset($parameter['schema']) ? $parameter['schema'] : new stdClass();
259 11
        $required = isset($parameter['required']) ? $parameter['required'] : false;
260
261 11
        unset($parameter['in']);
262 11
        unset($parameter['name']);
263 11
        unset($parameter['required']);
264 11
        unset($parameter['schema']);
265
266
        // Every remaining parameter may be json schema properties
267 11
        foreach ($parameter as $key => $value) {
268 11
            $schema->{$key} = $value;
269
        }
270
271
        // It's not relevant to validate file type
272 11
        if (isset($schema->format) && $schema->format === 'file') {
273
            $schema = null;
274
        }
275
276 11
        return new Parameter($location, $name, $required, $schema);
277
    }
278
}
279