Repository navigation
Expand file tree
/
Copy pathJaneOpenApi.php
More file actions
230 lines (187 loc) · 9.48 KB
/
Copy pathJaneOpenApi.php
File metadata and controls
230 lines (187 loc) · 9.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
<?php
namespace Jane\Component\OpenApiCommon;
use Jane\Component\JsonSchema\Event\PropertyGuessedEvent;
use Jane\Component\JsonSchema\Generator\ChainGenerator;
use Jane\Component\JsonSchema\Generator\Context\Context;
use Jane\Component\JsonSchema\Generator\Naming;
use Jane\Component\JsonSchema\Generator\Options;
use Jane\Component\JsonSchema\Guesser\ChainGuesser;
use Jane\Component\JsonSchema\Guesser\Guess\NonObjectGuessInterface;
use Jane\Component\JsonSchema\Guesser\Validator\ChainValidatorFactory;
use Jane\Component\JsonSchema\Registry\Registry;
use Jane\Component\JsonSchemaRuntime\ReferenceResolver;
use Jane\Component\OpenApiCommon\Contracts\WhitelistFetchInterface;
use Jane\Component\OpenApiCommon\Guesser\Guess\ClassGuess;
use Jane\Component\OpenApiCommon\Guesser\Guess\ParentClass;
use Jane\Component\OpenApiCommon\Naming\OperationNamingFactory;
use Jane\Component\OpenApiCommon\Registry\Registry as OpenApiRegistry;
use Jane\Component\OpenApiCommon\Registry\Schema;
use Jane\Component\OpenApiCommon\SchemaParser\SchemaParser;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Serializer\Encoder\JsonDecode;
use Symfony\Component\Serializer\Encoder\JsonEncode;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\YamlEncoder;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Yaml\Dumper;
use Symfony\Component\Yaml\Parser;
abstract class JaneOpenApi extends ChainGenerator
{
protected const OBJECT_NORMALIZER_CLASS = null;
protected const WHITELIST_FETCH_CLASS = null;
protected SchemaParser $schemaParser;
protected Naming $naming;
protected ChainValidatorFactory $chainValidatorFactory;
/** @var array<string, mixed> */
protected array $options = [];
protected NormalizerInterface|DenormalizerInterface $serializer;
/**
* @param class-string $schemaParserClass
*/
public function __construct(
string $schemaParserClass,
protected ChainGuesser $chainGuesser,
protected bool $strict = true,
) {
$this->serializer = static::buildSerializer();
$this->schemaParser = new $schemaParserClass($this->serializer);
$this->naming = new Naming();
}
public function getSerializer(): NormalizerInterface|DenormalizerInterface
{
return $this->serializer;
}
/**
* @param OpenApiRegistry $registry
*/
public function createContext(Registry $registry): Context
{
/** @var Schema[] $schemas */
$schemas = array_values($registry->getSchemas());
foreach ($schemas as $schema) {
$openApiSpec = $this->schemaParser->parseSchema($schema->getOrigin());
$this->chainGuesser->guessClass($openApiSpec, $schema->getRootName(), $schema->getOrigin() . '#', $registry);
$schema->setParsed($openApiSpec);
}
$chainValidator = $this->chainValidatorFactory->create($this->naming, $registry, $this->serializer);
$checkWhitelistedPaths = \count($registry->getWhitelistedPaths()) > 0;
foreach ($schemas as $schema) {
/** @var array<string, \RuntimeException> Guessing failures indexed by class reference */
$guessingFailures = [];
foreach ($schema->getClasses() as $class) {
if ($class instanceof NonObjectGuessInterface) {
continue;
}
try {
$properties = $this->chainGuesser->guessProperties($class->getObject(), $schema->getRootName(), $class->getReference(), $registry);
$names = [];
foreach ($properties as $property) {
$deduplicatedName = $this->naming->getDeduplicatedName($property->getName(), $names);
$property->setAccessorName($deduplicatedName);
$property->setPhpName($this->naming->getPropertyName($deduplicatedName));
$property->setType($this->chainGuesser->guessType($property->getObject(), $property->getName(), $property->getReference(), $registry));
}
$class->setProperties($properties);
$extensionsTypes = [];
foreach ($class->getExtensionsObject() as $pattern => $extensionData) {
$extensionsTypes[$pattern] = $this->chainGuesser->guessType($extensionData['object'], $class->getName(), $extensionData['reference'], $registry);
}
$class->setExtensionsType($extensionsTypes);
// after the extension types: they are relations the whitelist pruning must follow
$schema->addClassRelations($class);
$chainValidator->guess($class->getObject(), $class->getName(), $class);
foreach ($properties as $property) {
$this->dispatcher->dispatch(new PropertyGuessedEvent($schema, $class, $property));
}
} catch (\RuntimeException $exception) {
if (!$checkWhitelistedPaths) {
throw $exception;
}
// the class might be pruned by the whitelist filtering, so the failure is deferred until we know if it is needed
$guessingFailures[$class->getReference()] = $exception;
}
}
$this->hydrateDiscriminatedClasses($schema, $registry);
// when we have a whitelist, we want to have only needed models to be generated
if ($checkWhitelistedPaths) {
$this->whitelistFetch($schema, $registry);
// a deferred guessing failure only matters if the class survived the whitelist filtering,
// meaning it is needed by one of the whitelisted operations
foreach ($guessingFailures as $reference => $exception) {
if (null !== $schema->getClass($reference)) {
throw $exception;
}
}
}
}
return new Context($registry, $this->strict, $this->dispatcher);
}
/**
* @param OpenApiRegistry $registry
*/
protected function whitelistFetch(Schema $schema, Registry $registry): void
{
$whitelistFetchClass = static::WHITELIST_FETCH_CLASS;
$naming = OperationNamingFactory::create($this->options['operation-namings'] ?? []);
/** @var WhitelistFetchInterface $whitelistedSchema */
$whitelistedSchema = new $whitelistFetchClass($schema, static::buildSerializer(), $naming);
foreach ($schema->getOperations() as $operation) {
$whitelistedSchema->addOperationRelations($operation, $registry);
}
$schema->filterRelations();
}
protected function hydrateDiscriminatedClasses(Schema $schema, Registry $registry)
{
foreach ($schema->getClasses() as $class) {
if ($class instanceof ParentClass) { // is parent class
$class->setModelNamespace($this->naming->getModelNamespace($schema->getNamespace(), $class->getSubNamespace()));
foreach ($class->getChildReferences() as $reference) {
$guess = $registry->getClass($reference);
if ($guess instanceof ClassGuess) { // is child class
$guess->setParentClass($class);
}
}
}
}
}
public static function buildSerializer(): SerializerInterface|DenormalizerInterface|NormalizerInterface
{
$encoders = [
new JsonEncoder(new JsonEncode([JsonEncode::OPTIONS => \JSON_UNESCAPED_SLASHES]), new JsonDecode()),
new YamlEncoder(new Dumper(), new Parser()),
];
$objectNormalizerClass = static::OBJECT_NORMALIZER_CLASS;
return new Serializer([new $objectNormalizerClass()], $encoders);
}
abstract protected static function create(array $options = [], ?ChainValidatorFactory $chainValidatorFactory = null): self;
abstract protected static function generators(DenormalizerInterface $denormalizer, array $options = []): \Generator;
public static function build(array $options = [], ?EventDispatcherInterface $dispatcher = null)
{
$options = Options::fromArray($options);
$optionsArray = $options->toArray();
ReferenceResolver::default()->applyOptions($optionsArray);
$chainValidatorFactory = new ChainValidatorFactory(
$options->fullDateFormat,
$options->dateFormat,
$options->dateInputFormat,
);
foreach ($options->validators as $validator) {
$chainValidatorFactory->addValidator($validator);
}
$instance = static::create($optionsArray, $chainValidatorFactory);
$instance->options = $optionsArray;
$instance->chainValidatorFactory = $chainValidatorFactory;
$instance->dispatcher = $dispatcher ?? new EventDispatcher();
/** @var DenormalizerInterface $denormalizer */
$denormalizer = $instance->getSerializer();
$generators = static::generators($denormalizer, $optionsArray);
foreach ($generators as $generator) {
$instance->addGenerator($generator);
}
return $instance;
}
}