6 Commits
4.0 ... 5.1

Author SHA1 Message Date
User
73b7cb3a5f 20250218#3 2025-02-18 01:24:05 +03:00
User
4f7993750c 20250218#2 2025-02-18 01:08:03 +03:00
User
bdff890b41 20250218#1 2025-02-18 00:14:52 +03:00
User
e390bc262e 20250128#2 2025-01-28 03:32:28 +03:00
User
2afc439354 20250128#1 2025-01-28 03:31:47 +03:00
User
2cfc92584c 20250126#2 2025-01-26 14:56:59 +03:00
7 changed files with 233 additions and 103 deletions

View File

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

View File

@@ -11,8 +11,11 @@ abstract class AbstractMysqlRepository extends AbstractRepository implements Mys
public const DEBUG = false; public const DEBUG = false;
public const TABLE = null; public const TABLE = null;
public const ENTINY = null; public const ENTITY = null;
private string $table;
private string $entity;
private bool $debug;
public function __construct( public function __construct(
public readonly MysqlStorageInterface $mysql public readonly MysqlStorageInterface $mysql
@@ -42,24 +45,20 @@ abstract class AbstractMysqlRepository extends AbstractRepository implements Mys
/** @inheritDoc */ /** @inheritDoc */
public function getEntityById(int $id, $require = false) { public function getEntityById(int $id, string $table = null): mixed {
$this->checkConst(); if(!isset($table)) $table = $this->getTable();
if($result = $this->mysql->findById(static::TABLE, $id)) $out = $this->createFromData(static::ENTINY, $result); if($result = $this->mysql->findById($table, $id)) $out = $this->createFromData($this->getEntityClass(), $result);
if(empty($out) && $require) throw new RepositoryException("Запись не найдена");
return $out ?? null; return $out ?? null;
} }
/** @inheritDoc */ /** @inheritDoc */
public function saveEntity(EntityInterface $object, string $table = null) : mixed { public function saveEntity(EntityInterface $object, string $table = null) : mixed {
if(!isset($table)){ if(!isset($table)) $table = $this->getTable();
$this->checkConst();
$table = static::TABLE;
}
$in = $this->getProperties($object, function ($value){ $in = $this->getProperties($object, function ($value){
return (is_string($value)) ? $this->mysql->escapeStr($value) : $value; return (is_string($value)) ? $this->mysql->escapeStr($value) : $value;
}); });
if(static::DEBUG) {$this->getSaveDebug($object, $in, $table); exit;} if($this->getDebug()) {$this->debug($object, $in, $table); exit;}
try { try {
if (!empty($object->getId()) && !empty($this->mysql->findById($table, $object->getId()))) { if (!empty($object->getId()) && !empty($this->mysql->findById($table, $object->getId()))) {
$this->mysql->updateById($table, $in, $object->getId()); $this->mysql->updateById($table, $in, $object->getId());
@@ -73,11 +72,26 @@ abstract class AbstractMysqlRepository extends AbstractRepository implements Mys
/** @inheritDoc */ /** @inheritDoc */
public function saveGroup(array $objects, string $table = null): array { public function saveData(array $data, string $table = null, string $primaryKey = 'id') : mixed {
if(!isset($table)){ if(!isset($table)) $table = $this->getTable();
$this->checkConst(); $in = array_map(function ($value){
$table = static::TABLE; return (is_string($value)) ? $this->mysql->escapeStr($value) : $value;
}, $data);
if($this->getDebug()) {$this->debug($data, $in, $table); 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{ try{
$this->mysql->mysql()->begin_transaction(); $this->mysql->mysql()->begin_transaction();
foreach($objects as $object) $id[] = $this->saveEntity($object, $table); foreach($objects as $object) $id[] = $this->saveEntity($object, $table);
@@ -92,11 +106,23 @@ abstract class AbstractMysqlRepository extends AbstractRepository implements Mys
/** @inheritDoc */ /** @inheritDoc */
public function deleteEntity(EntityInterface $object, string $table = null) : bool { public function saveDataGroup(array $objects, string $table = null, string $primaryKey = 'id'): array {
if(!isset($table)){ try{
$this->checkConst(); $this->mysql->mysql()->begin_transaction();
$table = static::TABLE; 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())){ if(!empty($object->getId())){
return $this->mysql->deleteById($table, $object->getId()); return $this->mysql->deleteById($table, $object->getId());
} }
@@ -110,23 +136,63 @@ abstract class AbstractMysqlRepository extends AbstractRepository implements Mys
} }
/** @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 * @param ...$arg
* @return void * @return void
*/ */
protected function getSaveDebug(...$arg) : void { protected function debug(...$arg) : void {
if(function_exists('dd')) dd(...$arg); if(function_exists('dd')) dd(...$arg);
if(function_exists('vdd')) vdd(...$arg); if(function_exists('vdd')) vdd(...$arg);
var_dump(...$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

@@ -12,16 +12,80 @@ abstract class AbstractRepository implements RepositoryInterface {
static array $classes = []; static array $classes = [];
/** @inheritDoc */ /** @inheritDoc */
public function createFromData(string $class, $data) : mixed { public function createFromData(string $class, $data) : object {
try { try {
if(!isset(static::$classes[$class])) static::$classes[$class] = new ReflectionClass($class); if(!isset(static::$classes[$class])) static::$classes[$class] = new ReflectionClass($class);
$object = new $class; return $this->fillObject(static::$classes[$class], new $class, $data);
}
catch (ReflectionException $exception) {
throw new RepositoryException($exception->getMessage());
}
}
/** @inheritDoc */
public function updateFromData(object $object, array $data) : object {
try {
$class = get_class($object);
if(!isset(static::$classes[$class])) static::$classes[$class] = new ReflectionClass($class);
return $this->fillObject(static::$classes[$class], clone $object, $data, true);
}
catch (RepositoryException|ReflectionException $exception) {
throw new RepositoryException($exception->getMessage());
}
}
/**
* @param object $object
* @param callable|null $method
* @return array
* @throws RepositoryException
*/
public function getProperties(object $object, callable $method = null) : array {
try{
$class = get_class($object);
if(!isset(static::$classes[$class])) static::$classes[$class] = new ReflectionClass($class);
/** @var ReflectionProperty $property */ /** @var ReflectionProperty $property */
foreach(static::$classes[$class]->getProperties() as $property){ foreach(static::$classes[$class]->getProperties() as $property){
if(!$property->isInitialized($object) || is_array($property->getValue($object))) continue;
if(static::$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){
$fieldValue[$property->getName()] = $property->getValue($object)->get();
}
elseif(is_bool($property->getValue($object))){
$fieldValue[$property->getName()] = (int) $property->getValue($object);
}
else $fieldValue[$property->getName()] = $property->getValue($object);
$fieldNameSnakeCase = strtolower(preg_replace("'([A-Z])'", "_$1", $property->getName()));
if(false !== $fieldValue[$property->getName()]) $out[$fieldNameSnakeCase] = $fieldValue[$property->getName()];
}
return (isset($method)) ? array_map($method, $out ?? []) : $out ?? [];
}
catch (ReflectionException $exception) {
throw new RepositoryException($exception->getMessage());
}
}
/**
* @param ReflectionClass $class
* @param object $object
* @param array $data
* @param bool $update
* @return mixed
* @throws RepositoryException
*/
private function fillObject(ReflectionClass $class, object $object, array $data, bool $update = false) : mixed {
try {
foreach($class->getProperties() as $property){
if($update && !array_key_exists($property->getName(), $data) && !array_key_exists(strtolower(preg_replace("'([A-Z])'", "_$1", $property->getName())), $data)) continue;
// data[propertyName] ?? data[property_name] ?? null // data[propertyName] ?? data[property_name] ?? null
$value = $data[$property->getName()] ?? $data[strtolower(preg_replace("'([A-Z])'", "_$1", $property->getName()))] ?? 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); if($class->hasMethod('set'.ucfirst($property->getName()))) $object->{'set'.ucfirst($property->getName())}($value);
// Если тип свойства класс (valueObject) // Если тип свойства класс (valueObject)
elseif($property->hasType() && class_exists($property->getType()->getName())) $object->{$property->getName()} = (is_object($value)) ? $value : new ($property->getType()->getName())($value); elseif($property->hasType() && class_exists($property->getType()->getName())) $object->{$property->getName()} = (is_object($value)) ? $value : new ($property->getType()->getName())($value);
// если значения не пустое // если значения не пустое
@@ -35,62 +99,4 @@ abstract class AbstractRepository implements RepositoryInterface {
throw new RepositoryException($exception->getMessage()); 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

@@ -5,10 +5,27 @@ namespace Rmphp\Storage\Entity;
abstract class AbstractEntity implements EntityInterface { abstract class AbstractEntity implements EntityInterface {
/** /**
* @return int|null * @return mixed
*/ */
public function getId(): mixed { public function getId(): mixed {
return (isset($this->id)) ? (($this->id instanceof ValueObjectInterface) ? $this->id->get() : $this->id) : null; return (isset($this->id)) ? (($this->id instanceof ValueObjectInterface) ? $this->id->get() : $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 ?? "";
}
} }

View File

@@ -11,7 +11,7 @@ namespace Rmphp\Storage\Entity;
interface EntityInterface { interface EntityInterface {
/** /**
* @return int|null * @return mixed
*/ */
public function getId(): mixed; public function getId(): mixed;

View File

@@ -33,9 +33,12 @@ interface MysqlRepositoryInterface extends RepositoryInterface {
public function createListFromResult(string $class, bool|MysqlResultData $result, callable $function = null): array; public function createListFromResult(string $class, bool|MysqlResultData $result, callable $function = null): array;
/** /**
* @param int $id
* @param string|null $table
* @return mixed
* @throws RepositoryException * @throws RepositoryException
*/ */
public function getEntityById(int $id, $require = false); public function getEntityById(int $id, string $table = null): mixed;
/** /**
* @param EntityInterface $object * @param EntityInterface $object
@@ -45,13 +48,31 @@ interface MysqlRepositoryInterface extends RepositoryInterface {
*/ */
public function saveEntity(EntityInterface $object, string $table = null) : mixed; 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 array $objects
* @param string|null $table * @param string|null $table
* @return array * @return array
* @throws RepositoryException * @throws RepositoryException
*/ */
public function saveGroup(array $objects, string $table = null): array; 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 EntityInterface $object
@@ -66,5 +87,22 @@ interface MysqlRepositoryInterface extends RepositoryInterface {
*/ */
public function getStorageLogs() : 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;
} }

View File

@@ -8,6 +8,7 @@
namespace Rmphp\Storage; namespace Rmphp\Storage;
use ReflectionException;
use Rmphp\Storage\Entity\EntityInterface; use Rmphp\Storage\Entity\EntityInterface;
interface RepositoryInterface { interface RepositoryInterface {
@@ -22,18 +23,20 @@ interface RepositoryInterface {
/** /**
* @param object $class * @param object $object
* @param callable|null $method * @param array $data
* @return array * @return mixed
* @throws RepositoryException
*/ */
public function getAllProperties(object $class, callable $method = null) : array; public function updateFromData(object $object, array $data) : mixed;
/** /**
* @param object $class * @param object $object
* @param callable|null $method * @param callable|null $method
* @return array * @return array
* @throws RepositoryException
*/ */
public function getProperties(object $class, callable $method = null) : array; public function getProperties(object $object, callable $method = null) : array;
} }