<?php
/**
* Test: NetteUtilsArrayHash basic usage.
*/
declare(strict_types=1);
use NetteUtilsArrayHash;
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('', function () {
$list = new ArrayHash;
$jack = new Person('Jack');
$mary = new Person('Mary');
$list['m'] = $mary;
$list['j'] = $jack;
assert::
same($mary,
$list['m']);
assert::
same($jack,
$list['j']);
assert::
same($mary,
$list->
m);
assert::
same($jack,
$list->
j);
'm' => $mary,
'j' => $jack,
], iterator_to_array($list));
'm' => $mary,
'j' => $jack,
foreach ($list as $key => $person) {
$tmp[] = $key . ' => ' . $person->sayHi();
}
'm => My name is Mary',
'j => My name is Jack',
], $tmp);
assert::
same(2,
$list->
count());
'm' => $mary,
], iterator_to_array($list));
});
test('', function () {
$mary = new Person('Mary');
$list = ArrayHash::from([
'm' => $mary,
'j' => 'Jack',
'children' => [
'c' => 'John',
],
], false);
assert::
type(NetteUtilsArrayHash::
class,
$list);
assert::
type('array',
$list['children']);
});
test('', function () {
$mary = new Person('Mary');
$list = ArrayHash::from([
'm' => $mary,
'j' => 'Jack',
'children' => [
'c' => 'John',
],
]);
assert::
type(NetteUtilsArrayHash::
class,
$list);
assert::
same($mary,
$list['m']);
assert::
same('Jack',
$list['j']);
assert::
type(NetteUtilsArrayHash::
class,
$list['children']);
assert::
same('John',
$list['children']['c']);
$list['children']['c'] = 'Jim';
assert::
same('Jim',
$list['children']['c']);
'm' => $mary,
'j' => 'Jack',
'children' => $list['children'],
'c' => 'Jim',
], iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($list), RecursiveIteratorIterator::SELF_FIRST)));
});
test('numeric fields', function () {
$row = ArrayHash::from([1, 2]);
foreach ($row as $key => $value) {
$keys[] = $key;
}
if (PHP_VERSION_ID < 70200) {
assert::
same(['0',
'1'],
$keys);
} else {
}
$row[3] = 'new';
assert::
same('new',
$row->
{3});
assert::
same('new',
$row->
{'3'});
assert::
same('new',
$row['3']);
});
test('null fields', function () {
$row = ArrayHash::from(['null' => null]);
});
test('undeclared fields', function () {
$row = new ArrayHash;
fn() => $row->undef,
PHP_VERSION_ID < 80000 ? e_notice : e_warning,
'Undefined property: NetteUtilsArrayHash::$undef',
);
fn() => $row['undef'],
PHP_VERSION_ID < 80000 ? e_notice : e_warning,
'Undefined property: NetteUtilsArrayHash::$undef',
);
});
test('PHP 7 changed behavior https://3v4l.org/2A1pf', function () {
$hash = ArrayHash::from([1, 2, 3]);
foreach ($hash as $key => $value) {
}
});
test('iteration with reference', function () {
$hash = ArrayHash::from([1, 2, 3]);
foreach ($hash as $key => &$value) {
$value = 'new';
}
});