forked from canvural/php-openapi-faker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObjectFaker.php
51 lines (40 loc) · 1.35 KB
/
ObjectFaker.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
<?php
declare(strict_types=1);
namespace Vural\OpenAPIFaker\SchemaFaker;
use cebe\openapi\spec\Schema;
use Faker\Provider\Base;
use Vural\OpenAPIFaker\Options;
use function array_diff;
use function array_keys;
use function array_merge;
use function count;
use function in_array;
/**
* @internal
*/
final class ObjectFaker
{
/**
* @return array<mixed>
*/
public static function generate(Schema $schema, Options $options, bool $request = false): array
{
$result = [];
$requiredKeys = $schema->required ?? [];
$optionalKeys = array_diff(array_keys($schema->properties), $requiredKeys);
$selectedOptionalKeys = Base::randomElements($optionalKeys, Base::numberBetween(0, count($optionalKeys)));
$allPropertyKeys = array_merge($requiredKeys, $selectedOptionalKeys);
foreach ($schema->properties as $key => $property) {
if ($property instanceof Schema) {
if (($request && $property->readOnly) || (! $request && $property->writeOnly)) {
continue;
}
}
if (! $options->getAlwaysFakeOptionals() && ! in_array($key, $allPropertyKeys, true)) {
continue;
}
$result[$key] = (new SchemaFaker($property, $options))->generate();
}
return $result;
}
}