Passed
Push — master ( 6457e8...13f804 )
by Nathan
05:48
created

GetBlockTemplateValidator::validate()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
c 0
b 0
f 0
rs 7.551
cc 7
eloc 12
nc 5
nop 1
1
<?php
2
3
namespace ZenCash\Rpc\Validation\Mining;
4
5
use ZenCash\Rpc\Validation\Exception\JsonFormatException;
6
use ZenCash\Rpc\Validation\JsonValidator;
7
8
final class GetBlockTemplateValidator implements JsonValidator
9
{
10
    /** @throws JsonFormatException */
11
    public static function validate(string $json)
12
    {
13
        if (!$decoded = json_decode($json)) {
14
            throw new JsonFormatException("JSON object has an invalid structure:\n$json");
15
        }
16
17
        if (($decoded->mode ?? false) && ($decoded->mode !== 'template')) {
18
            throw new JsonFormatException("JSON property `mode` must be either 'template' or omitted.");
19
        }
20
21
        if ($decoded->capabilities ?? false) {
22
            if (!is_array($decoded->capabilities)) {
23
                throw new JsonFormatException(
24
                    'JSON property `capabilities` must be of type `array`, `' .
25
                    gettype($decoded->capabilities) . '` provided.'
26
                );
27
            }
28
29
            array_walk($decoded->capabilities, function ($item) {
30
                if (!is_string($item)) {
31
                    throw new JsonFormatException("JSON property `capabilities` must only contain strings.");
32
                }
33
            });
34
        }
35
    }
36
}
37