Changes for beta8 #4
|
@ -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
|
||||
*/
|
||||
|
|
|
@ -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');
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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');
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user