-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
IntlDateFormatter.php
645 lines (564 loc) · 19.7 KB
/
IntlDateFormatter.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Polyfill\Intl\Icu;
use Symfony\Polyfill\Intl\Icu\DateFormat\FullTransformer;
use Symfony\Polyfill\Intl\Icu\Exception\MethodArgumentNotImplementedException;
use Symfony\Polyfill\Intl\Icu\Exception\MethodArgumentValueNotImplementedException;
use Symfony\Polyfill\Intl\Icu\Exception\MethodNotImplementedException;
/**
* Replacement for PHP's native {@link \IntlDateFormatter} class.
*
* The only methods currently supported in this class are:
*
* - {@link __construct}
* - {@link create}
* - {@link format}
* - {@link getCalendar}
* - {@link getDateType}
* - {@link getErrorCode}
* - {@link getErrorMessage}
* - {@link getLocale}
* - {@link getPattern}
* - {@link getTimeType}
* - {@link getTimeZoneId}
* - {@link isLenient}
* - {@link parse}
* - {@link setLenient}
* - {@link setPattern}
* - {@link setTimeZoneId}
* - {@link setTimeZone}
*
* @author Igor Wiedler <igor@wiedler.ch>
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @internal
*/
abstract class IntlDateFormatter
{
/**
* The error code from the last operation.
*
* @var int
*/
protected $errorCode = Icu::U_ZERO_ERROR;
/**
* The error message from the last operation.
*
* @var string
*/
protected $errorMessage = 'U_ZERO_ERROR';
/* date/time format types */
public const NONE = -1;
public const FULL = 0;
public const LONG = 1;
public const MEDIUM = 2;
public const SHORT = 3;
/* date format types */
public const RELATIVE_FULL = 128;
public const RELATIVE_LONG = 129;
public const RELATIVE_MEDIUM = 130;
public const RELATIVE_SHORT = 131;
/* calendar formats */
public const TRADITIONAL = 0;
public const GREGORIAN = 1;
/**
* Patterns used to format the date when no pattern is provided.
*/
private $defaultDateFormats = [
self::NONE => '',
self::FULL => 'EEEE, MMMM d, y',
self::LONG => 'MMMM d, y',
self::MEDIUM => 'MMM d, y',
self::SHORT => 'M/d/yy',
self::RELATIVE_FULL => 'EEEE, MMMM d, y',
self::RELATIVE_LONG => 'MMMM d, y',
self::RELATIVE_MEDIUM => 'MMM d, y',
self::RELATIVE_SHORT => 'M/d/yy',
];
/**
* Patterns used to format the time when no pattern is provided.
*/
private $defaultTimeFormats = [
self::FULL => 'h:mm:ss a zzzz',
self::LONG => 'h:mm:ss a z',
self::MEDIUM => 'h:mm:ss a',
self::SHORT => 'h:mm a',
];
private $dateType;
private $timeType;
/**
* @var string
*/
private $pattern;
/**
* @var \DateTimeZone
*/
private $dateTimeZone;
/**
* @var bool
*/
private $uninitializedTimeZoneId = false;
/**
* @var string
*/
private $timezoneId;
/**
* @var bool
*/
private $isRelativeDateType = false;
/**
* @param string|null $locale The locale code. The only currently supported locale is "en" (or null using the default locale, i.e. "en")
* @param \IntlTimeZone|\DateTimeZone|string|null $timezone Timezone identifier
* @param \IntlCalendar|int|null $calendar Calendar to use for formatting or parsing. The only currently
* supported value is IntlDateFormatter::GREGORIAN (or null using the default calendar, i.e. "GREGORIAN")
*
* @see https://php.net/intldateformatter.create
* @see http://userguide.icu-project.org/formatparse/datetime
*
* @throws MethodArgumentValueNotImplementedException When $locale different than "en" or null is passed
* @throws MethodArgumentValueNotImplementedException When $calendar different than GREGORIAN is passed
*/
public function __construct(?string $locale, ?int $dateType, ?int $timeType, $timezone = null, $calendar = null, ?string $pattern = '')
{
if ('en' !== $locale && null !== $locale) {
throw new MethodArgumentValueNotImplementedException(__METHOD__, 'locale', $locale, 'Only the locale "en" is supported');
}
if (self::GREGORIAN !== $calendar && null !== $calendar) {
throw new MethodArgumentValueNotImplementedException(__METHOD__, 'calendar', $calendar, 'Only the GREGORIAN calendar is supported');
}
if (\PHP_VERSION_ID >= 80100) {
if (null === $dateType) {
@trigger_error('Passing null to parameter #2 ($dateType) of type int is deprecated', \E_USER_DEPRECATED);
}
if (null === $timeType) {
@trigger_error('Passing null to parameter #3 ($timeType) of type int is deprecated', \E_USER_DEPRECATED);
}
}
$this->dateType = $dateType ?? self::FULL;
$this->timeType = $timeType ?? self::FULL;
if ('' === ($pattern ?? '')) {
$pattern = $this->getDefaultPattern();
}
$this->setPattern($pattern);
$this->setTimeZone($timezone);
if (\in_array($this->dateType, [self::RELATIVE_FULL, self::RELATIVE_LONG, self::RELATIVE_MEDIUM, self::RELATIVE_SHORT], true)) {
$this->isRelativeDateType = true;
}
}
/**
* Static constructor.
*
* @param string|null $locale The locale code. The only currently supported locale is "en" (or null using the default locale, i.e. "en")
* @param \IntlTimeZone|\DateTimeZone|string|null $timezone Timezone identifier
* @param \IntlCalendar|int|null $calendar Calendar to use for formatting or parsing; default is Gregorian
* One of the calendar constants
*
* @return static
*
* @see https://php.net/intldateformatter.create
* @see http://userguide.icu-project.org/formatparse/datetime
*
* @throws MethodArgumentValueNotImplementedException When $locale different than "en" or null is passed
* @throws MethodArgumentValueNotImplementedException When $calendar different than GREGORIAN is passed
*/
public static function create(?string $locale, ?int $dateType, ?int $timeType, $timezone = null, ?int $calendar = null, ?string $pattern = '')
{
return new static($locale, $dateType, $timeType, $timezone, $calendar, $pattern);
}
/**
* Format the date/time value (timestamp) as a string.
*
* @param int|string|\DateTimeInterface $datetime The timestamp to format
*
* @return string|false The formatted value or false if formatting failed
*
* @see https://php.net/intldateformatter.format
*
* @throws MethodArgumentValueNotImplementedException If one of the formatting characters is not implemented
*/
public function format($datetime)
{
// intl allows timestamps to be passed as arrays - we don't
if (\is_array($datetime)) {
$message = 'Only Unix timestamps and DateTime objects are supported';
throw new MethodArgumentValueNotImplementedException(__METHOD__, 'datetime', $datetime, $message);
}
if (\is_string($datetime) && $dt = \DateTime::createFromFormat('U', $datetime)) {
$datetime = $dt;
}
// behave like the intl extension
$argumentError = null;
if (!\is_int($datetime) && !$datetime instanceof \DateTimeInterface) {
$argumentError = sprintf('datefmt_format: string \'%s\' is not numeric, which would be required for it to be a valid date', $datetime);
}
if (null !== $argumentError) {
Icu::setError(Icu::U_ILLEGAL_ARGUMENT_ERROR, $argumentError);
$this->errorCode = Icu::getErrorCode();
$this->errorMessage = Icu::getErrorMessage();
return false;
}
if ($datetime instanceof \DateTimeInterface) {
$datetime = $datetime->format('U');
}
$pattern = $this->getPattern();
$formatted = '';
if ($this->isRelativeDateType && $formatted = $this->getRelativeDateFormat($datetime)) {
if (self::NONE === $this->timeType) {
$pattern = '';
} else {
$pattern = $this->defaultTimeFormats[$this->timeType];
if (\in_array($this->dateType, [self::RELATIVE_MEDIUM, self::RELATIVE_SHORT], true)) {
$formatted .= ', ';
} else {
$formatted .= ' at ';
}
}
}
$transformer = new FullTransformer($pattern, $this->getTimeZoneId());
$formatted .= $transformer->format($this->createDateTime($datetime));
// behave like the intl extension
Icu::setError(Icu::U_ZERO_ERROR);
$this->errorCode = Icu::getErrorCode();
$this->errorMessage = Icu::getErrorMessage();
return $formatted;
}
/**
* Not supported. Formats an object.
*
* @return string The formatted value
*
* @see https://php.net/intldateformatter.formatobject
*
* @throws MethodNotImplementedException
*/
public static function formatObject($datetime, $format = null, ?string $locale = null)
{
throw new MethodNotImplementedException(__METHOD__);
}
/**
* Returns the formatter's calendar.
*
* @return int The calendar being used by the formatter. Currently always returns
* IntlDateFormatter::GREGORIAN.
*
* @see https://php.net/intldateformatter.getcalendar
*/
public function getCalendar()
{
return self::GREGORIAN;
}
/**
* Not supported. Returns the formatter's calendar object.
*
* @return object The calendar's object being used by the formatter
*
* @see https://php.net/intldateformatter.getcalendarobject
*
* @throws MethodNotImplementedException
*/
public function getCalendarObject()
{
throw new MethodNotImplementedException(__METHOD__);
}
/**
* Returns the formatter's datetype.
*
* @return int The current value of the formatter
*
* @see https://php.net/intldateformatter.getdatetype
*/
public function getDateType()
{
return $this->dateType;
}
/**
* Returns formatter's last error code. Always returns the U_ZERO_ERROR class constant value.
*
* @return int The error code from last formatter call
*
* @see https://php.net/intldateformatter.geterrorcode
*/
public function getErrorCode()
{
return $this->errorCode;
}
/**
* Returns formatter's last error message. Always returns the U_ZERO_ERROR_MESSAGE class constant value.
*
* @return string The error message from last formatter call
*
* @see https://php.net/intldateformatter.geterrormessage
*/
public function getErrorMessage()
{
return $this->errorMessage;
}
/**
* Returns the formatter's locale.
*
* @param int $type Not supported. The locale name type to return (Locale::VALID_LOCALE or Locale::ACTUAL_LOCALE)
*
* @return string The locale used to create the formatter. Currently always
* returns "en".
*
* @see https://php.net/intldateformatter.getlocale
*/
public function getLocale(int $type = Locale::ACTUAL_LOCALE)
{
return 'en';
}
/**
* Returns the formatter's pattern.
*
* @return string The pattern string used by the formatter
*
* @see https://php.net/intldateformatter.getpattern
*/
public function getPattern()
{
return $this->pattern;
}
/**
* Returns the formatter's time type.
*
* @return int The time type used by the formatter
*
* @see https://php.net/intldateformatter.gettimetype
*/
public function getTimeType()
{
return $this->timeType;
}
/**
* Returns the formatter's timezone identifier.
*
* @return string The timezone identifier used by the formatter
*
* @see https://php.net/intldateformatter.gettimezoneid
*/
public function getTimeZoneId()
{
if (!$this->uninitializedTimeZoneId) {
return $this->timezoneId;
}
return date_default_timezone_get();
}
/**
* Not supported. Returns the formatter's timezone.
*
* @return mixed The timezone used by the formatter
*
* @see https://php.net/intldateformatter.gettimezone
*
* @throws MethodNotImplementedException
*/
public function getTimeZone()
{
throw new MethodNotImplementedException(__METHOD__);
}
/**
* Returns whether the formatter is lenient.
*
* @return bool Currently always returns false
*
* @see https://php.net/intldateformatter.islenient
*
* @throws MethodNotImplementedException
*/
public function isLenient()
{
return false;
}
/**
* Not supported. Parse string to a field-based time value.
*
* @return string Localtime compatible array of integers: contains 24 hour clock value in tm_hour field
*
* @see https://php.net/intldateformatter.localtime
*
* @throws MethodNotImplementedException
*/
public function localtime(string $string, &$offset = null)
{
throw new MethodNotImplementedException(__METHOD__);
}
/**
* Parse string to a timestamp value.
*
* @return int|false Parsed value as a timestamp
*
* @see https://php.net/intldateformatter.parse
*
* @throws MethodArgumentNotImplementedException When $offset different than null, behavior not implemented
*/
public function parse(string $string, &$offset = null)
{
// We don't calculate the position when parsing the value
if (null !== $offset) {
throw new MethodArgumentNotImplementedException(__METHOD__, 'offset');
}
$dateTime = $this->createDateTime(0);
$transformer = new FullTransformer($this->getPattern(), $this->getTimeZoneId());
$timestamp = $transformer->parse($dateTime, $string);
// behave like the intl extension. FullTransformer::parse() set the proper error
$this->errorCode = Icu::getErrorCode();
$this->errorMessage = Icu::getErrorMessage();
return $timestamp;
}
/**
* Not supported. Set the formatter's calendar.
*
* @param \IntlCalendar|int|null $calendar
*
* @return bool true on success or false on failure
*
* @see https://php.net/intldateformatter.setcalendar
*
* @throws MethodNotImplementedException
*/
public function setCalendar($calendar)
{
throw new MethodNotImplementedException(__METHOD__);
}
/**
* Set the leniency of the parser.
*
* Define if the parser is strict or lenient in interpreting inputs that do not match the pattern
* exactly. Enabling lenient parsing allows the parser to accept otherwise flawed date or time
* patterns, parsing as much as possible to obtain a value. Extra space, unrecognized tokens, or
* invalid values ("February 30th") are not accepted.
*
* @param bool $lenient Sets whether the parser is lenient or not. Currently
* only false (strict) is supported.
*
* @return bool true on success or false on failure
*
* @see https://php.net/intldateformatter.setlenient
*
* @throws MethodArgumentValueNotImplementedException When $lenient is true
*/
public function setLenient(bool $lenient)
{
if ($lenient) {
throw new MethodArgumentValueNotImplementedException(__METHOD__, 'lenient', $lenient, 'Only the strict parser is supported');
}
return true;
}
/**
* Set the formatter's pattern.
*
* @return bool true on success or false on failure
*
* @see https://php.net/intldateformatter.setpattern
* @see http://userguide.icu-project.org/formatparse/datetime
*/
public function setPattern(string $pattern)
{
$this->pattern = $pattern;
return true;
}
/**
* Sets formatterʼs timezone.
*
* @param \IntlTimeZone|\DateTimeZone|string|null $timezone
*
* @return bool true on success or false on failure
*
* @see https://php.net/intldateformatter.settimezone
*/
public function setTimeZone($timezone)
{
if ($timezone instanceof \IntlTimeZone) {
$timezone = $timezone->getID();
}
if ($timezone instanceof \DateTimeZone) {
$timezone = $timezone->getName();
// DateTimeZone returns the GMT offset timezones without the leading GMT, while our parsing requires it.
if (!empty($timezone) && ('+' === $timezone[0] || '-' === $timezone[0])) {
$timezone = 'GMT'.$timezone;
}
}
if (null === $timezone) {
$timezone = date_default_timezone_get();
$this->uninitializedTimeZoneId = true;
}
// Backup original passed time zone
$timezoneId = $timezone;
// Get an Etc/GMT time zone that is accepted for \DateTimeZone
if ('GMT' !== $timezone && 0 === strpos($timezone, 'GMT')) {
try {
$timezone = DateFormat\TimezoneTransformer::getEtcTimeZoneId($timezone);
} catch (\InvalidArgumentException $e) {
// Does nothing, will fallback to UTC
}
}
try {
$this->dateTimeZone = new \DateTimeZone($timezone);
if ('GMT' !== $timezone && $this->dateTimeZone->getName() !== $timezone) {
$timezoneId = $this->getTimeZoneId();
}
} catch (\Exception $e) {
$timezoneId = $timezone = $this->getTimeZoneId();
$this->dateTimeZone = new \DateTimeZone($timezone);
}
$this->timezoneId = $timezoneId;
return true;
}
/**
* Create and returns a DateTime object with the specified timestamp and with the
* current time zone.
*
* @return \DateTime
*/
protected function createDateTime($timestamp)
{
$dateTime = \DateTime::createFromFormat('U', $timestamp);
$dateTime->setTimezone($this->dateTimeZone);
return $dateTime;
}
/**
* Returns a pattern string based in the datetype and timetype values.
*
* @return string
*/
protected function getDefaultPattern()
{
$pattern = '';
if (self::NONE !== $this->dateType) {
$pattern = $this->defaultDateFormats[$this->dateType];
}
if (self::NONE !== $this->timeType) {
if (\in_array($this->dateType, [self::FULL, self::LONG, self::RELATIVE_FULL, self::RELATIVE_LONG], true)) {
$pattern .= ' \'at\' ';
} elseif (self::NONE !== $this->dateType) {
$pattern .= ', ';
}
$pattern .= $this->defaultTimeFormats[$this->timeType];
}
return $pattern;
}
private function getRelativeDateFormat(int $timestamp): string
{
$today = $this->createDateTime(time());
$today->setTime(0, 0, 0);
$datetime = $this->createDateTime($timestamp);
$datetime->setTime(0, 0, 0);
$interval = $today->diff($datetime);
if (false !== $interval) {
if (0 === $interval->days) {
return 'today';
}
if (1 === $interval->days) {
return 1 === $interval->invert ? 'yesterday' : 'tomorrow';
}
}
return '';
}
}