Skip to content

Commit f4bd8a6

Browse files
author
Miloslav Hůla
committed
Arrays: added updateDiff()
1 parent 3d71c31 commit f4bd8a6

File tree

3 files changed

+86
-0
lines changed

3 files changed

+86
-0
lines changed

src/Utils/Arrays.php

+15
Original file line numberDiff line numberDiff line change
@@ -343,4 +343,19 @@ public static function toKey($value)
343343
{
344344
return key([$value => null]);
345345
}
346+
347+
348+
/**
349+
* Returns items required to synchronize associative array $from to array $to.
350+
*/
351+
public static function updateDiff(array $from, array $to): array
352+
{
353+
$diff = [];
354+
foreach ($to as $k => $v) {
355+
if (!array_key_exists($k, $from) || $v !== $from[$k]) {
356+
$diff[$k] = $v;
357+
}
358+
}
359+
return $diff;
360+
}
346361
}

tests/Utils/Arrays.updateDiff().phpt

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
<?php
2+
3+
/**
4+
* Test: Nette\Utils\Arrays::updateDiff()
5+
*/
6+
7+
declare(strict_types=1);
8+
9+
use Nette\Utils\Arrays;
10+
use Tester\Assert;
11+
12+
13+
require __DIR__ . '/../bootstrap.php';
14+
15+
16+
test('Basics', function () {
17+
Assert::same([], Arrays::updateDiff([], []));
18+
Assert::same([], Arrays::updateDiff(['a' => ''], []));
19+
});
20+
21+
22+
test('New keys', function () {
23+
$to = [
24+
'a' => null,
25+
'b' => false,
26+
'c' => '',
27+
'd' => 0,
28+
];
29+
Assert::same($to, Arrays::updateDiff([], $to));
30+
});
31+
32+
33+
test('To falsy values', function () {
34+
$from = [
35+
'a' => null,
36+
'b' => false,
37+
'c' => '',
38+
'd' => 0,
39+
];
40+
41+
$toNull = ['a' => null, 'b' => null, 'c' => null, 'd' => null];
42+
Assert::same([
43+
'b' => null,
44+
'c' => null,
45+
'd' => null,
46+
], Arrays::updateDiff($from, $toNull));
47+
48+
49+
$toFalse = ['a' => false, 'b' => false, 'c' => false, 'd' => false];
50+
Assert::same([
51+
'a' => false,
52+
'c' => false,
53+
'd' => false,
54+
], Arrays::updateDiff($from, $toFalse));
55+
56+
57+
$toEmpty = ['a' => '', 'b' => '', 'c' => '', 'd' => ''];
58+
Assert::same([
59+
'a' => '',
60+
'b' => '',
61+
'd' => '',
62+
], Arrays::updateDiff($from, $toEmpty));
63+
64+
65+
$toZero = ['a' => 0, 'b' => 0, 'c' => 0, 'd' => 0];
66+
Assert::same([
67+
'a' => 0,
68+
'b' => 0,
69+
'c' => 0,
70+
], Arrays::updateDiff($from, $toZero));
71+
});

tests/lock

Whitespace-only changes.

0 commit comments

Comments
 (0)