Add mapToArray to doc list

This commit is contained in:
Daniel J. Summers 2024-07-28 20:01:55 -04:00
parent 3d2bc2a904
commit 407441e857
3 changed files with 40 additions and 0 deletions

View File

@ -103,6 +103,24 @@ class DocumentList
}
}
/**
* Iterate the generator, extracting key/value pairs returned as an associative array
*
* @template TValue The type for the mapped value
* @param callable(TDoc): (int|string) $keyFunc The function to extract a key from the document
* @param callable(TDoc): TValue $valueFunc The function to extract a value from the document
* @return TValue[] An associative array of values, keyed by the extracted keys
* @throws DocumentException If this is called once the generator has been consumed
*/
public function mapToArray(callable $keyFunc, callable $valueFunc): array
{
$results = [];
foreach ($this->items() as $item) {
$results[$keyFunc($item)] = $valueFunc($item);
}
return $results;
}
/**
* Ensure the statement is destroyed if the generator is not exhausted
*/

View File

@ -113,4 +113,15 @@ class DocumentListTest extends TestCase
$this->assertEquals('*** *** ***** **** ****', implode(' ', $splats),
'Iteration did not have the expected result');
}
public function testMapToArraySucceeds(): void
{
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'There should have been a document list created');
$this->assertTrue($list->hasItems(), 'There should be items in the list');
$lookup = $list->mapToArray(fn($it) => $it->id, fn($it) => $it->value);
$expected = ['one' => 'FIRST!', 'two' => 'another', 'three' => '', 'four' => 'purple', 'five' => 'purple'];
$this->assertEquals($expected, $lookup, 'The array was not mapped correctly');
}
}

View File

@ -111,4 +111,15 @@ class DocumentListTest extends TestCase
$this->assertEquals('*** *** ***** **** ****', implode(' ', $splats),
'Iteration did not have the expected result');
}
public function testMapToArraySucceeds(): void
{
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'There should have been a document list created');
$this->assertTrue($list->hasItems(), 'There should be items in the list');
$lookup = $list->mapToArray(fn($it) => $it->id, fn($it) => $it->value);
$expected = ['one' => 'FIRST!', 'two' => 'another', 'three' => '', 'four' => 'purple', 'five' => 'purple'];
$this->assertEquals($expected, $lookup, 'The array was not mapped correctly');
}
}