DateTimePlus.php 22.5 KB
Newer Older
1 2 3
<?php

namespace Drupal\Component\Datetime;
4

5
use Drupal\Component\Utility\ToStringTrait;
6 7

/**
8
 * Wraps DateTime().
9
 *
10
 * This class wraps the PHP DateTime class with more flexible initialization
11 12 13 14 15
 * parameters, allowing a date to be created from an existing date object,
 * a timestamp, a string with an unknown format, a string with a known
 * format, or an array of date parts. It also adds an errors array
 * and a __toString() method to the date object.
 *
16
 * This class is less lenient than the DateTime class. It changes
17
 * the default behavior for handling date values like '2011-00-00'.
18
 * The DateTime class would convert that value to '2010-11-30' and report
19 20
 * a warning but not an error. This extension treats that as an error.
 *
21
 * As with the DateTime class, a date object may be created even if it has
22 23 24 25
 * errors. It has an errors array attached to it that explains what the
 * errors are. This is less disruptive than allowing datetime exceptions
 * to abort processing. The calling script can decide what to do about
 * errors using hasErrors() and getErrors().
26 27 28 29 30 31 32 33 34 35 36 37 38
 *
 * @method $this add(\DateInterval $interval)
 * @method static array getLastErrors()
 * @method $this modify(string $modify)
 * @method $this setDate(int $year, int $month, int $day)
 * @method $this setISODate(int $year, int $week, int $day = 1)
 * @method $this setTime(int $hour, int $minute, int $second = 0, int $microseconds = 0)
 * @method $this setTimestamp(int $unixtimestamp)
 * @method $this setTimezone(\DateTimeZone $timezone)
 * @method $this sub(\DateInterval $interval)
 * @method int getOffset()
 * @method int getTimestamp()
 * @method \DateTimeZone getTimezone()
39
 */
40
class DateTimePlus {
41

42 43
  use ToStringTrait;

44 45
  const FORMAT   = 'Y-m-d H:i:s';

46 47 48 49 50 51 52 53 54
  /**
   * A RFC7231 Compliant date.
   *
   * http://tools.ietf.org/html/rfc7231#section-7.1.1.1
   *
   * Example: Sun, 06 Nov 1994 08:49:37 GMT
   */
  const RFC7231 = 'D, d M Y H:i:s \G\M\T';

55 56 57
  /**
   * An array of possible date parts.
   */
58
  protected static $dateParts = [
59 60 61 62 63 64
    'year',
    'month',
    'day',
    'hour',
    'minute',
    'second',
65
  ];
66 67 68

  /**
   * The value of the time value passed to the constructor.
69 70
   *
   * @var string
71 72 73 74 75
   */
  protected $inputTimeRaw = '';

  /**
   * The prepared time, without timezone, for this date.
76 77
   *
   * @var string
78 79 80 81 82
   */
  protected $inputTimeAdjusted = '';

  /**
   * The value of the timezone passed to the constructor.
83 84
   *
   * @var string
85 86 87 88 89
   */
  protected $inputTimeZoneRaw = '';

  /**
   * The prepared timezone object used to construct this date.
90 91
   *
   * @var string
92 93 94 95 96
   */
  protected $inputTimeZoneAdjusted = '';

  /**
   * The value of the format passed to the constructor.
97 98
   *
   * @var string
99 100 101 102 103
   */
  protected $inputFormatRaw = '';

  /**
   * The prepared format, if provided.
104 105
   *
   * @var string
106 107 108 109 110 111 112 113 114 115 116
   */
  protected $inputFormatAdjusted = '';

  /**
   * The value of the language code passed to the constructor.
   */
  protected $langcode = NULL;

  /**
   * An array of errors encountered when creating this date.
   */
117
  protected $errors = [];
118

119 120 121 122 123 124 125
  /**
   * The DateTime object.
   *
   * @var \DateTime
   */
  protected $dateTimeObject = NULL;

126 127
  /**
   * Creates a date object from an input date object.
128
   *
129 130 131 132
   * @param \DateTime $datetime
   *   A DateTime object.
   * @param array $settings
   *   @see __construct()
133 134 135
   *
   * @return static
   *   A new DateTimePlus object.
136
   */
137
  public static function createFromDateTime(\DateTime $datetime, $settings = []) {
138 139 140 141 142 143 144 145 146 147
    return new static($datetime->format(static::FORMAT), $datetime->getTimezone(), $settings);
  }

  /**
   * Creates a date object from an array of date parts.
   *
   * Converts the input value into an ISO date, forcing a full ISO
   * date even if some values are missing.
   *
   * @param array $date_parts
148
   *   An array of date parts, like ('year' => 2014, 'month' => 4).
149
   * @param mixed $timezone
150 151
   *   (optional) \DateTimeZone object, time zone string or NULL. NULL uses the
   *   default system time zone. Defaults to NULL.
152
   * @param array $settings
153 154 155 156
   *   (optional) A keyed array for settings, suitable for passing on to
   *   __construct().
   *
   * @return static
157 158
   *   A new DateTimePlus object.
   *
159
   * @throws \InvalidArgumentException
160
   *   If the array date values or value combination is not correct.
161
   */
162
  public static function createFromArray(array $date_parts, $timezone = NULL, $settings = []) {
163 164 165
    $date_parts = static::prepareArray($date_parts, TRUE);
    if (static::checkArray($date_parts)) {
      // Even with validation, we can end up with a value that the
166
      // DateTime class won't handle, like a year outside the range
167 168 169 170 171 172
      // of -9999 to 9999, which will pass checkdate() but
      // fail to construct a date object.
      $iso_date = static::arrayToISO($date_parts);
      return new static($iso_date, $timezone, $settings);
    }
    else {
173
      throw new \InvalidArgumentException('The array contains invalid values.');
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    }
  }

  /**
   * Creates a date object from timestamp input.
   *
   * The timezone of a timestamp is always UTC. The timezone for a
   * timestamp indicates the timezone used by the format() method.
   *
   * @param int $timestamp
   *   A UNIX timestamp.
   * @param mixed $timezone
   *   @see __construct()
   * @param array $settings
   *   @see __construct()
189 190 191 192
   *
   * @return static
   *   A new DateTimePlus object.
   *
193
   * @throws \InvalidArgumentException
194
   *   If the timestamp is not numeric.
195
   */
196
  public static function createFromTimestamp($timestamp, $timezone = NULL, $settings = []) {
197
    if (!is_numeric($timestamp)) {
198
      throw new \InvalidArgumentException('The timestamp must be numeric.');
199 200 201 202 203 204 205 206 207
    }
    $datetime = new static('', $timezone, $settings);
    $datetime->setTimestamp($timestamp);
    return $datetime;
  }

  /**
   * Creates a date object from an input format.
   *
208 209
   * @param string $format
   *   PHP date() type format for parsing the input. This is recommended
210 211
   *   to use things like negative years, which php's parser fails on, or
   *   any other specialized input with a known format. If provided the
212
   *   date will be created using the createFromFormat() method.
213
   *   @see http://php.net/manual/datetime.createfromformat.php
214 215 216 217
   * @param mixed $time
   *   @see __construct()
   * @param mixed $timezone
   *   @see __construct()
218 219 220 221 222 223 224 225
   * @param array $settings
   *   - validate_format: (optional) Boolean choice to validate the
   *     created date using the input format. The format used in
   *     createFromFormat() allows slightly different values than format().
   *     Using an input format that works in both functions makes it
   *     possible to a validation step to confirm that the date created
   *     from a format string exactly matches the input. This option
   *     indicates the format can be used for validation. Defaults to TRUE.
226
   *   @see __construct()
227 228 229 230
   *
   * @return static
   *   A new DateTimePlus object.
   *
231 232 233 234
   * @throws \InvalidArgumentException
   *   If the a date cannot be created from the given format.
   * @throws \UnexpectedValueException
   *   If the created date does not match the input value.
235
   */
236
  public static function createFromFormat($format, $time, $timezone = NULL, $settings = []) {
237 238 239 240 241 242 243 244 245
    if (!isset($settings['validate_format'])) {
      $settings['validate_format'] = TRUE;
    }

    // Tries to create a date from the format and use it if possible.
    // A regular try/catch won't work right here, if the value is
    // invalid it doesn't return an exception.
    $datetimeplus = new static('', $timezone, $settings);

246
    $date = \DateTime::createFromFormat($format, $time, $datetimeplus->getTimezone());
247
    if (!$date instanceof \DateTime) {
248
      throw new \InvalidArgumentException('The date cannot be created from a format.');
249 250
    }
    else {
251 252 253 254 255
      // Functions that parse date is forgiving, it might create a date that
      // is not exactly a match for the provided value, so test for that by
      // re-creating the date/time formatted string and comparing it to the input. For
      // instance, an input value of '11' using a format of Y (4 digits) gets
      // created as '0011' instead of '2011'.
256
      if ($date instanceof DateTimePlus) {
257 258
        $test_time = $date->format($format, $settings);
      }
259
      elseif ($date instanceof \DateTime) {
260 261
        $test_time = $date->format($format);
      }
262 263 264
      $datetimeplus->setTimestamp($date->getTimestamp());
      $datetimeplus->setTimezone($date->getTimezone());

265
      if ($settings['validate_format'] && $test_time != $time) {
266
        throw new \UnexpectedValueException('The created date does not match the input value.');
267 268 269 270 271 272 273 274 275
      }
    }
    return $datetimeplus;
  }

  /**
   * Constructs a date object set to a requested date and timezone.
   *
   * @param string $time
276
   *   (optional) A date/time string. Defaults to 'now'.
277
   * @param mixed $timezone
278
   *   (optional) \DateTimeZone object, time zone string or NULL. NULL uses the
279 280 281 282 283
   *   default system time zone. Defaults to NULL. Note that the $timezone
   *   parameter and the current timezone are ignored when the $time parameter
   *   either is a UNIX timestamp (e.g. @946684800) or specifies a timezone
   *   (e.g. 2010-01-28T15:00:00+02:00).
   *   @see http://php.net/manual/en/datetime.construct.php
284
   * @param array $settings
285
   *   (optional) Keyed array of settings. Defaults to empty array.
286 287
   *   - langcode: (optional) String two letter language code used to control
   *     the result of the format(). Defaults to NULL.
288 289 290
   *   - debug: (optional) Boolean choice to leave debug values in the
   *     date object for debugging purposes. Defaults to FALSE.
   */
291
  public function __construct($time = 'now', $timezone = NULL, $settings = []) {
292 293 294 295 296

    // Unpack settings.
    $this->langcode = !empty($settings['langcode']) ? $settings['langcode'] : NULL;

    // Massage the input values as necessary.
297 298
    $prepared_time = $this->prepareTime($time);
    $prepared_timezone = $this->prepareTimezone($timezone);
299

300
    try {
301
      $this->errors = [];
302 303 304
      if (!empty($prepared_time)) {
        $test = date_parse($prepared_time);
        if (!empty($test['errors'])) {
305
          $this->errors = $test['errors'];
306 307
        }
      }
308

309
      if (empty($this->errors)) {
310
        $this->dateTimeObject = new \DateTime($prepared_time, $prepared_timezone);
311
      }
312
    }
313 314
    catch (\Exception $e) {
      $this->errors[] = $e->getMessage();
315 316 317 318 319 320 321
    }

    // Clean up the error messages.
    $this->checkErrors();
  }

  /**
322
   * Renders the timezone name.
323
   *
324
   * @return string
325
   */
326
  public function render() {
327
    return $this->format(static::FORMAT) . ' ' . $this->getTimeZone()->getName();
328 329
  }

330 331 332 333
  /**
   * Implements the magic __call method.
   *
   * Passes through all unknown calls onto the DateTime object.
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
   *
   * @param string $method
   *   The method to call on the decorated object.
   * @param array $args
   *   Call arguments.
   *
   * @return mixed
   *   The return value from the method on the decorated object. If the proxied
   *   method call returns a DateTime object, then return the original
   *   DateTimePlus object, which allows function chaining to work properly.
   *   Otherwise, the value from the proxied method call is returned.
   *
   * @throws \Exception
   *   Thrown when the DateTime object is not set.
   * @throws \BadMethodCallException
   *   Thrown when there is no corresponding method on the DateTime object to
   *   call.
351
   */
352
  public function __call($method, array $args) {
353 354 355 356 357 358 359
    // @todo consider using assert() as per https://www.drupal.org/node/2451793.
    if (!isset($this->dateTimeObject)) {
      throw new \Exception('DateTime object not set.');
    }
    if (!method_exists($this->dateTimeObject, $method)) {
      throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s()', get_class($this), $method));
    }
360 361 362 363

    $result = call_user_func_array([$this->dateTimeObject, $method], $args);

    return $result === $this->dateTimeObject ? $this : $result;
364 365
  }

366 367 368 369
  /**
   * Returns the difference between two DateTimePlus objects.
   *
   * @param \Drupal\Component\Datetime\DateTimePlus|\DateTime $datetime2
370
   *   The date to compare to.
371
   * @param bool $absolute
372
   *   Should the interval be forced to be positive?
373 374
   *
   * @return \DateInterval
375
   *   A DateInterval object representing the difference between the two dates.
376 377 378 379 380 381 382 383 384 385 386 387 388 389
   *
   * @throws \BadMethodCallException
   *    If the input isn't a DateTime or DateTimePlus object.
   */
  public function diff($datetime2, $absolute = FALSE) {
    if ($datetime2 instanceof DateTimePlus) {
      $datetime2 = $datetime2->dateTimeObject;
    }
    if (!($datetime2 instanceof \DateTime)) {
      throw new \BadMethodCallException(sprintf('Method %s expects parameter 1 to be a \DateTime or \Drupal\Component\Datetime\DateTimePlus object', __METHOD__));
    }
    return $this->dateTimeObject->diff($datetime2, $absolute);
  }

390 391 392 393 394 395 396 397 398
  /**
   * Implements the magic __callStatic method.
   *
   * Passes through all unknown static calls onto the DateTime object.
   */
  public static function __callStatic($method, $args) {
    if (!method_exists('\DateTime', $method)) {
      throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s()', get_called_class(), $method));
    }
399
    return call_user_func_array(['\DateTime', $method], $args);
400 401 402 403 404 405 406 407 408 409 410
  }

  /**
   * Implements the magic __clone method.
   *
   * Deep-clones the DateTime object we're wrapping.
   */
  public function __clone() {
    $this->dateTimeObject = clone($this->dateTimeObject);
  }

411 412 413 414 415 416 417 418 419
  /**
   * Prepares the input time value.
   *
   * Changes the input value before trying to use it, if necessary.
   * Can be overridden to handle special cases.
   *
   * @param mixed $time
   *   An input value, which could be a timestamp, a string,
   *   or an array of date parts.
420 421 422
   *
   * @return mixed
   *   The massaged time.
423 424
   */
  protected function prepareTime($time) {
425
    return $time;
426 427 428 429 430 431
  }

  /**
   * Prepares the input timezone value.
   *
   * Changes the timezone before trying to use it, if necessary.
432
   * Most importantly, makes sure there is a valid timezone
433 434 435 436
   * object before moving further.
   *
   * @param mixed $timezone
   *   Either a timezone name or a timezone object or NULL.
437 438 439
   *
   * @return \DateTimeZone
   *   The massaged time zone.
440 441 442
   */
  protected function prepareTimezone($timezone) {
    // If the input timezone is a valid timezone object, use it.
443
    if ($timezone instanceof \DateTimezone) {
444 445 446 447 448 449 450 451 452 453
      $timezone_adjusted = $timezone;
    }

    // Allow string timezone input, and create a timezone from it.
    elseif (!empty($timezone) && is_string($timezone)) {
      $timezone_adjusted = new \DateTimeZone($timezone);
    }

    // Default to the system timezone when not explicitly provided.
    // If the system timezone is missing, use 'UTC'.
454
    if (empty($timezone_adjusted) || !$timezone_adjusted instanceof \DateTimezone) {
455 456 457 458 459 460
      $system_timezone = date_default_timezone_get();
      $timezone_name = !empty($system_timezone) ? $system_timezone : 'UTC';
      $timezone_adjusted = new \DateTimeZone($timezone_name);
    }

    // We are finally certain that we have a usable timezone.
461
    return $timezone_adjusted;
462 463 464 465 466 467 468 469 470 471
  }

  /**
   * Prepares the input format value.
   *
   * Changes the input format before trying to use it, if necessary.
   * Can be overridden to handle special cases.
   *
   * @param string $format
   *   A PHP format string.
472 473 474
   *
   * @return string
   *   The massaged PHP format string.
475 476
   */
  protected function prepareFormat($format) {
477
    return $format;
478 479 480 481 482 483 484 485 486 487 488
  }


  /**
   * Examines getLastErrors() to see what errors to report.
   *
   * Two kinds of errors are important: anything that DateTime
   * considers an error, and also a warning that the date was invalid.
   * PHP creates a valid date from invalid data with only a warning,
   * 2011-02-30 becomes 2011-03-03, for instance, but we don't want that.
   *
489
   * @see http://php.net/manual/time.getlasterrors.php
490 491
   */
  public function checkErrors() {
492
    $errors = \DateTime::getLastErrors();
493
    if (!empty($errors['errors'])) {
494
      $this->errors = array_merge($this->errors, $errors['errors']);
495 496 497 498 499 500 501 502
    }
    // Most warnings are messages that the date could not be parsed
    // which causes it to be altered. For validation purposes, a warning
    // as bad as an error, because it means the constructed date does
    // not match the input value.
    if (!empty($errors['warnings'])) {
      $this->errors[] = 'The date is invalid.';
    }
503 504

    $this->errors = array_values(array_unique($this->errors));
505 506 507 508
  }

  /**
   * Detects if there were errors in the processing of this date.
509
   *
alexpott's avatar
alexpott committed
510
   * @return bool
511 512
   *   TRUE if there were errors in the processing of this date, FALSE
   *   otherwise.
513 514 515 516 517 518
   */
  public function hasErrors() {
    return (boolean) count($this->errors);
  }

  /**
519
   * Gets error messages.
520 521
   *
   * Public function to return the error messages.
522 523 524
   *
   * @return array
   *   An array of errors encountered when creating this date.
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
   */
  public function getErrors() {
    return $this->errors;
  }

  /**
   * Creates an ISO date from an array of values.
   *
   * @param array $array
   *   An array of date values keyed by date part.
   * @param bool $force_valid_date
   *   (optional) Whether to force a full date by filling in missing
   *   values. Defaults to FALSE.
   *
   * @return string
   *   The date as an ISO string.
   */
  public static function arrayToISO($array, $force_valid_date = FALSE) {
    $array = static::prepareArray($array, $force_valid_date);
    $input_time = '';
    if ($array['year'] !== '') {
      $input_time = static::datePad(intval($array['year']), 4);
      if ($force_valid_date || $array['month'] !== '') {
        $input_time .= '-' . static::datePad(intval($array['month']));
        if ($force_valid_date || $array['day'] !== '') {
          $input_time .= '-' . static::datePad(intval($array['day']));
        }
      }
    }
    if ($array['hour'] !== '') {
      $input_time .= $input_time ? 'T' : '';
      $input_time .= static::datePad(intval($array['hour']));
      if ($force_valid_date || $array['minute'] !== '') {
        $input_time .= ':' . static::datePad(intval($array['minute']));
        if ($force_valid_date || $array['second'] !== '') {
          $input_time .= ':' . static::datePad(intval($array['second']));
        }
      }
    }
    return $input_time;
  }

  /**
   * Creates a complete array from a possibly incomplete array of date parts.
   *
   * @param array $array
   *   An array of date values keyed by date part.
   * @param bool $force_valid_date
   *   (optional) Whether to force a valid date by filling in missing
   *   values with valid values or just to use empty values instead.
   *   Defaults to FALSE.
   *
   * @return array
   *   A complete array of date parts.
   */
  public static function prepareArray($array, $force_valid_date = FALSE) {
    if ($force_valid_date) {
      $now = new \DateTime();
583
      $array += [
584 585 586 587 588 589
        'year'   => $now->format('Y'),
        'month'  => 1,
        'day'    => 1,
        'hour'   => 0,
        'minute' => 0,
        'second' => 0,
590
      ];
591 592
    }
    else {
593
      $array += [
594 595 596 597 598 599
        'year'   => '',
        'month'  => '',
        'day'    => '',
        'hour'   => '',
        'minute' => '',
        'second' => '',
600
      ];
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
    }
    return $array;
  }

  /**
   * Checks that arrays of date parts will create a valid date.
   *
   * Checks that an array of date parts has a year, month, and day,
   * and that those values create a valid date. If time is provided,
   * verifies that the time values are valid. Sort of an
   * equivalent to checkdate().
   *
   * @param array $array
   *   An array of datetime values keyed by date part.
   *
616
   * @return bool
617 618 619 620 621 622 623 624 625 626 627 628 629 630
   *   TRUE if the datetime parts contain valid values, otherwise FALSE.
   */
  public static function checkArray($array) {
    $valid_date = FALSE;
    $valid_time = TRUE;
    // Check for a valid date using checkdate(). Only values that
    // meet that test are valid.
    if (array_key_exists('year', $array) && array_key_exists('month', $array) && array_key_exists('day', $array)) {
      if (@checkdate($array['month'], $array['day'], $array['year'])) {
        $valid_date = TRUE;
      }
    }
    // Testing for valid time is reversed. Missing time is OK,
    // but incorrect values are not.
631
    foreach (['hour', 'minute', 'second'] as $key) {
632 633
      if (array_key_exists($key, $array)) {
        $value = $array[$key];
634
        switch ($key) {
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
          case 'hour':
            if (!preg_match('/^([1-2][0-3]|[01]?[0-9])$/', $value)) {
              $valid_time = FALSE;
            }
            break;
          case 'minute':
          case 'second':
          default:
            if (!preg_match('/^([0-5][0-9]|[0-9])$/', $value)) {
              $valid_time = FALSE;
            }
            break;
        }
      }
    }
    return $valid_date && $valid_time;
  }

  /**
   * Pads date parts with zeros.
   *
   * Helper function for a task that is often required when working with dates.
   *
   * @param int $value
   *   The value to pad.
   * @param int $size
   *   (optional) Size expected, usually 2 or 4. Defaults to 2.
   *
   * @return string
   *   The padded value.
   */
  public static function datePad($value, $size = 2) {
    return sprintf("%0" . $size . "d", $value);
  }

  /**
   * Formats the date for display.
   *
   * @param string $format
674
   *   A format string using either PHP's date().
675 676 677 678
   * @param array $settings
   *   - timezone: (optional) String timezone name. Defaults to the timezone
   *     of the date object.
   *
679 680 681
   * @return string|null
   *   The formatted value of the date or NULL if there were construction
   *   errors.
682
   */
683
  public function format($format, $settings = []) {
684 685 686 687 688 689 690 691

    // If there were construction errors, we can't format the date.
    if ($this->hasErrors()) {
      return;
    }

    // Format the date and catch errors.
    try {
692 693 694 695 696 697 698
      // Clone the date/time object so we can change the time zone without
      // disturbing the value stored in the object.
      $dateTimeObject = clone $this->dateTimeObject;
      if (isset($settings['timezone'])) {
        $dateTimeObject->setTimezone(new \DateTimeZone($settings['timezone']));
      }
      $value = $dateTimeObject->format($format);
699 700 701 702
    }
    catch (\Exception $e) {
      $this->errors[] = $e->getMessage();
    }
703

704 705
    return $value;
  }
706

707 708 709 710 711 712 713 714 715 716 717
  /**
   * Sets the default time for an object built from date-only data.
   *
   * The default time for a date without time can be anything, so long as it is
   * consistently applied. If we use noon, dates in most timezones will have the
   * same value for in both the local timezone and UTC.
   */
  public function setDefaultDateTime() {
    $this->dateTimeObject->setTime(12, 0, 0);
  }

718
}