Skip to content

Commit

Permalink
Fix collecting data from data providers
Browse files Browse the repository at this point in the history
  • Loading branch information
kubawerlos authored and sebastianbergmann committed Apr 19, 2024
1 parent 0e03860 commit 1e82280
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 36 deletions.
45 changes: 17 additions & 28 deletions src/Metadata/Api/DataProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
namespace PHPUnit\Metadata\Api;

use function array_key_exists;
use function array_merge;
use function assert;
use function explode;
use function is_array;
Expand Down Expand Up @@ -39,7 +38,6 @@
use ReflectionClass;
use ReflectionMethod;
use Throwable;
use Traversable;

/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
Expand Down Expand Up @@ -176,33 +174,24 @@ private function dataProvidedByMethods(string $className, string $methodName, Me
);
}

if ($data instanceof Traversable) {
$origData = $data;
$data = [];

foreach ($origData as $key => $value) {
if (is_int($key)) {
$data[] = $value;
} elseif (array_key_exists($key, $data)) {
Event\Facade::emitter()->dataProviderMethodFinished(
$testMethod,
...$methodsCalled,
);

throw new InvalidDataProviderException(
sprintf(
'The key "%s" has already been defined by a previous data provider',
$key,
),
);
} else {
$data[$key] = $value;
}
}
}
foreach ($data as $key => $value) {
if (is_int($key)) {
$result[] = $value;
} elseif (array_key_exists($key, $result)) {
Event\Facade::emitter()->dataProviderMethodFinished(
$testMethod,
...$methodsCalled,
);

if (is_array($data)) {
$result = array_merge($result, $data);
throw new InvalidDataProviderException(
sprintf(
'The key "%s" has already been defined by a previous data provider',
$key,
),
);
} else {
$result[$key] = $value;
}
}
}

Expand Down
13 changes: 5 additions & 8 deletions tests/unit/Metadata/Api/DataProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -168,13 +168,10 @@ public function testWithDuplicateKeyDataProvider(): void

public function testWithDuplicateKeyDataProviders(): void
{
$dataSets = (new DataProvider)->providedData(DuplicateKeyDataProvidersTest::class, 'test');

$this->assertSame(
[
'bar' => [2],
],
$dataSets,
);
$this->expectException(InvalidDataProviderException::class);
$this->expectExceptionMessage('The key "bar" has already been defined by a previous data provider');

/* @noinspection UnusedFunctionResultInspection */
(new DataProvider)->providedData(DuplicateKeyDataProvidersTest::class, 'test');
}
}

0 comments on commit 1e82280

Please sign in to comment.