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

DatetimeField::validateCastValue()   C

Complexity

Conditions 8
Paths 11

Size

Total Lines 37
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 28
nc 11
nop 1
dl 0
loc 37
rs 5.3846
c 0
b 0
f 0
1
<?php
2
3
namespace frictionlessdata\tableschema\Fields;
4
5
use Carbon\Carbon;
6
7
class DatetimeField extends BaseField
8
{
9
    protected function validateCastValue($val)
10
    {
11
        $val = trim($val);
12
        switch ($this->format()) {
13
            case 'default':
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
14
                if (substr($val, -1) != 'Z') {
15
                    throw $this->getValidationException('must have trailing Z', $val);
16
                } else {
17
                    try {
18
                        $val = rtrim($val, 'Z');
19
                        $val = explode('T', $val);
20
                        list($year, $month, $day) = explode('-', $val[0]);
21
                        list($hour, $minute, $second) = explode(':', $val[1]);
22
23
                        return Carbon::create($year, $month, $day, $hour, $minute, $second, 'UTC');
24
                    } catch (\Exception $e) {
25
                        throw $this->getValidationException($e->getMessage(), $val);
26
                    }
27
                }
28
            case 'any':
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
29
                try {
30
                    return new Carbon($val);
31
                } catch (\Exception $e) {
32
                    throw $this->getValidationException($e->getMessage(), $val);
33
                }
34
            default:
35
                $date = strptime($val, $this->format());
36
                if ($date === false || $date['unparsed'] != '') {
37
                    throw $this->getValidationException("couldn't parse date/time according to given strptime format '{$this->format()}''", $val);
38
                } else {
39
                    return Carbon::create(
40
                        (int) $date['tm_year'] + 1900, (int) $date['tm_mon'] + 1, (int) $date['tm_mday'],
41
                        (int) $date['tm_hour'], (int) $date['tm_min'], (int) $date['tm_sec']
42
                    );
43
                }
44
        }
45
    }
46
47
    public static function type()
48
    {
49
        return 'datetime';
50
    }
51
}
52