index/src/Data/MariaDB/MariaDBWarning.php

96 lines
2.4 KiB
PHP

<?php
// MariaDBWarning.php
// Created: 2021-05-02
// Updated: 2022-02-27
namespace Index\Data\MariaDB;
use mysqli_warning;
use Stringable;
use Index\XArray;
/**
* Represents a MariaDB/MySQL warning.
*/
class MariaDBWarning implements Stringable {
private string $message;
private string $sqlState;
private int $code;
/**
* Creates a new MariaDBWarning object.
*
* @param string $message Warning message string.
* @param string $sqlState SQL State of the warning.
* @param int $code Error code of the warning.
* @return MariaDBWarning A new warning instance.
*/
public function __construct(string $message, string $sqlState, int $code) {
$this->message = $message;
$this->sqlState = $sqlState;
$this->code = $code;
}
/**
* Gets the warning message string.
*
* @return string Warning message string.
*/
public function getMessage(): string {
return $this->message;
}
/**
* Gets the warning SQL State.
*
* @return string SQL State.
*/
public function getSQLState(): string {
return $this->sqlState;
}
/**
* Gets the warning error code.
*
* @return int Warning error code.
*/
public function getCode(): int {
return $this->code;
}
public function __toString(): string {
return sprintf('[%s] %d: %s', $this->sqlState, $this->code, $this->message);
}
/**
* Creates an array of warning objects from the output of $last_errors.
*
* @param array $errors Array of warning arrays.
* @return array Array of warnings objects.
*/
public static function fromLastErrors(array $errors): array {
return XArray::select($errors, fn($error) => new MariaDBWarning($error['error'], $error['sqlstate'], $error['errno']));
}
/**
* Creates an array of warning objects from a mysqli_warning instance.
*
* @param mysqli_warning|false $warnings Warning object.
* @return array Array of warning objects.
*/
public static function fromGetWarnings(mysqli_warning|false $warnings): array {
$array = [];
if($warnings !== false)
do {
$array[] = new MariaDBWarning(
$warnings->message,
$warnings->sqlstate,
$warnings->errno
);
} while($warnings->next());
return $array;
}
}