Compare commits
6 Commits
Author | SHA1 | Date | |
---|---|---|---|
7e57e5cb56 | |||
62762374e0 | |||
117deab9d8 | |||
3fbb7dc81c | |||
83a76dc8e2 | |||
6e831e2650 |
6
.gitignore
vendored
6
.gitignore
vendored
@@ -78,4 +78,8 @@ fabric.properties
|
|||||||
.idea/caches/build_file_checksums.ser
|
.idea/caches/build_file_checksums.ser
|
||||||
|
|
||||||
.idea/
|
.idea/
|
||||||
vendor/
|
vendor/
|
||||||
|
/tests/extensions/class.txt
|
||||||
|
/tests/classesserialized1.txt
|
||||||
|
/tests/classesserialized2.txt
|
||||||
|
/tests/classesserialized3.txt
|
||||||
|
@@ -20,7 +20,7 @@
|
|||||||
"ext-mbstring": "*"
|
"ext-mbstring": "*"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"phpunit/phpunit": "^12.2.1"
|
"phpunit/phpunit": "^12.2.7"
|
||||||
},
|
},
|
||||||
"autoload": {
|
"autoload": {
|
||||||
"psr-4": {
|
"psr-4": {
|
||||||
|
30
composer.lock
generated
30
composer.lock
generated
@@ -4,21 +4,21 @@
|
|||||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||||
"This file is @generated automatically"
|
"This file is @generated automatically"
|
||||||
],
|
],
|
||||||
"content-hash": "f5bf0ec4042cb12fb3a702cad65f099d",
|
"content-hash": "45c3c2e33a7aa403660825318375a599",
|
||||||
"packages": [],
|
"packages": [],
|
||||||
"packages-dev": [
|
"packages-dev": [
|
||||||
{
|
{
|
||||||
"name": "myclabs/deep-copy",
|
"name": "myclabs/deep-copy",
|
||||||
"version": "1.13.1",
|
"version": "1.13.3",
|
||||||
"source": {
|
"source": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://github.com/myclabs/DeepCopy.git",
|
"url": "https://github.com/myclabs/DeepCopy.git",
|
||||||
"reference": "1720ddd719e16cf0db4eb1c6eca108031636d46c"
|
"reference": "faed855a7b5f4d4637717c2b3863e277116beb36"
|
||||||
},
|
},
|
||||||
"dist": {
|
"dist": {
|
||||||
"type": "zip",
|
"type": "zip",
|
||||||
"url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/1720ddd719e16cf0db4eb1c6eca108031636d46c",
|
"url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/faed855a7b5f4d4637717c2b3863e277116beb36",
|
||||||
"reference": "1720ddd719e16cf0db4eb1c6eca108031636d46c",
|
"reference": "faed855a7b5f4d4637717c2b3863e277116beb36",
|
||||||
"shasum": ""
|
"shasum": ""
|
||||||
},
|
},
|
||||||
"require": {
|
"require": {
|
||||||
@@ -57,7 +57,7 @@
|
|||||||
],
|
],
|
||||||
"support": {
|
"support": {
|
||||||
"issues": "https://github.com/myclabs/DeepCopy/issues",
|
"issues": "https://github.com/myclabs/DeepCopy/issues",
|
||||||
"source": "https://github.com/myclabs/DeepCopy/tree/1.13.1"
|
"source": "https://github.com/myclabs/DeepCopy/tree/1.13.3"
|
||||||
},
|
},
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
@@ -65,7 +65,7 @@
|
|||||||
"type": "tidelift"
|
"type": "tidelift"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"time": "2025-04-29T12:36:36+00:00"
|
"time": "2025-07-05T12:25:42+00:00"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "nikic/php-parser",
|
"name": "nikic/php-parser",
|
||||||
@@ -579,16 +579,16 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "phpunit/phpunit",
|
"name": "phpunit/phpunit",
|
||||||
"version": "12.2.5",
|
"version": "12.2.7",
|
||||||
"source": {
|
"source": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://github.com/sebastianbergmann/phpunit.git",
|
"url": "https://github.com/sebastianbergmann/phpunit.git",
|
||||||
"reference": "b71849b29f7a8d7574e4401873cb8b539896613f"
|
"reference": "8b1348b254e5959acaf1539c6bd790515fb49414"
|
||||||
},
|
},
|
||||||
"dist": {
|
"dist": {
|
||||||
"type": "zip",
|
"type": "zip",
|
||||||
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/b71849b29f7a8d7574e4401873cb8b539896613f",
|
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/8b1348b254e5959acaf1539c6bd790515fb49414",
|
||||||
"reference": "b71849b29f7a8d7574e4401873cb8b539896613f",
|
"reference": "8b1348b254e5959acaf1539c6bd790515fb49414",
|
||||||
"shasum": ""
|
"shasum": ""
|
||||||
},
|
},
|
||||||
"require": {
|
"require": {
|
||||||
@@ -598,7 +598,7 @@
|
|||||||
"ext-mbstring": "*",
|
"ext-mbstring": "*",
|
||||||
"ext-xml": "*",
|
"ext-xml": "*",
|
||||||
"ext-xmlwriter": "*",
|
"ext-xmlwriter": "*",
|
||||||
"myclabs/deep-copy": "^1.13.1",
|
"myclabs/deep-copy": "^1.13.3",
|
||||||
"phar-io/manifest": "^2.0.4",
|
"phar-io/manifest": "^2.0.4",
|
||||||
"phar-io/version": "^3.2.1",
|
"phar-io/version": "^3.2.1",
|
||||||
"php": ">=8.3",
|
"php": ">=8.3",
|
||||||
@@ -656,7 +656,7 @@
|
|||||||
"support": {
|
"support": {
|
||||||
"issues": "https://github.com/sebastianbergmann/phpunit/issues",
|
"issues": "https://github.com/sebastianbergmann/phpunit/issues",
|
||||||
"security": "https://github.com/sebastianbergmann/phpunit/security/policy",
|
"security": "https://github.com/sebastianbergmann/phpunit/security/policy",
|
||||||
"source": "https://github.com/sebastianbergmann/phpunit/tree/12.2.5"
|
"source": "https://github.com/sebastianbergmann/phpunit/tree/12.2.7"
|
||||||
},
|
},
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
@@ -680,7 +680,7 @@
|
|||||||
"type": "tidelift"
|
"type": "tidelift"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"time": "2025-06-27T04:37:55+00:00"
|
"time": "2025-07-11T04:11:13+00:00"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "sebastian/cli-parser",
|
"name": "sebastian/cli-parser",
|
||||||
@@ -1633,4 +1633,4 @@
|
|||||||
},
|
},
|
||||||
"platform-dev": {},
|
"platform-dev": {},
|
||||||
"plugin-api-version": "2.6.0"
|
"plugin-api-version": "2.6.0"
|
||||||
}
|
}
|
@@ -8,7 +8,7 @@
|
|||||||
namespace goodboyalex\php_components_pack\classes;
|
namespace goodboyalex\php_components_pack\classes;
|
||||||
|
|
||||||
use goodboyalex\php_components_pack\interfaces\ISerializable;
|
use goodboyalex\php_components_pack\interfaces\ISerializable;
|
||||||
use goodboyalex\php_components_pack\models\ActionStateMessageModel;
|
use goodboyalex\php_components_pack\models\ActionStateMessage;
|
||||||
use goodboyalex\php_components_pack\traits\ActionState\ActionStateAddTrait;
|
use goodboyalex\php_components_pack\traits\ActionState\ActionStateAddTrait;
|
||||||
use goodboyalex\php_components_pack\traits\ActionState\ActionStateGetTrait;
|
use goodboyalex\php_components_pack\traits\ActionState\ActionStateGetTrait;
|
||||||
use goodboyalex\php_components_pack\traits\ActionState\ActionStateHasTrait;
|
use goodboyalex\php_components_pack\traits\ActionState\ActionStateHasTrait;
|
||||||
@@ -103,7 +103,7 @@ final class ActionState implements ISerializable
|
|||||||
// Для каждого сообщения
|
// Для каждого сообщения
|
||||||
foreach ($list as $messageSerialized) {
|
foreach ($list as $messageSerialized) {
|
||||||
// - создаю новое сообщение
|
// - создаю новое сообщение
|
||||||
$message = new ActionStateMessageModel();
|
$message = new ActionStateMessage();
|
||||||
// - десериализую его
|
// - десериализую его
|
||||||
$message->UnSerialize($messageSerialized);
|
$message->UnSerialize($messageSerialized);
|
||||||
// - добавляю в список
|
// - добавляю в список
|
||||||
|
@@ -9,6 +9,7 @@ use goodboyalex\php_components_pack\traits\ArrayBasicTrait;
|
|||||||
use goodboyalex\php_components_pack\traits\ObjectArray\ObjectArrayConstantsTrait;
|
use goodboyalex\php_components_pack\traits\ObjectArray\ObjectArrayConstantsTrait;
|
||||||
use goodboyalex\php_components_pack\traits\ObjectArray\ObjectArrayLINQTrait;
|
use goodboyalex\php_components_pack\traits\ObjectArray\ObjectArrayLINQTrait;
|
||||||
use goodboyalex\php_components_pack\traits\ObjectArray\ObjectArraySearchAndSortTrait;
|
use goodboyalex\php_components_pack\traits\ObjectArray\ObjectArraySearchAndSortTrait;
|
||||||
|
use goodboyalex\php_components_pack\traits\ObjectArray\ObjectArraySerializeExTrait;
|
||||||
use goodboyalex\php_components_pack\traits\ObjectArray\ObjectArraySpecialTrait;
|
use goodboyalex\php_components_pack\traits\ObjectArray\ObjectArraySpecialTrait;
|
||||||
use IteratorAggregate;
|
use IteratorAggregate;
|
||||||
|
|
||||||
@@ -17,7 +18,7 @@ use IteratorAggregate;
|
|||||||
*
|
*
|
||||||
* @author Александр Бабаев
|
* @author Александр Бабаев
|
||||||
* @package php_components_pack
|
* @package php_components_pack
|
||||||
* @version 1.0.5
|
* @version 1.0.6
|
||||||
* @since 1.0
|
* @since 1.0
|
||||||
*/
|
*/
|
||||||
final class ObjectArray implements ArrayAccess, IteratorAggregate, Countable, ISerializable
|
final class ObjectArray implements ArrayAccess, IteratorAggregate, Countable, ISerializable
|
||||||
@@ -42,6 +43,9 @@ final class ObjectArray implements ArrayAccess, IteratorAggregate, Countable, IS
|
|||||||
// Специальные методы
|
// Специальные методы
|
||||||
use ObjectArraySpecialTrait;
|
use ObjectArraySpecialTrait;
|
||||||
|
|
||||||
|
// Расширенные методы для сериализации
|
||||||
|
use ObjectArraySerializeExTrait;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Конструктор класса.
|
* Конструктор класса.
|
||||||
*
|
*
|
||||||
|
40
sources/enums/ObjectArraySerializeMethod.php
Normal file
40
sources/enums/ObjectArraySerializeMethod.php
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace goodboyalex\php_components_pack\enums;
|
||||||
|
|
||||||
|
use goodboyalex\php_components_pack\traits\EnumExtensionsTrait;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Перечисление типов сериализации массива объектов.
|
||||||
|
*
|
||||||
|
* @author Александр Бабаев
|
||||||
|
* @package php_components_pack
|
||||||
|
* @version 1.0
|
||||||
|
* @since 1.1.1
|
||||||
|
*/
|
||||||
|
enum ObjectArraySerializeMethod: int
|
||||||
|
{
|
||||||
|
// Подключаю расширение для Enum
|
||||||
|
use EnumExtensionsTrait;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Сериализация массива объектов с помощью serialize.
|
||||||
|
*/
|
||||||
|
case Serialize = 1;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Сериализация массива объектов с помощью json_encode.
|
||||||
|
*
|
||||||
|
* @warning Для корректной работы требуется наличие json_encode в php.ini
|
||||||
|
* @warning Этот способ сериализации НЕ РЕКОМЕНДУЕТСЯ для массивов объектов, представляющих собой классы, так как
|
||||||
|
* при десериализации классы не будут созданы: вместо этого будет созданы объекты класса stdClass. Вместо этого
|
||||||
|
* следует использовать метод JsonEncodeWithToArray.
|
||||||
|
*/
|
||||||
|
case JsonEncode = 2;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Сериализация массива объектов с помощью ToArray, который возвращает массив. Этот массив впоследствии
|
||||||
|
* сериализуется с помощью json_encode. Десерилизация происходит в обратном порядке.
|
||||||
|
*/
|
||||||
|
case JsonEncodeWithToArray = 3;
|
||||||
|
}
|
36
sources/exceptions/TypeException.php
Normal file
36
sources/exceptions/TypeException.php
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace goodboyalex\php_components_pack\exceptions;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ошибка работы с расширением типов.
|
||||||
|
*
|
||||||
|
* @author Александр Бабаев
|
||||||
|
* @package php_components_pack
|
||||||
|
* @version 1.0
|
||||||
|
* @since 1.1.1
|
||||||
|
*/
|
||||||
|
final class TypeException extends Exception
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var string $TypeName Имя типа.
|
||||||
|
*/
|
||||||
|
public string $TypeName;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Конструктор.
|
||||||
|
*
|
||||||
|
* @param string $typeName Имя типа.
|
||||||
|
* @param string $message Сообщение об ошибке.
|
||||||
|
*/
|
||||||
|
public function __construct (string $typeName = "", string $message = "")
|
||||||
|
{
|
||||||
|
// Запускаем базовый конструктор
|
||||||
|
parent::__construct($message);
|
||||||
|
|
||||||
|
// Присваиваем тип
|
||||||
|
$this->TypeName = $typeName;
|
||||||
|
}
|
||||||
|
}
|
179
sources/extensions/TypeExtension.md
Normal file
179
sources/extensions/TypeExtension.md
Normal file
@@ -0,0 +1,179 @@
|
|||||||
|
# Описание класса TypeExtension
|
||||||
|
|
||||||
|
## Информация о версии
|
||||||
|
|
||||||
|
Версия класса: 1.0
|
||||||
|
|
||||||
|
Впервые введено в пакет с версии: 1.1.1
|
||||||
|
|
||||||
|
Описание класса: Расширение для любого типа.
|
||||||
|
|
||||||
|
## Публичные свойства и константы класса
|
||||||
|
|
||||||
|
К публичным свойствам можно отнести следующие статичные функции: `DEFAULT_TO_ARRAY_ON_CLASS` и
|
||||||
|
`DEFAULT_FROM_ARRAY_ON_CLASS`. Они описывают методы обработки классов по умолчанию для методов `ToArray` и `FromArray`
|
||||||
|
соответственно.
|
||||||
|
|
||||||
|
### Метод `DEFAULT_TO_ARRAY_ON_CLASS`
|
||||||
|
|
||||||
|
Этот метод возвращает `Closure`, который можно использовать (и он используется при значении параметра `null`) во втором
|
||||||
|
параметре метода `ToArray`.
|
||||||
|
|
||||||
|
### Метод `DEFAULT_FROM_ARRAY_ON_CLASS`
|
||||||
|
|
||||||
|
Этот метод возвращает `Closure`, который можно использовать (и он используется при значении параметра `null`) во втором
|
||||||
|
параметре метода `FromArray`.
|
||||||
|
|
||||||
|
## Методы и функции
|
||||||
|
|
||||||
|
### Метод `ToArray`
|
||||||
|
|
||||||
|
Этот _статический_ метод переводит класс в массив. Он содержит **1 обязательный параметр**:
|
||||||
|
|
||||||
|
* `object $class` - класс, который нужно перевести в массив
|
||||||
|
|
||||||
|
и **1 необязательный параметр**:
|
||||||
|
|
||||||
|
* `?callable $onClass = null` - метод обработки классов. Если передаётся `null`, то используется
|
||||||
|
`DEFAULT_TO_ARRAY_ON_CLASS`. По умолчанию, `null`.
|
||||||
|
|
||||||
|
В качестве метода обработки классов `onClass` подойдет любое `Closure` вида
|
||||||
|
|
||||||
|
fn (object $class): array => <ДЕЙСТВИЕ>;
|
||||||
|
|
||||||
|
Метод возвращает `array` - массив публичных свойств.
|
||||||
|
|
||||||
|
Синтаксис:
|
||||||
|
|
||||||
|
public static function ToArray (object $class, ?callable $onClass = null): array
|
||||||
|
|
||||||
|
Пример,
|
||||||
|
|
||||||
|
// Создаём тестовый класс (см. TypeExtensionTest)
|
||||||
|
$class = new D (
|
||||||
|
'test_string',
|
||||||
|
12345,
|
||||||
|
true,
|
||||||
|
new A("test_string_A", 6789, false),
|
||||||
|
new B("test_string_B", 9876, "false"),
|
||||||
|
new C("test_string_C", 54321, true)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Создаём метод обработки классов
|
||||||
|
// - воспользуемся тем, что класс C реализует интерфейс ISerialize
|
||||||
|
$c_closure = fn (C $class): array =>
|
||||||
|
[
|
||||||
|
"type_class" => C::class,
|
||||||
|
"type_value" => $class->Serialize()
|
||||||
|
];
|
||||||
|
|
||||||
|
// - зададим метод обработки
|
||||||
|
$closure = fn (object $class): array => $class instanceof C
|
||||||
|
? $c_closure($class)
|
||||||
|
: TypeExtension::ToArray($class);
|
||||||
|
|
||||||
|
// Преобразуем в массив
|
||||||
|
try {
|
||||||
|
$array = TypeExtension::ToArray($class, $closure);
|
||||||
|
}
|
||||||
|
catch (TypeException $e) {
|
||||||
|
// - если ошибка, то выводим её и завершаем работу
|
||||||
|
die($e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Вывожу в файл
|
||||||
|
file_put_contents(__DIR__ . "/class.txt", json_encode($array, JSON_PRETTY_PRINT));
|
||||||
|
|
||||||
|
В результате содержимое файла:
|
||||||
|
|
||||||
|
{
|
||||||
|
"type_class": "goodboyalex\\php_components_pack\\tests\\data\\D",
|
||||||
|
"stringD": "test_string",
|
||||||
|
"intD": 12345,
|
||||||
|
"boolD": true,
|
||||||
|
"a": {
|
||||||
|
"type_class": "goodboyalex\\php_components_pack\\tests\\data\\A",
|
||||||
|
"a": "test_string_A",
|
||||||
|
"b": 6789,
|
||||||
|
"c": false
|
||||||
|
},
|
||||||
|
"b": {
|
||||||
|
"type_class": "goodboyalex\\php_components_pack\\tests\\data\\B",
|
||||||
|
"a": "test_string_B",
|
||||||
|
"b": 9876,
|
||||||
|
"d": "false"
|
||||||
|
},
|
||||||
|
"c": {
|
||||||
|
"type_class": "goodboyalex\\php_components_pack\\tests\\data\\C",
|
||||||
|
"type_value": "{\"string\":\"test_string_C\",\"int\":54321,\"bool\":true}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#### Выбрасываемые исключения
|
||||||
|
|
||||||
|
Этот метод выбрасывает исключение типа `TypeException` в случае, если объект `$class` (обязательный параметр метода) не является классом.
|
||||||
|
|
||||||
|
### Метод `FromArray`
|
||||||
|
|
||||||
|
Этот _статический_ метод переводит массив в класс. Он содержит **1 обязательный параметр**:
|
||||||
|
|
||||||
|
* `array $array` - массив публичных свойств
|
||||||
|
|
||||||
|
и **1 необязательный параметр**:
|
||||||
|
|
||||||
|
* `?callable $onClass = null` - метод обработки классов. Если передаётся `null`, то используется
|
||||||
|
`DEFAULT_FROM_ARRAY_ON_CLASS`. По умолчанию, `null`.
|
||||||
|
|
||||||
|
В качестве метода обработки классов `onClass` подойдет любое `Closure` вида
|
||||||
|
|
||||||
|
fn (array $classArray): object => <ДЕЙСТВИЕ>;
|
||||||
|
|
||||||
|
Метод возвращает `object` - экземпляр класса.
|
||||||
|
|
||||||
|
Синтаксис:
|
||||||
|
|
||||||
|
public static function FromArray (array $array, ?callable $onClass = null): object
|
||||||
|
|
||||||
|
Пример,
|
||||||
|
|
||||||
|
// Считываем данные из файла и преобразуем в массив
|
||||||
|
$array = json_decode(file_get_contents(__DIR__ . "/class.txt"), true);
|
||||||
|
|
||||||
|
// Создаём метод обработки классов
|
||||||
|
// - воспользуемся тем, что класс C реализует интерфейс ISerialize
|
||||||
|
$c_closure = function (string $serializedC): C
|
||||||
|
{
|
||||||
|
$classC = new C();
|
||||||
|
$classC->UnSerialize($serializedC);
|
||||||
|
return $classC;
|
||||||
|
};
|
||||||
|
|
||||||
|
// - зададим метод обработки
|
||||||
|
$closure = fn (array $classArray): object =>
|
||||||
|
$classArray['type_class'] == C::class
|
||||||
|
? $c_closure($classArray["type_value"])
|
||||||
|
: TypeExtension::FromArray($classArray);
|
||||||
|
|
||||||
|
// Преобразуем в объект
|
||||||
|
try {
|
||||||
|
$class = TypeExtension::FromArray($array, D::CLOSURE_FROM_ARRAY());
|
||||||
|
} catch (TypeException $e) {
|
||||||
|
// - если ошибка, то выводим её и завершаем работу
|
||||||
|
die($e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Вывожу тестовую строку
|
||||||
|
echo $class->c->stringC;
|
||||||
|
|
||||||
|
В результате на экране отобразится:
|
||||||
|
|
||||||
|
test_string_C
|
||||||
|
|
||||||
|
#### Выбрасываемые исключения
|
||||||
|
|
||||||
|
Этот метод выбрасывает исключение типа `TypeException` в случаях, если:
|
||||||
|
|
||||||
|
* массив `$array` не создан через метод `ToArray`;
|
||||||
|
* при попытке создать объект, он не создаётся;
|
||||||
|
* дата передана не корректного формата;
|
||||||
|
* пытается передать `null` не `nullable` типу.
|
235
sources/extensions/TypeExtension.php
Normal file
235
sources/extensions/TypeExtension.php
Normal file
@@ -0,0 +1,235 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace goodboyalex\php_components_pack\extensions;
|
||||||
|
|
||||||
|
use Closure;
|
||||||
|
use DateMalformedStringException;
|
||||||
|
use DateTime;
|
||||||
|
use DateTimeImmutable;
|
||||||
|
use DateTimeInterface;
|
||||||
|
use Exception;
|
||||||
|
use goodboyalex\php_components_pack\exceptions\TypeException;
|
||||||
|
use UnitEnum;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Расширение для любого типа.
|
||||||
|
*
|
||||||
|
* @author Александр Бабаев
|
||||||
|
* @package php_components_pack
|
||||||
|
* @version 1.0
|
||||||
|
* @since 1.1.1
|
||||||
|
*/
|
||||||
|
final class TypeExtension
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Дефолтный метод обработки классов для ToArray.
|
||||||
|
*
|
||||||
|
* @return Closure Метод обработки классов для ToArray.
|
||||||
|
*/
|
||||||
|
public static function DEFAULT_TO_ARRAY_ON_CLASS (): Closure
|
||||||
|
{
|
||||||
|
return fn (object $class): array => self::ToArray($class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Переводит объект в массив.
|
||||||
|
*
|
||||||
|
* @param object $class Объект.
|
||||||
|
* @param callable|null $onClass Метод обработки классов. Если передаётся null, то используется
|
||||||
|
* <code>DEFAULT_TO_ARRAY_ON_CLASS</code>. По умолчанию, null.
|
||||||
|
*
|
||||||
|
* @return array Массив свойств типа.
|
||||||
|
* @throws TypeException Исключение, если объект не является классом.
|
||||||
|
*/
|
||||||
|
public static function ToArray (object $class, ?callable $onClass = null): array
|
||||||
|
{
|
||||||
|
// Проверяю, что метод обработки классов не null и если null, то присваиваю дефолтный метод
|
||||||
|
$onClass ??= self::DEFAULT_TO_ARRAY_ON_CLASS();
|
||||||
|
|
||||||
|
// Создаю массив результата
|
||||||
|
$result = [];
|
||||||
|
|
||||||
|
// Сперва проверяю, что объект является классом
|
||||||
|
if (!is_object($class))
|
||||||
|
// - если нет, то выбрасываю исключение
|
||||||
|
throw new TypeException($class::class, "Object is not class / Объект не является классом.");
|
||||||
|
|
||||||
|
// Затем записываю имя класса
|
||||||
|
$result["type_class"] = $class::class;
|
||||||
|
|
||||||
|
// Получаю свойства класса
|
||||||
|
$properties = get_object_vars($class);
|
||||||
|
|
||||||
|
// Для каждого свойства класса
|
||||||
|
foreach ($properties as $key => $value) {
|
||||||
|
// - если значение является датой
|
||||||
|
if ($value instanceof DateTimeInterface) {
|
||||||
|
|
||||||
|
// -- добавляю в массив
|
||||||
|
$result[$key] = $value->getTimestamp();
|
||||||
|
|
||||||
|
// -- следующий элемент
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// - если значение является перечислением
|
||||||
|
if ($value instanceof UnitEnum) {
|
||||||
|
// -- получаю перечисление
|
||||||
|
$result[$key] = $value->name;
|
||||||
|
|
||||||
|
// -- следующий элемент
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// - если значение является NULL
|
||||||
|
if (is_null($value)) {
|
||||||
|
// -- присваиваю NULL
|
||||||
|
$result[$key] = "null";
|
||||||
|
// -- следующий элемент
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// - если значение является классом
|
||||||
|
if (is_object($value)) {
|
||||||
|
// -- добавляю в массив через рекурсию
|
||||||
|
$result[$key] = $onClass($value);
|
||||||
|
|
||||||
|
// -- следующий элемент
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// - присваиваю значение
|
||||||
|
$result[$key] = $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Возвращаю результат
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Дефолтный метод обработки классов для FromArray.
|
||||||
|
*
|
||||||
|
* @return Closure Метод обработки классов для FromArray.
|
||||||
|
*/
|
||||||
|
public static function DEFAULT_FROM_ARRAY_ON_CLASS (): Closure
|
||||||
|
{
|
||||||
|
return fn (array $classArray): object => self::FromArray($classArray);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Переводит массив в объект.
|
||||||
|
*
|
||||||
|
* @param array $array Массив свойств.
|
||||||
|
* @param callable|null $onClass Метод обработки классов. Если передаётся null, то используется
|
||||||
|
* <code>DEFAULT_FROM_ARRAY_ON_CLASS</code>. По умолчанию, null.
|
||||||
|
*
|
||||||
|
* @return mixed Восстановленный объект.
|
||||||
|
* @throws TypeException Исключение, если массив не создан через ToArray, объект не создан, дата не корректного
|
||||||
|
* формата или пытается передать null не nullable типу.
|
||||||
|
*/
|
||||||
|
public static function FromArray (array $array, ?callable $onClass = null): object
|
||||||
|
{
|
||||||
|
// Проверяю, что массив является массивом, созданным через ToArray, то есть содержит ключ type_class
|
||||||
|
if (!array_key_exists("type_class", $array))
|
||||||
|
// - если нет, то выбрасываю исключение
|
||||||
|
throw new TypeException("array", "Array is not created by ToArray / Массив не создан через ToArray.");
|
||||||
|
|
||||||
|
// Получаю имя класса
|
||||||
|
$className = $array["type_class"];
|
||||||
|
|
||||||
|
// Создаем объект
|
||||||
|
$instance = new $className();
|
||||||
|
|
||||||
|
// Проверяем, что объект создан
|
||||||
|
if (!is_object($instance) && $instance instanceof $className)
|
||||||
|
// - если нет, то выбрасываю исключение
|
||||||
|
throw new TypeException($className, "Object is not created / Объект не создан.");
|
||||||
|
|
||||||
|
// Получаю свойства класса
|
||||||
|
$properties = get_object_vars($instance);
|
||||||
|
|
||||||
|
// Для каждого свойства класса
|
||||||
|
foreach ($properties as $key => $value) {
|
||||||
|
// - проверяю, есть ли свойство в массиве
|
||||||
|
if (!array_key_exists($key, $array))
|
||||||
|
// -- если нет, то пропускаю
|
||||||
|
continue;
|
||||||
|
|
||||||
|
// - получаю значение из массива
|
||||||
|
$value = $array[$key];
|
||||||
|
|
||||||
|
// - если значение является датой DateTime
|
||||||
|
if ($instance->$key instanceof DateTime && is_int($value)) {
|
||||||
|
// -- присваиваю значение
|
||||||
|
try {
|
||||||
|
$instance->$key = new DateTime ('@' . $value);
|
||||||
|
}
|
||||||
|
catch (DateMalformedStringException) {
|
||||||
|
throw new TypeException($className . "->{$key}::DateTime",
|
||||||
|
"Date is not correct format / Дата не корректного формата.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// -- следующий элемент
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// - если значение является датой DateTimeImmutable
|
||||||
|
if ($instance->$key instanceof DateTimeImmutable && is_int($value)) {
|
||||||
|
// -- присваиваю значение
|
||||||
|
try {
|
||||||
|
$instance->$key = new DateTimeImmutable('@' . $value);
|
||||||
|
}
|
||||||
|
catch (DateMalformedStringException) {
|
||||||
|
throw new TypeException($className . "->{$key}::DateTimeImmutable",
|
||||||
|
"Date is not correct format / Дата не корректного формата.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// -- следующий элемент
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// - если значение является перечислением
|
||||||
|
if ($instance->$key instanceof UnitEnum) {
|
||||||
|
// -- получаю все значения перечисления
|
||||||
|
foreach ($instance->$key::getCases() as $case)
|
||||||
|
// --- если значение совпадает
|
||||||
|
if ($case->name === $value)
|
||||||
|
// ---- присваиваю значение
|
||||||
|
$instance->$key = $case;
|
||||||
|
|
||||||
|
// -- следующий элемент
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// - если значение является NULL
|
||||||
|
if (is_string($value) && $value == "null") {
|
||||||
|
// -- присваиваю NULL
|
||||||
|
try {
|
||||||
|
$instance->$key = null;
|
||||||
|
}
|
||||||
|
catch (Exception $exception) {
|
||||||
|
throw new TypeException($className . "->$key",
|
||||||
|
"Cannot assign null to non-nullable property. / Невозможно присвоить null не nullable типу: {$exception->getMessage()}.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// -- следующий элемент
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// - если значение является классом
|
||||||
|
if (is_object($instance->$key) && is_array($array[$key]) && array_key_exists("type_class", $array[$key])) {
|
||||||
|
// -- добавляю в массив через рекурсию
|
||||||
|
$instance->$key = $onClass($array[$key]);
|
||||||
|
|
||||||
|
// -- следующий элемент
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// - присваиваю значение
|
||||||
|
$instance->$key = $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Возвращаю объект
|
||||||
|
return $instance;
|
||||||
|
}
|
||||||
|
}
|
@@ -6,14 +6,14 @@ use goodboyalex\php_components_pack\enums\MessageType;
|
|||||||
use goodboyalex\php_components_pack\interfaces\ISerializable;
|
use goodboyalex\php_components_pack\interfaces\ISerializable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Класс сообщения состояния.
|
* Модель сообщения о состоянии.
|
||||||
*
|
*
|
||||||
* @author Александр Бабаев
|
* @author Александр Бабаев
|
||||||
* @package php_components_pack
|
* @package php_components_pack
|
||||||
* @version 1.0
|
* @version 1.1
|
||||||
* @since 1.0
|
* @since 1.0
|
||||||
*/
|
*/
|
||||||
final class ActionStateMessageModel implements ISerializable
|
final class ActionStateMessage implements ISerializable
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* @var MessageType $MessageType Тип сообщения
|
* @var MessageType $MessageType Тип сообщения
|
52
sources/models/ObjectArraySerializeOptions.php
Normal file
52
sources/models/ObjectArraySerializeOptions.php
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace goodboyalex\php_components_pack\models;
|
||||||
|
|
||||||
|
use Closure;
|
||||||
|
use goodboyalex\php_components_pack\enums\ObjectArraySerializeMethod;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Модель настроек сериализации для класса ObjectArray.
|
||||||
|
*
|
||||||
|
* @author Александр Бабаев
|
||||||
|
* @package php_components_pack
|
||||||
|
* @version 1.0
|
||||||
|
* @since 1.1.1
|
||||||
|
*/
|
||||||
|
final class ObjectArraySerializeOptions
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var ObjectArraySerializeMethod $SerializeMethod Метод сериализации/десериализации.
|
||||||
|
*/
|
||||||
|
public ObjectArraySerializeMethod $SerializeMethod;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var Closure|null $OnClassTo Функция обратного вызова для сериализации объекта методом JsonEncodeWithToArray.
|
||||||
|
* Она передается в качестве параметра в функцию ToArray и служит для правильного преобразования типа в массив.
|
||||||
|
*/
|
||||||
|
public ?Closure $OnClassTo;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var Closure|null $OnClassFrom Функция обратного вызова для десериализации объекта методом
|
||||||
|
* JsonEncodeWithToArray. Она передается в качестве параметра в функцию FromArray и служит для правильного
|
||||||
|
* преобразования массива в тип.
|
||||||
|
*/
|
||||||
|
public ?Closure $OnClassFrom;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Конструктор.
|
||||||
|
*
|
||||||
|
* @param ObjectArraySerializeMethod $serializeMethod Метод сериализации/десериализации.
|
||||||
|
* @param callable|null $onClassTo Функция обратного вызова для сериализации объекта методом JsonEncodeWithToArray
|
||||||
|
* (для ToArray).
|
||||||
|
* @param callable|null $onClassFrom Функция обратного вызова для десериализации объекта методом
|
||||||
|
* JsonEncodeWithToArray (для FromArray).
|
||||||
|
*/
|
||||||
|
public function __construct (ObjectArraySerializeMethod $serializeMethod = ObjectArraySerializeMethod::Serialize,
|
||||||
|
?callable $onClassTo = null, ?callable $onClassFrom = null)
|
||||||
|
{
|
||||||
|
$this->SerializeMethod = $serializeMethod;
|
||||||
|
$this->OnClassTo = $onClassTo;
|
||||||
|
$this->OnClassFrom = $onClassFrom;
|
||||||
|
}
|
||||||
|
}
|
@@ -5,7 +5,7 @@ namespace goodboyalex\php_components_pack\traits\ActionState;
|
|||||||
use goodboyalex\php_components_pack\classes\ActionState;
|
use goodboyalex\php_components_pack\classes\ActionState;
|
||||||
use goodboyalex\php_components_pack\classes\ObjectArray;
|
use goodboyalex\php_components_pack\classes\ObjectArray;
|
||||||
use goodboyalex\php_components_pack\enums\MessageType;
|
use goodboyalex\php_components_pack\enums\MessageType;
|
||||||
use goodboyalex\php_components_pack\models\ActionStateMessageModel;
|
use goodboyalex\php_components_pack\models\ActionStateMessage;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Часть кода класса ActionState, отвечающая за методы добавления сообщений.
|
* Часть кода класса ActionState, отвечающая за методы добавления сообщений.
|
||||||
@@ -30,7 +30,7 @@ trait ActionStateAddTrait
|
|||||||
// Если нужно очистить список сообщений
|
// Если нужно очистить список сообщений
|
||||||
if ($clearAllBefore)
|
if ($clearAllBefore)
|
||||||
// - то очищаю список сообщений
|
// - то очищаю список сообщений
|
||||||
$this->Clear(fn (ActionStateMessageModel $message) => true);
|
$this->Clear(fn (ActionStateMessage $message) => true);
|
||||||
|
|
||||||
// Добавляю сообщения из другого состояния
|
// Добавляю сообщения из другого состояния
|
||||||
$this->AddRange($state->GetMessages(ActionState::GET_STRING_ALL()));
|
$this->AddRange($state->GetMessages(ActionState::GET_STRING_ALL()));
|
||||||
@@ -61,17 +61,17 @@ trait ActionStateAddTrait
|
|||||||
*/
|
*/
|
||||||
public function AddCritical (string $message): void
|
public function AddCritical (string $message): void
|
||||||
{
|
{
|
||||||
$this->Add(new ActionStateMessageModel(MessageType::Error, true, $message));
|
$this->Add(new ActionStateMessage(MessageType::Error, true, $message));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Добавление сообщения.
|
* Добавление сообщения.
|
||||||
*
|
*
|
||||||
* @param ActionStateMessageModel $message Сообщение
|
* @param ActionStateMessage $message Сообщение
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function Add (ActionStateMessageModel $message): void
|
public function Add (ActionStateMessage $message): void
|
||||||
{
|
{
|
||||||
$this->Messages->Add($message);
|
$this->Messages->Add($message);
|
||||||
}
|
}
|
||||||
@@ -85,7 +85,7 @@ trait ActionStateAddTrait
|
|||||||
*/
|
*/
|
||||||
public function AddError (string $message): void
|
public function AddError (string $message): void
|
||||||
{
|
{
|
||||||
$this->Add(new ActionStateMessageModel(MessageType::Error, false, $message));
|
$this->Add(new ActionStateMessage(MessageType::Error, false, $message));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -97,7 +97,7 @@ trait ActionStateAddTrait
|
|||||||
*/
|
*/
|
||||||
public function AddWarning (string $message): void
|
public function AddWarning (string $message): void
|
||||||
{
|
{
|
||||||
$this->Add(new ActionStateMessageModel(MessageType::Warning, false, $message));
|
$this->Add(new ActionStateMessage(MessageType::Warning, false, $message));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -109,6 +109,6 @@ trait ActionStateAddTrait
|
|||||||
*/
|
*/
|
||||||
public function AddInfo (string $message): void
|
public function AddInfo (string $message): void
|
||||||
{
|
{
|
||||||
$this->Add(new ActionStateMessageModel(MessageType::Info, false, $message));
|
$this->Add(new ActionStateMessage(MessageType::Info, false, $message));
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -3,7 +3,7 @@
|
|||||||
namespace goodboyalex\php_components_pack\traits\ActionState;
|
namespace goodboyalex\php_components_pack\traits\ActionState;
|
||||||
|
|
||||||
use goodboyalex\php_components_pack\enums\MessageType;
|
use goodboyalex\php_components_pack\enums\MessageType;
|
||||||
use goodboyalex\php_components_pack\models\ActionStateMessageModel;
|
use goodboyalex\php_components_pack\models\ActionStateMessage;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Часть кода класса ActionState, отвечающая за методы проверки на наличие сообщений.
|
* Часть кода класса ActionState, отвечающая за методы проверки на наличие сообщений.
|
||||||
@@ -22,7 +22,7 @@ trait ActionStateHasTrait
|
|||||||
*/
|
*/
|
||||||
public function HasInfos (): bool
|
public function HasInfos (): bool
|
||||||
{
|
{
|
||||||
return $this->Messages->IsExist(fn (ActionStateMessageModel $message)
|
return $this->Messages->IsExist(fn (ActionStateMessage $message)
|
||||||
=> $message->MessageType
|
=> $message->MessageType
|
||||||
== MessageType::Info);
|
== MessageType::Info);
|
||||||
}
|
}
|
||||||
@@ -48,7 +48,7 @@ trait ActionStateHasTrait
|
|||||||
*/
|
*/
|
||||||
public function HasErrors (bool $onlyCritical = false): bool
|
public function HasErrors (bool $onlyCritical = false): bool
|
||||||
{
|
{
|
||||||
return $this->Messages->IsExist(fn (ActionStateMessageModel $message): bool
|
return $this->Messages->IsExist(fn (ActionStateMessage $message): bool
|
||||||
=> $onlyCritical
|
=> $onlyCritical
|
||||||
? $message->MessageType == MessageType::Error && $message->IsCritical
|
? $message->MessageType == MessageType::Error && $message->IsCritical
|
||||||
: $message->MessageType == MessageType::Error);
|
: $message->MessageType == MessageType::Error);
|
||||||
@@ -61,7 +61,7 @@ trait ActionStateHasTrait
|
|||||||
*/
|
*/
|
||||||
public function HasWarnings (): bool
|
public function HasWarnings (): bool
|
||||||
{
|
{
|
||||||
return $this->Messages->IsExist(fn (ActionStateMessageModel $message)
|
return $this->Messages->IsExist(fn (ActionStateMessage $message)
|
||||||
=> $message->MessageType
|
=> $message->MessageType
|
||||||
== MessageType::Warning);
|
== MessageType::Warning);
|
||||||
}
|
}
|
||||||
|
@@ -4,7 +4,7 @@ namespace goodboyalex\php_components_pack\traits\ActionState;
|
|||||||
|
|
||||||
use Closure;
|
use Closure;
|
||||||
use goodboyalex\php_components_pack\enums\MessageType;
|
use goodboyalex\php_components_pack\enums\MessageType;
|
||||||
use goodboyalex\php_components_pack\models\ActionStateMessageModel;
|
use goodboyalex\php_components_pack\models\ActionStateMessage;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Часть кода класса ActionState, отвечающая за статичные методы и константы.
|
* Часть кода класса ActionState, отвечающая за статичные методы и константы.
|
||||||
@@ -23,7 +23,7 @@ trait ActionStateStaticTrait
|
|||||||
*/
|
*/
|
||||||
public static function GET_STRING_ERROR_ONLY (): Closure
|
public static function GET_STRING_ERROR_ONLY (): Closure
|
||||||
{
|
{
|
||||||
return fn (ActionStateMessageModel $message)
|
return fn (ActionStateMessage $message)
|
||||||
=> $message->MessageType === MessageType::Error;
|
=> $message->MessageType === MessageType::Error;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,7 +34,7 @@ trait ActionStateStaticTrait
|
|||||||
*/
|
*/
|
||||||
public static function GET_STRING_ERROR_AND_WARNING (): Closure
|
public static function GET_STRING_ERROR_AND_WARNING (): Closure
|
||||||
{
|
{
|
||||||
return fn (ActionStateMessageModel $message)
|
return fn (ActionStateMessage $message)
|
||||||
=> $message->MessageType === MessageType::Error
|
=> $message->MessageType === MessageType::Error
|
||||||
|| $message->MessageType === MessageType::Warning;
|
|| $message->MessageType === MessageType::Warning;
|
||||||
}
|
}
|
||||||
@@ -46,6 +46,6 @@ trait ActionStateStaticTrait
|
|||||||
*/
|
*/
|
||||||
public static function GET_STRING_ALL (): Closure
|
public static function GET_STRING_ALL (): Closure
|
||||||
{
|
{
|
||||||
return fn (ActionStateMessageModel $message) => true;
|
return fn (ActionStateMessage $message) => true;
|
||||||
}
|
}
|
||||||
}
|
}
|
176
sources/traits/ObjectArray/ObjectArraySerializeExTrait.php
Normal file
176
sources/traits/ObjectArray/ObjectArraySerializeExTrait.php
Normal file
@@ -0,0 +1,176 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace goodboyalex\php_components_pack\traits\ObjectArray;
|
||||||
|
|
||||||
|
use goodboyalex\php_components_pack\classes\ObjectArray;
|
||||||
|
use goodboyalex\php_components_pack\enums\ObjectArraySerializeMethod;
|
||||||
|
use goodboyalex\php_components_pack\exceptions\TypeException;
|
||||||
|
use goodboyalex\php_components_pack\extensions\TypeExtension;
|
||||||
|
use goodboyalex\php_components_pack\models\ObjectArraySerializeOptions;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Часть кода класса ObjectArray, отвечающая за расширенный функции сериализации.
|
||||||
|
*
|
||||||
|
* @author Александр Бабаев
|
||||||
|
* @package php_components_pack
|
||||||
|
* @version 1.0
|
||||||
|
* @since 1.1.1
|
||||||
|
*/
|
||||||
|
trait ObjectArraySerializeExTrait
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Десериализует массив объектов.
|
||||||
|
*
|
||||||
|
* @param string $serialized Сериализованный массив.
|
||||||
|
* @param ObjectArraySerializeOptions|null $options Настройки сериализации. По умолчанию используется настройка по
|
||||||
|
* умолчанию.
|
||||||
|
*
|
||||||
|
* @return ObjectArray Массив объектов.
|
||||||
|
*/
|
||||||
|
public static function UnSerializeEx (string $serialized, ?ObjectArraySerializeOptions $options = null): ObjectArray
|
||||||
|
{
|
||||||
|
// По умолчанию используем настройки по умолчанию
|
||||||
|
$options ??= new ObjectArraySerializeOptions();
|
||||||
|
|
||||||
|
// Десериализуем массив объектов
|
||||||
|
return match ($options->SerializeMethod) {
|
||||||
|
// - стандартный метод UnSerialize
|
||||||
|
ObjectArraySerializeMethod::Serialize => self::UnSerializeBySerialize($serialized),
|
||||||
|
// - метод JsonEncode
|
||||||
|
ObjectArraySerializeMethod::JsonEncode => self::UnSerializeByJsonEncode($serialized),
|
||||||
|
// - метод JsonEncodeWithToArray
|
||||||
|
ObjectArraySerializeMethod::JsonEncodeWithToArray => self::UnSerializeByJsonEncodeWithToArray($serialized,
|
||||||
|
$options->OnClassFrom)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Десериализует массив объектов с помощью стандартного метода UnSerialize.
|
||||||
|
*
|
||||||
|
* @param string $serialized Сериализованный массив.
|
||||||
|
*
|
||||||
|
* @return ObjectArray Массив объектов.
|
||||||
|
*/
|
||||||
|
private static function UnSerializeBySerialize (string $serialized): ObjectArray
|
||||||
|
{
|
||||||
|
// Создаем новый объект
|
||||||
|
$result = new ObjectArray();
|
||||||
|
|
||||||
|
// Десериализуем массив объектов с помощью стандартного метода
|
||||||
|
$result->UnSerialize($serialized);
|
||||||
|
|
||||||
|
// Возвращаем результат
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Десериализует массив объектов с помощью метода JsonEncode.
|
||||||
|
*
|
||||||
|
* @param string $serialized Сериализованный массив.
|
||||||
|
*
|
||||||
|
* @return ObjectArray Массив объектов.
|
||||||
|
*/
|
||||||
|
private static function UnSerializeByJsonEncode (string $serialized): ObjectArray
|
||||||
|
{
|
||||||
|
// Десериализуем массив
|
||||||
|
$container = json_decode($serialized, false, flags: JSON_UNESCAPED_UNICODE);
|
||||||
|
|
||||||
|
// Создаем новый объект
|
||||||
|
return new ObjectArray($container);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Десериализует массив объектов с помощью метода JsonEncodeWithToArray.
|
||||||
|
*
|
||||||
|
* @param string $serialized Сериализованный массив.
|
||||||
|
* @param callable|null $onClass Функция обратного вызова для десериализации объекта методом JsonEncodeWithToArray.
|
||||||
|
* Она передается в качестве параметра в функцию FromArray и служит для правильного преобразования массива в
|
||||||
|
* тип.
|
||||||
|
*
|
||||||
|
* @return ObjectArray Массив объектов.
|
||||||
|
*/
|
||||||
|
private static function UnSerializeByJsonEncodeWithToArray (string $serialized, ?callable $onClass): ObjectArray
|
||||||
|
{
|
||||||
|
// Десериализуем массив
|
||||||
|
$container = json_decode($serialized, true, flags: JSON_UNESCAPED_UNICODE);
|
||||||
|
|
||||||
|
// Создаем новый объект, в который будем помещать объекты
|
||||||
|
$result = new ObjectArray();
|
||||||
|
|
||||||
|
// Переберем все объекты в контейнере
|
||||||
|
foreach ($container as $item)
|
||||||
|
try {
|
||||||
|
// - пробуем преобразовать массив в объект, если это возможно
|
||||||
|
$result[] = TypeExtension::FromArray($item, $onClass);
|
||||||
|
}
|
||||||
|
catch (TypeException) {
|
||||||
|
// - если не получилось, то просто добавляем объект в массив
|
||||||
|
$result[] = $item;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Возвращаем результат
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Сериализует массив объектов.
|
||||||
|
*
|
||||||
|
* @param ObjectArraySerializeOptions|null $options Настройки сериализации. По умолчанию используется настройка по
|
||||||
|
* умолчанию.
|
||||||
|
*
|
||||||
|
* @return string Сериализованный массив.
|
||||||
|
*/
|
||||||
|
public function SerializeEx (?ObjectArraySerializeOptions $options = null): string
|
||||||
|
{
|
||||||
|
// По умолчанию используем настройки по умолчанию
|
||||||
|
$options ??= new ObjectArraySerializeOptions();
|
||||||
|
|
||||||
|
// Сериализуем массив
|
||||||
|
return match ($options->SerializeMethod) {
|
||||||
|
// - стандартный метод Serialize
|
||||||
|
ObjectArraySerializeMethod::Serialize => $this->Serialize(),
|
||||||
|
// - метод JsonEncode
|
||||||
|
ObjectArraySerializeMethod::JsonEncode => $this->SerializeByJsonEncode(),
|
||||||
|
// - метод JsonEncodeWithToArray
|
||||||
|
ObjectArraySerializeMethod::JsonEncodeWithToArray => $this->SerializeByJsonEncodeWithToArray($options->OnClassTo)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Сериализует массив методом JsonEncode.
|
||||||
|
*
|
||||||
|
* @return string Сериализованный массив.
|
||||||
|
*/
|
||||||
|
private function SerializeByJsonEncode (): string
|
||||||
|
{
|
||||||
|
return json_encode($this->Container, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Сериализует массив методом JsonEncodeWithToArray.
|
||||||
|
*
|
||||||
|
* @param callable|null $onClass Функция обратного вызова для сериализации объекта методом JsonEncodeWithToArray.
|
||||||
|
* Она передается в качестве параметра в функцию ToArray и служит для правильного преобразования типа в массив.
|
||||||
|
*
|
||||||
|
* @return string Сериализованный массив.
|
||||||
|
*/
|
||||||
|
private function SerializeByJsonEncodeWithToArray (?callable $onClass): string
|
||||||
|
{
|
||||||
|
// Создадим массив, в который будем помещать объекты
|
||||||
|
$container = [];
|
||||||
|
|
||||||
|
// Переберем все объекты в контейнере
|
||||||
|
foreach ($this->Container as $item)
|
||||||
|
try {
|
||||||
|
// - пробуем преобразовать объект в массив, если это возможно
|
||||||
|
$container[] = TypeExtension::ToArray($item, $onClass);
|
||||||
|
}
|
||||||
|
catch (TypeException) {
|
||||||
|
// - если не получилось, то просто добавляем объект в массив
|
||||||
|
$container[] = $item;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Возвращаем сериализованный массив
|
||||||
|
return json_encode($container, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
|
||||||
|
}
|
||||||
|
}
|
@@ -4,7 +4,7 @@ namespace goodboyalex\php_components_pack\tests\classes;
|
|||||||
|
|
||||||
use goodboyalex\php_components_pack\classes\ActionState;
|
use goodboyalex\php_components_pack\classes\ActionState;
|
||||||
use goodboyalex\php_components_pack\enums\MessageType;
|
use goodboyalex\php_components_pack\enums\MessageType;
|
||||||
use goodboyalex\php_components_pack\models\ActionStateMessageModel;
|
use goodboyalex\php_components_pack\models\ActionStateMessage;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
class ActionStateTest extends TestCase
|
class ActionStateTest extends TestCase
|
||||||
@@ -29,7 +29,7 @@ class ActionStateTest extends TestCase
|
|||||||
$this->assertEquals(2, $messages->Count());
|
$this->assertEquals(2, $messages->Count());
|
||||||
|
|
||||||
$this->assertEquals("Non critical error",
|
$this->assertEquals("Non critical error",
|
||||||
$actionState->GetStringMessages(fn (ActionStateMessageModel $message)
|
$actionState->GetStringMessages(fn (ActionStateMessage $message)
|
||||||
=> $message->MessageType
|
=> $message->MessageType
|
||||||
== MessageType::Error
|
== MessageType::Error
|
||||||
&& !$message->IsCritical));
|
&& !$message->IsCritical));
|
||||||
@@ -51,4 +51,4 @@ class ActionStateTest extends TestCase
|
|||||||
require_once __DIR__ . '/../../sources/traits/ActionState/ActionStateStaticTrait.php';
|
require_once __DIR__ . '/../../sources/traits/ActionState/ActionStateStaticTrait.php';
|
||||||
require_once __DIR__ . '/../../sources/enums/MessageType.php';
|
require_once __DIR__ . '/../../sources/enums/MessageType.php';
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -3,7 +3,7 @@
|
|||||||
namespace goodboyalex\php_components_pack\tests\classes;
|
namespace goodboyalex\php_components_pack\tests\classes;
|
||||||
|
|
||||||
use goodboyalex\php_components_pack\classes\File;
|
use goodboyalex\php_components_pack\classes\File;
|
||||||
use goodboyalex\php_components_pack\classes\JsonReWriter;
|
use goodboyalex\php_components_pack\classes\BoolEx;
|
||||||
use goodboyalex\php_components_pack\exceptions\JsonException;
|
use goodboyalex\php_components_pack\exceptions\JsonException;
|
||||||
use goodboyalex\php_components_pack\tests\data\A;
|
use goodboyalex\php_components_pack\tests\data\A;
|
||||||
use goodboyalex\php_components_pack\tests\data\C;
|
use goodboyalex\php_components_pack\tests\data\C;
|
||||||
@@ -15,7 +15,7 @@ class JsonReWriterTest extends TestCase
|
|||||||
{
|
{
|
||||||
$this->PrepareForTest();
|
$this->PrepareForTest();
|
||||||
|
|
||||||
$json = new JsonReWriter();
|
$json = new BoolEx();
|
||||||
try {
|
try {
|
||||||
$json->Write("test/subtest/AAA", "123");
|
$json->Write("test/subtest/AAA", "123");
|
||||||
}
|
}
|
||||||
@@ -43,7 +43,7 @@ class JsonReWriterTest extends TestCase
|
|||||||
{
|
{
|
||||||
$this->PrepareForTest();
|
$this->PrepareForTest();
|
||||||
|
|
||||||
$json = new JsonReWriter();
|
$json = new BoolEx();
|
||||||
try {
|
try {
|
||||||
$json->Write("test/test", 123);
|
$json->Write("test/test", 123);
|
||||||
}
|
}
|
||||||
@@ -58,7 +58,7 @@ class JsonReWriterTest extends TestCase
|
|||||||
{
|
{
|
||||||
$this->PrepareForTest();
|
$this->PrepareForTest();
|
||||||
|
|
||||||
$json = new JsonReWriter();
|
$json = new BoolEx();
|
||||||
try {
|
try {
|
||||||
$json->Write("test/test1", false);
|
$json->Write("test/test1", false);
|
||||||
$json->Write("test/test2", true);
|
$json->Write("test/test2", true);
|
||||||
@@ -75,7 +75,7 @@ class JsonReWriterTest extends TestCase
|
|||||||
{
|
{
|
||||||
$this->PrepareForTest();
|
$this->PrepareForTest();
|
||||||
|
|
||||||
$json = new JsonReWriter();
|
$json = new BoolEx();
|
||||||
try {
|
try {
|
||||||
$json->Write("test/test", "test string");
|
$json->Write("test/test", "test string");
|
||||||
}
|
}
|
||||||
@@ -95,7 +95,7 @@ class JsonReWriterTest extends TestCase
|
|||||||
if (file_exists($fileName))
|
if (file_exists($fileName))
|
||||||
unlink($fileName);
|
unlink($fileName);
|
||||||
|
|
||||||
$json = new JsonReWriter();
|
$json = new BoolEx();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$json->Write("test/subtest/AAA", "123");
|
$json->Write("test/subtest/AAA", "123");
|
||||||
@@ -123,7 +123,7 @@ class JsonReWriterTest extends TestCase
|
|||||||
{
|
{
|
||||||
$this->PrepareForTest();
|
$this->PrepareForTest();
|
||||||
|
|
||||||
$json = new JsonReWriter();
|
$json = new BoolEx();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$json->Write("test/subtest/AAA", "123");
|
$json->Write("test/subtest/AAA", "123");
|
||||||
@@ -143,7 +143,7 @@ class JsonReWriterTest extends TestCase
|
|||||||
{
|
{
|
||||||
$this->PrepareForTest();
|
$this->PrepareForTest();
|
||||||
|
|
||||||
$json = new JsonReWriter();
|
$json = new BoolEx();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$json->Write("test/subtest/AAA", "123");
|
$json->Write("test/subtest/AAA", "123");
|
||||||
@@ -165,7 +165,7 @@ class JsonReWriterTest extends TestCase
|
|||||||
{
|
{
|
||||||
$this->PrepareForTest();
|
$this->PrepareForTest();
|
||||||
|
|
||||||
$json = new JsonReWriter();
|
$json = new BoolEx();
|
||||||
|
|
||||||
$class = new A("test", 123, true);
|
$class = new A("test", 123, true);
|
||||||
|
|
||||||
@@ -188,7 +188,7 @@ class JsonReWriterTest extends TestCase
|
|||||||
if (file_exists($fileName))
|
if (file_exists($fileName))
|
||||||
unlink($fileName);
|
unlink($fileName);
|
||||||
|
|
||||||
$json = new JsonReWriter();
|
$json = new BoolEx();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$json->Write("test/subtest/AAA", "123");
|
$json->Write("test/subtest/AAA", "123");
|
||||||
@@ -205,7 +205,7 @@ class JsonReWriterTest extends TestCase
|
|||||||
|
|
||||||
unset($json);
|
unset($json);
|
||||||
|
|
||||||
$json = new JsonReWriter();
|
$json = new BoolEx();
|
||||||
|
|
||||||
$json->LoadFromFile($fileName);
|
$json->LoadFromFile($fileName);
|
||||||
|
|
||||||
@@ -218,7 +218,7 @@ class JsonReWriterTest extends TestCase
|
|||||||
{
|
{
|
||||||
$this->PrepareForTest();
|
$this->PrepareForTest();
|
||||||
|
|
||||||
$json = new JsonReWriter();
|
$json = new BoolEx();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$json->Write("test/subtest/AAA", "123");
|
$json->Write("test/subtest/AAA", "123");
|
||||||
@@ -240,7 +240,7 @@ class JsonReWriterTest extends TestCase
|
|||||||
{
|
{
|
||||||
$this->PrepareForTest();
|
$this->PrepareForTest();
|
||||||
|
|
||||||
$json = new JsonReWriter();
|
$json = new BoolEx();
|
||||||
try {
|
try {
|
||||||
$json->Write("test/subtest/AAA", "123");
|
$json->Write("test/subtest/AAA", "123");
|
||||||
$json->Write("test/subtest/BBB", 1.23);
|
$json->Write("test/subtest/BBB", 1.23);
|
||||||
@@ -261,7 +261,7 @@ class JsonReWriterTest extends TestCase
|
|||||||
{
|
{
|
||||||
$this->PrepareForTest();
|
$this->PrepareForTest();
|
||||||
|
|
||||||
$json = new JsonReWriter();
|
$json = new BoolEx();
|
||||||
try {
|
try {
|
||||||
$json->Write("test/subtest/AAA", "123");
|
$json->Write("test/subtest/AAA", "123");
|
||||||
$json->Write("test/subtest/BBB", 1.23);
|
$json->Write("test/subtest/BBB", 1.23);
|
||||||
@@ -283,7 +283,7 @@ class JsonReWriterTest extends TestCase
|
|||||||
|
|
||||||
$serializableClass = new C("test", 123, true);
|
$serializableClass = new C("test", 123, true);
|
||||||
|
|
||||||
$json = new JsonReWriter();
|
$json = new BoolEx();
|
||||||
try {
|
try {
|
||||||
$json->WriteSerializable("test", $serializableClass);
|
$json->WriteSerializable("test", $serializableClass);
|
||||||
|
|
||||||
@@ -306,7 +306,7 @@ class JsonReWriterTest extends TestCase
|
|||||||
{
|
{
|
||||||
$this->PrepareForTest();
|
$this->PrepareForTest();
|
||||||
|
|
||||||
$json = new JsonReWriter();
|
$json = new BoolEx();
|
||||||
try {
|
try {
|
||||||
$json->Write("test", 1.23);
|
$json->Write("test", 1.23);
|
||||||
}
|
}
|
||||||
|
@@ -3,8 +3,14 @@
|
|||||||
namespace goodboyalex\php_components_pack\tests\classes;
|
namespace goodboyalex\php_components_pack\tests\classes;
|
||||||
|
|
||||||
use goodboyalex\php_components_pack\classes\ObjectArray;
|
use goodboyalex\php_components_pack\classes\ObjectArray;
|
||||||
|
use goodboyalex\php_components_pack\enums\ObjectArraySerializeMethod;
|
||||||
|
use goodboyalex\php_components_pack\models\ObjectArraySerializeOptions;
|
||||||
use goodboyalex\php_components_pack\tests\data\A;
|
use goodboyalex\php_components_pack\tests\data\A;
|
||||||
|
use goodboyalex\php_components_pack\tests\data\B;
|
||||||
|
use goodboyalex\php_components_pack\tests\data\C;
|
||||||
|
use goodboyalex\php_components_pack\tests\data\D;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use stdClass;
|
||||||
|
|
||||||
class ObjectArrayTest extends TestCase
|
class ObjectArrayTest extends TestCase
|
||||||
{
|
{
|
||||||
@@ -38,6 +44,8 @@ class ObjectArrayTest extends TestCase
|
|||||||
{
|
{
|
||||||
require_once __DIR__ . '/../data/A.php';
|
require_once __DIR__ . '/../data/A.php';
|
||||||
require_once __DIR__ . '/../data/B.php';
|
require_once __DIR__ . '/../data/B.php';
|
||||||
|
require_once __DIR__ . '/../data/C.php';
|
||||||
|
require_once __DIR__ . '/../data/D.php';
|
||||||
require_once __DIR__ . '/../../sources/interfaces/ISerializable.php';
|
require_once __DIR__ . '/../../sources/interfaces/ISerializable.php';
|
||||||
require_once __DIR__ . '/../../sources/traits/ArrayBasicTrait.php';
|
require_once __DIR__ . '/../../sources/traits/ArrayBasicTrait.php';
|
||||||
require_once __DIR__ . '/../../sources/traits/ObjectArray/ObjectArrayConstantsTrait.php';
|
require_once __DIR__ . '/../../sources/traits/ObjectArray/ObjectArrayConstantsTrait.php';
|
||||||
@@ -480,4 +488,66 @@ class ObjectArrayTest extends TestCase
|
|||||||
|
|
||||||
$this->assertEquals(12, $a_Array->Count());
|
$this->assertEquals(12, $a_Array->Count());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function testSerializeEx ()
|
||||||
|
{
|
||||||
|
$this->PrepareForTest();
|
||||||
|
|
||||||
|
// Создаём тестовые классы
|
||||||
|
$class1 = new D ('test_string1', 12345, true, new A("test_string_A1", 6789, false),
|
||||||
|
new B("test_string_B1", 9876, "false"), new C("test_string_C1", 54321, true));
|
||||||
|
$class2 = new D ('test_string2', 123456, false, new A("test_string_A1", 678910, true),
|
||||||
|
new B("test_string_B2", 98765, "true"), new C("test_string_C2", 543210, false));
|
||||||
|
$class = new D ('test_string3', 123450, true, new A("test_string_A2", 67890, false),
|
||||||
|
new B("test_string_B3", 90876, "false"), new C("test_string_C3", 543201, true));
|
||||||
|
|
||||||
|
// Создаём массив объектов
|
||||||
|
$objectArray = new ObjectArray([$class1, $class2, $class]);
|
||||||
|
|
||||||
|
// Сериализуем
|
||||||
|
$serialized1 =
|
||||||
|
$objectArray->SerializeEx(new ObjectArraySerializeOptions(ObjectArraySerializeMethod::Serialize));
|
||||||
|
$serialized2 =
|
||||||
|
$objectArray->SerializeEx(new ObjectArraySerializeOptions(ObjectArraySerializeMethod::JsonEncode));
|
||||||
|
$serialized3 =
|
||||||
|
$objectArray->SerializeEx(new ObjectArraySerializeOptions(ObjectArraySerializeMethod::JsonEncodeWithToArray,
|
||||||
|
D::CLOSURE_TO_ARRAY()));
|
||||||
|
|
||||||
|
// Сохраняем в файл
|
||||||
|
file_put_contents(__DIR__ . 'serialized1.txt', $serialized1);
|
||||||
|
file_put_contents(__DIR__ . 'serialized2.txt', $serialized2);
|
||||||
|
file_put_contents(__DIR__ . 'serialized3.txt', $serialized3);
|
||||||
|
|
||||||
|
// Проверяем, что всё хорошо
|
||||||
|
$this->assertNotEmpty($serialized1);
|
||||||
|
$this->assertNotEmpty($serialized2);
|
||||||
|
$this->assertNotEmpty($serialized3);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testUnSerializeEx ()
|
||||||
|
{
|
||||||
|
$this->PrepareForTest();
|
||||||
|
|
||||||
|
// Загружаем данные
|
||||||
|
$serialized1 = file_get_contents(__DIR__ . 'serialized1.txt');
|
||||||
|
$serialized2 = file_get_contents(__DIR__ . 'serialized2.txt');
|
||||||
|
$serialized3 = file_get_contents(__DIR__ . 'serialized3.txt');
|
||||||
|
|
||||||
|
// Десериализуем
|
||||||
|
$objectArray1 = ObjectArray::UnSerializeEx($serialized1,
|
||||||
|
new ObjectArraySerializeOptions(ObjectArraySerializeMethod::Serialize));
|
||||||
|
$objectArray2 = ObjectArray::UnSerializeEx($serialized2,
|
||||||
|
new ObjectArraySerializeOptions(ObjectArraySerializeMethod::JsonEncode));
|
||||||
|
$objectArray3 = ObjectArray::UnSerializeEx($serialized3,
|
||||||
|
new ObjectArraySerializeOptions(ObjectArraySerializeMethod::JsonEncodeWithToArray,
|
||||||
|
onClassFrom: D::CLOSURE_FROM_ARRAY()));
|
||||||
|
|
||||||
|
// Проверяем, что всё хорошо
|
||||||
|
$this->assertEquals('test_string_A1',
|
||||||
|
$objectArray1->GetRow(fn (D $value) => $value->stringD == 'test_string1')->a->a);
|
||||||
|
$this->assertEquals('test_string_B2',
|
||||||
|
$objectArray2->GetRow(fn (stdClass $value) => $value->stringD == 'test_string2')->b->a);
|
||||||
|
$this->assertEquals('test_string_C3',
|
||||||
|
$objectArray3->GetRow(fn (D $value) => $value->stringD == 'test_string3')->c->stringC);
|
||||||
|
}
|
||||||
}
|
}
|
56
tests/data/D.php
Normal file
56
tests/data/D.php
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace goodboyalex\php_components_pack\tests\data;
|
||||||
|
|
||||||
|
use Closure;
|
||||||
|
use goodboyalex\php_components_pack\extensions\TypeExtension;
|
||||||
|
|
||||||
|
class D
|
||||||
|
{
|
||||||
|
public string $stringD;
|
||||||
|
public int $intD;
|
||||||
|
public bool $boolD;
|
||||||
|
public A $a;
|
||||||
|
public B $b;
|
||||||
|
public C $c;
|
||||||
|
|
||||||
|
public function __construct (string $string = "", int $int = 0, bool $bool = false, ?A $a = null, ?B $b = null,
|
||||||
|
?C $c = null)
|
||||||
|
{
|
||||||
|
$this->stringD = $string;
|
||||||
|
$this->intD = $int;
|
||||||
|
$this->boolD = $bool;
|
||||||
|
|
||||||
|
$this->a = $a ?? new A();
|
||||||
|
$this->b = $b ?? new B();
|
||||||
|
$this->c = $c ?? new C();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function CLOSURE_FROM_ARRAY (): Closure
|
||||||
|
{
|
||||||
|
return fn (array $classArray): object
|
||||||
|
=> $classArray['type_class'] == C::class
|
||||||
|
? self::CLOSURE_FROM_FOR_C($classArray["type_value"]) : TypeExtension::FromArray($classArray);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function CLOSURE_FROM_FOR_C (string $serializedC): object
|
||||||
|
{
|
||||||
|
$classC = new C();
|
||||||
|
$classC->UnSerialize($serializedC);
|
||||||
|
return $classC;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function CLOSURE_TO_ARRAY (): Closure
|
||||||
|
{
|
||||||
|
return fn (object $class): array => $class instanceof C ? self::CLOSURE_TO_FOR_C($class)
|
||||||
|
: TypeExtension::ToArray($class);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function CLOSURE_TO_FOR_C (C $class): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
"type_class" => C::class,
|
||||||
|
"type_value" => $class->Serialize()
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
91
tests/extensions/TypeExtensionTest.php
Normal file
91
tests/extensions/TypeExtensionTest.php
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace goodboyalex\php_components_pack\tests\extensions;
|
||||||
|
|
||||||
|
use goodboyalex\php_components_pack\exceptions\TypeException;
|
||||||
|
use goodboyalex\php_components_pack\extensions\TypeExtension;
|
||||||
|
use goodboyalex\php_components_pack\tests\data\A;
|
||||||
|
use goodboyalex\php_components_pack\tests\data\B;
|
||||||
|
use goodboyalex\php_components_pack\tests\data\C;
|
||||||
|
use goodboyalex\php_components_pack\tests\data\D;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
class TypeExtensionTest extends TestCase
|
||||||
|
{
|
||||||
|
public function testFromArray ()
|
||||||
|
{
|
||||||
|
// Подготавливаем данные к тестированию
|
||||||
|
$this->PrepareForTest();
|
||||||
|
|
||||||
|
// Зададим имя файла
|
||||||
|
$fileName = __DIR__ . "/class.txt";
|
||||||
|
|
||||||
|
// Если файл не найден
|
||||||
|
if (!file_exists($fileName))
|
||||||
|
// - то завершаем работу
|
||||||
|
die("The test data file could not be found or has not yet passed the ToArray test! / Файл с данными для тестирования не найден или не пройдено ещё тестирование ToArray!");
|
||||||
|
|
||||||
|
// Считываем данные из файла и преобразуем в массив
|
||||||
|
$array = json_decode(file_get_contents($fileName), true);
|
||||||
|
|
||||||
|
// Преобразуем в объект
|
||||||
|
try {
|
||||||
|
$class = TypeExtension::FromArray($array, D::CLOSURE_FROM_ARRAY());
|
||||||
|
}
|
||||||
|
catch (TypeException $e) {
|
||||||
|
// - если ошибка, то выводим её и завершаем работу
|
||||||
|
die($e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Проверяем
|
||||||
|
$this->assertEquals(D::class, $class::class);
|
||||||
|
$this->assertEquals(A::class, $class->a::class);
|
||||||
|
$this->assertEquals(B::class, $class->b::class);
|
||||||
|
$this->assertEquals(9876, $class->b->b);
|
||||||
|
$this->assertEquals(C::class, $class->c::class);
|
||||||
|
$this->assertEquals(54321, $class->c->intC);
|
||||||
|
$this->assertEquals('test_string', $class->stringD);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function PrepareForTest (): void
|
||||||
|
{
|
||||||
|
require_once __DIR__ . '/../../sources/exceptions/TypeException.php';
|
||||||
|
require_once __DIR__ . '/../../sources/extensions/TypeExtension.php';
|
||||||
|
require_once __DIR__ . '/../data/A.php';
|
||||||
|
require_once __DIR__ . '/../data/B.php';
|
||||||
|
require_once __DIR__ . '/../data/C.php';
|
||||||
|
require_once __DIR__ . '/../data/D.php';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testToArray ()
|
||||||
|
{
|
||||||
|
// Подготавливаем данные к тестированию
|
||||||
|
$this->PrepareForTest();
|
||||||
|
|
||||||
|
// Создаём тестовый класс
|
||||||
|
$class = new D ('test_string', 12345, true, new A("test_string_A", 6789, false),
|
||||||
|
new B("test_string_B", 9876, "false"), new C("test_string_C", 54321, true));
|
||||||
|
|
||||||
|
// Преобразуем в массив
|
||||||
|
try {
|
||||||
|
$array = TypeExtension::ToArray($class, D::CLOSURE_TO_ARRAY());
|
||||||
|
}
|
||||||
|
catch (TypeException $e) {
|
||||||
|
// - если ошибка, то выводим её и завершаем работу
|
||||||
|
die($e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Сохраняем массив в файл (для тестирования FromArray)
|
||||||
|
file_put_contents(__DIR__ . "/class.txt", json_encode($array, JSON_PRETTY_PRINT));
|
||||||
|
|
||||||
|
// Проверяем
|
||||||
|
$this->assertEquals(D::class, $array['type_class']);
|
||||||
|
$this->assertEquals(A::class, $array['a']['type_class']);
|
||||||
|
$this->assertEquals(B::class, $array['b']['type_class']);
|
||||||
|
$this->assertEquals(9876, $array['b']['b']);
|
||||||
|
$this->assertEquals(C::class, $array['c']['type_class']);
|
||||||
|
$this->assertEquals('test_string', $array['stringD']);
|
||||||
|
$this->assertEquals(12345, $array['intD']);
|
||||||
|
$this->assertTrue($array['boolD']);
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user