Skip to content

Commit

Permalink
Arrays: added updateDiff()
Browse files Browse the repository at this point in the history
  • Loading branch information
Miloslav Hůla committed Jan 7, 2021
1 parent 3d71c31 commit f4bd8a6
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/Utils/Arrays.php
Original file line number Diff line number Diff line change
Expand Up @@ -343,4 +343,19 @@ public static function toKey($value)
{
return key([$value => null]);
}


/**
* Returns items required to synchronize associative array $from to array $to.
*/
public static function updateDiff(array $from, array $to): array
{
$diff = [];
foreach ($to as $k => $v) {
if (!array_key_exists($k, $from) || $v !== $from[$k]) {
$diff[$k] = $v;
}
}
return $diff;
}
}
71 changes: 71 additions & 0 deletions tests/Utils/Arrays.updateDiff().phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

/**
* Test: Nette\Utils\Arrays::updateDiff()
*/

declare(strict_types=1);

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


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


test('Basics', function () {
Assert::same([], Arrays::updateDiff([], []));
Assert::same([], Arrays::updateDiff(['a' => ''], []));
});


test('New keys', function () {
$to = [
'a' => null,
'b' => false,
'c' => '',
'd' => 0,
];
Assert::same($to, Arrays::updateDiff([], $to));
});


test('To falsy values', function () {
$from = [
'a' => null,
'b' => false,
'c' => '',
'd' => 0,
];

$toNull = ['a' => null, 'b' => null, 'c' => null, 'd' => null];
Assert::same([
'b' => null,
'c' => null,
'd' => null,
], Arrays::updateDiff($from, $toNull));


$toFalse = ['a' => false, 'b' => false, 'c' => false, 'd' => false];
Assert::same([
'a' => false,
'c' => false,
'd' => false,
], Arrays::updateDiff($from, $toFalse));


$toEmpty = ['a' => '', 'b' => '', 'c' => '', 'd' => ''];
Assert::same([
'a' => '',
'b' => '',
'd' => '',
], Arrays::updateDiff($from, $toEmpty));


$toZero = ['a' => 0, 'b' => 0, 'c' => 0, 'd' => 0];
Assert::same([
'a' => 0,
'b' => 0,
'c' => 0,
], Arrays::updateDiff($from, $toZero));
});
Empty file added tests/lock
Empty file.

0 comments on commit f4bd8a6

Please sign in to comment.