Skip to content

Commit de43221

Browse files
committed
Improve uniqeu array functionality
1 parent a995824 commit de43221

File tree

2 files changed

+26
-8
lines changed

2 files changed

+26
-8
lines changed

src/SchemaFaker/ArrayFaker.php

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@
66

77
use cebe\openapi\spec\Schema;
88
use Faker\Provider\Base;
9-
109
use function array_unique;
11-
use function array_values;
10+
use function count;
11+
use function dump;
1212

1313
/**
1414
* @internal
@@ -30,10 +30,20 @@ public static function generate(Schema $schema): array
3030

3131
for ($i = 0; $i < $itemSize; $i++) {
3232
$fakeData[] = $itemSchema->generate();
33-
}
3433

35-
if ($schema->uniqueItems === true) {
36-
$fakeData = array_values(array_unique($fakeData));
34+
if ($schema->uniqueItems !== true) {
35+
continue;
36+
}
37+
38+
$uniqueData = array_unique($fakeData);
39+
40+
if (count($uniqueData) >= count($fakeData)) {
41+
continue;
42+
}
43+
44+
$i -= count($fakeData) - count($uniqueData);
45+
46+
$fakeData = $uniqueData;
3747
}
3848

3949
return $fakeData;

tests/Unit/SchemaFaker/ArrayFakerTest.php

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,13 @@
99
use Vural\OpenAPIFaker\Tests\Unit\UnitTestCase;
1010

1111
use function array_unique;
12+
use function count;
13+
use function mt_srand;
14+
use function random_int;
1215
use function Safe\sort;
1316

17+
use const MT_RAND_PHP;
18+
1419
/**
1520
* @uses \Vural\OpenAPIFaker\SchemaFaker\SchemaFaker
1621
* @uses \Vural\OpenAPIFaker\SchemaFaker\StringFaker
@@ -127,23 +132,26 @@ function it_handles_nested_arrays()
127132
/** @test */
128133
function it_can_generate_unique_elements()
129134
{
135+
mt_srand(227, MT_RAND_PHP);
136+
130137
$fakeData = ArrayFaker::generate(SchemaFactory::fromJson(
131138
<<< JSON
132139
{
133140
"type": "array",
134141
"items": {
135142
"type": "integer",
136143
"minimum": 1,
137-
"maximum": 2
144+
"maximum": 5
138145
},
139-
"minItems": 1,
140-
"maxItems": 2,
146+
"minItems": 5,
147+
"maxItems": 5,
141148
"uniqueItems": true
142149
}
143150
JSON
144151
));
145152

146153
self::assertIsArray($fakeData);
154+
self::assertCount(5, $fakeData);
147155
self::assertSame($fakeData, array_unique($fakeData));
148156
}
149157

0 commit comments

Comments
 (0)