Completed
Push — develop ( 888c61...656149 )
by Adrien
35:11
created

DataValidator::isValid()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 11
nc 4
nop 1
dl 0
loc 21
ccs 11
cts 11
cp 1
crap 6
rs 8.7624
c 0
b 0
f 0
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Cell;
4
5
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
6
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
7
use PhpOffice\PhpSpreadsheet\Exception;
8
9
/**
10
 * Validate a cell value according to its validation rules.
11
 */
12
class DataValidator
13
{
14
    /**
15
     * Does this cell contain valid value?
16
     *
17
     * @param Cell $cell Cell to check the value
18
     *
19
     * @return bool
20
     */
21 3
    public function isValid(Cell $cell)
22
    {
23 3
        if (!$cell->hasDataValidation()) {
24 1
            return true;
25
        }
26
27 2
        $cellValue = $cell->getValue();
28 2
        $dataValidation = $cell->getDataValidation();
29
30 2
        if (!$dataValidation->getAllowBlank() && ($cellValue === null || $cellValue === '')) {
31 1
            return false;
32
        }
33
34
        // TODO: write check on all cases
35 2
        switch ($dataValidation->getType()) {
36 2
            case DataValidation::TYPE_LIST:
37 1
                return $this->isValueInList($cell);
38
        }
39
40 1
        return false;
41
    }
42
43
    /**
44
     * Does this cell contain valid value, based on list?
45
     *
46
     * @param Cell $cell Cell to check the value
47
     *
48
     * @return bool
49
     */
50 1
    private function isValueInList(Cell $cell)
51
    {
52 1
        $cellValue = $cell->getValue();
53 1
        $dataValidation = $cell->getDataValidation();
54
55 1
        $formula1 = $dataValidation->getFormula1();
56 1
        if (!empty($formula1)) {
57
            // inline values list
58 1
            if ($formula1[0] === '"') {
59 1
                return in_array(strtolower($cellValue), explode(',', strtolower(trim($formula1, '"'))), true);
60 1
            } elseif (strpos($formula1, ':') > 0) {
61
                // values list cells
62 1
                $matchFormula = '=MATCH(' . $cell->getCoordinate() . ', ' . $formula1 . ', 0)';
63 1
                $calculation = Calculation::getInstance($cell->getWorksheet()->getParent());
64
65
                try {
66 1
                    $result = $calculation->calculateFormula($matchFormula, $cell->getCoordinate(), $cell);
67
68 1
                    return $result !== Functions::NA();
69 1
                } catch (Exception $ex) {
70 1
                    return false;
71
                }
72
            }
73
        }
74
75 1
        return true;
76
    }
77
}
78