1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
<?php
/**
* Test: Nette\Utils\Arrays::getRef()
*/
declare(strict_types=1);
use Nette\Utils\Arrays;
use Tester\Assert;
require __DIR__ . '/../bootstrap.php';
$arr = [
'' => 'first',
1 => 'second',
7 => [
'item' => 'third',
],
];
test('reference update and auto-add missing key', function () use ($arr) {
$dolly = $arr;
$item = &Arrays::getRef($dolly, '');
$item = 'changed';
Assert::same([
'' => 'changed',
1 => 'second',
7 => [
'item' => 'third',
],
], $dolly);
$dolly = $arr;
$item = &Arrays::getRef($dolly, 'undefined');
$item = 'changed';
Assert::same([
'' => 'first',
1 => 'second',
7 => [
'item' => 'third',
],
'undefined' => 'changed',
], $dolly);
});
test('nested reference assignment and full array override', function () use ($arr) {
$dolly = $arr;
$item = &Arrays::getRef($dolly, []);
$item = 'changed';
Assert::same('changed', $dolly);
$dolly = $arr;
$item = &Arrays::getRef($dolly, [7, 'item']);
$item = 'changed';
Assert::same([
'' => 'first',
1 => 'second',
7 => [
'item' => 'changed',
],
], $dolly);
});
test('exception on invalid nested reference', function () use ($arr) {
$dolly = $arr;
Assert::exception(
fn() => $item = &Arrays::getRef($dolly, [7, 'item', 3]),
InvalidArgumentException::class,
'Traversed item is not an array.',
);
});
|