Completed
Pull Request — dev (#297)
by Tristan
11:17
created

BaseModel::asDateTime()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 35
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 35
rs 9.2222
c 0
b 0
f 0
cc 6
nc 6
nop 1
1
<?php
2
3
namespace App\Models;
4
5
use Reliese\Database\Eloquent\Model as Eloquent;
6
7
use Carbon\Carbon;
8
use DateTimeInterface;
9
use Jenssegers\Date\Date;
10
11
abstract class BaseModel extends Eloquent {
12
    //Override date functions to return Jenssegers Data instead of Carbon
13
14
    /**
15
     * Get a fresh timestamp for the model.
16
     *
17
     * @return Date
18
     */
19
    public function freshTimestamp()
20
    {
21
        return new Date;
22
    }
23
24
    /**
25
     * Return a timestamp as DateTime object.
26
     *
27
     * @param  mixed $value
28
     * @return Date
29
     */
30
    protected function asDateTime($value)
31
    {
32
        // If this value is already a Carbon instance, we shall just return it as is.
33
        // This prevents us having to re-instantiate a Carbon instance when we know
34
        // it already is one, which wouldn't be fulfilled by the DateTime check.
35
        if ($value instanceof Carbon) {
36
            return Date::parse($value);
37
        }
38
        if ($value instanceof Date) {
39
            return $value;
40
        }
41
        // If the value is already a DateTime instance, we will just skip the rest of
42
        // these checks since they will be a waste of time, and hinder performance
43
        // when checking the field. We will just return the DateTime right away.
44
        if ($value instanceof DateTimeInterface) {
45
            return new Date(
46
                $value->format('Y-m-d H:i:s.u'), $value->getTimeZone()
47
            );
48
        }
49
        // If this value is an integer, we will assume it is a UNIX timestamp's value
50
        // and format a Carbon object from this timestamp. This allows flexibility
51
        // when defining your date fields as they might be UNIX timestamps here.
52
        if (is_numeric($value)) {
53
            return Date::createFromTimestamp($value);
54
        }
55
        // If the value is in simply year, month, day format, we will instantiate the
56
        // Carbon instances from that format. Again, this provides for simple date
57
        // fields on the database, while still supporting Carbonized conversion.
58
        if (preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $value)) {
59
            return Date::createFromFormat('Y-m-d', $value)->startOfDay();
60
        }
61
        // Finally, we will just assume this date is in the format used by default on
62
        // the database connection and use that format to create the Carbon object
63
        // that is returned back out to the developers after we convert it here.
64
        return Date::createFromFormat($this->getDateFormat(), $value);
65
    }
66
}
67