<?php
// MariaDBResultLib.php
// Created: 2021-05-02
// Updated: 2021-05-04

namespace Index\Data\MariaDB;

use mysqli_stmt;
use Index\Data\QueryExecuteException;

/**
 * Implementation of MariaDBResult for libmysql.
 *
 * @internal
 */
class MariaDBResultLib extends MariaDBResult {
    private array $fields = [];
    private array $data = [];

    public function __construct(mysqli_stmt $statement) {
        parent::__construct($statement);

        if(!$statement->store_result())
            throw new QueryExecuteException($statement->error, $statement->errno);

        $metadata = $statement->result_metadata();
        while($field = $metadata->fetch_field())
            $this->fields[] = &$this->data[$field->name];

        call_user_func_array([$statement, 'bind_result'], $this->fields);
    }

    public function next(): bool {
        $result = $this->result->fetch();
        if($result === false)
            throw new QueryExecuteException($this->result->error, $this->result->errno);
        if($result === null)
            return false;

        $i = 0;
        $this->currentRow = [];
        foreach($this->data as $key => $value) {
            $this->currentRow[$i++] = $value;
            $this->currentRow[$key] = $value;
        }

        return true;
    }

    public function close(): void {
        $this->result->free_result();
    }
}