Completed
Push — master ( fbe049...cd378b )
by Ori
07:11
created

YearMonthField::validateCastValue()   C

Complexity

Conditions 7
Paths 8

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 16
nc 8
nop 1
dl 0
loc 22
rs 6.9811
c 0
b 0
f 0
1
<?php
2
3
namespace frictionlessdata\tableschema\Fields;
4
5
/**
6
 * Class YearMonthField
7
 * casts to array [year, month].
8
 */
9
class YearMonthField extends BaseField
10
{
11
    protected function validateCastValue($val)
12
    {
13
        if (!is_array($val)) {
14
            $val = explode('-', $val);
15
        }
16
        if (count($val) != 2) {
17
            throw $this->getValidationException(null, $val);
18
        } else {
19
            list($year, $month) = $val;
20
            if ($year == '' || $month == '') {
21
                throw $this->getValidationException(null, $val);
22
            } else {
23
                $year = (int) $year;
24
                $month = (int) $month;
25
                if ($month < 1 || $month > 12) {
26
                    throw $this->getValidationException(null, $val);
27
                } else {
28
                    return $this->getNativeYearMonth($year, $month);
29
                }
30
            }
31
        }
32
    }
33
34
    public static function type()
35
    {
36
        return 'yearmonth';
37
    }
38
39
    protected function getNativeYearMonth($year, $month)
40
    {
41
        return [$year, $month];
42
    }
43
}
44