aboutsummaryrefslogtreecommitdiffstats
path: root/apps/dav/lib/Paginate/LimitedCopyIterator.php
blob: 7f19885bc7deaabb2c5042a73c77fda1cd1c11d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php

declare(strict_types=1);

/**
 * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

namespace OCA\DAV\Paginate;

/**
 * Save a copy of the first X items into a separate iterator
 *
 * This allows us to pass the iterator to the cache while keeping a copy
 * of the required items.
 *
 * @extends \AppendIterator<int, int, \Iterator<int, int>>
 */
class LimitedCopyIterator extends \AppendIterator {
	private array $skipped = [];
	private array $copy = [];

	public function __construct(\Traversable $iterator, int $count, int $offset = 0) {
		parent::__construct();

		if (!$iterator instanceof \Iterator) {
			$iterator = new \IteratorIterator($iterator);
		}
		$iterator = new \NoRewindIterator($iterator);

		$i = 0;
		while ($iterator->valid() && ++$i <= $offset) {
			$this->skipped[] = $iterator->current();
			$iterator->next();
		}

		while ($iterator->valid() && count($this->copy) < $count) {
			$this->copy[] = $iterator->current();
			$iterator->next();
		}

		$this->append(new \ArrayIterator($this->skipped));
		$this->append($this->getRequestedItems());
		$this->append($iterator);
	}

	public function getRequestedItems(): \Iterator {
		return new \ArrayIterator($this->copy);
	}
}