Passed
Pull Request — master (#63)
by James
11:28 queued 06:14
created

Timezone   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Importance

Changes 6
Bugs 1 Features 0
Metric Value
eloc 20
c 6
b 1
f 0
dl 0
loc 67
rs 10
wmc 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
A formatTimezone() 0 10 2
A convertFromLocal() 0 3 1
A convertToLocal() 0 25 5
A convertToLocalDiffForHumans() 0 3 1
1
<?php
2
3
namespace JamesMills\LaravelTimezone;
4
5
use Carbon\Carbon;
6
7
class Timezone
8
{
9
    /**
10
     * @param  Carbon|null  $date
11
     * @param  null  $format
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $format is correct as it would always require null to be passed?
Loading history...
12
     * @param  bool  $format_timezone
13
     * @return string
14
     */
15
    public function convertToLocal(?Carbon $date, $format = null, $format_timezone = false, $diff_for_humans = false): string
16
    {
17
        if (is_null($date)) {
18
            return 'Empty';
19
        }
20
21
        $timezone = (auth()->user()->timezone) ?? config('app.timezone');
22
23
        $date->setTimezone($timezone);
24
25
        if (is_null($format)) {
0 ignored issues
show
introduced by
The condition is_null($format) is always true.
Loading history...
26
            return $date->format(config('timezone.format'));
27
        }
28
29
        if ($diff_for_humans) {
30
            return $date->diffForHumans();
31
        }
32
33
        $formatted_date_time = $date->format($format);
34
35
        if ($format_timezone) {
36
            return $formatted_date_time . ' ' . $this->formatTimezone($date);
37
        }
38
39
        return $formatted_date_time;
40
    }
41
42
    /**
43
     * @param  Carbon|null  $date
44
     * @return string
45
     */
46
    public function convertToLocalDiffForHumans(?Carbon $date): string
47
    {
48
        return $this->convertToLocal($date, null, false, true);
49
    }
50
51
    /**
52
     * @param $date
53
     * @return Carbon
54
     */
55
    public function convertFromLocal($date): Carbon
56
    {
57
        return Carbon::parse($date, auth()->user()->timezone)->setTimezone('UTC');
58
    }
59
60
    /**
61
     * @param  Carbon  $date
62
     * @return string
63
     */
64
    private function formatTimezone(Carbon $date): string
65
    {
66
        $timezone = $date->format('e');
67
        $parts = explode('/', $timezone);
68
69
        if (count($parts) > 1) {
70
            return str_replace('_', ' ', $parts[1]) . ', ' . $parts[0];
71
        }
72
73
        return str_replace('_', ' ', $parts[0]);
74
    }
75
}
76