Completed
Push — master ( 86815f...7e02e6 )
by wen
02:47
created

DateTime::setFormat()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
nc 1
cc 1
eloc 3
nop 1
1
<?php
2
3
4
namespace Sco\Admin\View\Columns;
5
6
use Carbon\Carbon;
7
8
class DateTime extends Column
9
{
10
11
    /**
12
     * Datetime format.
13
     * @var string
14
     */
15
    protected $format;
16
17
    /**
18
     * Datetime timezone.
19
     * @var string
20
     */
21
    protected $timezone;
22
23
    /**
24
     * @return string
25
     */
26
    public function getFormat()
27
    {
28
        if (is_null($this->format)) {
29
            $this->format = config('admin.datetimeFormat');
30
        }
31
32
        return $this->format;
33
    }
34
35
    /**
36
     * @return string
37
     */
38
    public function getTimezone()
39
    {
40
        if (is_null($this->timezone)) {
41
            $this->timezone = config('app.timezone');
42
        }
43
44
        return $this->timezone;
45
    }
46
47
    /**
48
     * @param string $format
49
     *
50
     * @return $this
51
     */
52
    public function setFormat($format)
53
    {
54
        $this->format = $format;
55
56
        return $this;
57
    }
58
59
    /**
60
     * @param string $timezone
61
     *
62
     * @return $this
63
     */
64
    public function setTimezone($timezone)
65
    {
66
        $this->timezone = $timezone;
67
68
        return $this;
69
    }
70
71
    public function getModelValue()
72
    {
73
        $value = parent::getModelValue();
74
        return $this->getFormatValue($value);
75
    }
76
77
    public function getFormatValue($date)
78
    {
79
        if (!is_null($date)) {
80
            if (!$date instanceof Carbon) {
81
                $date = Carbon::parse($date);
82
            }
83
84
            $date->timezone($this->getTimezone());
85
86
            if ($this->getFormat() == 'humans') {
87
                $date = $date->diffForHumans();
88
            } else {
89
                $date = $date->format($this->getFormat());
90
            }
91
        }
92
93
        return $date;
94
    }
95
}
96