Passed
Pull Request — master (#53)
by
unknown
03:19
created

Timezone   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Importance

Changes 4
Bugs 1 Features 0
Metric Value
eloc 23
c 4
b 1
f 0
dl 0
loc 73
rs 10
wmc 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
A convertFromLocal() 0 3 1
A convertToLocalDiffForHumans() 0 13 2
A formatTimezone() 0 10 2
A convertToLocal() 0 21 4
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): 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
        $formatted_date_time = $date->format($format);
30
31
        if ($format_timezone) {
32
            return $formatted_date_time.' '.$this->formatTimezone($date);
33
        }
34
35
        return $formatted_date_time;
36
    }
37
38
    /**
39
     * @param  Carbon|null  $date
40
     * @return string
41
     */
42
    public function convertToLocalDiffForHumans(?Carbon $date): string
43
    {
44
        if (is_null($date)) {
45
            return 'Empty';
46
        }
47
48
        $timezone = (auth()->user()->timezone) ?? config('app.timezone');
49
50
        $date->setTimezone($timezone);
51
52
        $diffTime = Carbon::parse($date)->diffForHumans();
53
54
        return $diffTime;
55
    }
56
57
    /**
58
     * @param $date
59
     * @return Carbon
60
     */
61
    public function convertFromLocal($date): Carbon
62
    {
63
        return Carbon::parse($date, auth()->user()->timezone)->setTimezone('UTC');
64
    }
65
66
    /**
67
     * @param  Carbon  $date
68
     * @return string
69
     */
70
    private function formatTimezone(Carbon $date): string
71
    {
72
        $timezone = $date->format('e');
73
        $parts = explode('/', $timezone);
74
75
        if (count($parts) > 1) {
76
            return str_replace('_', ' ', $parts[1]).', '.$parts[0];
77
        }
78
79
        return str_replace('_', ' ', $parts[0]);
80
    }
81
}
82