-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathVectorRangeIterator.php
More file actions
85 lines (70 loc) · 2.16 KB
/
VectorRangeIterator.php
File metadata and controls
85 lines (70 loc) · 2.16 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
namespace Upstash\Vector\Iterators;
use Iterator;
use Upstash\Vector\Operations\RangeVectorsOperation;
use Upstash\Vector\VectorMatch;
use Upstash\Vector\VectorRange;
use Upstash\Vector\VectorRangeResult;
/**
* @implements \Iterator<string, VectorMatch>
*/
class VectorRangeIterator implements Iterator
{
private string $nextCursor;
private int $position = 0;
/**
* @var VectorMatch[]
*/
private array $results = [];
public function __construct(
private readonly RangeVectorsOperation $operation,
private VectorRange $range,
) {
$rangeResult = $this->operation->range($range);
$this->nextCursor = $rangeResult->nextCursor;
$this->results = $rangeResult->getResults();
}
public function current(): VectorMatch
{
return $this->results[$this->position];
}
public function next(): void
{
$this->position++;
if ($this->position >= count($this->results) && $this->nextCursor !== '') {
$rangeResult = $this->fetchWithCursor($this->nextCursor);
$this->nextCursor = $rangeResult->nextCursor;
$this->results = $rangeResult->getResults();
$this->position = 0;
}
}
public function key(): string
{
return $this->current()->getIdentifier();
}
public function valid(): bool
{
if ($this->nextCursor === '' && $this->position >= count($this->results)) {
return false;
}
return true;
}
public function rewind(): void
{
$rangeResult = $this->fetchWithCursor('0');
$this->nextCursor = $rangeResult->nextCursor;
$this->position = 0;
$this->results = $rangeResult->getResults();
}
private function fetchWithCursor(string $cursor): VectorRangeResult
{
return $this->operation->range(new VectorRange(
limit: $this->range->limit,
cursor: $cursor,
prefix: $this->range->prefix,
includeMetadata: $this->range->includeMetadata,
includeVectors: $this->range->includeVectors,
includeData: $this->range->includeData,
));
}
}