Init
This commit is contained in:
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
.idea/
|
||||
/vendor
|
||||
composer.lock
|
||||
20
composer.json
Normal file
20
composer.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "rmphp/storage",
|
||||
"license": "proprietary",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Yuri Zuev",
|
||||
"email": "y_zuev@mail.ru"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": "^8.1",
|
||||
"ext-mysqli": "*"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Rmphp\\Storage\\": "src/"
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
8
src/Exception/MysqlException.php
Normal file
8
src/Exception/MysqlException.php
Normal file
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace Rmphp\Storage\Exception;
|
||||
|
||||
|
||||
class MysqlException extends \Exception {
|
||||
|
||||
}
|
||||
166
src/MysqlStorage.php
Normal file
166
src/MysqlStorage.php
Normal file
@@ -0,0 +1,166 @@
|
||||
<?php
|
||||
|
||||
namespace Rmphp\Storage;
|
||||
|
||||
use Exception;
|
||||
use Mysqli;
|
||||
use mysqli_result;
|
||||
|
||||
class MysqlStorage implements MysqlStorageInterface {
|
||||
|
||||
public array $log = array();
|
||||
public bool $logsEnabled = false;
|
||||
private Mysqli $mysqli;
|
||||
|
||||
/**
|
||||
* Внутренний конструктор подключения к БД
|
||||
* Mysql constructor.
|
||||
* @param array $params
|
||||
* @throws Exception
|
||||
*/
|
||||
public function __construct(array $params) {
|
||||
$this->mysqli = new mysqli($params['host'], $params['user'], $params['pass'], $params['base']);
|
||||
// выводим ошибку при неудачном подключении
|
||||
if ($this->mysqli->connect_errno) {
|
||||
throw new Exception($this->mysqli->connect_errno);
|
||||
}
|
||||
$this->mysqli->set_charset("utf8");
|
||||
if(!empty($params['logsEnable'])) $this->logsEnabled = true;
|
||||
}
|
||||
|
||||
/** @inheritDoc */
|
||||
public function mysql() : Mysqli {
|
||||
return $this->mysqli;
|
||||
}
|
||||
|
||||
/** @inheritDoc */
|
||||
public function query(string $sql) : bool|mysqli_result
|
||||
{
|
||||
try{
|
||||
$result = $this->mysqli->query($sql);
|
||||
// запись в log
|
||||
($this->mysqli->errno)
|
||||
? $this->addLog("Err - SQL: ".$sql." | error: ".$this->mysqli->error)
|
||||
: $this->addLog("OK - ".$sql);
|
||||
return $result;
|
||||
}
|
||||
/* 8.1.0 Теперь по умолчанию установлено значение MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT и выбрасывается исключение. Ранее оно было MYSQLI_REPORT_OFF. */
|
||||
catch (Exception $exception){
|
||||
$this->addLog("Err - SQL: ".$sql." | error: ".$this->mysqli->error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** @inheritDoc */
|
||||
public function add(string $tbl, array $arr, bool $update = false) : bool {
|
||||
foreach ($arr as $key => $value) {
|
||||
$col[] = "`$key`";
|
||||
$val[] = ($value !== NULL) ? "'$value'" : "NULL";
|
||||
$upd[] = ($value !== NULL) ? "`$key`='$value'" : "`$key`=NULL";
|
||||
}
|
||||
// Собираем в строки для использования в запросе
|
||||
$col = implode(", ", $col);
|
||||
$val = implode(", ", $val);
|
||||
|
||||
if (!$update) {
|
||||
$sql = "insert low_priority into ".$this->escapeStr($tbl)." (".$col.") values (" . $val . ")";
|
||||
} else{
|
||||
$sql = "insert low_priority into ".$this->escapeStr($tbl)." (".$col.") values (".$val.") on duplicate key update ".implode(", ", $upd);
|
||||
}
|
||||
return $this->query($sql);
|
||||
}
|
||||
|
||||
/** @inheritDoc */
|
||||
public function edit(string $tbl, array $arr, string $case, bool $ignore=false) : bool {
|
||||
foreach ($arr as $key => $value) {
|
||||
$isql[] = ($value !== NULL) ? "`$key`='$value'" : "`$key`=NULL";
|
||||
}
|
||||
$where = (preg_match("'^[0-9]+$'",$case)) ? "id = '".(int) $case."'" : $case;
|
||||
if(empty($ignore)) {
|
||||
$sql = "update low_priority " . $this->escapeStr($tbl) . " set " . implode(", ", $isql) . " where " . $where;
|
||||
} else {
|
||||
$sql = "update low_priority ignore " . $this->escapeStr($tbl) . " set " . implode(", ", $isql) . " where " . $where;
|
||||
}
|
||||
return $this->query($sql);
|
||||
}
|
||||
|
||||
/** @inheritDoc */
|
||||
public function replace(string $tbl, array $arr) : bool {
|
||||
foreach ($arr as $key => $value) {
|
||||
$col[] = "`$key`";
|
||||
$val[] = ($value !== NULL) ? "'$value'" : "NULL";
|
||||
}
|
||||
// Собираем в строки для использования в запросе
|
||||
$col = implode(", ", $col);
|
||||
$val = implode(", ", $val);
|
||||
|
||||
$sql = "replace low_priority into ".$this->escapeStr($tbl)." (".$col.") values (".$val.")";
|
||||
return $this->query($sql);
|
||||
}
|
||||
|
||||
/** @inheritDoc */
|
||||
public function del(string $tbl, string $case) : bool {
|
||||
$where = (preg_match("'^[0-9]+$'",$case)) ? "id = '".(int) $case."'" : $case;
|
||||
$sql = "delete low_priority from ".$this->escapeStr($tbl)." where ".$where;
|
||||
// возвращаем число затронутых строк/false
|
||||
return $this->query($sql);
|
||||
}
|
||||
|
||||
/** @inheritDoc */
|
||||
public function read(string $sql, int $ln = 0, int $numPage = 1) : bool|MysqlStorageData {
|
||||
if ($ln > 1) {
|
||||
$cnts = $this->query($sql)->num_rows;
|
||||
}
|
||||
// часть строки запроса с лимит
|
||||
switch (true){
|
||||
case ($ln > 1 || $numPage > 1) : $limit = " limit ".(($numPage * $ln) - $ln).", ".$ln; break;
|
||||
case ($ln == 1): $limit = " limit 0, 1"; break;
|
||||
default: $limit = "";
|
||||
}
|
||||
|
||||
$result = $this->query($sql.$limit);
|
||||
if (!$result || $result->num_rows == 0) return false;
|
||||
|
||||
$data = new MysqlStorageData($result);
|
||||
$data->count = $cnts ?? 0;
|
||||
return $data;
|
||||
}
|
||||
|
||||
/** @inheritDoc */
|
||||
public function chktbl(string $tbl) : bool {
|
||||
$result = $this->mysqli->query("SHOW TABLES LIKE '".$this->escapeStr($tbl)."'");
|
||||
if ($result->num_rows == 0) {
|
||||
$this->addLog(__METHOD__.":"." Err - Table ".$tbl." doesn't exist"); return false;
|
||||
}
|
||||
$this->addLog(__METHOD__.":"." OK - Table ".$tbl." exist");
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @inheritDoc */
|
||||
public function escapeReg(string $var) : ?string {
|
||||
if(!isset($var)) return null;
|
||||
return trim(addcslashes($this->mysqli->real_escape_string($var), "%_"));
|
||||
}
|
||||
|
||||
/** @inheritDoc */
|
||||
public function escapeStr(?string $var) : ?string {
|
||||
if(!isset($var)) return null;
|
||||
return trim($this->mysqli->real_escape_string($var));
|
||||
}
|
||||
|
||||
/** @inheritDoc */
|
||||
public function addLog(string $log) : void {
|
||||
if($this->logsEnabled) $this->log[] = $log;
|
||||
}
|
||||
|
||||
/** @inheritDoc */
|
||||
public function getLogs() : array {
|
||||
return $this->log;
|
||||
}
|
||||
|
||||
/** @inheritDoc */
|
||||
public function getLastLog() : string {
|
||||
return $this->log[count($this->log)-1];
|
||||
}
|
||||
|
||||
}
|
||||
77
src/MysqlStorageData.php
Normal file
77
src/MysqlStorageData.php
Normal file
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace Rmphp\Storage;
|
||||
|
||||
|
||||
class MysqlStorageData {
|
||||
|
||||
private ?\mysqli_result $result;
|
||||
private array $arrayData = [];
|
||||
public int $count;
|
||||
|
||||
/**
|
||||
* MysqlDataObject constructor.
|
||||
* @param \mysqli_result|null $result
|
||||
*/
|
||||
public function __construct(\mysqli_result $result = null) {
|
||||
$this->result = $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function isResult() : bool {
|
||||
return isset($this->result);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \mysqli_result|null
|
||||
*/
|
||||
public function getMysqlResult() : ?\mysqli_result {
|
||||
return $this->result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return iterable
|
||||
*/
|
||||
public function fatch(): iterable {
|
||||
if(!empty($this->arrayData)) return $this->arrayData;
|
||||
if(!$this->result) return [];
|
||||
return $this->generator();
|
||||
}
|
||||
|
||||
|
||||
public function fatchOne(int $index = 0) : array {
|
||||
if(!$this->result) return [];
|
||||
$this->result->data_seek($index);
|
||||
return $this->result->fetch_assoc();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getData() : array {
|
||||
if(!empty($this->arrayData)) return $this->arrayData;
|
||||
if(!$this->result) return [];
|
||||
$this->result->data_seek(0);
|
||||
while ($row = $this->result->fetch_assoc()) {
|
||||
$this->arrayData[] = $row;
|
||||
}
|
||||
return $this->arrayData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return iterable
|
||||
*/
|
||||
private function generator() : iterable {
|
||||
$this->result->data_seek(0);
|
||||
while ($row = $this->result->fetch_assoc()) {
|
||||
yield $row;
|
||||
}
|
||||
}
|
||||
|
||||
public function __destruct() {
|
||||
if($this->result) $this->result->close();
|
||||
}
|
||||
|
||||
}
|
||||
97
src/MysqlStorageInterface.php
Normal file
97
src/MysqlStorageInterface.php
Normal file
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace Rmphp\Storage;
|
||||
|
||||
interface MysqlStorageInterface {
|
||||
|
||||
/**
|
||||
* @return \Mysqli
|
||||
*/
|
||||
public function mysql() : \Mysqli;
|
||||
|
||||
/**
|
||||
* Метод прямого запроса к текущей БД
|
||||
* @param string $sql
|
||||
* @return bool|\mysqli_result
|
||||
*/
|
||||
public function query(string $sql) : bool|\mysqli_result;
|
||||
|
||||
/**
|
||||
* Метод добавления записи в текущую БД
|
||||
* @param string $tbl
|
||||
* @param array $arr
|
||||
* @param bool $update
|
||||
* @return bool
|
||||
*/
|
||||
public function add(string $tbl, array $arr, bool $update = false) : bool;
|
||||
|
||||
/**
|
||||
* Метод редактирования записи в текущей БД по ID
|
||||
* @param string $tbl
|
||||
* @param array $arr
|
||||
* @param string $case
|
||||
* @param bool $ignore
|
||||
* @return bool
|
||||
*/
|
||||
public function edit(string $tbl, array $arr, string $case, bool $ignore=false) : bool;
|
||||
|
||||
/**
|
||||
* Метод добавления записи в текущую БД
|
||||
* @param string $tbl
|
||||
* @param array $arr
|
||||
* @return bool
|
||||
*/
|
||||
public function replace(string $tbl, array $arr) : bool;
|
||||
|
||||
/**
|
||||
* @param string $tbl
|
||||
* @param string $case
|
||||
* @return bool
|
||||
*/
|
||||
public function del(string $tbl, string $case) : bool;
|
||||
|
||||
/**
|
||||
* @param string $sql
|
||||
* @param int $ln
|
||||
* @param int $numPage
|
||||
* @param int $count
|
||||
* @return bool|MysqlStorageData
|
||||
*/
|
||||
public function read(string $sql, int $ln = 0, int $numPage = 1) : bool|MysqlStorageData;
|
||||
|
||||
/**
|
||||
* @param string $tbl
|
||||
* @return bool
|
||||
*/
|
||||
public function chktbl(string $tbl) : bool;
|
||||
|
||||
/**
|
||||
* Метод экранирования данных с учетом текущего подключения в т.ч для LIKE
|
||||
* @param string $var
|
||||
* @return string|null
|
||||
*/
|
||||
public function escapeReg(string $var) : ?string;
|
||||
|
||||
/**
|
||||
* Метод экранирования данных с учетом текущего подключения
|
||||
* @param string|null $var
|
||||
* @return string|null
|
||||
*/
|
||||
public function escapeStr(?string $var) : ?string;
|
||||
|
||||
/**
|
||||
* Метод наполнения статичного массива с логами
|
||||
* @param string $log
|
||||
*/
|
||||
public function addLog(string $log) : void;
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getLogs() : array;
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getLastLog() : string;
|
||||
}
|
||||
Reference in New Issue
Block a user