<?php
 class vB_dB_Result implements Iterator { use vB_Trait_NoSerialize; protected $db = false; protected $useReplica = false; protected $querystring = false; protected $recordset = false; protected $eof = false; protected $bof = false; protected $resultrow = false; protected $resultseq = 0; protected $buffered = true; public function __construct($db, $querystring, $useReplica = false, $buffered = true) { $this->querystring = $querystring; $this->db = $db; $this->useReplica = $useReplica; $this->buffered = $buffered; $this->rewind(); } public function db() { return $this->db; } public function __destruct() { $this->free(); } public function current() : mixed { return $this->resultrow; } public function key() : mixed { return $this->resultseq; } public function next() : void { if ($this->eof) { return; } if ($this->recordset AND !$this->eof) { $this->resultrow = $this->db->fetch_array($this->recordset); if (!$this->resultrow) { $this->eof = true; } $this->bof = false; $this->resultseq++; } } public function rewind() : void { if ($this->bof) { return; } $seekSuccess = false; if ($this->recordset AND $this->buffered) { $seekSuccess = $this->db->data_seek($this->recordset, 0); } if (!$seekSuccess) { if ($this->recordset) { $this->db->free_result($this->recordset); } if (!$this->useReplica) { $this->recordset = $this->db->query_read($this->querystring, $this->buffered); } else { $this->recordset = $this->db->query_read_slave($this->querystring, $this->buffered); } } if ($this->recordset === false) { $this->resultrow = false; $this->eof = true; $this->bof = true; return; } $this->resultrow = $this->db->fetch_array($this->recordset); $this->resultseq = 0; if ($this->resultrow) { $this->eof = false; } else { $this->eof = true; } $this->bof = true; } public function valid() : bool { return ($this->recordset AND !$this->eof AND ($this->resultrow !== false)); } public function free() { if (isset($this->db) AND !empty($this->recordset)) { try { $this->db->free_result($this->recordset); } catch(Throwable $e) { } finally { $this->recordset = false; $this->resultrow = false; $this->eof = true; $this->bof = true; } } } } 