Changes for beta8 #4

Merged
danieljsummers merged 3 commits from beta8 into main 2024-07-29 00:08:44 +00:00
3 changed files with 40 additions and 0 deletions
Showing only changes of commit 407441e857 - Show all commits

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 * 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), $this->assertEquals('*** *** ***** **** ****', implode(' ', $splats),
'Iteration did not have the expected result'); '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), $this->assertEquals('*** *** ***** **** ****', implode(' ', $splats),
'Iteration did not have the expected result'); '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');
}
} }