index/src/Data/MariaDB/MariaDBResult.php

104 lines
2.7 KiB
PHP

<?php
// MariaDBResult.php
// Created: 2021-05-02
// Updated: 2022-02-16
namespace Index\Data\MariaDB;
use mysqli_result;
use mysqli_stmt;
use InvalidArgumentException;
use Index\AString;
use Index\WString;
use Index\Data\IDbResult;
use Index\IO\Stream;
use Index\IO\TempFileStream;
/**
* Represents a MariaDB/MySQL database result.
*/
abstract class MariaDBResult implements IDbResult {
protected mysqli_stmt|mysqli_result $result;
protected array $currentRow = [];
/**
* Creates a new MariaDBResult instance.
*
* @param mysqli_stmt|mysqli_result $result A result to work with.
* @return MariaDBResult A result instance.
*/
public function __construct(mysqli_stmt|mysqli_result $result) {
$this->result = $result;
}
/**
* Gets the number of available rows in this result.
*
* @return int|string Number of available rows.
*/
public function getRowCount(): int|string {
return $this->result->num_rows;
}
/**
* Gets the number of fields in the result per row.
*
* @return int Number of fields.
*/
public function getFieldCount(): int {
return $this->result->field_count;
}
/**
* Seek to a specific row.
*
* @param int $offset Offset of the row.
*/
public function seekRow(int $offset): void {
if(!$this->result->data_seek($offset))
throw new InvalidArgumentException('$offset is not a valid row offset.');
}
abstract public function next(): bool;
public function isNull(int|string $index): bool {
return array_key_exists($index, $this->currentRow) && $this->currentRow[$index] === null;
}
public function getValue(int|string $index): mixed {
return $this->currentRow[$index] ?? null;
}
public function getString(int|string $index): string {
return strval($this->getValue($index));
}
public function getAString(int|string $index): AString {
return new AString($this->getString($index));
}
public function getWString(int|string $index, string $encoding): WString {
return new WString($this->getString($index), $encoding);
}
public function getInteger(int|string $index): int {
return intval($this->getValue($index));
}
public function getFloat(int|string $index): float {
return floatval($this->getValue($index));
}
public function getStream(int|string $index): ?Stream {
if($this->isNull($index))
return null;
return new TempFileStream($this->getValue($index));
}
abstract function close(): void;
public function __destruct() {
$this->close();
}
}