2 Commits

Author SHA1 Message Date
ebfd42a88e 20250222
[О] [ClassMapper::GetDefaults]: Улучшено определение типа. Теперь проверка integer не вызовет ошибку, что ожидается int.

[О] [ClassMapper::MapClass]: Теперь идёт проверка свойства на доступность get и set. Свойства с только get и только set пропускаются.
2025-02-22 13:09:54 +03:00
054e6a7cdc 20250221 2025-02-21 18:33:23 +03:00
5 changed files with 324 additions and 371 deletions

View File

@@ -16,11 +16,11 @@
} }
], ],
"require": { "require": {
"php": ">=8.4", "php": "^8.4",
"ext-mbstring": "*" "ext-mbstring": "*"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": ">=11.5.6" "phpunit/phpunit": "^12.0.4"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {

538
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -4,10 +4,12 @@ namespace goodboyalex\php_components_pack\classes;
use DateTimeImmutable; use DateTimeImmutable;
use DateTimeInterface; use DateTimeInterface;
use Error;
use Exception; use Exception;
use ReflectionClass; use ReflectionClass;
use ReflectionException; use ReflectionException;
use stdClass; use stdClass;
use Throwable;
use UnitEnum; use UnitEnum;
/** /**
@@ -49,21 +51,79 @@ final class ClassMapper
// ---- то исключаю его из массива разрешенных // ---- то исключаю его из массива разрешенных
unset($options['allowed'][array_search($ignoredProperty, $options['allowed'])]); unset($options['allowed'][array_search($ignoredProperty, $options['allowed'])]);
// Получаю массив свойств // Задаю массив свойств
$properties = get_class_vars(get_class($from)); $properties = [];
// Получаю имя исходного класса
$className = get_class($from);
// Получение всех свойств класса
try {
$reflection = new ReflectionClass($className);
}
catch (ReflectionException) {
return;
}
// Получение всех свойств класса
$props = $reflection->getProperties();
// Создаю экземпляр класса
$instance = new $className();
// Для каждого свойства
foreach ($props as $prop) {
// - получаю имя свойства
$propName = $prop->getName();
// - получаю значение свойства
$value = $from->$propName;
try {
// - получаю тип свойства
$typeOf = gettype($from->$propName);
// - получаю значение свойства по типу и по умолчанию
$writeValue = self::GetDefaults($typeOf);
try {
// - проверяем, можно ли записать и прочитать значение
// -- пытаюсь установить значение
$instance->$propName = $writeValue;
// -- пытаюсь прочитать установленное значение
$readValue = $instance->$propName;
// -- и проверяю, что значение совпадают
/** @noinspection PhpConditionAlreadyCheckedInspection */
if ($readValue !== $writeValue)
continue;
}
catch (Throwable) {
// - в случае ошибки, понимаем, что свойство доступно или только для чтения, или
// только для записи и оно нам не подходит. Поэтому пропускаем его.
continue;
}
// - если свойство игнорируется
if (in_array($propName, $options['ignored']))
// -- пропускаю
continue;
// - если свойство не разрешено
if (count($options['allowed']) > 0 && !in_array($propName, $options['allowed']))
// -- пропускаю
continue;
// Если не было ошибки, значит свойство имеет и геттер, и сеттер
$properties[$propName] = $value;
}
catch (Error) {
// - в случае ошибки, понимаем, что свойство нам не подходит. Поэтому пропускаю его.
continue;
}
}
// Для каждого элемента массива // Для каждого элемента массива
foreach ($properties as $name => $value) { foreach ($properties as $name => $value) {
// - если свойство игнорируется
if (in_array($name, $options['ignored']))
// -- пропускаю
continue;
// - если свойство не разрешено
if (count($options['allowed']) > 0 && !in_array($name, $options['allowed']))
// -- пропускаю
continue;
// - если свойство есть в объекте // - если свойство есть в объекте
if (property_exists($to, $name)) if (property_exists($to, $name))
// -- то присваиваю значение // -- то присваиваю значение
@@ -71,6 +131,26 @@ final class ClassMapper
} }
} }
/**
* Возвращает значение по умолчанию для типа $typeName.
*
* @param string $typeName Тип
*
* @return mixed Значение по умолчанию
*/
public static function GetDefaults (string $typeName): mixed
{
return match (strtolower($typeName)) {
'int', 'integer' => 0,
'float', 'double' => 0.0,
'bool', 'boolean' => false,
'string' => '',
'array' => [],
'object' => new stdClass(),
default => null,
};
}
/** /**
* Подготавливает значения свойств класса. * Подготавливает значения свойств класса.
* *
@@ -80,7 +160,8 @@ final class ClassMapper
* *
* @return array Массив данных класса. * @return array Массив данных класса.
*/ */
public static function PrepareClassProperties (array $params, ReflectionClass $classReflector, public
static function PrepareClassProperties (array $params, ReflectionClass $classReflector,
array $options = self::DefaultOptions): array array $options = self::DefaultOptions): array
{ {
// Создаю массив данных класса // Создаю массив данных класса
@@ -140,7 +221,8 @@ final class ClassMapper
* *
* @return void * @return void
*/ */
public static function GetClassParametersArrayParser (array &$source, array $parametersKeys, mixed $value, public
static function GetClassParametersArrayParser (array &$source, array $parametersKeys, mixed $value,
array $options = self::DefaultOptions): void array $options = self::DefaultOptions): void
{ {
// Если массив имен свойств пустой // Если массив имен свойств пустой
@@ -189,7 +271,8 @@ final class ClassMapper
* @return mixed Объект класса * @return mixed Объект класса
* @throws Exception * @throws Exception
*/ */
public static function MapToClassProperty (string $className, array $properties): mixed public
static function MapToClassProperty (string $className, array $properties): mixed
{ {
// Создаю // Создаю
try { try {
@@ -285,7 +368,8 @@ final class ClassMapper
* *
* @throws Exception * @throws Exception
*/ */
public static function SetParameterToClass (ReflectionClass $classReflector, string $propertyName, public
static function SetParameterToClass (ReflectionClass $classReflector, string $propertyName,
mixed $classObj, mixed $value): void mixed $classObj, mixed $value): void
{ {
try { try {
@@ -312,24 +396,4 @@ final class ClassMapper
throw new Exception($exception->getMessage()); throw new Exception($exception->getMessage());
} }
} }
/**
* Получает значение по умолчанию для разных типов данных.
*
* @param string $typeName Имя типа данных.
*
* @return mixed|null Результат.
*/
public static function GetDefaults (string $typeName): mixed
{
return match ($typeName) {
'int' => 0,
'float' => 0.0,
'bool' => false,
'string' => '',
'array' => [],
'object' => new stdClass(),
default => null,
};
}
} }

View File

@@ -3,6 +3,8 @@
namespace goodboyalex\php_components_pack\tests\classes; namespace goodboyalex\php_components_pack\tests\classes;
use goodboyalex\php_components_pack\classes\ClassMapper; use goodboyalex\php_components_pack\classes\ClassMapper;
use goodboyalex\php_components_pack\tests\data\A;
use goodboyalex\php_components_pack\tests\data\B;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
class ClassMapperTest extends TestCase class ClassMapperTest extends TestCase
@@ -11,12 +13,10 @@ class ClassMapperTest extends TestCase
{ {
$this->PrepareForTest(); $this->PrepareForTest();
$a = new \goodboyalex\php_components_pack\tests\data\A(); $a = new A('a', 2, true);
$a->a = 'a';
$a->b = 2;
$a->c = true;
$b = new B(); $b = new B();
ClassMapper::MapClass($a, $b); ClassMapper::MapClass($a, $b);
$this->assertEquals('a', $b->a); $this->assertEquals('a', $b->a);

View File

@@ -1,10 +1,17 @@
<?php <?php
namespace goodboyalex\php_components_pack\tests\classes; namespace goodboyalex\php_components_pack\tests\data;
class B class B
{ {
public string $a; public string $a;
public int $b; public int $b;
public string $d; public string $d;
public function __construct (string $a = "", int $b = 0, string $d = "")
{
$this->a = $a;
$this->b = $b;
$this->d = $d;
}
} }