summaryrefslogtreecommitdiffstats
path: root/library/Director/Db/Branch/PlainObjectPropertyDiff.php
blob: 0256798508cf3368d646581449ed86aeb2d01963 (plain)
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
<?php

namespace Icinga\Module\Director\Db\Branch;

class PlainObjectPropertyDiff
{
    public static function calculate(array $old = null, array $new = null)
    {
        if ($new === null) {
            throw new \RuntimeException('Cannot diff for delete');
        }
        if ($old === null) {
            foreach (BranchSettings::ENCODED_DICTIONARIES as $property) {
                self::flattenProperty($new, $property);
            }

            return $new;
        }
        $unchangedKeys = [];
        foreach (BranchSettings::ENCODED_DICTIONARIES as $property) {
            self::flattenProperty($old, $property);
            self::flattenProperty($new, $property);
        }
        foreach ($old as $key => $value) {
            if (array_key_exists($key, $new)) {
                if ($value === $new[$key]) {
                    $unchangedKeys[] = $key;
                }
            } else {
                $new[$key] = null;
            }
        }
        foreach ($unchangedKeys as $key) {
            unset($new[$key]);
        }

        return $new;
    }

    protected static function flattenProperty(array &$properties, $property)
    {
        // TODO: dots in varnames -> throw or escape?
        if (isset($properties[$property])) {
            foreach ((array) $properties[$property] as $key => $value) {
                $properties["$property.$key"] = $value;
            }
            unset($properties[$property]);
        }
    }
}