Passed
Push — master ( 03d969...bf76ef )
by Vitalii
08:57 queued 16s
created

get_num()   B

Complexity

Conditions 8
Paths 16

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 8
eloc 16
c 1
b 0
f 1
nc 16
nop 1
dl 0
loc 24
rs 8.4444
1
<?php
2
3
// the following functions return a [value, errmsg] pair.
4
// The errmsg is null if no error
5
6
function get_num($field) {
7
    $x = get_str($field->name);
8
    if ($field->type == 'integer') {
9
        if (filter_var($x, FILTER_VALIDATE_INT) === false) {
10
            return [null, 'not an integer'];
11
        }
12
        $x = intval($x);
13
    } else {
14
        if (filter_var($x, FILTER_VALIDATE_FLOAT) === false) {
15
            return [null, 'not a float'];
16
        }
17
        $x = floatval($x);
18
    }
19
    if (isset($field->min_value)) {
20
        if ($x < $field->min_value) {
21
            return [null, 'value is less than min'];
22
        }
23
    }
24
    if (isset($field->max_value)) {
25
        if ($x > $field->max_value) {
26
            return [null, 'value is greater than max'];
27
        }
28
    }
29
    return [$x, null];
30
}
31
32
function get_multi($field) {
33
    $x = get_array($field->name);
34
    $n = count($x);
35
    if (isset($field->min_items)) {
36
        if ($n < $field->min_items) {
37
            return [null, 'too few items selected'];
38
        }
39
    }
40
    if (isset($field->max_items)) {
41
        if ($n > $field->max_items) {
42
            return [null, 'too many items selected'];
43
        }
44
    }
45
    return [$x, null];
46
}
47
48
// returns either
49
// - an object containing the field values, or
50
// - a list of [title, errmsg] pairs
51
//
52
function get_inputs($form_desc) {
53
    $vals = new StdClass;
54
    $errs = [];
55
    foreach ($form_desc->fields as $field) {
56
        switch ($field->type) {
57
        case 'text':
58
        case 'select':
59
        case 'file_select':
60
            $err = null;
61
            $val = get_str($field->name);
62
            break;
63
        case 'integer':
64
        case 'float':
65
            [$val, $err] = get_num($field);
66
            break;
67
        case 'select_multi':
68
        case 'file_select_multi':
69
            [$val, $err] = get_multi($field);
70
            break;
71
        }
72
        if ($err) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $err does not seem to be defined for all execution paths leading up to this point.
Loading history...
73
            $errs[] = [$field->title, $err];
74
        } else {
75
            $x = $field->name;
76
            $vals->$x = $val;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $val does not seem to be defined for all execution paths leading up to this point.
Loading history...
77
        }
78
    }
79
    return [$vals, $errs];
80
}
81
82
?>
83