-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathSpecBaseObject.php
612 lines (554 loc) · 21.9 KB
/
SpecBaseObject.php
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
<?php
/**
* @copyright Copyright (c) 2018 Carsten Brandt <[email protected]> and contributors
* @license https://github.com/cebe/php-openapi/blob/master/LICENSE
*/
namespace cebe\openapi;
use cebe\openapi\exceptions\TypeErrorException;
use cebe\openapi\exceptions\UnknownPropertyException;
use cebe\openapi\json\JsonPointer;
use cebe\openapi\json\JsonReference;
use cebe\openapi\spec\Reference;
use cebe\openapi\spec\Schema;
use cebe\openapi\spec\Type;
/**
* Base class for all spec objects.
*
* Implements property management and validation basics.
*
*/
abstract class SpecBaseObject implements SpecObjectInterface, DocumentContextInterface
{
private $_properties = [];
private $_errors = [];
private $_recursingSerializableData = false;
private $_recursingValidate = false;
private $_recursingErrors = false;
private $_recursingReferences = false;
private $_recursingReferenceContext = false;
private $_recursingDocumentContext = false;
private $_recursingAllOf = false;
private $_baseDocument;
private $_jsonPointer;
/**
* @return array array of attributes available in this object.
*/
abstract protected function attributes(): array;
/**
* @return array array of attributes default values.
*/
protected function attributeDefaults(): array
{
return [];
}
/**
* Perform validation on this object, check data against OpenAPI Specification rules.
*
* Call `addError()` in case of validation errors.
*/
abstract protected function performValidation();
/**
* Create an object from spec data.
* @param array $data spec data read from YAML or JSON
* @throws TypeErrorException in case invalid data is supplied.
*/
public function __construct(array $data)
{
foreach ($this->attributes() as $property => $type) {
if (!isset($data[$property])) {
continue;
}
if ($type === Type::BOOLEAN) {
if (!\is_bool($data[$property])) {
$this->_errors[] = "property '$property' must be boolean, but " . gettype($data[$property]) . " given.";
continue;
}
$this->_properties[$property] = (bool) $data[$property];
} elseif (\is_array($type)) {
if (!\is_array($data[$property])) {
$this->_errors[] = "property '$property' must be array, but " . gettype($data[$property]) . " given.";
continue;
}
switch (\count($type)) {
case 1:
if (isset($data[$property]['$ref'])) {
$this->_properties[$property] = new Reference($data[$property], null);
} else {
// array
$this->_properties[$property] = [];
foreach ($data[$property] as $item) {
if ($type[0] === Type::STRING) {
if (!is_string($item)) {
$this->_errors[] = "property '$property' must be array of strings, but array has " . gettype($item) . " element.";
}
$this->_properties[$property][] = $item;
} elseif (Type::isScalar($type[0])) {
$this->_properties[$property][] = $item;
} elseif ($type[0] === Type::ANY) {
if (is_array($item) && isset($item['$ref'])) {
$this->_properties[$property][] = new Reference($item, null);
} else {
$this->_properties[$property][] = $item;
}
} else {
$this->_properties[$property][] = $this->instantiate($type[0], $item);
}
}
}
break;
case 2:
// map
if ($type[0] !== Type::STRING) {
throw new TypeErrorException('Invalid map key type: ' . $type[0]);
}
$this->_properties[$property] = [];
foreach ($data[$property] as $key => $item) {
if ($type[1] === Type::STRING) {
if (!is_string($item)) {
$this->_errors[] = "property '$property' must be map<string, string>, but entry '$key' is of type " . \gettype($item) . '.';
}
$this->_properties[$property][$key] = $item;
} elseif ($type[1] === Type::ANY || Type::isScalar($type[1])) {
$this->_properties[$property][$key] = $item;
} else {
$this->_properties[$property][$key] = $this->instantiate($type[1], $item);
}
}
break;
}
} elseif (Type::isScalar($type)) {
$this->_properties[$property] = $data[$property];
} elseif ($type === Type::ANY) {
if (is_array($data[$property]) && isset($data[$property]['$ref'])) {
$this->_properties[$property] = new Reference($data[$property], null);
} else {
$this->_properties[$property] = $data[$property];
}
} else {
$this->_properties[$property] = $this->instantiate($type, $data[$property]);
}
unset($data[$property]);
}
foreach ($data as $additionalProperty => $value) {
$this->_properties[$additionalProperty] = $value;
}
}
/**
* @throws TypeErrorException
*/
protected function instantiate($type, $data)
{
if ($data instanceof $type || $data instanceof Reference) {
return $data;
}
if (is_array($data) && isset($data['$ref'])) {
return new Reference($data, $type);
}
if (!is_array($data)) {
throw new TypeErrorException(
"Unable to instantiate {$type} Object with data '" . print_r($data, true) . "' at " . $this->getDocumentPosition()
);
}
try {
return new $type($data);
} catch (\TypeError $e) {
throw new TypeErrorException(
"Unable to instantiate {$type} Object with data '" . print_r($data, true) . "' at " . $this->getDocumentPosition(),
$e->getCode(),
$e
);
}
}
/**
* @return mixed returns the serializable data of this object for converting it
* to JSON or YAML.
*/
public function getSerializableData()
{
if ($this->_recursingSerializableData) {
// return a reference
return (object) ['$ref' => JsonReference::createFromUri('', $this->getDocumentPosition())->getReference()];
}
$this->_recursingSerializableData = true;
$data = $this->_properties;
foreach ($data as $k => $v) {
if ($v instanceof SpecObjectInterface) {
$data[$k] = $v->getSerializableData();
} elseif (is_array($v)) {
// test if php arrays should be represented as object in YAML/JSON
$toObject = false;
if (!empty($v)) {
// case 1: non-empty array should be an object if it does not contain
// consecutive numeric keys
$j = 0;
foreach ($v as $i => $d) {
if ($j++ !== $i) {
$toObject = true;
}
if ($d instanceof SpecObjectInterface) {
$data[$k][$i] = $d->getSerializableData();
}
}
} elseif (isset($this->attributes()[$k]) && is_array($this->attributes()[$k]) && 2 === count($this->attributes()[$k])) {
// case 2: Attribute type is an object (specified in attributes() by an array which specifies two items (key and value type)
$toObject = true;
}
if ($toObject) {
$data[$k] = (object) $data[$k];
}
}
}
$this->_recursingSerializableData = false;
return (object) $data;
}
/**
* Validate object data according to OpenAPI spec.
* @return bool whether the loaded data is valid according to OpenAPI spec
* @see getErrors()
*/
public function validate(): bool
{
// avoid recursion to get stuck in a loop
if ($this->_recursingValidate) {
return true;
}
$this->_recursingValidate = true;
$valid = true;
foreach ($this->_properties as $v) {
if ($v instanceof SpecObjectInterface) {
if (!$v->validate()) {
$valid = false;
}
} elseif (is_array($v)) {
foreach ($v as $item) {
if ($item instanceof SpecObjectInterface) {
if (!$item->validate()) {
$valid = false;
}
}
}
}
}
$this->_recursingValidate = false;
$this->performValidation();
if (!empty($this->_errors)) {
$valid = false;
}
return $valid;
}
/**
* @return string[] list of validation errors according to OpenAPI spec.
* @see validate()
*/
public function getErrors(): array
{
// avoid recursion to get stuck in a loop
if ($this->_recursingErrors) {
return [];
}
$this->_recursingErrors = true;
if (($pos = $this->getDocumentPosition()) !== null) {
$errors = [
array_map(function ($e) use ($pos) {
return "[{$pos->getPointer()}] $e";
}, $this->_errors)
];
} else {
$errors = [$this->_errors];
}
foreach ($this->_properties as $v) {
if ($v instanceof SpecObjectInterface) {
$errors[] = $v->getErrors();
} elseif (is_array($v)) {
foreach ($v as $item) {
if ($item instanceof SpecObjectInterface) {
$errors[] = $item->getErrors();
}
}
}
}
$this->_recursingErrors = false;
return array_merge(...$errors);
}
/**
* @param string $error error message to add.
*/
protected function addError(string $error, $class = '')
{
$shortName = explode('\\', $class);
$this->_errors[] = end($shortName).$error;
}
/**
* @param string $name property name.
* @return bool true when this object has a property with a non-null value or the property is defined in the OpenAPI spec.
* @deprecated since 1.6.0, will be removed in 2.0.0
*/
protected function hasProperty(string $name): bool
{
return isset($this->_properties[$name]) || isset($this->attributes()[$name]);
}
/**
* @param string $name property name.
* @return bool true, when a property has a non-null value (does not check for default values)
* @since 1.6.0
*/
protected function hasPropertyValue(string $name): bool
{
return isset($this->_properties[$name]);
}
protected function requireProperties(array $names)
{
foreach ($names as $name) {
if (!isset($this->_properties[$name])) {
$this->addError(" is missing required property: $name", get_class($this));
}
}
}
protected function validateEmail(string $property)
{
if (!empty($this->$property) && strpos($this->$property, '@') === false) {
$this->addError('::$'.$property.' does not seem to be a valid email address: ' . $this->$property, get_class($this));
}
}
protected function validateUrl(string $property)
{
if (!empty($this->$property) && strpos($this->$property, '//') === false) {
$this->addError('::$'.$property.' does not seem to be a valid URL: ' . $this->$property, get_class($this));
}
}
public function __get($name)
{
if (isset($this->_properties[$name])) {
return $this->_properties[$name];
}
$defaults = $this->attributeDefaults();
if (array_key_exists($name, $defaults)) {
return $defaults[$name];
}
if (isset($this->attributes()[$name])) {
if (is_array($this->attributes()[$name])) {
return [];
} elseif ($this->attributes()[$name] === Type::BOOLEAN) {
return false;
}
return null;
}
throw new UnknownPropertyException('Getting unknown property: ' . \get_class($this) . '::' . $name);
}
public function __set($name, $value)
{
$this->_properties[$name] = $value;
}
public function __isset($name)
{
if (isset($this->_properties[$name]) || isset($this->attributeDefaults()[$name]) || isset($this->attributes()[$name])) {
return $this->__get($name) !== null;
}
return false;
}
public function __unset($name)
{
unset($this->_properties[$name]);
}
/**
* Resolves all Reference Objects in this object and replaces them with their resolution.
* @throws exceptions\UnresolvableReferenceException in case resolving a reference fails.
*/
public function resolveReferences(ReferenceContext $context = null)
{
// avoid recursion to get stuck in a loop
if ($this->_recursingReferences) {
return;
}
$this->_recursingReferences = true;
foreach ($this->_properties as $property => $value) {
if ($value instanceof Reference) {
$referencedObject = $value->resolve($context);
$this->_properties[$property] = $referencedObject;
if (!$referencedObject instanceof Reference && $referencedObject instanceof SpecObjectInterface) {
$referencedObject->resolveReferences();
}
} elseif ($value instanceof SpecObjectInterface) {
$value->resolveReferences($context);
} elseif (is_array($value)) {
foreach ($value as $k => $item) {
if ($item instanceof Reference) {
$referencedObject = $item->resolve($context);
$this->_properties[$property][$k] = $referencedObject;
if (!$referencedObject instanceof Reference && $referencedObject instanceof SpecObjectInterface) {
$referencedObject->resolveReferences();
}
} elseif ($item instanceof SpecObjectInterface) {
$item->resolveReferences($context);
}
}
}
}
$this->_recursingReferences = false;
}
/**
* Set context for all Reference Objects in this object.
*/
public function setReferenceContext(ReferenceContext $context)
{
// avoid recursion to get stuck in a loop
if ($this->_recursingReferenceContext) {
return;
}
$this->_recursingReferenceContext = true;
foreach ($this->_properties as $property => $value) {
if ($value instanceof Reference) {
$value->setContext($context);
} elseif ($value instanceof SpecObjectInterface) {
$value->setReferenceContext($context);
} elseif (is_array($value)) {
foreach ($value as $k => $item) {
if ($item instanceof Reference) {
$item->setContext($context);
} elseif ($item instanceof SpecObjectInterface) {
$item->setReferenceContext($context);
}
}
}
}
$this->_recursingReferenceContext = false;
}
/**
* Provide context information to the object.
*
* Context information contains a reference to the base object where it is contained in
* as well as a JSON pointer to its position.
* @param SpecObjectInterface $baseDocument
* @param JsonPointer $jsonPointer
*/
public function setDocumentContext(SpecObjectInterface $baseDocument, JsonPointer $jsonPointer)
{
$this->_baseDocument = $baseDocument;
$this->_jsonPointer = $jsonPointer;
// avoid recursion to get stuck in a loop
if ($this->_recursingDocumentContext) {
return;
}
$this->_recursingDocumentContext = true;
foreach ($this->_properties as $property => $value) {
if ($value instanceof DocumentContextInterface) {
$value->setDocumentContext($baseDocument, $jsonPointer->append($property));
} elseif (is_array($value)) {
foreach ($value as $k => $item) {
if ($item instanceof DocumentContextInterface) {
$item->setDocumentContext($baseDocument, $jsonPointer->append($property)->append($k));
}
}
}
}
$this->_recursingDocumentContext = false;
}
/**
* @return SpecObjectInterface|null returns the base document where this object is located in.
* Returns `null` if no context information was provided by [[setDocumentContext]].
*/
public function getBaseDocument(): ?SpecObjectInterface
{
return $this->_baseDocument;
}
/**
* @return JsonPointer|null returns a JSON pointer describing the position of this object in the base document.
* Returns `null` if no context information was provided by [[setDocumentContext]].
*/
public function getDocumentPosition(): ?JsonPointer
{
return $this->_jsonPointer;
}
/**
* Returns extension properties with `x-` prefix.
* @see https://github.com/OAI/OpenAPI-Specification/blob/3.0.2/versions/3.0.2.md#specificationExtensions
* @return array<string, mixed>
* @since 1.6.0
*/
public function getExtensions(): array
{
$extensions = [];
foreach ($this->_properties as $propertyKey => $extension) {
if (strpos($propertyKey, 'x-') !== 0) {
continue;
}
$extensions[$propertyKey] = $extension;
}
return $extensions;
}
public function getProperties(): array
{
return $this->_properties;
}
public function mergeProperties($properties)
{
$this->_properties = Helper::arrayMergeRecursiveDistinct($this->_properties, $properties);
}
public function resolveAllOf()
{
// avoid recursion to get stuck in a loop
if ($this->_recursingAllOf) {
return;
}
$this->_recursingAllOf = true;
foreach ($this->_properties as $property => $value) {
$this->handleMergingOfAllAllOfs($property, $value);
$this->removeAllOfKey($property, $value);
}
$this->_recursingAllOf = false;
}
private function mergeAllAllOfsInToSingleObject(): self
{
$allOfs = $this->allOf;
/** @var static $first */
$first = $this->allOf[0];
unset($allOfs[0]);
foreach ($allOfs as $allOf) {
/** @var Schema $allOf */
$first->mergeProperties($allOf->getProperties());
}
return $first;
}
private function handleMergingOfAllAllOfs(string $property, $value): void
{
if ($property === 'allOf' && !empty($value)) {
$this->_properties[$property] = $this->mergeAllAllOfsInToSingleObject();
} elseif ($value instanceof SpecObjectInterface && method_exists($value, 'resolveAllOf')) {
$value->resolveAllOf();
} elseif (is_array($value)) {
foreach ($value as $k => $item) {
if ($k === 'allOf' && !empty($item)) {
$this->_properties[$property][$k] = $this->mergeAllAllOfsInToSingleObject();
} elseif ($item instanceof SpecObjectInterface && method_exists($item, 'resolveAllOf')) {
$item->resolveAllOf();
}
}
}
}
private function removeAllOfKey(string $property, $value): void
{
if ($property === 'properties' && !empty($value)) {
foreach ($value as $k => $v) {
if (!empty($v->allOf)) {
$temp = $v->allOf;
$this->_properties[$property][$k] = $temp;
}
}
} elseif ($value instanceof SpecObjectInterface && method_exists($value, 'resolveAllOf')) {
$value->resolveAllOf();
} elseif (is_array($value)) {
foreach ($value as $arrayValueKey => $item) {
if ($arrayValueKey === 'properties' && !empty($item)) {
foreach ($item as $itemKey => $itemValue) {
if (!empty($itemValue->allOf)) {
$tempIn = $itemValue->allOf;
$this->_properties[$property][$arrayValueKey][$itemKey] = $tempIn;
}
}
} elseif ($item instanceof SpecObjectInterface && method_exists($item, 'resolveAllOf')) {
$item->resolveAllOf();
}
}
}
}
}