Assert::keysMatch()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 2
nop 4
dl 0
loc 16
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Copyright 2014 SURFnet bv
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace Surfnet\StepupMiddleware\ManagementBundle\Validator;
20
21
use Assert\InvalidArgumentException;
22
23
final class Assert
24
{
25
    /**
26
     * @param array $value
27
     * @param array $keys
28
     */
29
    public static function keysMatch(array $value, array $keys, ?string $message = null, ?string $propertyPath = null): void
30
    {
31
        $keysOfValue = array_keys($value);
32
        $extraKeys = array_diff($keysOfValue, $keys);
33
        $missingKeys = array_diff($keys, $keysOfValue);
34
35
        if ($extraKeys === [] && $missingKeys === []) {
36
            return;
37
        }
38
39
        throw new InvalidArgumentException(
40
            $message,
41
            0,
42
            $propertyPath,
43
            $value,
44
            ['expected' => $keys, 'actual' => $keysOfValue],
45
        );
46
    }
47
48
    public static function requiredAndOptionalOptions(
49
        array $value,
50
        array $required,
51
        array $optional,
52
        ?string $message = null,
53
        ?string $propertyPath = null,
54
    ): void {
55
        // Filter out the optional items from the value array
56
        $requiredValueSet = array_diff_key($value, array_flip($optional));
57
58
        // Verify the required keys match.
59
        self::keysMatch($requiredValueSet, $required, $message, $propertyPath);
60
61
        // Verify the optional keys do not contain illegal entries.
62
        $keysOfValue = array_keys($value);
63
        $extraKeys = array_diff($keysOfValue, array_merge($optional, $required));
64
65
        if ($extraKeys === []) {
66
            return;
67
        }
68
69
        throw new InvalidArgumentException(
70
            $message,
71
            0,
72
            $propertyPath,
73
            $value,
74
            ['expected' => $optional, 'actual' => $keysOfValue],
75
        );
76
    }
77
}
78