-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
DateTimeWidget.php
245 lines (219 loc) · 7.67 KB
/
DateTimeWidget.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\View\Widget;
use Cake\Chronos\ChronosDate;
use Cake\Chronos\ChronosTime;
use Cake\Database\Schema\TableSchemaInterface;
use Cake\View\Form\ContextInterface;
use Cake\View\StringTemplate;
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use DateTimeZone;
use Exception;
use InvalidArgumentException;
/**
* Input widget class for generating a date time input widget.
*
* This class is usually used internally by `Cake\View\Helper\FormHelper`,
* it but can be used to generate standalone date time inputs.
*/
class DateTimeWidget extends BasicWidget
{
/**
* Template instance.
*
* @var \Cake\View\StringTemplate
*/
protected StringTemplate $_templates;
/**
* Data defaults.
*
* @var array<string, mixed>
*/
protected array $defaults = [
'name' => '',
'val' => null,
'type' => 'datetime-local',
'escape' => true,
'timezone' => null,
'templateVars' => [],
];
/**
* Formats for various input types.
*
* @var array<string>
*/
protected array $formatMap = [
'datetime-local' => 'Y-m-d\TH:i:s',
'date' => 'Y-m-d',
'time' => 'H:i:s',
'month' => 'Y-m',
'week' => 'Y-\WW',
];
/**
* Step size for various input types.
*
* If not set, defaults to browser default.
*
* @var array<string, mixed>
*/
protected array $defaultStep = [
'datetime-local' => '1',
'date' => null,
'time' => '1',
'month' => null,
'week' => null,
];
/**
* Render a date / time form widget.
*
* Data supports the following keys:
*
* - `name` The name attribute.
* - `val` The value attribute.
* - `escape` Set to false to disable escaping on all attributes.
* - `type` A valid HTML date/time input type. Defaults to "datetime-local".
* - `timezone` The timezone the input value should be converted to.
* - `step` The "step" attribute. Defaults to `1` for "time" and "datetime-local" type inputs.
* You can set it to `null` or `false` to prevent explicit step attribute being added in HTML.
* - `format` A `date()` function compatible datetime format string.
* By default, the widget will use a suitable format based on the input type and
* database type for the context. If an explicit format is provided, then no
* default value will be set for the `step` attribute, and it needs to be
* explicitly set if required.
*
* All other keys will be converted into HTML attributes.
*
* @param array<string, mixed> $data The data to build a file input with.
* @param \Cake\View\Form\ContextInterface $context The current form context.
* @return string HTML elements.
*/
public function render(array $data, ContextInterface $context): string
{
$data += $this->mergeDefaults($data, $context);
if (!isset($this->formatMap[$data['type']])) {
throw new InvalidArgumentException(sprintf(
'Invalid type `%s` for input tag, expected datetime-local, date, time, month or week',
$data['type']
));
}
$data = $this->setStep($data, $context, $data['fieldName'] ?? '');
$data['value'] = $this->formatDateTime($data['val'] === true ? new DateTimeImmutable() : $data['val'], $data);
unset($data['val'], $data['timezone'], $data['format']);
return $this->_templates->format('input', [
'name' => $data['name'],
'type' => $data['type'],
'templateVars' => $data['templateVars'],
'attrs' => $this->_templates->formatAttributes(
$data,
['name', 'type']
),
]);
}
/**
* Set value for "step" attribute if applicable.
*
* @param array<string, mixed> $data Data array
* @param \Cake\View\Form\ContextInterface $context Context instance.
* @param string $fieldName Field name.
* @return array<string, mixed> Updated data array.
*/
protected function setStep(array $data, ContextInterface $context, string $fieldName): array
{
if (array_key_exists('step', $data)) {
return $data;
}
if (isset($data['format'])) {
$data['step'] = null;
} else {
$data['step'] = $this->defaultStep[$data['type']];
}
if (empty($data['fieldName'])) {
return $data;
}
$dbType = $context->type($fieldName);
$fractionalTypes = [
TableSchemaInterface::TYPE_DATETIME_FRACTIONAL,
TableSchemaInterface::TYPE_TIMESTAMP_FRACTIONAL,
TableSchemaInterface::TYPE_TIMESTAMP_TIMEZONE,
];
if (in_array($dbType, $fractionalTypes, true)) {
$data['step'] = '0.001';
}
return $data;
}
/**
* Formats the passed date/time value into required string format.
*
* @param \Cake\Chronos\ChronosDate|\Cake\Chronos\ChronosTime|\DateTimeInterface|string|int|null $value Value to deconstruct.
* @param array<string, mixed> $options Options for conversion.
* @return string
* @throws \InvalidArgumentException If invalid input type is passed.
*/
protected function formatDateTime(
ChronosDate|ChronosTime|DateTimeInterface|string|int|null $value,
array $options
): string {
if ($value === '' || $value === null) {
return '';
}
try {
if ($value instanceof DateTimeInterface || $value instanceof ChronosDate || $value instanceof ChronosTime) {
/** @var \Cake\Chronos\ChronosDate|\DateTime|\DateTimeImmutable $dateTime Expand type for phpstan */
$dateTime = clone $value;
} elseif (is_string($value) && !is_numeric($value)) {
$dateTime = new DateTime($value);
} elseif (is_numeric($value)) {
$dateTime = new DateTime('@' . $value);
} else {
$dateTime = new DateTime();
}
} catch (Exception) {
$dateTime = new DateTime();
}
if (isset($options['timezone'])) {
$timezone = $options['timezone'];
if (!$timezone instanceof DateTimeZone) {
$timezone = new DateTimeZone($timezone);
}
$dateTime = $dateTime->setTimezone($timezone);
}
if (isset($options['format'])) {
$format = $options['format'];
} else {
$format = $this->formatMap[$options['type']];
if (
$options['type'] === 'datetime-local'
&& is_numeric($options['step'])
&& $options['step'] < 1
) {
$format = 'Y-m-d\TH:i:s.v';
}
}
return $dateTime->format($format);
}
/**
* @inheritDoc
*/
public function secureFields(array $data): array
{
if (!isset($data['name']) || $data['name'] === '') {
return [];
}
return [$data['name']];
}
}