summaryrefslogtreecommitdiffstats
path: root/library/Director/Data/DataArrayHelper.php
blob: 442eb0fdbba9b39e226f89e8c6965ab9eb4c0b10 (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
<?php

namespace Icinga\Module\Director\Data;

use InvalidArgumentException;
use function array_diff;
use function array_key_exists;
use function implode;
use function is_array;
use function is_object;

class DataArrayHelper
{
    public static function wantArray($value)
    {
        if (is_object($value)) {
            return (array) $value;
        }
        if (! is_array($value)) {
            throw new InvalidDataException('Object', $value);
        }

        return $value;
    }

    public static function failOnUnknownProperties(array $values, array $knownProperties)
    {
        $unknownProperties = array_diff($knownProperties, array_keys($values));

        if (! empty($unknownProperties)) {
            throw new InvalidArgumentException('Unexpected properties: ' . implode(', ', $unknownProperties));
        }
    }

    public static function requireProperties(array $value, array $properties)
    {
        $missing = [];
        foreach ($properties as $property) {
            if (! array_key_exists($property, $value)) {
                $missing[] = $property;
            }
        }

        if (! empty($missing)) {
            throw new InvalidArgumentException('Missing properties: ' . implode(', ', $missing));
        }
    }
}