HasTimezones::asDateTime()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 3
nop 1
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
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