Completed
Push — master ( f7a702...8975d9 )
by Abdelrahman
01:48 queued 11s
created

HasTimezones   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
dl 0
loc 44
rs 10
c 0
b 0
f 0
wmc 7
lcom 0
cbo 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A asDateTime() 0 20 4
A freshTimestamp() 0 8 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Rinvex\Support\Traits;
6
7
use DateTimeZone;
8
use Illuminate\Support\Arr;
9
use Illuminate\Support\Facades\Date;
10
11
trait HasTimezones
12
{
13
    /**
14
     * Return a timestamp as DateTime object.
15
     *
16
     * @param mixed $value
17
     *
18
     * @return \Illuminate\Support\Carbon
19
     */
20
    protected function asDateTime($value)
21
    {
22
        $datetime = parent::asDateTime($value);
23
        $timezone = optional(request()->user())->timezone;
24
25
        if (! $timezone || $timezone === config('app.timezone')) {
26
            return $datetime;
27
        }
28
29
        $thisIsUpdateRequest = Arr::first(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 30), function ($trace) {
0 ignored issues
show
Documentation introduced by
debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 30) is of type array, but the function expects a object<Illuminate\Support\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
30
            return $trace['function'] === 'setAttribute';
31
        });
32
33
        if ($thisIsUpdateRequest) {
34
            // When updating attributes, we need to reset user timezone to system timezone before saving!
35
            return Date::parse($datetime->toDateTimeString(), $timezone)->setTimezone(config('app.timezone'));
36
        }
37
38
        return $datetime->setTimezone(new DateTimeZone($timezone));
39
    }
40
41
    /**
42
     * Get a fresh timestamp for the model.
43
     *
44
     * @return \Illuminate\Support\Carbon
45
     */
46
    public function freshTimestamp()
47
    {
48
        $now = Date::now();
49
50
        $timezone = optional(request()->user())->timezone;
51
52
        return (! $timezone || $timezone === config('app.timezone')) ? $now : $now->setTimezone($timezone);
53
    }
54
}
55