6 Commits
5.1 ... 6.x

Author SHA1 Message Date
User
d0e38875e6 20250224#3 2025-02-24 19:22:20 +03:00
User
73c9af71ab 20250224#2 2025-02-24 19:02:59 +03:00
User
5b0c0bc7b4 20250224#1 2025-02-24 18:33:53 +03:00
User
dfbcfdf321 20250222#1 2025-02-22 16:22:21 +03:00
User
a54b55cc4e 20250218#5 2025-02-18 02:34:04 +03:00
User
612132f938 20250218#4 2025-02-18 02:32:22 +03:00
11 changed files with 233 additions and 133 deletions

View File

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

View File

@@ -16,5 +16,5 @@
"Rmphp\\Storage\\": "src/" "Rmphp\\Storage\\": "src/"
} }
} }
} }

View File

@@ -3,9 +3,11 @@
namespace Rmphp\Storage; namespace Rmphp\Storage;
use Rmphp\Storage\Entity\EntityInterface; use Rmphp\Storage\Entity\EntityInterface;
use Rmphp\Storage\Exception\RepositoryException;
use Rmphp\Storage\Mysql\MysqlRepositoryInterface; use Rmphp\Storage\Mysql\MysqlRepositoryInterface;
use Rmphp\Storage\Mysql\MysqlResultData; use Rmphp\Storage\Mysql\MysqlResultData;
use Rmphp\Storage\Mysql\MysqlStorageInterface; use Rmphp\Storage\Mysql\MysqlStorageInterface;
use Rmphp\Storage\Repository\AbstractRepository;
abstract class AbstractMysqlRepository extends AbstractRepository implements MysqlRepositoryInterface { abstract class AbstractMysqlRepository extends AbstractRepository implements MysqlRepositoryInterface {
@@ -58,7 +60,7 @@ abstract class AbstractMysqlRepository extends AbstractRepository implements Mys
$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($this->getDebug()) {$this->debug($object, $in, $table); exit;} if($this->getDebug()) {$this->debug($object, $in, $table, $this->getRepositoryStack()); 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());
@@ -77,7 +79,7 @@ abstract class AbstractMysqlRepository extends AbstractRepository implements Mys
$in = array_map(function ($value){ $in = array_map(function ($value){
return (is_string($value)) ? $this->mysql->escapeStr($value) : $value; return (is_string($value)) ? $this->mysql->escapeStr($value) : $value;
}, $data); }, $data);
if($this->getDebug()) {$this->debug($data, $in, $table); exit;} if($this->getDebug()) {$this->debug($data, $in, $table, $this->getRepositoryStack()); exit;}
try { try {
if (!empty($data[$primaryKey]) && !empty($this->mysql->findById($table, $data[$primaryKey], $primaryKey))) { if (!empty($data[$primaryKey]) && !empty($this->mysql->findById($table, $data[$primaryKey], $primaryKey))) {
$this->mysql->updateById($table, $in, $data[$primaryKey]); $this->mysql->updateById($table, $in, $data[$primaryKey]);

View File

@@ -1,102 +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) : object {
try {
if(!isset(static::$classes[$class])) static::$classes[$class] = new ReflectionClass($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 */
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
$value = $data[$property->getName()] ?? $data[strtolower(preg_replace("'([A-Z])'", "_$1", $property->getName()))] ?? null;
// если есть внутренний метод (приоритетная обработка)
if($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());
}
}
}

View 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;
}
}

View File

@@ -8,7 +8,7 @@ abstract class AbstractEntity implements EntityInterface {
* @return mixed * @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->getValue() : $this->id) : null;
} }
/** /**

View File

@@ -4,7 +4,7 @@ namespace Rmphp\Storage\Entity;
interface ValueObjectInterface { interface ValueObjectInterface {
public function get(); public function getValue();
public function __toString(): string; public function __toString(): string;
} }

View File

@@ -1,6 +1,6 @@
<?php <?php
namespace Rmphp\Storage; namespace Rmphp\Storage\Exception;
use Throwable; use Throwable;

View File

@@ -9,8 +9,8 @@
namespace Rmphp\Storage\Mysql; namespace Rmphp\Storage\Mysql;
use Rmphp\Storage\Entity\EntityInterface; use Rmphp\Storage\Entity\EntityInterface;
use Rmphp\Storage\RepositoryException; use Rmphp\Storage\Exception\RepositoryException;
use Rmphp\Storage\RepositoryInterface; use Rmphp\Storage\Repository\RepositoryInterface;
interface MysqlRepositoryInterface extends RepositoryInterface { interface MysqlRepositoryInterface extends RepositoryInterface {

View 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;
}
}

View File

@@ -6,31 +6,13 @@
* Time: 21:48 * Time: 21:48
*/ */
namespace Rmphp\Storage; namespace Rmphp\Storage\Repository;
use ReflectionException;
use Rmphp\Storage\Entity\EntityInterface; use Rmphp\Storage\Exception\RepositoryException;
interface RepositoryInterface { interface RepositoryInterface {
/**
* @param string $class
* @param $data
* @return object
* @throws RepositoryException
*/
public function createFromData(string $class, $data) : mixed;
/**
* @param object $object
* @param array $data
* @return mixed
* @throws RepositoryException
*/
public function updateFromData(object $object, array $data) : mixed;
/** /**
* @param object $object * @param object $object
* @param callable|null $method * @param callable|null $method
@@ -39,4 +21,28 @@ interface RepositoryInterface {
*/ */
public function getProperties(object $object, callable $method = null) : array; 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;
} }