diff --git a/sources/classes/Dictionary.php b/sources/classes/Dictionary.php index 43612db..15f5e54 100644 --- a/sources/classes/Dictionary.php +++ b/sources/classes/Dictionary.php @@ -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; + } } \ No newline at end of file diff --git a/tests/classes/DictionaryTest.php b/tests/classes/DictionaryTest.php index 28be388..70b1a07 100644 --- a/tests/classes/DictionaryTest.php +++ b/tests/classes/DictionaryTest.php @@ -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); + } } \ No newline at end of file