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

DateField::type()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
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
Coding Style introduced by
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
Coding Style introduced by
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