Completed
Push — master ( 4c8d32...c7efbc )
by James Ekow Abaka
04:08
created

ModelValidator::__construct()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 4

Importance

Changes 4
Bugs 0 Features 1
Metric Value
c 4
b 0
f 1
dl 0
loc 27
ccs 19
cts 19
cp 1
rs 8.5806
cc 4
eloc 18
nc 8
nop 2
crap 4
1
<?php
2
namespace ntentan\nibii;
3
4
class ModelValidator extends \ntentan\utils\Validator
5
{
6
    private $model;
7
    
8
    /**
9
     * 
10
     * @param RecordWrapper
11
     */
12 10
    public function __construct($model, $mode) {
13 10
        $pk = null;
14 10
        $rules = [];
15 10
        $this->model = $model;
16 10
        $description = $model->getDescription();
17
18 10
        if($description->getAutoPrimaryKey()) {
19 10
            $pk = $description->getPrimaryKey()[0];
20
        }
21
22 10
        $fields = $description->getFields();
23 10
        foreach($fields as $field) {
24 10
            $this->getFieldRules($rules, $field, $pk);
25
        }
26
        
27 10
        $unique = $description->getUniqueKeys();
28 10
        foreach($unique as $constraints) {
29 6
            $rules['unique'][] = [$constraints['fields']];
30
        }
31
        
32 10
        $this->setRules($rules);
33 10
        $this->registerValidation(
34 10
            'unique', 
35 10
            '\ntentan\nibii\validations\UniqueValidation',
36 10
            ['model' => $model, 'mode' => $mode]
37
        );        
38 10
    }
39
40 10
    private function getFieldRules(&$rules, $field, $pk)
41
    {
42 10
        if($field['required'] && $field['name'] != $pk && $field['default'] === null) {
43 10
            $rules['required'][] = $field['name'];
44
        }
45 10
        if($field['type'] === 'integer' || $field['type'] === 'double') {
46 10
            $rules['numeric'][] = $field['name'];
47
        }
48 10
    }
49
}
50