Skip to content

PHPLIB-609: Allow CachingIterator to handle Iterators with non-unique keys #896

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Mar 24, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions src/Model/CachingIterator.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@
*/
class CachingIterator implements Countable, Iterator
{
private const FIELD_KEY = 'key';
private const FIELD_VALUE = 'value';

/** @var array */
private $items = [];

Expand Down Expand Up @@ -87,7 +90,9 @@ public function count()
#[ReturnTypeWillChange]
public function current()
{
return current($this->items);
/* Fetching current item */
$currentItem = current($this->items);
return $currentItem !== false ? $currentItem[self::FIELD_VALUE] : false;
}

/**
Expand All @@ -97,7 +102,9 @@ public function current()
#[ReturnTypeWillChange]
public function key()
{
return key($this->items);
/* Fetching current item */
$currentItem = current($this->items);
return $currentItem !== false ? $currentItem[self::FIELD_KEY] : null;
}

/**
Expand Down Expand Up @@ -165,6 +172,10 @@ private function storeCurrentItem()
return;
}

$this->items[$this->iterator->key()] = $this->iterator->current();
/* Storing a new item in the internal cache */
$this->items[] = [
self::FIELD_KEY => $this->iterator->key(),
self::FIELD_VALUE => $this->iterator->current(),
];
}
}