/
DateTimeType.php
309 lines (274 loc) · 8.5 KB
/
DateTimeType.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Database\Type;
use Cake\Database\Driver;
use Cake\Database\TypeInterface;
use DateTimeInterface;
use Exception;
use PDO;
use RuntimeException;
/**
* Datetime type converter.
*
* Use to convert datetime instances to strings & back.
*/
class DateTimeType implements TypeInterface
{
/**
* The class to use for representing date objects
*
* This property can only be used before an instance of this type
* class is constructed. After that use `useMutable()` or `useImmutable()` instead.
*
* @var string
* @deprecated Use DateTimeType::useMutable() or DateTimeType::useImmutable() instead.
*/
public static $dateTimeClass = 'Cake\I18n\Time';
/**
* String format to use for DateTime parsing
*
* @var string
*/
protected $_format = 'Y-m-d H:i:s';
/**
* Whether dates should be parsed using a locale aware parser
* when marshalling string inputs.
*
* @var bool
*/
protected $_useLocaleParser = false;
/**
* The date format to use for parsing incoming dates for marshalling.
*
* @var string|array|int
*/
protected $_localeFormat;
/**
* An instance of the configured dateTimeClass, used to quickly generate
* new instances without calling the constructor.
*
* @var \DateTime
*/
protected $_datetimeInstance;
/**
* The classname to use when creating objects.
*
* @var string
*/
protected $_className;
/**
* Identifier name for this type
*
* @var string|null
*/
protected $_name = null;
/**
* {@inheritDoc}
*/
public function __construct($name = null)
{
$this->_name = $name;
$this->_setClassName(static::$dateTimeClass, 'DateTime');
}
/**
* Convert DateTime instance into strings.
*
* @param string|int|\DateTime $value The value to convert.
* @param \Cake\Database\Driver $driver The driver instance to convert with.
* @return string
*/
public function toDatabase($value, Driver $driver)
{
if ($value === null || is_string($value)) {
return $value;
}
if (is_int($value)) {
$class = $this->_className;
$value = new $class('@' . $value);
}
return $value->format($this->_format);
}
/**
* Convert strings into DateTime instances.
*
* @param string $value The value to convert.
* @param \Cake\Database\Driver $driver The driver instance to convert with.
* @return \Cake\I18n\Time|\DateTime
*/
public function toPHP($value, Driver $driver)
{
if ($value === null || strpos($value, '0000-00-00') === 0) {
return null;
}
if (strpos($value, '.') !== false) {
list($value) = explode('.', $value);
}
$instance = clone $this->_datetimeInstance;
return $instance->modify($value);
}
/**
* Convert request data into a datetime object.
*
* @param mixed $value Request data
* @return \Cake\I18n\Time|\DateTime
*/
public function marshal($value)
{
if ($value instanceof DateTimeInterface) {
return $value;
}
$class = $this->_className;
try {
$compare = $date = false;
if ($value === '' || $value === null || $value === false || $value === true) {
return null;
} elseif (is_numeric($value)) {
$date = new $class('@' . $value);
} elseif (is_string($value) && $this->_useLocaleParser) {
return $this->_parseValue($value);
} elseif (is_string($value)) {
$date = new $class($value);
$compare = true;
}
if ($compare && $date && $date->format($this->_format) !== $value) {
return $value;
}
if ($date) {
return $date;
}
} catch (Exception $e) {
return $value;
}
if (is_array($value) && implode('', $value) === '') {
return null;
}
$value += ['hour' => 0, 'minute' => 0, 'second' => 0];
$format = '';
if (isset($value['year'], $value['month'], $value['day']) &&
(is_numeric($value['year']) && is_numeric($value['month']) && is_numeric($value['day']))
) {
$format .= sprintf('%d-%02d-%02d', $value['year'], $value['month'], $value['day']);
}
if (isset($value['meridian']) && (int)$value['hour'] === 12) {
$value['hour'] = 0;
}
if (isset($value['meridian'])) {
$value['hour'] = strtolower($value['meridian']) === 'am' ? $value['hour'] : $value['hour'] + 12;
}
$format .= sprintf(
'%s%02d:%02d:%02d',
empty($format) ? '' : ' ',
$value['hour'],
$value['minute'],
$value['second']
);
$tz = isset($value['timezone']) ? $value['timezone'] : null;
return new $class($format, $tz);
}
/**
* Sets whether or not to parse dates passed to the marshal() function
* by using a locale aware parser.
*
* @param bool $enable Whether or not to enable
* @return $this
*/
public function useLocaleParser($enable = true)
{
if ($enable === false) {
$this->_useLocaleParser = $enable;
return $this;
}
if (method_exists($this->_className, 'parseDateTime')) {
$this->_useLocaleParser = $enable;
return $this;
}
throw new RuntimeException(
sprintf('Cannot use locale parsing with the %s class', $this->_className)
);
}
/**
* Sets the format string to use for parsing dates in this class. The formats
* that are accepted are documented in the `Cake\I18n\Time::parseDateTime()`
* function.
*
* @param string|array $format The format in which the string are passed.
* @see \Cake\I18n\Time::parseDateTime()
* @return $this
*/
public function setLocaleFormat($format)
{
$this->_localeFormat = $format;
return $this;
}
/**
* Change the preferred class name to the FrozenTime implementation.
*
* @return $this
*/
public function useImmutable()
{
$this->_setClassName('Cake\I18n\FrozenTime', 'DateTimeImmutable');
return $this;
}
/**
* Set the classname to use when building objects.
*
* @param string $class The classname to use.
* @param string $fallback The classname to use when the preferred class does not exist.
* @return void
*/
protected function _setClassName($class, $fallback)
{
if (!class_exists($class)) {
$class = $fallback;
}
$this->_className = $class;
$this->_datetimeInstance = new $this->_className;
}
/**
* Change the preferred class name to the mutable Time implementation.
*
* @return $this
*/
public function useMutable()
{
$this->_setClassName('Cake\I18n\Time', 'DateTime');
return $this;
}
/**
* Converts a string into a DateTime object after parsing it using the locale
* aware parser with the specified format.
*
* @param string $value The value to parse and convert to an object.
* @return \Cake\I18n\Time|null
*/
protected function _parseValue($value)
{
$class = $this->_className;
return $class::parseDateTime($value, $this->_localeFormat);
}
/**
* Casts given value to Statement equivalent
*
* @param mixed $value value to be converted to PDO statement
* @param \Cake\Database\Driver $driver object from which database preferences and configuration will be extracted
*
* @return mixed
*/
public function toStatement($value, Driver $driver)
{
return PDO::PARAM_STR;
}
}