zendframework/zf2 — pull request #4450 by mrsombre (2013-05-09 06:05:42+00:00)
Title: Fix iterating over empty result set with buffering enabled

In case we using result set with buffering dataSource rewind method should be called at least once before resultSet rewind call, to ensure dataSource valid() would work as expected.

Simple test case:

```php
$adapter = new \Zend\Db\Adapter\Adapter(...);

$hydrator = new Zend\Stdlib\Hydrator\ArraySerializable();
$resultSet = new \Zend\Db\ResultSet\HydratingResultSet($hydrator);
// any empty table for test
$table = new \Zend\Db\TableGateway\TableGateway('test', $adapter, null, $resultSet);

$test = $table->select();
$test->buffer();
foreach ($test as $item) {
var_dump($item);
}
```

If no data in result set (ie empty result) when Iterator rewind calls (\Zend\Db\ResultSet\AbstractResultSet::rewind) and buffer is enabled, then dataSource rewind never be called and in this case iteration loop started and first item will be false (at least for Adapter/Pdo/Result). But expected behavior is iteration not started for empty result set.

```php
public function rewind()
{
if (!is_array($this->buffer)) {
if ($this->dataSource instanceof Iterator) {
$this->dataSource->rewind();
} else {
reset($this->dataSource);
}
}
$this->position = 0;
}
```

So, we introduce result set position default state is -1, to ensure first iteration calls dataSource rewind at least one even buffer is enabled
`if (!is_array($this->buffer) || $this->position === -1) {`
BTW if buffering is disabled we call rewind on dataSource for every iteration as before