[Dictionary] добавлен метод AddRange (array $dictionary), который добавляет элементы в виде ассоциативного массива ключ => значение в словарь.

[Dictionary] Добавлен метод ToArray (), который возвращает все элементы словаря в виде массива..
This commit is contained in:
Александр Бабаев 2025-05-20 12:42:06 +03:00
parent 2e684cb862
commit 2d16baaef9
2 changed files with 60 additions and 13 deletions

View File

@ -13,7 +13,7 @@ use IteratorAggregate;
*
* @author Александр Бабаев
* @package php_components_pack
* @version 1.0.2
* @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);
}
/**
* Добавление элемента в словарь.
*
@ -125,4 +140,14 @@ final class Dictionary implements ArrayAccess, IteratorAggregate, Countable, ISe
// - иначе, стандартная сортировка по ключам в порядке возрастания
ksort($this->Container);
}
/**
* Возвращает все элементы словаря в виде массива.
*
* @return array Массив, содержащий все элементы словаря.
*/
public function ToArray (): array
{
return $this->Container;
}
}

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();
@ -129,4 +117,38 @@ class DictionaryTest extends TestCase
$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);
}
}