Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
945c95441f | ||
|
|
d0e38875e6 | ||
|
|
73c9af71ab | ||
|
|
5b0c0bc7b4 | ||
|
|
dfbcfdf321 | ||
|
|
a54b55cc4e | ||
|
|
612132f938 | ||
|
|
73b7cb3a5f | ||
|
|
4f7993750c | ||
|
|
bdff890b41 | ||
|
|
e390bc262e | ||
|
|
2afc439354 | ||
|
|
2cfc92584c | ||
|
|
ac572cc92b | ||
|
|
448128d228 | ||
|
|
120d795b85 | ||
|
|
6caceefc17 | ||
|
|
c681de9bfb | ||
|
|
2e384e2071 | ||
|
|
368ccfa44b | ||
|
|
f0f862d979 | ||
|
|
c43f3a4768 |
@@ -7,15 +7,15 @@ DB component for **Rmphp**
|
|||||||
Stable version
|
Stable version
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
composer require rmphp/kernel
|
composer require rmphp/storage
|
||||||
```
|
```
|
||||||
```bash
|
```bash
|
||||||
composer require rmphp/kernel:"^1.0"
|
composer require rmphp/storage:"^6.0"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
Dev version contains the latest changes
|
Dev version contains the latest changes
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
composer require rmphp/kernel:"1.x-dev"
|
composer require rmphp/storage:"6.x-dev"
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -16,5 +16,5 @@
|
|||||||
"Rmphp\\Storage\\": "src/"
|
"Rmphp\\Storage\\": "src/"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
200
src/AbstractMysqlRepository.php
Normal file
200
src/AbstractMysqlRepository.php
Normal file
@@ -0,0 +1,200 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Rmphp\Storage;
|
||||||
|
|
||||||
|
use Rmphp\Storage\Entity\EntityInterface;
|
||||||
|
use Rmphp\Storage\Exception\RepositoryException;
|
||||||
|
use Rmphp\Storage\Mysql\MysqlRepositoryInterface;
|
||||||
|
use Rmphp\Storage\Mysql\MysqlResultData;
|
||||||
|
use Rmphp\Storage\Mysql\MysqlStorageInterface;
|
||||||
|
use Rmphp\Storage\Repository\AbstractRepository;
|
||||||
|
|
||||||
|
abstract class AbstractMysqlRepository extends AbstractRepository implements MysqlRepositoryInterface {
|
||||||
|
|
||||||
|
public const DEBUG = false;
|
||||||
|
public const TABLE = null;
|
||||||
|
public const ENTITY = null;
|
||||||
|
|
||||||
|
private string $table;
|
||||||
|
private string $entity;
|
||||||
|
private bool $debug;
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
public readonly MysqlStorageInterface $mysql
|
||||||
|
) {}
|
||||||
|
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function createFromResult(string $class, bool|MysqlResultData $result, callable $function = null): mixed {
|
||||||
|
if($result instanceof MysqlResultData) {
|
||||||
|
$val = (isset($function)) ? $function($result->fetchOne()) : $result->fetchOne();
|
||||||
|
$out = $this->createFromData($class, $val);
|
||||||
|
}
|
||||||
|
return $out ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function createListFromResult(string $class, bool|MysqlResultData $result, callable $function = null): array {
|
||||||
|
if($result instanceof MysqlResultData) {
|
||||||
|
foreach($result->fetch() as $resultValue) {
|
||||||
|
$val = (isset($function)) ? $function($resultValue) : $resultValue;
|
||||||
|
$out[] = $this->createFromData($class, $val);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $out ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function getEntityById(int $id, string $table = null): mixed {
|
||||||
|
if(!isset($table)) $table = $this->getTable();
|
||||||
|
if($result = $this->mysql->findById($table, $id)) $out = $this->createFromData($this->getEntityClass(), $result);
|
||||||
|
return $out ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function saveEntity(EntityInterface $object, string $table = null) : mixed {
|
||||||
|
if(!isset($table)) $table = $this->getTable();
|
||||||
|
$in = $this->getProperties($object, function ($value){
|
||||||
|
return (is_string($value)) ? $this->mysql->escapeStr($value) : $value;
|
||||||
|
});
|
||||||
|
if($this->getDebug()) {$this->debug($object, $in, $table, $this->getRepositoryStack()); exit;}
|
||||||
|
try {
|
||||||
|
if (!empty($object->getId()) && !empty($this->mysql->findById($table, $object->getId()))) {
|
||||||
|
$this->mysql->updateById($table, $in, $object->getId());
|
||||||
|
return $object->getId();
|
||||||
|
} else {
|
||||||
|
$this->mysql->insert($table, $in);
|
||||||
|
return (is_string($object->getId())) ? $object->getId() : $this->mysql->mysql()->insert_id;
|
||||||
|
}
|
||||||
|
} catch (\Throwable $throwable) {throw new RepositoryException($throwable->getMessage());}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function saveData(array $data, string $table = null, string $primaryKey = 'id') : mixed {
|
||||||
|
if(!isset($table)) $table = $this->getTable();
|
||||||
|
$in = array_map(function ($value){
|
||||||
|
return (is_string($value)) ? $this->mysql->escapeStr($value) : $value;
|
||||||
|
}, $data);
|
||||||
|
if($this->getDebug()) {$this->debug($data, $in, $table, $this->getRepositoryStack()); exit;}
|
||||||
|
try {
|
||||||
|
if (!empty($data[$primaryKey]) && !empty($this->mysql->findById($table, $data[$primaryKey], $primaryKey))) {
|
||||||
|
$this->mysql->updateById($table, $in, $data[$primaryKey]);
|
||||||
|
return $data[$primaryKey];
|
||||||
|
} else {
|
||||||
|
$this->mysql->insert($table, $in);
|
||||||
|
return (is_string($data[$primaryKey])) ? $data[$primaryKey] : $this->mysql->mysql()->insert_id;
|
||||||
|
}
|
||||||
|
} catch (\Throwable $throwable) {throw new RepositoryException($throwable->getMessage());}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function saveEntityGroup(array $objects, string $table = null): array {
|
||||||
|
try{
|
||||||
|
$this->mysql->mysql()->begin_transaction();
|
||||||
|
foreach($objects as $object) $id[] = $this->saveEntity($object, $table);
|
||||||
|
$this->mysql->mysql()->commit();
|
||||||
|
return $id ?? [];
|
||||||
|
}
|
||||||
|
catch (\Exception $exception){
|
||||||
|
$this->mysql->mysql()->rollback();
|
||||||
|
throw new RepositoryException($exception->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function saveDataGroup(array $objects, string $table = null, string $primaryKey = 'id'): array {
|
||||||
|
try{
|
||||||
|
$this->mysql->mysql()->begin_transaction();
|
||||||
|
foreach($objects as $object) $id[] = $this->saveData($object, $table, $primaryKey);
|
||||||
|
$this->mysql->mysql()->commit();
|
||||||
|
return $id ?? [];
|
||||||
|
}
|
||||||
|
catch (\Exception $exception){
|
||||||
|
$this->mysql->mysql()->rollback();
|
||||||
|
throw new RepositoryException($exception->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function deleteEntity(EntityInterface $object, string $table = null) : bool {
|
||||||
|
if(!isset($table)) $table = $this->getTable();
|
||||||
|
if(!empty($object->getId())){
|
||||||
|
return $this->mysql->deleteById($table, $object->getId());
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function getStorageLogs() : array {
|
||||||
|
return $this->mysql->getLogs();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function setTable(string $table) : void {
|
||||||
|
$this->table = $table;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function setEntity(string $entity) : void {
|
||||||
|
$this->entity = $entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function setDebug(bool $debug) : void {
|
||||||
|
$this->debug = $debug;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return string
|
||||||
|
* @throws RepositoryException
|
||||||
|
*/
|
||||||
|
private function getTable() : string {
|
||||||
|
if(!empty($this->table)) return $this->table;
|
||||||
|
if(!empty(static::TABLE)) return static::TABLE;
|
||||||
|
throw new RepositoryException("Имя таблицы не задано");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return string
|
||||||
|
* @throws RepositoryException
|
||||||
|
*/
|
||||||
|
private function getEntityClass() : string {
|
||||||
|
if(!empty($this->entity)) return $this->entity;
|
||||||
|
if(!empty(static::ENTITY)) return static::ENTITY;
|
||||||
|
throw new RepositoryException("Не указан объект");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
private function getDebug(): bool {
|
||||||
|
if(!empty($this->debug)) return $this->debug;
|
||||||
|
if(!empty(static::DEBUG)) return static::DEBUG;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param ...$arg
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
protected function debug(...$arg) : void {
|
||||||
|
if(function_exists('dd')) dd(...$arg);
|
||||||
|
if(function_exists('vdd')) vdd(...$arg);
|
||||||
|
var_dump(...$arg);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
104
src/Component/AbstractDataObject.php
Normal file
104
src/Component/AbstractDataObject.php
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Rmphp\Storage\Component;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
use ReflectionClass;
|
||||||
|
use ReflectionException;
|
||||||
|
|
||||||
|
class AbstractDataObject {
|
||||||
|
|
||||||
|
private static array $constructorEmptyAvailableClasses = [];
|
||||||
|
private static array $stack = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param ReflectionClass $class
|
||||||
|
* @param object $object
|
||||||
|
* @param array $data
|
||||||
|
* @param bool $update
|
||||||
|
* @return mixed
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
protected static function fillObject(ReflectionClass $class, object $object, array $data, bool $update = false) : mixed {
|
||||||
|
try {
|
||||||
|
$value = [];
|
||||||
|
foreach($class->getProperties() as $property){
|
||||||
|
$prop[$property->getName()] = ($property->hasType()) ? $property->getType()->getName() : "";
|
||||||
|
// значение в массиве по ключю с именем свойства
|
||||||
|
if(array_key_exists($property->getName(), $data)){
|
||||||
|
$value[$property->getName()] = $data[$property->getName()];
|
||||||
|
}
|
||||||
|
// значение в массиве по ключю с именем свойства в snake case
|
||||||
|
elseif(array_key_exists(strtolower(preg_replace("'([A-Z])'", "_$1", $property->getName())), $data)){
|
||||||
|
$value[$property->getName()] = $data[strtolower(preg_replace("'([A-Z])'", "_$1", $property->getName()))];
|
||||||
|
}
|
||||||
|
elseif($update) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// если есть внутренний метод (приоритетная обработка)
|
||||||
|
if($class->hasMethod('set'.ucfirst($property->getName()))) {
|
||||||
|
$object->{'set'.ucfirst($property->getName())}($value[$property->getName()] ?? null);
|
||||||
|
}
|
||||||
|
// Если тип свойства класс (valueObject)
|
||||||
|
elseif($property->hasType() && class_exists($property->getType()->getName())) {
|
||||||
|
if(is_object($value[$property->getName()])){
|
||||||
|
$object->{$property->getName()} = $value[$property->getName()];
|
||||||
|
}
|
||||||
|
elseif(isset($value[$property->getName()])){
|
||||||
|
$object->{$property->getName()} = new ($property->getType()->getName())($value[$property->getName()]);
|
||||||
|
}
|
||||||
|
// Значения нет и VO может быть без параметров
|
||||||
|
elseif(self::isEmptyAvailable($property->getType()->getName())) {
|
||||||
|
$object->{$property->getName()} = new ($property->getType()->getName())();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Базовые типы при наличии значения
|
||||||
|
elseif(array_key_exists($property->getName(), $value)){
|
||||||
|
if(!$property->hasType()){
|
||||||
|
$object->{$property->getName()} = $value[$property->getName()];
|
||||||
|
}
|
||||||
|
elseif(in_array($property->getType()->getName(), ['float', 'int'])){
|
||||||
|
if(is_numeric($value[$property->getName()])) $object->{$property->getName()} = $value[$property->getName()];
|
||||||
|
}
|
||||||
|
elseif($property->getType()->getName() == 'bool'){
|
||||||
|
$object->{$property->getName()} = (bool)$value[$property->getName()];
|
||||||
|
}
|
||||||
|
elseif(isset($value[$property->getName()])){
|
||||||
|
$object->{$property->getName()} = $value[$property->getName()];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self::$stack[$object::class." #".spl_object_id($object)]['properties'] = $prop ?? [];
|
||||||
|
self::$stack[$object::class." #".spl_object_id($object)]['values'] = $value;
|
||||||
|
self::$stack[$object::class." #".spl_object_id($object)]['object'] = $object;
|
||||||
|
return $object;
|
||||||
|
}
|
||||||
|
catch (ReflectionException $exception) {
|
||||||
|
throw new Exception($exception->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws ReflectionException
|
||||||
|
*/
|
||||||
|
private static function isEmptyAvailable(string $class) : bool {
|
||||||
|
if(isset(self::$constructorEmptyAvailableClasses[$class])) return self::$constructorEmptyAvailableClasses[$class];
|
||||||
|
if(!$constructor = (new \ReflectionClass($class))->getConstructor()) return self::$constructorEmptyAvailableClasses[$class] = false;
|
||||||
|
foreach($constructor->getParameters() as $param){
|
||||||
|
if(!$param->isDefaultValueAvailable()){
|
||||||
|
return self::$constructorEmptyAvailableClasses[$class] = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return self::$constructorEmptyAvailableClasses[$class] = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
protected function getFillObjectStack() : array {
|
||||||
|
return self::$stack;
|
||||||
|
}
|
||||||
|
}
|
||||||
31
src/Entity/AbstractEntity.php
Normal file
31
src/Entity/AbstractEntity.php
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Rmphp\Storage\Entity;
|
||||||
|
|
||||||
|
abstract class AbstractEntity implements EntityInterface {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return mixed
|
||||||
|
*/
|
||||||
|
public function getId(): mixed {
|
||||||
|
return (isset($this->id)) ? (($this->id instanceof ValueObjectInterface) ? $this->id->getValue() : $this->id) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $name
|
||||||
|
* @param $value
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __set(string $name, $value): void {
|
||||||
|
$this->$name = $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $name
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function __get(string $name) {
|
||||||
|
return $this->$name ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
18
src/Entity/EntityInterface.php
Normal file
18
src/Entity/EntityInterface.php
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* Created by PhpStorm.
|
||||||
|
* User: Zuev Yuri
|
||||||
|
* Date: 23.04.2024
|
||||||
|
* Time: 3:58
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace Rmphp\Storage\Entity;
|
||||||
|
|
||||||
|
interface EntityInterface {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return mixed
|
||||||
|
*/
|
||||||
|
public function getId(): mixed;
|
||||||
|
|
||||||
|
}
|
||||||
10
src/Entity/ValueObjectInterface.php
Normal file
10
src/Entity/ValueObjectInterface.php
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Rmphp\Storage\Entity;
|
||||||
|
|
||||||
|
interface ValueObjectInterface {
|
||||||
|
|
||||||
|
public function getValue();
|
||||||
|
public function __toString(): string;
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Rmphp\Storage\Exception;
|
|
||||||
|
|
||||||
|
|
||||||
class MysqlException extends \Exception {
|
|
||||||
|
|
||||||
}
|
|
||||||
16
src/Exception/RepositoryException.php
Normal file
16
src/Exception/RepositoryException.php
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Rmphp\Storage\Exception;
|
||||||
|
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class RepositoryException extends \Exception {
|
||||||
|
|
||||||
|
public array $data;
|
||||||
|
|
||||||
|
public function __construct($message="", $code=0, array $data = [], Throwable $previous=null) {
|
||||||
|
parent::__construct($message, $code, $previous);
|
||||||
|
$this->data = $data;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
108
src/Mysql/MysqlRepositoryInterface.php
Normal file
108
src/Mysql/MysqlRepositoryInterface.php
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* Created by PhpStorm.
|
||||||
|
* User: Zuev Yuri
|
||||||
|
* Date: 12.01.2025
|
||||||
|
* Time: 21:44
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace Rmphp\Storage\Mysql;
|
||||||
|
|
||||||
|
use Rmphp\Storage\Entity\EntityInterface;
|
||||||
|
use Rmphp\Storage\Exception\RepositoryException;
|
||||||
|
use Rmphp\Storage\Repository\RepositoryInterface;
|
||||||
|
|
||||||
|
interface MysqlRepositoryInterface extends RepositoryInterface {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $class
|
||||||
|
* @param bool|MysqlResultData $result
|
||||||
|
* @param callable|null $function
|
||||||
|
* @return mixed
|
||||||
|
* @throws RepositoryException
|
||||||
|
*/
|
||||||
|
public function createFromResult(string $class, bool|MysqlResultData $result, callable $function = null): mixed;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $class
|
||||||
|
* @param bool|MysqlResultData $result
|
||||||
|
* @param callable|null $function
|
||||||
|
* @return array
|
||||||
|
* @throws RepositoryException
|
||||||
|
*/
|
||||||
|
public function createListFromResult(string $class, bool|MysqlResultData $result, callable $function = null): array;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param int $id
|
||||||
|
* @param string|null $table
|
||||||
|
* @return mixed
|
||||||
|
* @throws RepositoryException
|
||||||
|
*/
|
||||||
|
public function getEntityById(int $id, string $table = null): mixed;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param EntityInterface $object
|
||||||
|
* @param string|null $table
|
||||||
|
* @return mixed
|
||||||
|
* @throws RepositoryException
|
||||||
|
*/
|
||||||
|
public function saveEntity(EntityInterface $object, string $table = null) : mixed;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array $data
|
||||||
|
* @param string|null $table
|
||||||
|
* @param string $primaryKey
|
||||||
|
* @return mixed
|
||||||
|
* @throws RepositoryException
|
||||||
|
*/
|
||||||
|
public function saveData(array $data, string $table = null, string $primaryKey = 'id') : mixed;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array $objects
|
||||||
|
* @param string|null $table
|
||||||
|
* @return array
|
||||||
|
* @throws RepositoryException
|
||||||
|
*/
|
||||||
|
public function saveEntityGroup(array $objects, string $table = null): array;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array $objects
|
||||||
|
* @param string|null $table
|
||||||
|
* @param string $primaryKey
|
||||||
|
* @return array
|
||||||
|
* @throws RepositoryException
|
||||||
|
*/
|
||||||
|
public function saveDataGroup(array $objects, string $table = null, string $primaryKey = 'id'): array;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param EntityInterface $object
|
||||||
|
* @param string|null $table
|
||||||
|
* @return bool
|
||||||
|
* @throws RepositoryException
|
||||||
|
*/
|
||||||
|
public function deleteEntity(EntityInterface $object, string $table = null) : bool;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function getStorageLogs() : array;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $table
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function setTable(string $table) : void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $entity
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function setEntity(string $entity) : void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param bool $debug
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function setDebug(bool $debug) : void;
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,13 +1,14 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace Rmphp\Storage;
|
namespace Rmphp\Storage\Mysql;
|
||||||
|
|
||||||
|
|
||||||
class MysqlStorageData {
|
class MysqlResultData {
|
||||||
|
|
||||||
private ?\mysqli_result $result;
|
private ?\mysqli_result $result;
|
||||||
private array $arrayData = [];
|
private array $arrayData = [];
|
||||||
public int $count;
|
public int $count;
|
||||||
|
public string $hex = "";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* MysqlDataObject constructor.
|
* MysqlDataObject constructor.
|
||||||
@@ -34,14 +35,14 @@ class MysqlStorageData {
|
|||||||
/**
|
/**
|
||||||
* @return iterable
|
* @return iterable
|
||||||
*/
|
*/
|
||||||
public function fatch(): iterable {
|
public function fetch(): iterable {
|
||||||
if(!empty($this->arrayData)) return $this->arrayData;
|
if(!empty($this->arrayData)) return $this->arrayData;
|
||||||
if(!$this->result) return [];
|
if(!$this->result) return [];
|
||||||
return $this->generator();
|
return $this->generator();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public function fatchOne(int $index = 0) : array {
|
public function fetchOne(int $index = 0) : array {
|
||||||
if(!$this->result) return [];
|
if(!$this->result) return [];
|
||||||
$this->result->data_seek($index);
|
$this->result->data_seek($index);
|
||||||
return $this->result->fetch_assoc();
|
return $this->result->fetch_assoc();
|
||||||
@@ -74,4 +75,4 @@ class MysqlStorageData {
|
|||||||
if($this->result) $this->result->close();
|
if($this->result) $this->result->close();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
214
src/Mysql/MysqlStorage.php
Normal file
214
src/Mysql/MysqlStorage.php
Normal file
@@ -0,0 +1,214 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Rmphp\Storage\Mysql;
|
||||||
|
|
||||||
|
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 object $params
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
private readonly object $params
|
||||||
|
) {
|
||||||
|
$this->mysqli = new mysqli(
|
||||||
|
$this->params->host,
|
||||||
|
$this->params->user,
|
||||||
|
$this->params->pass,
|
||||||
|
$this->params->base
|
||||||
|
);
|
||||||
|
// выводим ошибку при неудачном подключении
|
||||||
|
if ($this->mysqli->connect_errno) {
|
||||||
|
throw new Exception($this->mysqli->connect_errno);
|
||||||
|
}
|
||||||
|
$this->mysqli->set_charset("utf8");
|
||||||
|
if(!empty($this->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);
|
||||||
|
if($this->mysqli->errno) throw new Exception();
|
||||||
|
$this->addLog("OK - $sql");
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
catch (Exception $exception){
|
||||||
|
$this->addLog("Err - SQL: $sql | error: ".$this->mysqli->error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function insert(string $table, array $data, bool $update = false) : bool {
|
||||||
|
$chunks = $this->getInsertValue($data);
|
||||||
|
$upd = $this->getUpdateValue($data);
|
||||||
|
if (!$update) {
|
||||||
|
$sql = "insert low_priority into ".$this->escapeStr($table)." (".implode(",", $chunks['columns']).") values (".implode(",", $chunks['values']).")";
|
||||||
|
} else{
|
||||||
|
$sql = "insert low_priority into ".$this->escapeStr($table)." (".implode(",", $chunks['columns']).") values (".implode(",", $chunks['values']).") on duplicate key update ".implode(",", $upd);
|
||||||
|
}
|
||||||
|
return $this->query($sql);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function batchInsert(string $table, array $data) : bool {
|
||||||
|
foreach($data as $insertRow){
|
||||||
|
$chunks = $this->getInsertValue($insertRow);
|
||||||
|
$values[] = "(".implode(",", $chunks['values']).")";
|
||||||
|
}
|
||||||
|
$sql = "insert low_priority into ".$this->escapeStr($table)." (".implode(",", $chunks['columns'] ?? []).") values ".implode(",", $values ?? []);
|
||||||
|
return $this->query($sql);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function updateById(string $table, array $data, mixed $id, array $modifier = []) : bool {
|
||||||
|
$chunks = $this->getUpdateValue($data);
|
||||||
|
$id = (is_numeric($id)) ? (int) $id : $this->escapeStr($id);
|
||||||
|
$sql = "update low_priority ".implode(" ", $modifier)." ".$this->escapeStr($table)." set ".implode(",", $chunks)." where id = '$id'";
|
||||||
|
return $this->query($sql);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function updateByParam(string $table, array $data, string $case, array $modifier = []) : bool {
|
||||||
|
$chunks = $this->getUpdateValue($data);
|
||||||
|
$sql = "update low_priority ".implode(" ", $modifier)." ".$this->escapeStr($table)." set ". implode(",", $chunks)." where ".$case;
|
||||||
|
return $this->query($sql);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function replace(string $table, array $data) : bool {
|
||||||
|
$chunks = $this->getInsertValue($data);
|
||||||
|
$sql = "replace low_priority into ".$this->escapeStr($table)." (".implode(",", $chunks['columns']).") values (".implode(",", $chunks['values']).")";
|
||||||
|
return $this->query($sql);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function deleteById(string $table, mixed $id) : bool {
|
||||||
|
$id = (is_numeric($id)) ? (int) $id : $this->escapeStr($id);
|
||||||
|
$sql = "delete low_priority from ".$this->escapeStr($table)." where id='$id'";
|
||||||
|
// возвращаем число затронутых строк/false
|
||||||
|
return $this->query($sql);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function deleteByParam(string $table, string $case) : bool {
|
||||||
|
$sql = "delete low_priority from ".$this->escapeStr($table)." where ".$case;
|
||||||
|
// возвращаем число затронутых строк/false
|
||||||
|
return $this->query($sql);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function find(string $sql, int $ln=0, int $numPage=1, int $count=0): bool|MysqlResultData {
|
||||||
|
|
||||||
|
if ($ln > 1) {
|
||||||
|
$cnts = (!empty($count)) ? $count : $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 MysqlResultData($result);
|
||||||
|
$data->count = $cnts ?? 0;
|
||||||
|
$data->hex = md5($sql);
|
||||||
|
return $data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function findOne(string $sql) : bool|MysqlResultData {
|
||||||
|
$result = $this->query($sql." limit 0, 1");
|
||||||
|
if (!$result || $result->num_rows == 0) return false;
|
||||||
|
return new MysqlResultData($result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function findById(string $table, mixed $id, string $name = 'id') : bool|array {
|
||||||
|
$id = (is_numeric($id)) ? (int) $id : $this->escapeStr($id);
|
||||||
|
$result = $this->query("select * from ".$this->escapeStr($table)." where `$name`='$id' limit 0, 1");
|
||||||
|
if (!$result || $result->num_rows == 0) return false;
|
||||||
|
$data = new MysqlResultData($result);
|
||||||
|
return $data->fetchOne();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function escapeReg(string $string) : ?string {
|
||||||
|
if(!isset($string)) return null;
|
||||||
|
return trim(addcslashes($this->mysqli->real_escape_string($string), "%_"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function escapeStr(?string $string) : ?string {
|
||||||
|
if(!isset($string)) return null;
|
||||||
|
return trim($this->mysqli->real_escape_string($string));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** @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];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array $array
|
||||||
|
* @return array[]
|
||||||
|
*/
|
||||||
|
private function getInsertValue(array $array) : array {
|
||||||
|
foreach ($array as $key => $value) {
|
||||||
|
$colunms[] = "`$key`";
|
||||||
|
$values[] = ($value !== NULL) ? "'$value'" : "NULL";
|
||||||
|
}
|
||||||
|
return [
|
||||||
|
"columns" => $colunms ?? [],
|
||||||
|
"values" => $values ?? []
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array $array
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
private function getUpdateValue(array $array) : array {
|
||||||
|
foreach ($array as $key => $value) {
|
||||||
|
$out[] = ($value !== NULL) ? "`$key`='$value'" : "`$key`=NULL";
|
||||||
|
}
|
||||||
|
return $out ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
130
src/Mysql/MysqlStorageInterface.php
Normal file
130
src/Mysql/MysqlStorageInterface.php
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Rmphp\Storage\Mysql;
|
||||||
|
|
||||||
|
use Mysqli;
|
||||||
|
use mysqli_result;
|
||||||
|
|
||||||
|
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 $table
|
||||||
|
* @param array $data
|
||||||
|
* @param bool $update
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function insert(string $table, array $data, bool $update = false) : bool;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $table
|
||||||
|
* @param array $data
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function batchInsert(string $table, array $data) : bool;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Метод редактирования записи в текущей БД по ID
|
||||||
|
* @param string $table
|
||||||
|
* @param array $data
|
||||||
|
* @param mixed $id
|
||||||
|
* @param array $modifier
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function updateById(string $table, array $data, mixed $id, array $modifier = []) : bool;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $table
|
||||||
|
* @param array $data
|
||||||
|
* @param string $case
|
||||||
|
* @param array $modifier
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function updateByParam(string $table, array $data, string $case, array $modifier = []) : bool;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $table
|
||||||
|
* @param array $data
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function replace(string $table, array $data) : bool;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $table
|
||||||
|
* @param mixed $id
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function deleteById(string $table, mixed $id) : bool;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $table
|
||||||
|
* @param string $case
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function deleteByParam(string $table, string $case) : bool;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $sql
|
||||||
|
* @param int $ln
|
||||||
|
* @param int $numPage
|
||||||
|
* @param int $count
|
||||||
|
* @return bool|MysqlResultData
|
||||||
|
*/
|
||||||
|
public function find(string $sql, int $ln = 0, int $numPage = 1, int $count=0) : bool|MysqlResultData;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $sql
|
||||||
|
* @return bool|array
|
||||||
|
*/
|
||||||
|
public function findOne(string $sql) : bool|MysqlResultData;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $table
|
||||||
|
* @param mixed $id
|
||||||
|
* @param string $name
|
||||||
|
* @return bool|array
|
||||||
|
*/
|
||||||
|
public function findById(string $table, mixed $id, string $name = 'id') : bool|array;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Метод экранирования данных с учетом текущего подключения в т.ч для LIKE
|
||||||
|
* @param string $string
|
||||||
|
* @return string|null
|
||||||
|
*/
|
||||||
|
public function escapeReg(string $string) : ?string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Метод экранирования данных с учетом текущего подключения
|
||||||
|
* @param string|null $string
|
||||||
|
* @return string|null
|
||||||
|
*/
|
||||||
|
public function escapeStr(?string $string) : ?string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Метод наполнения статичного массива с логами
|
||||||
|
* @param string $log
|
||||||
|
*/
|
||||||
|
public function addLog(string $log) : void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function getLogs() : array;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getLastLog() : string;
|
||||||
|
}
|
||||||
@@ -1,166 +0,0 @@
|
|||||||
<?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];
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
<?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;
|
|
||||||
}
|
|
||||||
90
src/Repository/AbstractRepository.php
Normal file
90
src/Repository/AbstractRepository.php
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Rmphp\Storage\Repository;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
use ReflectionClass;
|
||||||
|
use ReflectionException;
|
||||||
|
use Rmphp\Storage\Component\AbstractDataObject;
|
||||||
|
use Rmphp\Storage\Entity\ValueObjectInterface;
|
||||||
|
use Rmphp\Storage\Exception\RepositoryException;
|
||||||
|
|
||||||
|
abstract class AbstractRepository extends AbstractDataObject implements RepositoryInterface {
|
||||||
|
|
||||||
|
private static array $classes = [];
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function getProperties(object $object, callable $method = null) : array {
|
||||||
|
try{
|
||||||
|
$class = get_class($object);
|
||||||
|
if(!isset(self::$classes[$class])) self::$classes[$class] = new ReflectionClass($class);
|
||||||
|
|
||||||
|
$fieldValue = [];
|
||||||
|
foreach(self::$classes[$class]->getProperties() as $property){
|
||||||
|
if(!$property->isInitialized($object) || is_array($property->getValue($object))) continue;
|
||||||
|
|
||||||
|
if(self::$classes[$class]->hasMethod('get'.ucfirst($property->getName()))){
|
||||||
|
$fieldValue[$property->getName()] = $object->{'get'.ucfirst($property->getName())}($property->getValue($object));
|
||||||
|
}
|
||||||
|
elseif($property->hasType() && class_exists($property->getType()->getName()) && $property->getValue($object) instanceof ValueObjectInterface){
|
||||||
|
$value = $property->getValue($object)->getValue();
|
||||||
|
if(isset($value)) $fieldValue[$property->getName()] = $value;
|
||||||
|
}
|
||||||
|
elseif(is_bool($property->getValue($object))){
|
||||||
|
$fieldValue[$property->getName()] = (int) $property->getValue($object);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
$fieldValue[$property->getName()] = $property->getValue($object);
|
||||||
|
}
|
||||||
|
|
||||||
|
if(array_key_exists($property->getName(), $fieldValue) && false !== $fieldValue[$property->getName()]) {
|
||||||
|
$out[strtolower(preg_replace("'([A-Z])'", "_$1", $property->getName()))] = $fieldValue[$property->getName()];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (isset($method)) ? array_map($method, $out ?? []) : $out ?? [];
|
||||||
|
}
|
||||||
|
catch (ReflectionException $exception) {
|
||||||
|
throw new RepositoryException($exception->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function createFromData(string $class, array|object $data) : object {
|
||||||
|
try {
|
||||||
|
if(!isset(self::$classes[$class])) self::$classes[$class] = new ReflectionClass($class);
|
||||||
|
return self::fillObject(self::$classes[$class], new $class, (is_object($data)) ? get_object_vars($data) : $data);
|
||||||
|
}
|
||||||
|
catch (Exception $exception) {
|
||||||
|
throw new RepositoryException($exception->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** @inheritDoc */
|
||||||
|
public function updateFromData(object $object, array|object $data) : object {
|
||||||
|
try {
|
||||||
|
$class = get_class($object);
|
||||||
|
if(!isset(self::$classes[$class])) self::$classes[$class] = new ReflectionClass($class);
|
||||||
|
return self::fillObject(self::$classes[$class], clone $object, (is_object($data)) ? get_object_vars($data) : $data, true);
|
||||||
|
}
|
||||||
|
catch (Exception $exception) {
|
||||||
|
throw new RepositoryException($exception->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function getRepositoryStack() : array {
|
||||||
|
return $this->getFillObjectStack();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function getClassesCash() : array {
|
||||||
|
return self::$classes;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
48
src/Repository/RepositoryInterface.php
Normal file
48
src/Repository/RepositoryInterface.php
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* Created by PhpStorm.
|
||||||
|
* User: Zuev Yuri
|
||||||
|
* Date: 12.01.2025
|
||||||
|
* Time: 21:48
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace Rmphp\Storage\Repository;
|
||||||
|
|
||||||
|
|
||||||
|
use Rmphp\Storage\Exception\RepositoryException;
|
||||||
|
|
||||||
|
interface RepositoryInterface {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param object $object
|
||||||
|
* @param callable|null $method
|
||||||
|
* @return array
|
||||||
|
* @throws RepositoryException
|
||||||
|
*/
|
||||||
|
public function getProperties(object $object, callable $method = null) : array;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $class
|
||||||
|
* @param array|object $data
|
||||||
|
* @return mixed
|
||||||
|
* @throws RepositoryException
|
||||||
|
*/
|
||||||
|
public function createFromData(string $class, array|object $data) : mixed;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param object $object
|
||||||
|
* @param array|object $data
|
||||||
|
* @return mixed
|
||||||
|
* @throws RepositoryException
|
||||||
|
*/
|
||||||
|
public function updateFromData(object $object, array|object $data) : mixed;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function getRepositoryStack() : array;
|
||||||
|
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user