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

src/Fields/DateField.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 DateField extends BaseField
8
{
9
    protected function validateCastValue($val)
10
    {
11
        switch ($this->format()) {
12
            case 'default':
0 ignored issues
show
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
13
                try {
14
                    list($year, $month, $day) = explode('-', $val);
15
16
                    return Carbon::create($year, $month, $day, 0, 0, 0, 'UTC');
17
                } catch (\Exception $e) {
18
                    throw $this->getValidationException($e->getMessage(), $val);
19
                }
20
            case 'any':
0 ignored issues
show
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
21
                try {
22
                    $date = new Carbon($val);
23
                    $date->setTime(0, 0, 0);
24
25
                    return $date;
26
                } catch (\Exception $e) {
27
                    throw $this->getValidationException($e->getMessage(), $val);
28
                }
29
            default:
30
                $date = strptime($val, $this->format());
31
                if ($date === false || $date['unparsed'] != '') {
32
                    throw $this->getValidationException("couldn't parse date/time according to given strptime format '{$this->format()}''", $val);
33
                } else {
34
                    return Carbon::create(
35
                        (int) $date['tm_year'] + 1900, (int) $date['tm_mon'] + 1, (int) $date['tm_mday'],
36
                        0, 0, 0
37
                    );
38
                }
39
        }
40
    }
41
42
    public static function type()
43
    {
44
        return 'date';
45
    }
46
}
47