Passed
Pull Request — master (#68)
by Sergey
07:18
created

Timezone::toLocal()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 13
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace JamesMills\LaravelTimezone;
4
5
use Carbon\Carbon;
6
7
class Timezone
8
{
9
    protected function formatTimezone(Carbon $date): string
10
    {
11
        $timezone = $date->format('e');
12
        $parts = explode('/', $timezone);
13
14
        if (count($parts) > 1) {
15
            return str_replace('_', ' ', $parts[1]) . ', ' . $parts[0];
16
        }
17
18
        return str_replace('_', ' ', $parts[0]);
19
    }
20
21
    public function toLocal(?Carbon $date): ?Carbon
22
    {
23
        if ($date === null) {
24
            return null;
25
        }
26
27
        // TODO(sergotail): use geoip timezone suggestion for non-authorized users too
28
        // (make it configurable)
29
        $timezone = auth()->user()->getTimezone() ??
30
            config('timezone.default', null) ??
31
            config('app.timezone');
32
33
        return $date->copy()->setTimezone($timezone);
34
    }
35
36
    public function convertToLocal(
37
        ?Carbon $date,
38
        ?string $format = null,
39
        bool $displayTimezone = false
40
    ): string {
41
        $date = $this->toLocal($date);
42
43
        if ($date === null) {
44
            return config('timezone.empty_date', 'Empty');
45
        }
46
47
        $formatted = $date->format($format ?? config('timezone.format', 'jS F Y g:i:a'));
48
49
        if ($displayTimezone) {
50
            return $formatted . ' ' . $this->formatTimezone($date);
51
        }
52
53
        return $formatted;
54
    }
55
56
    public function convertFromLocal($date): Carbon
57
    {
58
        return Carbon::parse($date, auth()->user()->getTimezone())->setTimezone('UTC');
59
    }
60
}
61