2 Commits
3.x ... 4.x

Author SHA1 Message Date
User
2cfc92584c 20250126#2 2025-01-26 14:56:59 +03:00
User
ac572cc92b 20250113#1 2025-01-13 04:23:59 +03:00
13 changed files with 396 additions and 23 deletions

View File

@@ -10,12 +10,12 @@ Stable version
composer require rmphp/storage
```
```bash
composer require rmphp/storage:"^3.0"
composer require rmphp/storage:"^4.0"
```
Dev version contains the latest changes
```bash
composer require rmphp/storage:"3.x-dev"
composer require rmphp/storage:"4.x-dev"
```

View File

@@ -0,0 +1,122 @@
<?php
namespace Rmphp\Storage;
use Rmphp\Storage\Entity\EntityInterface;
use Rmphp\Storage\Mysql\MysqlRepositoryInterface;
use Rmphp\Storage\Mysql\MysqlResultData;
use Rmphp\Storage\Mysql\MysqlStorageInterface;
abstract class AbstractMysqlRepository extends AbstractRepository implements MysqlRepositoryInterface {
public const DEBUG = false;
public const TABLE = null;
public const ENTINY = null;
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, $require = false) {
$this->checkConst();
if($result = $this->mysql->findById(static::TABLE, $id)) $out = $this->createFromData(static::ENTINY, $result);
if(empty($out) && $require) throw new RepositoryException("Запись не найдена");
return $out ?? null;
}
/** @inheritDoc */
public function saveEntity(EntityInterface $object) : mixed {
$this->checkConst();
$in = $this->getProperties($object, function ($value){
return (is_string($value)) ? $this->mysql->escapeStr($value) : $value;
});
if(static::DEBUG) {$this->getSaveDebug($object, $in, static::TABLE); exit;}
try {
if (!empty($object->getId()) && !empty($this->mysql->findById(static::TABLE, $object->getId()))) {
$this->mysql->updateById(static::TABLE, $in, $object->getId());
return $object->getId();
} else {
$this->mysql->insert(static::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 saveGroup(array $objects): array {
try{
$this->mysql->mysql()->begin_transaction();
foreach($objects as $object) $id[] = $this->saveEntity($object);
$this->mysql->mysql()->commit();
return $id ?? [];
}
catch (\Exception $exception){
$this->mysql->mysql()->rollback();
throw new RepositoryException($exception->getMessage());
}
}
/** @inheritDoc */
public function deleteEntity(EntityInterface $object) : bool {
$this->checkConst();
if(!empty($object->getId())){
return $this->mysql->deleteById(static::TABLE, $object->getId());
}
return false;
}
/** @inheritDoc */
public function getStorageLogs() : array {
return $this->mysql->getLogs();
}
/**
* @param ...$arg
* @return void
*/
protected function getSaveDebug(...$arg) : void {
if(function_exists('dd')) dd(...$arg);
if(function_exists('vdd')) vdd(...$arg);
var_dump(...$arg);
}
/**
* @throws RepositoryException
*/
protected function checkConst(): void {
if(empty(static::TABLE)) throw new RepositoryException("Имя таблицы не задано");
if(empty(static::ENTINY)) throw new RepositoryException("Не указан объект");
}
}

View File

@@ -0,0 +1,96 @@
<?php
namespace Rmphp\Storage;
use ReflectionClass;
use ReflectionException;
use ReflectionProperty;
use Rmphp\Storage\Entity\ValueObjectInterface;
abstract class AbstractRepository implements RepositoryInterface {
static array $classes = [];
/** @inheritDoc */
public function createFromData(string $class, $data) : mixed {
try {
if(!isset(static::$classes[$class])) static::$classes[$class] = new ReflectionClass($class);
$object = new $class;
/** @var ReflectionProperty $property */
foreach (static::$classes[$class]->getProperties() as $property) {
// data[propertyName] ?? data[property_name] ?? null
$value = $data[$property->getName()] ?? $data[strtolower(preg_replace("'([A-Z])'", "_$1", $property->getName()))] ?? null;
// если есть внутренний метод (приоритетная обработка)
if(static::$classes[$class]->hasMethod('set'.ucfirst($property->getName()))) $object->{'set'.ucfirst($property->getName())}($value);
// Если тип свойства класс (valueObject)
elseif($property->hasType() && class_exists($property->getType()->getName())) $object->{$property->getName()} = (is_object($value)) ? $value : new ($property->getType()->getName())($value);
// если значения не пустое
elseif(isset($value)) $object->{$property->getName()} = $value;
// если значения может быть пустое
elseif($property->getType()->allowsNull()) $object->{$property->getName()} = null;
}
return $object;
}
catch (ReflectionException $exception) {
throw new RepositoryException($exception->getMessage());
}
}
/** @inheritDoc */
public function getAllProperties(object $class, callable $method = null) : array {
$properties = $this->initProperties($class);
return (isset($method)) ? array_map($method, $properties) : $properties;
}
/** @inheritDoc */
public function getProperties(object $class, callable $method = null) : array {
$properties = $this->initProperties($class);
foreach ($properties as $fieldName => $value) {
if(isset($value)) $out[$fieldName] = $value;
}
return (isset($method)) ? array_map($method, $out ?? []) : $out ?? [];
}
/**
* @param object $class
* @return array
*/
private function initProperties(object $class): array {
$objectData = get_object_vars($class);
foreach ($objectData as $fieldName => $value)
{
// если есть внутренний метод (приоритетная обработка)
if(method_exists($class, 'get'.ucfirst($fieldName))) {
$fieldValue[$fieldName] = $class->{'get'.ucfirst($fieldName)}($value);
}
// если тип свойства класс (valueObject)
elseif($value instanceof ValueObjectInterface) {
$fieldValue[$fieldName] = $value->get();
}
// если это логическое значение
elseif(is_bool($value)){
$fieldValue[$fieldName] = (int) $value;
}
// если это дробное число
elseif(is_float($value)) {
$fieldValue[$fieldName] = $value;
}
// если это целое число
elseif(is_int($value)) {
$fieldValue[$fieldName] = $value;
}
// если это строка
elseif(is_string($value)) {
$fieldValue[$fieldName] = $value;
}
// to option_id
$fieldNameSnakeCase = strtolower(preg_replace("'([A-Z])'", "_$1", $fieldName));
$out[$fieldNameSnakeCase] = $fieldValue[$fieldName] ?? null;
}
return $out ?? [];
}
}

View File

@@ -0,0 +1,14 @@
<?php
namespace Rmphp\Storage\Entity;
abstract class AbstractEntity implements EntityInterface {
/**
* @return int|null
*/
public function getId(): mixed {
return (isset($this->id)) ? (($this->id instanceof ValueObjectInterface) ? $this->id->get() : $this->id) : null;
}
}

View 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 int|null
*/
public function getId(): mixed;
}

View File

@@ -0,0 +1,10 @@
<?php
namespace Rmphp\Storage\Entity;
interface ValueObjectInterface {
public function get();
public function __toString(): string;
}

View File

@@ -1,8 +0,0 @@
<?php
namespace Rmphp\Storage\Mysql\Exception;
class MysqlException extends \Exception {
}

View File

@@ -0,0 +1,67 @@
<?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\RepositoryException;
use Rmphp\Storage\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;
/**
* @throws RepositoryException
*/
public function getEntityById(int $id, $require = false);
/**
* @param EntityInterface $object
* @return mixed
* @throws RepositoryException
*/
public function saveEntity(EntityInterface $object) : mixed;
/**
* @param array $objects
* @return array
* @throws RepositoryException
*/
public function saveGroup(array $objects): array;
/**
* @param EntityInterface $object
* @return bool
* @throws RepositoryException
*/
public function deleteEntity(EntityInterface $object) : bool;
/**
* @return array
*/
public function getStorageLogs() : array;
}

View File

@@ -3,7 +3,7 @@
namespace Rmphp\Storage\Mysql;
class MysqlStorageData {
class MysqlResultData {
private ?\mysqli_result $result;
private array $arrayData = [];
@@ -75,4 +75,4 @@ class MysqlStorageData {
if($this->result) $this->result->close();
}
}
}

View File

@@ -111,7 +111,7 @@ class MysqlStorage implements MysqlStorageInterface {
/** @inheritDoc */
public function find(string $sql, int $ln=0, int $numPage=1, int $count=0): bool|MysqlStorageData {
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;
@@ -126,18 +126,17 @@ class MysqlStorage implements MysqlStorageInterface {
$result = $this->query($sql.$limit);
if (!$result || $result->num_rows == 0) return false;
$data = new MysqlStorageData($result);
$data = new MysqlResultData($result);
$data->count = $cnts ?? 0;
$data->hex = md5($sql);
return $data;
}
/** @inheritDoc */
public function findOne(string $sql) : bool|array {
public function findOne(string $sql) : bool|MysqlResultData {
$result = $this->query($sql." limit 0, 1");
if (!$result || $result->num_rows == 0) return false;
$data = new MysqlStorageData($result);
return $data->fetchOne();
return new MysqlResultData($result);
}
/** @inheritDoc */
@@ -145,7 +144,7 @@ class MysqlStorage implements MysqlStorageInterface {
$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 MysqlStorageData($result);
$data = new MysqlResultData($result);
return $data->fetchOne();
}
@@ -205,4 +204,4 @@ class MysqlStorage implements MysqlStorageInterface {
return $out ?? [];
}
}
}

View File

@@ -80,15 +80,15 @@ interface MysqlStorageInterface {
* @param int $ln
* @param int $numPage
* @param int $count
* @return bool|MysqlStorageData
* @return bool|MysqlResultData
*/
public function find(string $sql, int $ln = 0, int $numPage = 1, int $count=0) : bool|MysqlStorageData;
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|array;
public function findOne(string $sql) : bool|MysqlResultData;
/**
* @param string $table
@@ -127,4 +127,4 @@ interface MysqlStorageInterface {
* @return string
*/
public function getLastLog() : string;
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace Rmphp\Storage;
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;
}
}

View File

@@ -0,0 +1,39 @@
<?php
/**
* Created by PhpStorm.
* User: Zuev Yuri
* Date: 12.01.2025
* Time: 21:48
*/
namespace Rmphp\Storage;
use Rmphp\Storage\Entity\EntityInterface;
interface RepositoryInterface {
/**
* @param string $class
* @param $data
* @return object
* @throws RepositoryException
*/
public function createFromData(string $class, $data) : mixed;
/**
* @param object $class
* @param callable|null $method
* @return array
*/
public function getAllProperties(object $class, callable $method = null) : array;
/**
* @param object $class
* @param callable|null $method
* @return array
*/
public function getProperties(object $class, callable $method = null) : array;
}