Completed
Push — master ( 14fe81...675c2f )
by Guillem
02:29
created

SwaggerSchemaFactory::expandSchemaReferences()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 7

Importance

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