RequestBodyKeyValidator::requestBodyHasValidKeys()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.0312

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 4
nop 3
dl 0
loc 21
ccs 7
cts 8
cp 0.875
crap 4.0312
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace App\Domain\Validation;
4
5
/**
6
 * Validate that request body contains the given keys.
7
 */
8
class RequestBodyKeyValidator
9
{
10
    /**
11
     * Validate that parsed body array contains the given keys.
12
     *
13
     * @param array|null $parsedBody null if parsed body is empty
14
     * @param array $requiredKeys
15
     * @param array $optionalKeys
16
     *
17
     * @return bool
18
     */
19 2
    public function requestBodyHasValidKeys(?array $parsedBody, array $requiredKeys, array $optionalKeys = []): bool
20
    {
21
        // Init $amount to be the number of the required keys
22 2
        $amount = count($requiredKeys);
23 2
        foreach ($parsedBody ?? [] as $key => $item) {
24
            // isset cannot be used in this context as it returns false if the key exists but is null, and we don't want
25
            // to test required fields here, just that the request body syntax is right
26 2
            if (in_array($key, $requiredKeys, true)) {
27
                // Is a required key which is fine; nothing has to done
28 1
            } elseif (in_array($key, $optionalKeys, true)) {
29
                // Add one to amount if an optional key is set so that if there is an optional key, $amount goes up
30
                // meaning a required key cannot be skipped as expected amount won't be the same as parsed body
31
                $amount++;
32
            } else {
33
                // Given array key not in optional nor required
34 1
                return false;
35
            }
36
        }
37
38
        // Check that all required keys are set plus the additional ones if there were some
39 1
        return count($parsedBody ?? []) === $amount;
40
    }
41
}
42