6 Commits

Author SHA1 Message Date
10ec8df983 20250522
* [Dictionary, ObjectArray] Исправлен баг сериализации. Теперь классы нормально восстанавливаются.
2025-05-22 22:03:39 +03:00
2d16baaef9 20250520
[Dictionary] добавлен метод AddRange (array $dictionary), который добавляет элементы в виде ассоциативного массива ключ => значение в словарь.

[Dictionary] Добавлен метод ToArray (), который возвращает все элементы словаря в виде массива..
2025-05-20 12:42:06 +03:00
2e684cb862 20250519
* [Dictionary, ObjectArray] Исправлен метод сериализации. Теперь классы нормально восстанавливаются.
2025-05-19 07:04:25 +03:00
f98a277986 Merge remote-tracking branch 'Babaev-anGit/main' 2025-05-16 23:35:54 +03:00
5b83b096e5 20250516
* [Dictionary] Добавлен метод Keys (): array, который возвращает все ключи словаря.
* [Dictionary] Добавлен метод Sort (bool $descending = false): void, который сортирует внутренние данные по ключам (в обратном порядке, если выбран $descending = true).
2025-05-16 23:35:48 +03:00
b011d3930c 20250516
* [Dictionary] Добавлен метод Keys (): array, который возвращает все ключи словаря.
* [Dictionary] Добавлен метод Sort (bool $descending = false): void, который сортирует внутренние данные по ключам (в обратном порядке, если выбран $descending = true).
2025-05-16 23:34:24 +03:00
5 changed files with 137 additions and 24 deletions

16
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "8024da85d3650f107ba3254f5dfc3b79",
"content-hash": "62046e22c8307ed8e1f622a0f7bd7a05",
"packages": [],
"packages-dev": [
{
@@ -579,16 +579,16 @@
},
{
"name": "phpunit/phpunit",
"version": "12.1.4",
"version": "12.1.5",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git",
"reference": "5ee57ad690bda2c487594577600931a99053436c"
"reference": "f93ef2198df8d54b3195bcee381a33be51d8705e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/5ee57ad690bda2c487594577600931a99053436c",
"reference": "5ee57ad690bda2c487594577600931a99053436c",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/f93ef2198df8d54b3195bcee381a33be51d8705e",
"reference": "f93ef2198df8d54b3195bcee381a33be51d8705e",
"shasum": ""
},
"require": {
@@ -602,7 +602,7 @@
"phar-io/manifest": "^2.0.4",
"phar-io/version": "^3.2.1",
"php": ">=8.3",
"phpunit/php-code-coverage": "^12.1.2",
"phpunit/php-code-coverage": "^12.2.1",
"phpunit/php-file-iterator": "^6.0.0",
"phpunit/php-invoker": "^6.0.0",
"phpunit/php-text-template": "^5.0.0",
@@ -656,7 +656,7 @@
"support": {
"issues": "https://github.com/sebastianbergmann/phpunit/issues",
"security": "https://github.com/sebastianbergmann/phpunit/security/policy",
"source": "https://github.com/sebastianbergmann/phpunit/tree/12.1.4"
"source": "https://github.com/sebastianbergmann/phpunit/tree/12.1.5"
},
"funding": [
{
@@ -680,7 +680,7 @@
"type": "tidelift"
}
],
"time": "2025-05-02T07:01:56+00:00"
"time": "2025-05-11T06:44:52+00:00"
},
{
"name": "sebastian/cli-parser",

View File

@@ -13,7 +13,7 @@ use IteratorAggregate;
*
* @author Александр Бабаев
* @package php_components_pack
* @version 1.0
* @version 1.0.3
* @since 1.0.14
*/
final class Dictionary implements ArrayAccess, IteratorAggregate, Countable, ISerializable
@@ -26,6 +26,21 @@ final class Dictionary implements ArrayAccess, IteratorAggregate, Countable, ISe
// Реализация наследуемых интерфейсов и классов
use ArrayBasicTrait;
/**
* Добавление элементов в словарь.
*
* @param array $dictionary Ассоциативный массив вида ключ => значение, который будет добавлен в словарь.
*
* @return void
*/
public function AddRange (array $dictionary): void
{
// Для каждого элемента массива
foreach ($dictionary as $key => $value)
// - добавляем его в словарь.
$this->Add($key, $value);
}
/**
* Добавление элемента в словарь.
*
@@ -97,4 +112,42 @@ final class Dictionary implements ArrayAccess, IteratorAggregate, Countable, ISe
{
return count($this->Container);
}
/**
* Возвращает все ключи словаря.
*
* @return array Массив всех ключей словаря.
*/
public function Keys (): array
{
return array_keys($this->Container);
}
/**
* Сортирует внутренние данные по ключам.
*
* @param bool $descending Сортировать ли данные в обратном порядке?
*
* @return void
*/
public function Sort (bool $descending = false): void
{
// Если задана сортировка по убыванию
if ($descending)
// - сортируем данные в обратном порядке
krsort($this->Container);
else
// - иначе, стандартная сортировка по ключам в порядке возрастания
ksort($this->Container);
}
/**
* Возвращает все элементы словаря в виде массива.
*
* @return array Массив, содержащий все элементы словаря.
*/
public function ToArray (): array
{
return $this->Container;
}
}

View File

@@ -17,7 +17,7 @@ use IteratorAggregate;
*
* @author Александр Бабаев
* @package php_components_pack
* @version 1.0
* @version 1.0.5
* @since 1.0
*/
final class ObjectArray implements ArrayAccess, IteratorAggregate, Countable, ISerializable

View File

@@ -77,7 +77,11 @@ trait ArrayBasicTrait
*/
public function Serialize (): string
{
return json_encode($this->Container);
/**
* ВНИМАНИЕ! Не используйте json_encode для сериализации объектов данного класса, так как он НЕ СОХРАНЯЕТ классы объектов!
* Корректное восстановление объектов невозможно (восстанавливает только как ассоциативный массив).
*/
return serialize($this->Container);
}
/**
@@ -85,6 +89,10 @@ trait ArrayBasicTrait
*/
public function UnSerialize (string $serialized): void
{
$this->Container = json_decode($serialized, true);
/**
* ВНИМАНИЕ! Не используйте json_decode для десериализации объектов данного класса, так как он НЕ ВОССТАНОВЛЯЕТ
* классы объектов! Корректное восстановление объектов невозможно (восстанавливается только как ассоциативный массив).
*/
$this->Container = unserialize($serialized);
}
}

View File

@@ -31,18 +31,6 @@ class DictionaryTest extends TestCase
require_once __DIR__ . '/../../sources/classes/Dictionary.php';
}
public function testSerialize ()
{
$this->PrepareForTest();
$dict = new Dictionary();
$dict->Add('1', 1);
$dict->Add('2', '2');
$dict->Add('3', true);
$this->assertEquals("{\"1\":1,\"2\":\"2\",\"3\":true}", $dict->Serialize());
}
public function testGet ()
{
$this->PrepareForTest();
@@ -99,4 +87,68 @@ class DictionaryTest extends TestCase
$this->assertTrue($dict->Has('3'));
$this->assertFalse($dict->Has('4'));
}
public function testKeys ()
{
$this->PrepareForTest();
$dict = new Dictionary();
$dict->Add('1', 1);
$dict->Add('3', true);
$dict->Add('2', '2');
$array = ['1', '3', '2'];
$this->assertArrayIsEqualToArrayIgnoringListOfKeys($array, $dict->Keys(), []);
}
public function testSort ()
{
$this->PrepareForTest();
$dict = new Dictionary();
$dict->Add('1', 1);
$dict->Add('3', true);
$dict->Add('2', '2');
$array = ['1', '2', '3'];
$dict->Sort();
$this->assertArrayIsEqualToArrayIgnoringListOfKeys($array, $dict->Keys(), []);
}
public function testAddRange ()
{
$this->PrepareForTest();
$dict = new Dictionary();
$dict->Add('1', 1);
$array = ['2' => '2', '3' => true, '4' => false];
$dict->AddRange($array);
$this->assertEquals(1, $dict->Get('1'));
$this->assertTrue($dict->Get('3'));
$this->assertEquals(4, $dict->count());
$this->assertFalse($dict->Get("4"));
}
public function testToArray ()
{
$this->PrepareForTest();
$dict = new Dictionary();
$dict->Add('1', 1);
$dict->Add('3', true);
$dict->Add('2', '2');
$array = $dict->ToArray();
$this->assertIsArray($array);
$this->assertEquals(1, $array['1']);
$this->assertTrue($array['3']);
$this->assertCount(3, $array);
}
}