<?php
/**
* Test: NetteUtilsArrayList basic usage.
*/
declare(strict_types=1);
use NetteUtilsArrayList;
use TesterAssert;
require __DIR__ . '/../bootstrap.php';
class Person
{
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function sayHi()
{
return "My name is $this->name";
}
}
test('ArrayList::from', function () {
fn() => ArrayList::from(['a' => 1, 'b' => 2]),
NetteInvalidArgumentException::class,
'Array is not valid list.',
);
$mary = new Person('Mary');
$list = ArrayList::from([$mary, 'Jack']);
assert::
type(NetteUtilsArrayList::
class,
$list);
assert::
same([$mary,
'Jack'], iterator_to_array
($list));
});
test('', function () {
$list = new ArrayList;
$jack = new Person('Jack');
$mary = new Person('Mary');
$list[] = $mary;
$list[] = $jack;
assert::
same($mary,
$list[0]);
assert::
same($jack,
$list[1]);
$mary,
$jack,
], iterator_to_array($list));
foreach ($list as $key => $person) {
$tmp[] = $key . ' => ' . $person->sayHi();
}
'0 => My name is Mary',
'1 => My name is Jack',
], $tmp);
assert::
same(2,
$list->
count());
$mary,
], iterator_to_array($list));
$list->prepend('First');
assert::
same('First',
$list[0],
'Value "First" should be on the start of the array');
});
test('', function () {
$list = new ArrayList;
$list[] = 'a';
$list[] = 'b';
fn() => $list[-1] = true,
OutOfRangeException::class,
'Offset invalid or out of range',
);
fn() => $list[2] = true,
OutOfRangeException::class,
'Offset invalid or out of range',
);
fn() => $list['key'] = true,
OutOfRangeException::class,
'Offset invalid or out of range',
);
});
test('', function () {
$list = new ArrayList;
$list[] = 'a';
$list[] = 'b';
fn() => $list[-1],
OutOfRangeException::class,
'Offset invalid or out of range',
);
fn() => $list[2],
OutOfRangeException::class,
'Offset invalid or out of range',
);
fn() => $list['key'],
OutOfRangeException::class,
'Offset invalid or out of range',
);
});
test('', function () {
$list = new ArrayList;
$list[] = 'a';
$list[] = 'b';
assert::
exception(function () use
($list) {
}, OutOfRangeException::class, 'Offset invalid or out of range');
assert::
exception(function () use
($list) {
}, OutOfRangeException::class, 'Offset invalid or out of range');
assert::
exception(function () use
($list) {
}, OutOfRangeException::class, 'Offset invalid or out of range');
});
test('iteration with reference', function () {
$list = ArrayList::from([1, 2, 3]);
foreach ($list as $key => &$value) {
$value = 'new';
}
assert::
same(['new',
'new',
'new'], iterator_to_array
($list));
});