File: Arrays.renameKey%28%29.ref.phpt

package info (click to toggle)
php-nette-utils 4.1.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,480 kB
  • sloc: php: 4,219; xml: 9; makefile: 4
file content (103 lines) | stat: -rw-r--r-- 1,925 bytes parent folder | download
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php

/**
 * Test: Nette\Utils\Arrays::renameKey() - preserves references
 */

declare(strict_types=1);

use Nette\Utils\Arrays;
use Tester\Assert;


require __DIR__ . '/../bootstrap.php';


test('preserves references when renaming key', function () {
	$arr = [
		1 => 'a',
		2 => 'b',
	];

	$arr2 = [
		1 => &$arr[1],
		2 => &$arr[2],
	];

	Arrays::renameKey($arr, '1', 'new1');

	// Modify via reference
	$arr2[1] = 'A';
	$arr2[2] = 'B';

	// Should reflect in renamed array
	Assert::same('A', $arr['new1']);
	Assert::same('B', $arr[2]);
});


test('preserves references when renaming to existing numeric key', function () {
	$arr = [
		1 => 'a',
		2 => 'b',
	];

	$arr2 = [
		1 => &$arr[1],
		2 => &$arr[2],
	];

	Arrays::renameKey($arr, '1', 'new1');
	Arrays::renameKey($arr, 'new1', 2);

	// Modify via reference
	$arr2[1] = 'AA';
	$arr2[2] = 'BB';

	// The value at key 2 should now be the renamed value with preserved reference
	Assert::same('AA', $arr[2]);
});


test('maintains reference through multiple renames', function () {
	$value = 'original';
	$arr = ['key' => &$value];

	Arrays::renameKey($arr, 'key', 'temp');
	Arrays::renameKey($arr, 'temp', 'final');

	// Modify original variable
	$value = 'modified';

	// Should reflect in array with renamed key
	Assert::same('modified', $arr['final']);
});


test('reference is preserved when renaming to same key', function () {
	$value = 'test';
	$arr = ['key' => &$value];

	Arrays::renameKey($arr, 'key', 'key');

	$value = 'changed';

	Assert::same('changed', $arr['key']);
});


test('complex reference scenario with nested values', function () {
	$shared = ['shared' => 'data'];
	$arr = [
		'a' => &$shared,
		'b' => ['nested' => 'value'],
	];

	Arrays::renameKey($arr, 'a', 'shared_ref');

	// Modify shared reference
	$shared['shared'] = 'modified';

	// Should be reflected in renamed key
	Assert::same(['shared' => 'modified'], $arr['shared_ref']);
});