Completed
Push — master ( be4243...1976df )
by Ori
19:42
created

src/Fields/DatetimeField.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
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
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