Passed
Push — master ( 8ff4e3...ffee1f )
by Samuel
03:00
created

requestBodyHasValidKeys()   A

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 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 21
ccs 7
cts 8
cp 0.875
rs 10
cc 4
nc 4
nop 3
crap 4.0312
1
<?php
2
3
namespace App\Application\Validation;
4
5
/**
6
 * Validate that request body contains the given keys.
7
 */
8
class MalformedRequestBodyChecker
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 amount of the required keys meaning
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 optional key is set so that if there is an optional key, $amount goes up meaning
30
                // 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