Skip to content

Add keyBy() to key the documents by the given key - #69

Closed
thekid wants to merge 2 commits into
masterfrom
feature/key-by
Closed

Add keyBy() to key the documents by the given key#69
thekid wants to merge 2 commits into
masterfrom
feature/key-by

Conversation

@thekid

@thekid thekid commented Jul 13, 2026

Copy link
Copy Markdown
Member

This method keys the cursor's documents by the given key, yielding the key / value pairs.

Comparison

Before:

$claims= [];
foreach ($this->claims->find(['user' => $user]) as $claim) {
  $claims[$claim['tenant']]= $claim;
}

After:

$claims= [...$this->claims->find(['user' => $user])->keyBy('tenant')];

Overloads

  • keyBy('tenant') - uses the tenant field as keys and the docunents as associated values
  • keyBy(['tenant' => 'tokens.access']) will use the tenant field as keys and the access key in the tokens object as values
  • keyBy(fn($c) => [$c->get('tenant') => $c]) - same as above but shows the full flexibility
  • keyBy(function($c) { yield $c->get('tenant') => $c; }) - also works with generators

Prior art

@thekid

thekid commented Jul 26, 2026

Copy link
Copy Markdown
Member Author

This can already be done by the https://github.com/xp-forge/sequence library:

use util\cmd\Console;
use util\data\Sequence;

$users= [
  ['tenant' => 'example', 'jwt' => 'ey123...', 'valid' => '2027-01-01'],
  ['tenant' => 'platform', 'jwt' => 'ey345...', 'valid' => '2026-12-14'],
];
$claims= Sequence::of($users)->toMap(fn($user) => yield $user['tenant'] => $user);

Here's how we could extend this library_

use util\data\Collectors;

// Add optional "keyby" argument
$claims= Sequence::of($users)->toMap(keyby: 'tenant');

// Add keyBy()
$claims= Sequence::of($users)->keyBy('tenant');

// Extends Collectors API
$claims= Sequence::of($users)->collect(Collectors::keyBy('tenant'));

These would be even more elegant if extension methods were available:

Sequence::of($this->claims->find(['user' => $user]))->keyBy('tenant');

// With a "sequence" extension method:
$this->claims->find(['user' => $user])->sequence()->keyBy('tenant');

@thekid

thekid commented Jul 26, 2026

Copy link
Copy Markdown
Member Author

Closed in favor of adding this to the sequence library

@thekid thekid closed this Jul 26, 2026
@thekid
thekid deleted the feature/key-by branch July 26, 2026 08:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant