Skip to content

Commit 6bdaf6e

Browse files
committed
Cursors should return zero based keys
1 parent ed40868 commit 6bdaf6e

File tree

2 files changed

+40
-5
lines changed

2 files changed

+40
-5
lines changed

Tests/Unit/CursorTest.php

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
3+
namespace Tests\Unit;
4+
5+
class CursorTest extends \PHPUnit\Framework\TestCase
6+
{
7+
public function testCursor() : void
8+
{
9+
$table = new \Tests\App\Table\Customer();
10+
$table->addOrderBy('customer_id');
11+
12+
$index = 0;
13+
foreach ($table->getRecordCursor() as $key => $record)
14+
{
15+
$this->assertEquals($index++, $key, 'RecordCursor key is not correct');
16+
$this->assertEquals($index, $record->customer_id, 'RecordCursor record is not correct');
17+
$this->assertEquals($index, $record['customer_id'], 'RecordCursor array access is not correct');
18+
}
19+
20+
$index = 0;
21+
foreach ($table->getArrayCursor() as $key => $record)
22+
{
23+
$this->assertEquals($index++, $key, 'ArrayCursor key is not correct');
24+
$this->assertEquals($index, $record['customer_id'], 'ArrayCursor record is not correct');
25+
}
26+
27+
$index = 0;
28+
foreach ($table->getDataObjectCursor() as $key => $record)
29+
{
30+
$this->assertEquals($index++, $key, 'DataObjectCursor key is not correct');
31+
$this->assertEquals($index, $record->customer_id, 'DataObjectCursor record is not correct');
32+
$this->assertEquals($index, $record['customer_id'], 'DataObjectCursor array access is not correct');
33+
}
34+
}
35+
}

src/PHPFUI/ORM/BaseCursor.php

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
*/
1010
abstract class BaseCursor implements \Countable, \Iterator // @phpstan-ignore-line
1111
{
12-
protected int $index = -1;
12+
protected ?int $index = null;
1313

1414
private ?int $count = null;
1515

@@ -27,7 +27,7 @@ public function __construct(protected ?\PDOStatement $statement = null, protecte
2727
public function __destruct()
2828
{
2929
$this->statement?->closeCursor();
30-
$this->index = -1;
30+
$this->index = null;
3131
$this->total = null;
3232
$this->count = null;
3333
}
@@ -68,7 +68,7 @@ public function key() : int
6868
{
6969
$this->init();
7070

71-
return $this->index;
71+
return (int)$this->index;
7272
}
7373

7474
/**
@@ -81,7 +81,7 @@ abstract public function next() : void;
8181
*/
8282
public function rewind() : void
8383
{
84-
$this->index = 0;
84+
$this->index = -1;
8585

8686
if (! $this->statement)
8787
{
@@ -158,7 +158,7 @@ abstract public function valid() : bool;
158158
*/
159159
protected function init() : void
160160
{
161-
if (-1 == $this->index)
161+
if (null === $this->index)
162162
{
163163
$this->rewind();
164164
}

0 commit comments

Comments
 (0)