-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathDateTime.php
140 lines (119 loc) · 2.91 KB
/
DateTime.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
<?php
/*
* Copyright 2024 Cloud Creativity Limited
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
declare(strict_types=1);
namespace LaravelJsonApi\Eloquent\Fields;
use Carbon\CarbonInterface;
use Illuminate\Support\Facades\Date;
use LaravelJsonApi\Validation\Fields\IsValidated;
use LaravelJsonApi\Validation\Fields\ValidatedWithRules;
use LaravelJsonApi\Validation\Rules\DateTimeIso8601;
use function config;
class DateTime extends Attribute implements IsValidated
{
use ValidatedWithRules;
/**
* Should dates be converted to the defined time zone?
*
* @var bool
*/
private bool $useTz = true;
/**
* @var string|null
*/
private ?string $tz = null;
/**
* Create a datetime field.
*
* @param string $fieldName
* @param string|null $column
* @return static
*/
public static function make(string $fieldName, string $column = null): self
{
return new static($fieldName, $column);
}
/**
* Use the provided timezone.
*
* @param string $tz
* @return $this
*/
public function useTimezone(string $tz): self
{
$this->tz = $tz;
$this->useTz = true;
return $this;
}
/**
* Retain the timezone provided in the JSON value.
*
* @return $this
*/
public function retainTimezone(): self
{
$this->useTz = false;
return $this;
}
/**
* Get the server-side timezone.
*
* @return string
*/
public function timezone(): string
{
if ($this->tz) {
return $this->tz;
}
return $this->tz = config('app.timezone');
}
/**
* @inheritDoc
*/
protected function deserialize($value)
{
$value = parent::deserialize($value);
return $this->parse($value);
}
/**
* Parse a date time value.
*
* @param CarbonInterface|string|null $value
* @return CarbonInterface|null
*/
protected function parse($value): ?CarbonInterface
{
if (is_null($value)) {
return null;
}
$value = is_string($value) ? Date::parse($value) : Date::instance($value);
if (true === $this->useTz) {
return $value->setTimezone($this->timezone());
}
return $value;
}
/**
* @return DateTimeIso8601[]
*/
protected function defaultRules(): array
{
return [new DateTimeIso8601()];
}
/**
* @inheritDoc
*/
protected function assertValue($value): void
{
if (!is_null($value) && (!is_string($value) || empty($value))) {
throw new \UnexpectedValueException(sprintf(
'Expecting the value of attribute %s to be a string (datetime).',
$this->name()
));
}
}
}