Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
335c4d240c | ||
|
|
91af1ea14f | ||
|
|
41523e6899 | ||
|
|
4a56e42af4 | ||
|
|
4b1c0d7044 | ||
|
|
d300a6b628 | ||
|
|
09e8520ded | ||
|
|
e6fd18fa2f | ||
|
|
9c1f6be326 | ||
|
|
f3458d1870 | ||
|
|
1ce2a09e01 | ||
|
|
fd996d40c8 | ||
|
|
96ee46476c | ||
|
|
d8991dcef5 | ||
|
|
30a20d427b | ||
|
|
10f6d62b43 | ||
|
|
2beff209de | ||
|
|
a39c0a6bf1 | ||
|
|
c516546b5d | ||
|
|
945c95441f | ||
|
|
d0e38875e6 | ||
|
|
73c9af71ab | ||
|
|
5b0c0bc7b4 | ||
|
|
dfbcfdf321 | ||
|
|
a54b55cc4e | ||
|
|
612132f938 | ||
|
|
73b7cb3a5f | ||
|
|
4f7993750c | ||
|
|
bdff890b41 | ||
|
|
e390bc262e | ||
|
|
2afc439354 | ||
|
|
2cfc92584c |
@@ -10,12 +10,12 @@ Stable version
|
||||
composer require rmphp/storage
|
||||
```
|
||||
```bash
|
||||
composer require rmphp/storage:"^4.0"
|
||||
composer require rmphp/storage:"^10.0"
|
||||
```
|
||||
|
||||
|
||||
Dev version contains the latest changes
|
||||
|
||||
```bash
|
||||
composer require rmphp/storage:"4.x-dev"
|
||||
composer require rmphp/storage:"10.x-dev"
|
||||
```
|
||||
|
||||
@@ -3,16 +3,21 @@
|
||||
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 ENTINY = null;
|
||||
public const ENTITY = null;
|
||||
|
||||
private string $table;
|
||||
private string $entity;
|
||||
private bool $debug;
|
||||
|
||||
public function __construct(
|
||||
public readonly MysqlStorageInterface $mysql
|
||||
@@ -42,24 +47,20 @@ abstract class AbstractMysqlRepository extends AbstractRepository implements Mys
|
||||
|
||||
|
||||
/** @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("Запись не найдена");
|
||||
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)){
|
||||
$this->checkConst();
|
||||
$table = static::TABLE;
|
||||
}
|
||||
if(!isset($table)) $table = $this->getTable();
|
||||
$in = $this->getProperties($object, function ($value){
|
||||
return (is_string($value)) ? $this->mysql->escapeStr($value) : $value;
|
||||
});
|
||||
if(static::DEBUG) {$this->getSaveDebug($object, $in, $table); exit;}
|
||||
if($this->isDebug()) {$this->debug($object, $in, $table, ...$this->getDebugExtraData()); exit;}
|
||||
try {
|
||||
if (!empty($object->getId()) && !empty($this->mysql->findById($table, $object->getId()))) {
|
||||
$this->mysql->updateById($table, $in, $object->getId());
|
||||
@@ -73,11 +74,26 @@ abstract class AbstractMysqlRepository extends AbstractRepository implements Mys
|
||||
|
||||
|
||||
/** @inheritDoc */
|
||||
public function saveGroup(array $objects, string $table = null): array {
|
||||
if(!isset($table)){
|
||||
$this->checkConst();
|
||||
$table = static::TABLE;
|
||||
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->isDebug()) {$this->debug($data, $in, $table, ...$this->getDebugExtraData()); 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);
|
||||
@@ -92,11 +108,23 @@ abstract class AbstractMysqlRepository extends AbstractRepository implements Mys
|
||||
|
||||
|
||||
/** @inheritDoc */
|
||||
public function deleteEntity(EntityInterface $object, string $table = null) : bool {
|
||||
if(!isset($table)){
|
||||
$this->checkConst();
|
||||
$table = static::TABLE;
|
||||
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());
|
||||
}
|
||||
@@ -110,23 +138,70 @@ 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 isDebug(): bool {
|
||||
if(!empty($this->debug)) return $this->debug;
|
||||
if(!empty(static::DEBUG)) return static::DEBUG;
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
protected function getDebugExtraData() : array {
|
||||
return [$this->getRepositoryStack(), $this->getClassesCache(), $this->getAttributesObjectsCache()];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ...$arg
|
||||
* @return void
|
||||
*/
|
||||
protected function getSaveDebug(...$arg) : void {
|
||||
protected function debug(...$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("Не указан объект");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
<?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 ?? [];
|
||||
}
|
||||
|
||||
}
|
||||
14
src/Attribute/Data.php
Normal file
14
src/Attribute/Data.php
Normal file
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace Rmphp\Storage\Attribute;
|
||||
|
||||
use Attribute;
|
||||
|
||||
#[Attribute(Attribute::TARGET_CLASS)]
|
||||
class Data {
|
||||
|
||||
public function __construct(
|
||||
public bool $ignorEmpty = false,
|
||||
) {}
|
||||
|
||||
}
|
||||
8
src/Attribute/DataIgnorEmpty.php
Normal file
8
src/Attribute/DataIgnorEmpty.php
Normal file
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace Rmphp\Storage\Attribute;
|
||||
|
||||
use Attribute;
|
||||
|
||||
#[Attribute(Attribute::TARGET_CLASS)]
|
||||
class DataIgnorEmpty {}
|
||||
14
src/Attribute/Entity.php
Normal file
14
src/Attribute/Entity.php
Normal file
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace Rmphp\Storage\Attribute;
|
||||
|
||||
use Attribute;
|
||||
|
||||
#[Attribute(Attribute::TARGET_CLASS)]
|
||||
class Entity {
|
||||
|
||||
public function __construct(
|
||||
public bool $noReturnIfNull = false,
|
||||
) {}
|
||||
|
||||
}
|
||||
8
src/Attribute/EntityNoReturnIfNull.php
Normal file
8
src/Attribute/EntityNoReturnIfNull.php
Normal file
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace Rmphp\Storage\Attribute;
|
||||
|
||||
use Attribute;
|
||||
|
||||
#[Attribute(Attribute::TARGET_CLASS)]
|
||||
class EntityNoReturnIfNull {}
|
||||
16
src/Attribute/Property.php
Normal file
16
src/Attribute/Property.php
Normal file
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace Rmphp\Storage\Attribute;
|
||||
|
||||
use Attribute;
|
||||
|
||||
#[Attribute(Attribute::TARGET_PROPERTY)]
|
||||
class Property {
|
||||
|
||||
public function __construct(
|
||||
public ?string $keyName = null,
|
||||
public bool $noReturn = false,
|
||||
public bool $noReturnIfNull = false,
|
||||
) {}
|
||||
|
||||
}
|
||||
8
src/Attribute/PropertyNoReturn.php
Normal file
8
src/Attribute/PropertyNoReturn.php
Normal file
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace Rmphp\Storage\Attribute;
|
||||
|
||||
use Attribute;
|
||||
|
||||
#[Attribute(Attribute::TARGET_PROPERTY)]
|
||||
class PropertyNoReturn {}
|
||||
8
src/Attribute/PropertyNoReturnIfNull.php
Normal file
8
src/Attribute/PropertyNoReturnIfNull.php
Normal file
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace Rmphp\Storage\Attribute;
|
||||
|
||||
use Attribute;
|
||||
|
||||
#[Attribute(Attribute::TARGET_PROPERTY)]
|
||||
class PropertyNoReturnIfNull {}
|
||||
15
src/Attribute/ValueObject.php
Normal file
15
src/Attribute/ValueObject.php
Normal file
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace Rmphp\Storage\Attribute;
|
||||
|
||||
use Attribute;
|
||||
|
||||
#[Attribute(Attribute::TARGET_CLASS)]
|
||||
class ValueObject {
|
||||
|
||||
public function __construct(
|
||||
public ?string $propertyName = null,
|
||||
public bool $firstProperty = false
|
||||
) {}
|
||||
|
||||
}
|
||||
8
src/Attribute/ValueObjectFirstProperty.php
Normal file
8
src/Attribute/ValueObjectFirstProperty.php
Normal file
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace Rmphp\Storage\Attribute;
|
||||
|
||||
use Attribute;
|
||||
|
||||
#[Attribute(Attribute::TARGET_CLASS)]
|
||||
class ValueObjectFirstProperty {}
|
||||
14
src/Attribute/ValueObjectPropertyName.php
Normal file
14
src/Attribute/ValueObjectPropertyName.php
Normal file
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace Rmphp\Storage\Attribute;
|
||||
|
||||
use Attribute;
|
||||
|
||||
#[Attribute(Attribute::TARGET_CLASS)]
|
||||
class ValueObjectPropertyName {
|
||||
|
||||
public function __construct(
|
||||
public ?string $name = null,
|
||||
) {}
|
||||
|
||||
}
|
||||
134
src/Component/AbstractDataObject.php
Normal file
134
src/Component/AbstractDataObject.php
Normal file
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
namespace Rmphp\Storage\Component;
|
||||
|
||||
use Exception;
|
||||
use ReflectionClass;
|
||||
use ReflectionException;
|
||||
use Rmphp\Storage\Attribute\Data;
|
||||
use Rmphp\Storage\Attribute\DataIgnorEmpty;
|
||||
|
||||
abstract class AbstractDataObject {
|
||||
|
||||
private static array $stack = [];
|
||||
protected static array $constructorEmptyAvailableClasses = [];
|
||||
protected static array $classes = [];
|
||||
protected static array $attributeObjects = [];
|
||||
|
||||
/**
|
||||
* @param ReflectionClass $class
|
||||
* @param object $object
|
||||
* @param array $data
|
||||
* @param bool $update
|
||||
* @param bool $withEmpty
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
protected static function fillObject(ReflectionClass $class, object $object, array $data, bool $update = false, bool $withEmpty = true) : mixed {
|
||||
try {
|
||||
if(!isset(self::$attributeObjects[$class->getName()][0])){
|
||||
self::$attributeObjects[$class->getName()][0] = !empty($class->getAttributes(Data::class))
|
||||
? $class->getAttributes(Data::class)[0]->newInstance()
|
||||
: new Data();
|
||||
}
|
||||
/** @var Data $dataAttributes */
|
||||
$dataAttributes = self::$attributeObjects[$class->getName()][0];
|
||||
if(!empty($class->getAttributes(DataIgnorEmpty::class))) $dataAttributes->ignorEmpty = true;
|
||||
|
||||
$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);
|
||||
$case[$property->getName()] = 'Method set'.ucfirst($property->getName());
|
||||
}
|
||||
// Если тип свойства класс (valueObject)
|
||||
elseif($property->hasType() && class_exists($property->getType()->getName())) {
|
||||
// значение объект
|
||||
if(is_object($value[$property->getName()])){
|
||||
$object->{$property->getName()} = $value[$property->getName()];
|
||||
$case[$property->getName()] = 'VO: Object';
|
||||
}
|
||||
// значение не пустое
|
||||
elseif(isset($value[$property->getName()]) && $value[$property->getName()] !== ""){
|
||||
$object->{$property->getName()} = new ($property->getType()->getName())($value[$property->getName()]);
|
||||
$case[$property->getName()] = 'VO: NewInstance';
|
||||
}
|
||||
// Значения нет и VO может быть без параметров
|
||||
elseif(($withEmpty && empty($dataAttributes->ignorEmpty)) && self::isEmptyAvailable($property->getType()->getName())) {
|
||||
$object->{$property->getName()} = new ($property->getType()->getName())();
|
||||
$case[$property->getName()] = 'VO: Without params';
|
||||
}
|
||||
}
|
||||
// Базовые типы при наличии значения
|
||||
elseif(array_key_exists($property->getName(), $value)){
|
||||
if(!$property->hasType()){
|
||||
$object->{$property->getName()} = $value[$property->getName()];
|
||||
$case[$property->getName()] = 'Base: Hasn`t type';
|
||||
}
|
||||
elseif(in_array($property->getType()->getName(), ['float', 'int'])){
|
||||
if(is_numeric($value[$property->getName()])) $object->{$property->getName()} = $value[$property->getName()];
|
||||
$case[$property->getName()] = 'Base: Number';
|
||||
}
|
||||
elseif($property->getType()->getName() == 'bool'){
|
||||
$object->{$property->getName()} = (bool)$value[$property->getName()];
|
||||
$case[$property->getName()] = 'Base: Boolean';
|
||||
}
|
||||
elseif(isset($value[$property->getName()])){
|
||||
$object->{$property->getName()} = $value[$property->getName()];
|
||||
$case[$property->getName()] = 'Base: NotNull';
|
||||
}
|
||||
elseif($property->getType()->allowsNull()){
|
||||
$object->{$property->getName()} = $value[$property->getName()];
|
||||
$case[$property->getName()] = 'Base: Null';
|
||||
}
|
||||
}
|
||||
}
|
||||
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)]['matchCase'] = $case ?? [];
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -5,10 +5,35 @@ namespace Rmphp\Storage\Entity;
|
||||
abstract class AbstractEntity implements EntityInterface {
|
||||
|
||||
/**
|
||||
* @return int|null
|
||||
* @return 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->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 ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @return bool
|
||||
*/
|
||||
public function __isset(string $name): bool {
|
||||
return isset($this->$name);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ namespace Rmphp\Storage\Entity;
|
||||
interface EntityInterface {
|
||||
|
||||
/**
|
||||
* @return int|null
|
||||
* @return mixed
|
||||
*/
|
||||
public function getId(): mixed;
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ namespace Rmphp\Storage\Entity;
|
||||
|
||||
interface ValueObjectInterface {
|
||||
|
||||
public function get();
|
||||
public function __toString(): string;
|
||||
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace Rmphp\Storage;
|
||||
namespace Rmphp\Storage\Exception;
|
||||
|
||||
use Throwable;
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
namespace Rmphp\Storage\Mysql;
|
||||
|
||||
use Rmphp\Storage\Entity\EntityInterface;
|
||||
use Rmphp\Storage\RepositoryException;
|
||||
use Rmphp\Storage\RepositoryInterface;
|
||||
use Rmphp\Storage\Exception\RepositoryException;
|
||||
use Rmphp\Storage\Repository\RepositoryInterface;
|
||||
|
||||
interface MysqlRepositoryInterface extends RepositoryInterface {
|
||||
|
||||
@@ -33,9 +33,12 @@ interface MysqlRepositoryInterface extends RepositoryInterface {
|
||||
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, $require = false);
|
||||
public function getEntityById(int $id, string $table = null): mixed;
|
||||
|
||||
/**
|
||||
* @param EntityInterface $object
|
||||
@@ -45,13 +48,31 @@ interface MysqlRepositoryInterface extends RepositoryInterface {
|
||||
*/
|
||||
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 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
|
||||
@@ -66,5 +87,22 @@ interface MysqlRepositoryInterface extends RepositoryInterface {
|
||||
*/
|
||||
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;
|
||||
|
||||
}
|
||||
|
||||
@@ -13,19 +13,23 @@ class MysqlStorage implements MysqlStorageInterface {
|
||||
private Mysqli $mysqli;
|
||||
|
||||
/**
|
||||
* Внутренний конструктор подключения к БД
|
||||
* Mysql constructor.
|
||||
* @param array $params
|
||||
* @param array $paramsArray
|
||||
* @throws Exception
|
||||
*/
|
||||
public function __construct(array $params) {
|
||||
$this->mysqli = new mysqli($params['host'], $params['user'], $params['pass'], $params['base']);
|
||||
public function __construct(array $paramsArray) {
|
||||
$params = (object) $paramsArray;
|
||||
$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;
|
||||
$this->mysqli->set_charset($params->chartset ?? "utf8");
|
||||
if(!empty($params->logs)) $this->logsEnabled = true;
|
||||
}
|
||||
|
||||
/** @inheritDoc */
|
||||
|
||||
169
src/Repository/AbstractRepository.php
Normal file
169
src/Repository/AbstractRepository.php
Normal file
@@ -0,0 +1,169 @@
|
||||
<?php
|
||||
|
||||
namespace Rmphp\Storage\Repository;
|
||||
|
||||
use Exception;
|
||||
use ReflectionClass;
|
||||
use Rmphp\Storage\Attribute\Entity;
|
||||
use Rmphp\Storage\Attribute\EntityNoReturnIfNull;
|
||||
use Rmphp\Storage\Attribute\Property;
|
||||
use Rmphp\Storage\Attribute\PropertyNoReturn;
|
||||
use Rmphp\Storage\Attribute\PropertyNoReturnIfNull;
|
||||
use Rmphp\Storage\Attribute\ValueObject;
|
||||
use Rmphp\Storage\Attribute\ValueObjectFirstProperty;
|
||||
use Rmphp\Storage\Attribute\ValueObjectPropertyName;
|
||||
use Rmphp\Storage\Component\AbstractDataObject;
|
||||
use Rmphp\Storage\Exception\RepositoryException;
|
||||
|
||||
abstract class AbstractRepository extends AbstractDataObject implements RepositoryInterface {
|
||||
|
||||
/** @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);
|
||||
|
||||
if(!isset(self::$attributeObjects[$class][0])){
|
||||
self::$attributeObjects[$class][0] = !empty(self::$classes[$class]->getAttributes(Entity::class))
|
||||
? self::$classes[$class]->getAttributes(Entity::class)[0]->newInstance()
|
||||
: new Entity();
|
||||
}
|
||||
/** @var Entity $entityAttributes */
|
||||
$entityAttributes = self::$attributeObjects[$class][0];
|
||||
if(!empty(self::$classes[$class]->getAttributes(EntityNoReturnIfNull::class))) $entityAttributes->noReturnIfNull = true;
|
||||
|
||||
$fieldValue = [];
|
||||
foreach(self::$classes[$class]->getProperties() as $property){
|
||||
|
||||
if(!isset(self::$attributeObjects[$class][$property->getName()])){
|
||||
self::$attributeObjects[$class][$property->getName()] = !empty($property->getAttributes(Property::class))
|
||||
? $property->getAttributes(Property::class)[0]->newInstance()
|
||||
: new Property();
|
||||
}
|
||||
/** @var Property $propertyAttributes */
|
||||
$propertyAttributes = self::$attributeObjects[$class][$property->getName()];
|
||||
if(!empty($property->getAttributes(PropertyNoReturnIfNull::class))) $propertyAttributes->noReturnIfNull = true;
|
||||
|
||||
if(!empty($property->getAttributes(PropertyNoReturn::class)) || !empty($propertyAttributes->noReturn)) continue;
|
||||
|
||||
if($property->isInitialized($object)) {
|
||||
|
||||
if(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())){
|
||||
$valueObjectClass = get_class($property->getValue($object));
|
||||
if(!isset(self::$classes[$valueObjectClass])) self::$classes[$valueObjectClass] = new ReflectionClass($valueObjectClass);
|
||||
|
||||
if(!isset(self::$attributeObjects[$valueObjectClass])){
|
||||
self::$attributeObjects[$valueObjectClass] = !empty(self::$classes[$valueObjectClass]->getAttributes(ValueObject::class))
|
||||
? self::$classes[$valueObjectClass]->getAttributes(ValueObject::class)[0]->newInstance()
|
||||
: new ValueObject();
|
||||
if(!empty(self::$classes[$valueObjectClass]->getAttributes(ValueObjectFirstProperty::class))) {
|
||||
self::$attributeObjects[$valueObjectClass]->firstProperty = true;
|
||||
}
|
||||
if(!empty(self::$classes[$valueObjectClass]->getAttributes(ValueObjectPropertyName::class))) {
|
||||
$propertyName = self::$classes[$valueObjectClass]->getAttributes(ValueObjectPropertyName::class)[0]->newInstance();
|
||||
if(isset($propertyName->name)) self::$attributeObjects[$valueObjectClass]->propertyName = $propertyName->name;
|
||||
}
|
||||
}
|
||||
$valueObjectAttributes = self::$attributeObjects[$valueObjectClass];
|
||||
|
||||
if(!empty($valueObjectAttributes->propertyName) && self::$classes[$valueObjectClass]->hasProperty($valueObjectAttributes->propertyName)){
|
||||
if(self::$classes[$valueObjectClass]->getProperty($valueObjectAttributes->propertyName)->isInitialized($property->getValue($object))){
|
||||
$fieldValue[$property->getName()] = self::$classes[$valueObjectClass]->getProperty($valueObjectAttributes->propertyName)->getValue($property->getValue($object));
|
||||
}
|
||||
}
|
||||
elseif(!empty($valueObjectAttributes->firstProperty) && count(self::$classes[$valueObjectClass]->getProperties()) > 0){
|
||||
if(self::$classes[$valueObjectClass]->getProperties()[0]->isInitialized($property->getValue($object))){
|
||||
$fieldValue[$property->getName()] = self::$classes[$valueObjectClass]->getProperties()[0]->getValue($property->getValue($object));
|
||||
}
|
||||
}
|
||||
elseif(self::$classes[$valueObjectClass]->hasMethod('getValue')){
|
||||
$fieldValue[$property->getName()] = $property->getValue($object)->getValue();
|
||||
}
|
||||
}
|
||||
elseif(is_bool($property->getValue($object))){
|
||||
$fieldValue[$property->getName()] = (int)$property->getValue($object);
|
||||
}
|
||||
else{
|
||||
$fieldValue[$property->getName()] = $property->getValue($object);
|
||||
}
|
||||
|
||||
if(!isset($fieldValue[$property->getName()]) && (!empty($propertyAttributes->noReturnIfNull) || !empty($entityAttributes->noReturnIfNull))) continue;
|
||||
|
||||
if(array_key_exists($property->getName(), $fieldValue) && false !== $fieldValue[$property->getName()]) {
|
||||
$columnName = !empty($propertyAttributes->keyName) ? $propertyAttributes->keyName : strtolower(preg_replace("'([A-Z])'", "_$1", $property->getName()));
|
||||
$out[$columnName] = $fieldValue[$property->getName()];
|
||||
}
|
||||
}
|
||||
}
|
||||
return (isset($method)) ? array_map($method, $out ?? []) : $out ?? [];
|
||||
}
|
||||
catch (\ReflectionException $exception) {
|
||||
throw new RepositoryException($exception->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
* @throws RepositoryException
|
||||
*/
|
||||
public function createFromData(string $class, array|object $data, bool $withEmpty = true) : 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, false, $withEmpty);
|
||||
}
|
||||
catch (Exception $exception) {
|
||||
throw new RepositoryException($exception->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
* @throws RepositoryException
|
||||
*/
|
||||
public function updateFromData(object $object, array|object $data, bool $withEmpty = true) : 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, $withEmpty);
|
||||
}
|
||||
catch (Exception $exception) {
|
||||
throw new RepositoryException($exception->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getRepositoryStack() : array {
|
||||
return $this->getFillObjectStack();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getClassesCache() : array {
|
||||
return self::$classes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getAttributesObjectsCache() : array {
|
||||
return self::$attributeObjects;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getConstructorEmptyAvailableClassesCache() : array {
|
||||
return self::$constructorEmptyAvailableClasses;
|
||||
}
|
||||
|
||||
}
|
||||
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
|
||||
* @param bool $withEmpty
|
||||
* @return mixed
|
||||
*/
|
||||
public function createFromData(string $class, array|object $data, bool $withEmpty = true) : mixed;
|
||||
|
||||
|
||||
/**
|
||||
* @param object $object
|
||||
* @param array|object $data
|
||||
* @param bool $withEmpty
|
||||
* @return mixed
|
||||
*/
|
||||
public function updateFromData(object $object, array|object $data, bool $withEmpty = true) : mixed;
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getRepositoryStack() : array;
|
||||
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
<?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;
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user