Passed
Push — master ( 21e99f...8493af )
by George
03:07
created

Column::validateUnspecifiedColumns()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 5.5021

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 17
ccs 6
cts 11
cp 0.5455
rs 9.2
cc 4
eloc 9
nc 4
nop 0
crap 5.5021
1
<?php
2
namespace JsonTable\Analyse;
3
4
/**
5
 * Perform analysis on the CSV columns.
6
 *
7
 * @package JsonTable
8
 */
9
class Column extends Analyse implements AnalyseInterface
10
{
11
    /**
12
     * Validate that all fields are of the correct type, format and pattern.
13
     * This also checks that each CSV row has the expected number of columns.
14
     *
15
     * @return  boolean Is all data lexically valid.
16
     */
17 30
    public function validate()
18
    {
19 30
        if (!$this->validateMandatoryColumns()) {
20 2
            return false;
21
        }
22
23 28
        if (!$this->validateUnspecifiedColumns() && $this->stopIfInvalid) {
24
            return false;
25
        }
26
27 28
        return true;
28
    }
29
    
30
    
31
    /**
32
     * Validate that all mandatory columns are present.
33
     *
34
     * @return boolean Are all mandatory columns present.
35
     */
36 30
    private function validateMandatoryColumns()
37
    {
38 30
        $validMandatoryColumns = true;
39
40 30
        foreach (parent::$schemaJson->fields as $field) {
41 30
            if ($this->isColumnMandatory($field)) {
42 30
                if (!in_array($field->name, parent::$headerColumns)) {
43 2
                    $this->error->setError(Analyse::ERROR_REQUIRED_COLUMN_MISSING, $field->name);
44 2
                    $validMandatoryColumns = false;
45
46 2
                    if ($this->stopIfInvalid) {
47
                        return false;
48
                    }
49 2
                }
50 30
            }
51 30
        }
52
53 30
        return $validMandatoryColumns;
54
    }
55
56
57
    /**
58
     * Check that there are no columns in the CSV that are not specified in the schema.
59
     *
60
     * @return boolean Are all the CSV columns specified in the schema.
61
     */
62 28
    private function validateUnspecifiedColumns()
63
    {
64 28
        $validUnspecifiedColumns = true;
65
66 28
        foreach (parent::$headerColumns as $csvColumnName) {
67 28
            if (false === $this->getSchemaKeyFromName($csvColumnName)) {
68
                $this->error->setError(Analyse::ERROR_UNSPECIFIED_COLUMN, $csvColumnName);
69
                $validUnspecifiedColumns = false;
70
71
                if ($this->stopIfInvalid) {
72
                    return false;
73
                }
74
            }
75 28
        }
76
77 28
        return $validUnspecifiedColumns;
78
    }
79
}