Validation::evaluateResult()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 10
c 1
b 0
f 0
nc 3
nop 3
dl 0
loc 14
ccs 9
cts 9
cp 1
crap 4
rs 9.9332
1
<?php
2
3
namespace ntentan\utils\validator;
4
5
/**
6
 * An abstract class to be used as the base for validations.
7
 *
8
 * @package ntentan\utils\validator
9
 */
10
abstract class Validation
11
{
12
    /**
13
     * Holds messages generated during validation.
14
     *
15
     * @var array
16
     */
17
    private $messages = [];
18
19
    /**
20
     * @param $field
21
     * @param $data
22
     * @return mixed
23
     */
24
    abstract public function run($field, $data);
25
26
    /**
27
     * Utility function that evaluates the result of a validation test and prepares validation messages.
28
     * Receives a boolean from the validation function and a message to be displayed when the value is false. It also
29
     * receives the options array so it could override the standard message that the validation code generates.
30
     *
31
     * @param array $field
32
     * @param boolean $result
33
     * @param string $message
34
     * @return boolean
35
     */
36 14
    protected function evaluateResult($field, $result, $message)
37
    {
38 14
        $this->messages = [];
39 14
        if ($result) {
40 10
            return true;
41
        } else {
42 14
            if (is_array($field['name'])) {
43 2
                foreach ($field['name'] as $name) {
44 2
                    $this->messages[$name][] = $field['options']['message'] ?? $message;
45
                }
46
            } else {
47 12
                $this->messages[$field['name']][] = $field['options']['message'] ?? $message;
48
            }
49 14
            return false;
50
        }
51
    }
52
53
    /**
54
     * Extracts the value of the field description from the data passed.
55
     *
56
     * @param array $field
57
     * @param array $data
58
     * @return mixed
59
     */
60 12
    protected function getFieldValue($field, $data)
61
    {
62 12
        $value = null;
63 12
        if (isset($data[$field['name']])) {
64 12
            $value = $data[$field['name']];
65
        }
66 12
        return $value;
67
    }
68
69
    /**
70
     * Get the validation messages generated.
71
     *
72
     * @return array
73
     */
74 14
    public function getMessages()
75
    {
76 14
        return $this->messages;
77
    }
78
}
79