phplibrary/src/Database/PDOStatement.php
2025-11-02 12:33:26 +03:00

160 lines
3.1 KiB
PHP

<?php
namespace ctiso\Database;
use ctiso\Database\StatementIterator,
ctiso\Tools\StringUtil,
PDO;
use TheSeer\Tokenizer\Exception;
/**
* @implements \IteratorAggregate<int, array>
*/
class PDOStatement extends \PDOStatement implements \IteratorAggregate
{
/** @var int */
protected $cursorPos = 0;
/** @var array<int, mixed> */
public $cache = [];
/** @var ?array */
public $fields;
function getIterator(): \Iterator {
return new StatementIterator($this);
}
protected function __construct() {
}
function rewind(): void {
$this->cursorPos = 0;
}
/**
* @param int $rownum
* @return bool
*/
public function seek($rownum): bool {
if ($rownum < 0) {
return false;
}
// PostgreSQL rows start w/ 0, but this works, because we are
// looking to move the position _before_ the next desired position
$this->cursorPos = $rownum;
return true;
}
function valid(): bool {
return true;
}
/**
* @return bool
*/
public function first() {
if ($this->cursorPos !== 0) { $this->seek(0); }
return $this->next();
}
function next(): bool{
if ($this->getRecordCount() > $this->cursorPos) {
if (!isset($this->cache[$this->cursorPos])) {
$this->cache[$this->cursorPos] = $this->fetch(PDO::FETCH_ASSOC);
}
$this->fields = $this->cache[$this->cursorPos];
$this->cursorPos++;
return true;
} else {
$this->fields = null;
return false;
}
}
function key(): int {
return $this->cursorPos;
}
/**
* @return mixed
*/
function current() {
return $this->cache[$this->cursorPos];
}
/**
* @return array|null
*/
function getRow() {
return $this->fields;
}
/**
* @param string $name
* @return int
*/
function getInt($name): int {
if (!$this->fields) {
throw new \Exception('no fields');
}
return (int)$this->fields[$name];
}
/**
* @param string $name
* @return string
*/
function getBlob($name) {
return $this->fields[$name];
}
/**
* @param string $name
* @return string
*/
function getString($name) {
return $this->fields[$name] ?? null;
}
/**
* @param string $name
* @return bool
*/
function getBoolean($name) {
return (bool)$this->fields[$name];
}
/**
* @param string $name
* @return mixed
*/
function get($name) {
return $this->fields[$name];
}
/**
* @param string $name
* @return array
*/
function getArray($name) {
return StringUtil::strToArray($this->fields[$name]);
}
/**
* @return int
*/
function getRecordCount() {
return count($this->cache);
}
/**
* @param array $args
* @return bool
*/
function execute($args = null): bool {
$result = parent::execute($args);
return $result;
}
}