annotate core/lib/Drupal/Component/Datetime/DateTimePlus.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents 129ea1e6d783
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\Component\Datetime;
Chris@0 4
Chris@0 5 use Drupal\Component\Utility\ToStringTrait;
Chris@0 6
Chris@0 7 /**
Chris@0 8 * Wraps DateTime().
Chris@0 9 *
Chris@0 10 * This class wraps the PHP DateTime class with more flexible initialization
Chris@0 11 * parameters, allowing a date to be created from an existing date object,
Chris@0 12 * a timestamp, a string with an unknown format, a string with a known
Chris@0 13 * format, or an array of date parts. It also adds an errors array
Chris@0 14 * and a __toString() method to the date object.
Chris@0 15 *
Chris@0 16 * This class is less lenient than the DateTime class. It changes
Chris@0 17 * the default behavior for handling date values like '2011-00-00'.
Chris@0 18 * The DateTime class would convert that value to '2010-11-30' and report
Chris@0 19 * a warning but not an error. This extension treats that as an error.
Chris@0 20 *
Chris@0 21 * As with the DateTime class, a date object may be created even if it has
Chris@0 22 * errors. It has an errors array attached to it that explains what the
Chris@0 23 * errors are. This is less disruptive than allowing datetime exceptions
Chris@0 24 * to abort processing. The calling script can decide what to do about
Chris@0 25 * errors using hasErrors() and getErrors().
Chris@12 26 *
Chris@12 27 * @method $this add(\DateInterval $interval)
Chris@12 28 * @method static array getLastErrors()
Chris@12 29 * @method $this modify(string $modify)
Chris@12 30 * @method $this setDate(int $year, int $month, int $day)
Chris@12 31 * @method $this setISODate(int $year, int $week, int $day = 1)
Chris@12 32 * @method $this setTime(int $hour, int $minute, int $second = 0, int $microseconds = 0)
Chris@12 33 * @method $this setTimestamp(int $unixtimestamp)
Chris@12 34 * @method $this setTimezone(\DateTimeZone $timezone)
Chris@12 35 * @method $this sub(\DateInterval $interval)
Chris@12 36 * @method int getOffset()
Chris@12 37 * @method int getTimestamp()
Chris@12 38 * @method \DateTimeZone getTimezone()
Chris@0 39 */
Chris@0 40 class DateTimePlus {
Chris@0 41
Chris@0 42 use ToStringTrait;
Chris@0 43
Chris@17 44 const FORMAT = 'Y-m-d H:i:s';
Chris@0 45
Chris@0 46 /**
Chris@0 47 * A RFC7231 Compliant date.
Chris@0 48 *
Chris@17 49 * @see http://tools.ietf.org/html/rfc7231#section-7.1.1.1
Chris@0 50 *
Chris@0 51 * Example: Sun, 06 Nov 1994 08:49:37 GMT
Chris@0 52 */
Chris@0 53 const RFC7231 = 'D, d M Y H:i:s \G\M\T';
Chris@0 54
Chris@0 55 /**
Chris@0 56 * An array of possible date parts.
Chris@0 57 */
Chris@0 58 protected static $dateParts = [
Chris@0 59 'year',
Chris@0 60 'month',
Chris@0 61 'day',
Chris@0 62 'hour',
Chris@0 63 'minute',
Chris@0 64 'second',
Chris@0 65 ];
Chris@0 66
Chris@0 67 /**
Chris@0 68 * The value of the time value passed to the constructor.
Chris@12 69 *
Chris@12 70 * @var string
Chris@0 71 */
Chris@0 72 protected $inputTimeRaw = '';
Chris@0 73
Chris@0 74 /**
Chris@0 75 * The prepared time, without timezone, for this date.
Chris@12 76 *
Chris@12 77 * @var string
Chris@0 78 */
Chris@0 79 protected $inputTimeAdjusted = '';
Chris@0 80
Chris@0 81 /**
Chris@0 82 * The value of the timezone passed to the constructor.
Chris@12 83 *
Chris@12 84 * @var string
Chris@0 85 */
Chris@0 86 protected $inputTimeZoneRaw = '';
Chris@0 87
Chris@0 88 /**
Chris@0 89 * The prepared timezone object used to construct this date.
Chris@12 90 *
Chris@12 91 * @var string
Chris@0 92 */
Chris@0 93 protected $inputTimeZoneAdjusted = '';
Chris@0 94
Chris@0 95 /**
Chris@0 96 * The value of the format passed to the constructor.
Chris@12 97 *
Chris@12 98 * @var string
Chris@0 99 */
Chris@0 100 protected $inputFormatRaw = '';
Chris@0 101
Chris@0 102 /**
Chris@0 103 * The prepared format, if provided.
Chris@12 104 *
Chris@12 105 * @var string
Chris@0 106 */
Chris@0 107 protected $inputFormatAdjusted = '';
Chris@0 108
Chris@0 109 /**
Chris@0 110 * The value of the language code passed to the constructor.
Chris@0 111 */
Chris@0 112 protected $langcode = NULL;
Chris@0 113
Chris@0 114 /**
Chris@0 115 * An array of errors encountered when creating this date.
Chris@0 116 */
Chris@0 117 protected $errors = [];
Chris@0 118
Chris@0 119 /**
Chris@0 120 * The DateTime object.
Chris@0 121 *
Chris@0 122 * @var \DateTime
Chris@0 123 */
Chris@0 124 protected $dateTimeObject = NULL;
Chris@0 125
Chris@0 126 /**
Chris@0 127 * Creates a date object from an input date object.
Chris@0 128 *
Chris@0 129 * @param \DateTime $datetime
Chris@0 130 * A DateTime object.
Chris@0 131 * @param array $settings
Chris@0 132 * @see __construct()
Chris@0 133 *
Chris@0 134 * @return static
Chris@0 135 * A new DateTimePlus object.
Chris@0 136 */
Chris@0 137 public static function createFromDateTime(\DateTime $datetime, $settings = []) {
Chris@0 138 return new static($datetime->format(static::FORMAT), $datetime->getTimezone(), $settings);
Chris@0 139 }
Chris@0 140
Chris@0 141 /**
Chris@0 142 * Creates a date object from an array of date parts.
Chris@0 143 *
Chris@0 144 * Converts the input value into an ISO date, forcing a full ISO
Chris@0 145 * date even if some values are missing.
Chris@0 146 *
Chris@0 147 * @param array $date_parts
Chris@0 148 * An array of date parts, like ('year' => 2014, 'month' => 4).
Chris@0 149 * @param mixed $timezone
Chris@0 150 * (optional) \DateTimeZone object, time zone string or NULL. NULL uses the
Chris@0 151 * default system time zone. Defaults to NULL.
Chris@0 152 * @param array $settings
Chris@0 153 * (optional) A keyed array for settings, suitable for passing on to
Chris@0 154 * __construct().
Chris@0 155 *
Chris@0 156 * @return static
Chris@0 157 * A new DateTimePlus object.
Chris@0 158 *
Chris@0 159 * @throws \InvalidArgumentException
Chris@0 160 * If the array date values or value combination is not correct.
Chris@0 161 */
Chris@0 162 public static function createFromArray(array $date_parts, $timezone = NULL, $settings = []) {
Chris@0 163 $date_parts = static::prepareArray($date_parts, TRUE);
Chris@0 164 if (static::checkArray($date_parts)) {
Chris@0 165 // Even with validation, we can end up with a value that the
Chris@0 166 // DateTime class won't handle, like a year outside the range
Chris@0 167 // of -9999 to 9999, which will pass checkdate() but
Chris@0 168 // fail to construct a date object.
Chris@0 169 $iso_date = static::arrayToISO($date_parts);
Chris@0 170 return new static($iso_date, $timezone, $settings);
Chris@0 171 }
Chris@0 172 else {
Chris@0 173 throw new \InvalidArgumentException('The array contains invalid values.');
Chris@0 174 }
Chris@0 175 }
Chris@0 176
Chris@0 177 /**
Chris@0 178 * Creates a date object from timestamp input.
Chris@0 179 *
Chris@0 180 * The timezone of a timestamp is always UTC. The timezone for a
Chris@0 181 * timestamp indicates the timezone used by the format() method.
Chris@0 182 *
Chris@0 183 * @param int $timestamp
Chris@0 184 * A UNIX timestamp.
Chris@0 185 * @param mixed $timezone
Chris@0 186 * @see __construct()
Chris@0 187 * @param array $settings
Chris@0 188 * @see __construct()
Chris@0 189 *
Chris@0 190 * @return static
Chris@0 191 * A new DateTimePlus object.
Chris@0 192 *
Chris@0 193 * @throws \InvalidArgumentException
Chris@0 194 * If the timestamp is not numeric.
Chris@0 195 */
Chris@0 196 public static function createFromTimestamp($timestamp, $timezone = NULL, $settings = []) {
Chris@0 197 if (!is_numeric($timestamp)) {
Chris@0 198 throw new \InvalidArgumentException('The timestamp must be numeric.');
Chris@0 199 }
Chris@0 200 $datetime = new static('', $timezone, $settings);
Chris@0 201 $datetime->setTimestamp($timestamp);
Chris@0 202 return $datetime;
Chris@0 203 }
Chris@0 204
Chris@0 205 /**
Chris@0 206 * Creates a date object from an input format.
Chris@0 207 *
Chris@0 208 * @param string $format
Chris@0 209 * PHP date() type format for parsing the input. This is recommended
Chris@0 210 * to use things like negative years, which php's parser fails on, or
Chris@0 211 * any other specialized input with a known format. If provided the
Chris@0 212 * date will be created using the createFromFormat() method.
Chris@0 213 * @see http://php.net/manual/datetime.createfromformat.php
Chris@0 214 * @param mixed $time
Chris@0 215 * @see __construct()
Chris@0 216 * @param mixed $timezone
Chris@0 217 * @see __construct()
Chris@0 218 * @param array $settings
Chris@0 219 * - validate_format: (optional) Boolean choice to validate the
Chris@0 220 * created date using the input format. The format used in
Chris@0 221 * createFromFormat() allows slightly different values than format().
Chris@0 222 * Using an input format that works in both functions makes it
Chris@0 223 * possible to a validation step to confirm that the date created
Chris@0 224 * from a format string exactly matches the input. This option
Chris@0 225 * indicates the format can be used for validation. Defaults to TRUE.
Chris@0 226 * @see __construct()
Chris@0 227 *
Chris@0 228 * @return static
Chris@0 229 * A new DateTimePlus object.
Chris@0 230 *
Chris@0 231 * @throws \InvalidArgumentException
Chris@0 232 * If the a date cannot be created from the given format.
Chris@0 233 * @throws \UnexpectedValueException
Chris@0 234 * If the created date does not match the input value.
Chris@0 235 */
Chris@0 236 public static function createFromFormat($format, $time, $timezone = NULL, $settings = []) {
Chris@0 237 if (!isset($settings['validate_format'])) {
Chris@0 238 $settings['validate_format'] = TRUE;
Chris@0 239 }
Chris@0 240
Chris@0 241 // Tries to create a date from the format and use it if possible.
Chris@0 242 // A regular try/catch won't work right here, if the value is
Chris@0 243 // invalid it doesn't return an exception.
Chris@0 244 $datetimeplus = new static('', $timezone, $settings);
Chris@0 245
Chris@0 246 $date = \DateTime::createFromFormat($format, $time, $datetimeplus->getTimezone());
Chris@0 247 if (!$date instanceof \DateTime) {
Chris@0 248 throw new \InvalidArgumentException('The date cannot be created from a format.');
Chris@0 249 }
Chris@0 250 else {
Chris@0 251 // Functions that parse date is forgiving, it might create a date that
Chris@0 252 // is not exactly a match for the provided value, so test for that by
Chris@0 253 // re-creating the date/time formatted string and comparing it to the input. For
Chris@0 254 // instance, an input value of '11' using a format of Y (4 digits) gets
Chris@0 255 // created as '0011' instead of '2011'.
Chris@0 256 if ($date instanceof DateTimePlus) {
Chris@0 257 $test_time = $date->format($format, $settings);
Chris@0 258 }
Chris@0 259 elseif ($date instanceof \DateTime) {
Chris@0 260 $test_time = $date->format($format);
Chris@0 261 }
Chris@0 262 $datetimeplus->setTimestamp($date->getTimestamp());
Chris@0 263 $datetimeplus->setTimezone($date->getTimezone());
Chris@0 264
Chris@0 265 if ($settings['validate_format'] && $test_time != $time) {
Chris@0 266 throw new \UnexpectedValueException('The created date does not match the input value.');
Chris@0 267 }
Chris@0 268 }
Chris@0 269 return $datetimeplus;
Chris@0 270 }
Chris@0 271
Chris@0 272 /**
Chris@0 273 * Constructs a date object set to a requested date and timezone.
Chris@0 274 *
Chris@0 275 * @param string $time
Chris@0 276 * (optional) A date/time string. Defaults to 'now'.
Chris@0 277 * @param mixed $timezone
Chris@0 278 * (optional) \DateTimeZone object, time zone string or NULL. NULL uses the
Chris@0 279 * default system time zone. Defaults to NULL. Note that the $timezone
Chris@0 280 * parameter and the current timezone are ignored when the $time parameter
Chris@0 281 * either is a UNIX timestamp (e.g. @946684800) or specifies a timezone
Chris@0 282 * (e.g. 2010-01-28T15:00:00+02:00).
Chris@14 283 * @see http://php.net/manual/datetime.construct.php
Chris@0 284 * @param array $settings
Chris@0 285 * (optional) Keyed array of settings. Defaults to empty array.
Chris@0 286 * - langcode: (optional) String two letter language code used to control
Chris@0 287 * the result of the format(). Defaults to NULL.
Chris@0 288 * - debug: (optional) Boolean choice to leave debug values in the
Chris@0 289 * date object for debugging purposes. Defaults to FALSE.
Chris@0 290 */
Chris@0 291 public function __construct($time = 'now', $timezone = NULL, $settings = []) {
Chris@0 292
Chris@0 293 // Unpack settings.
Chris@0 294 $this->langcode = !empty($settings['langcode']) ? $settings['langcode'] : NULL;
Chris@0 295
Chris@0 296 // Massage the input values as necessary.
Chris@0 297 $prepared_time = $this->prepareTime($time);
Chris@0 298 $prepared_timezone = $this->prepareTimezone($timezone);
Chris@0 299
Chris@0 300 try {
Chris@0 301 $this->errors = [];
Chris@0 302 if (!empty($prepared_time)) {
Chris@0 303 $test = date_parse($prepared_time);
Chris@0 304 if (!empty($test['errors'])) {
Chris@0 305 $this->errors = $test['errors'];
Chris@0 306 }
Chris@0 307 }
Chris@0 308
Chris@0 309 if (empty($this->errors)) {
Chris@0 310 $this->dateTimeObject = new \DateTime($prepared_time, $prepared_timezone);
Chris@0 311 }
Chris@0 312 }
Chris@0 313 catch (\Exception $e) {
Chris@0 314 $this->errors[] = $e->getMessage();
Chris@0 315 }
Chris@0 316
Chris@0 317 // Clean up the error messages.
Chris@0 318 $this->checkErrors();
Chris@0 319 }
Chris@0 320
Chris@0 321 /**
Chris@0 322 * Renders the timezone name.
Chris@0 323 *
Chris@0 324 * @return string
Chris@0 325 */
Chris@0 326 public function render() {
Chris@0 327 return $this->format(static::FORMAT) . ' ' . $this->getTimeZone()->getName();
Chris@0 328 }
Chris@0 329
Chris@0 330 /**
Chris@0 331 * Implements the magic __call method.
Chris@0 332 *
Chris@0 333 * Passes through all unknown calls onto the DateTime object.
Chris@0 334 *
Chris@0 335 * @param string $method
Chris@0 336 * The method to call on the decorated object.
Chris@0 337 * @param array $args
Chris@0 338 * Call arguments.
Chris@0 339 *
Chris@0 340 * @return mixed
Chris@0 341 * The return value from the method on the decorated object. If the proxied
Chris@0 342 * method call returns a DateTime object, then return the original
Chris@0 343 * DateTimePlus object, which allows function chaining to work properly.
Chris@0 344 * Otherwise, the value from the proxied method call is returned.
Chris@0 345 *
Chris@0 346 * @throws \Exception
Chris@0 347 * Thrown when the DateTime object is not set.
Chris@0 348 * @throws \BadMethodCallException
Chris@0 349 * Thrown when there is no corresponding method on the DateTime object to
Chris@0 350 * call.
Chris@0 351 */
Chris@0 352 public function __call($method, array $args) {
Chris@0 353 // @todo consider using assert() as per https://www.drupal.org/node/2451793.
Chris@0 354 if (!isset($this->dateTimeObject)) {
Chris@0 355 throw new \Exception('DateTime object not set.');
Chris@0 356 }
Chris@0 357 if (!method_exists($this->dateTimeObject, $method)) {
Chris@0 358 throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s()', get_class($this), $method));
Chris@0 359 }
Chris@0 360
Chris@0 361 $result = call_user_func_array([$this->dateTimeObject, $method], $args);
Chris@0 362
Chris@0 363 return $result === $this->dateTimeObject ? $this : $result;
Chris@0 364 }
Chris@0 365
Chris@0 366 /**
Chris@0 367 * Returns the difference between two DateTimePlus objects.
Chris@0 368 *
Chris@0 369 * @param \Drupal\Component\Datetime\DateTimePlus|\DateTime $datetime2
Chris@0 370 * The date to compare to.
Chris@0 371 * @param bool $absolute
Chris@0 372 * Should the interval be forced to be positive?
Chris@0 373 *
Chris@0 374 * @return \DateInterval
Chris@0 375 * A DateInterval object representing the difference between the two dates.
Chris@0 376 *
Chris@0 377 * @throws \BadMethodCallException
Chris@0 378 * If the input isn't a DateTime or DateTimePlus object.
Chris@0 379 */
Chris@0 380 public function diff($datetime2, $absolute = FALSE) {
Chris@0 381 if ($datetime2 instanceof DateTimePlus) {
Chris@0 382 $datetime2 = $datetime2->dateTimeObject;
Chris@0 383 }
Chris@0 384 if (!($datetime2 instanceof \DateTime)) {
Chris@0 385 throw new \BadMethodCallException(sprintf('Method %s expects parameter 1 to be a \DateTime or \Drupal\Component\Datetime\DateTimePlus object', __METHOD__));
Chris@0 386 }
Chris@0 387 return $this->dateTimeObject->diff($datetime2, $absolute);
Chris@0 388 }
Chris@0 389
Chris@0 390 /**
Chris@0 391 * Implements the magic __callStatic method.
Chris@0 392 *
Chris@0 393 * Passes through all unknown static calls onto the DateTime object.
Chris@0 394 */
Chris@0 395 public static function __callStatic($method, $args) {
Chris@0 396 if (!method_exists('\DateTime', $method)) {
Chris@0 397 throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s()', get_called_class(), $method));
Chris@0 398 }
Chris@0 399 return call_user_func_array(['\DateTime', $method], $args);
Chris@0 400 }
Chris@0 401
Chris@0 402 /**
Chris@0 403 * Implements the magic __clone method.
Chris@0 404 *
Chris@0 405 * Deep-clones the DateTime object we're wrapping.
Chris@0 406 */
Chris@0 407 public function __clone() {
Chris@0 408 $this->dateTimeObject = clone($this->dateTimeObject);
Chris@0 409 }
Chris@0 410
Chris@0 411 /**
Chris@0 412 * Prepares the input time value.
Chris@0 413 *
Chris@0 414 * Changes the input value before trying to use it, if necessary.
Chris@0 415 * Can be overridden to handle special cases.
Chris@0 416 *
Chris@0 417 * @param mixed $time
Chris@0 418 * An input value, which could be a timestamp, a string,
Chris@0 419 * or an array of date parts.
Chris@0 420 *
Chris@0 421 * @return mixed
Chris@0 422 * The massaged time.
Chris@0 423 */
Chris@0 424 protected function prepareTime($time) {
Chris@0 425 return $time;
Chris@0 426 }
Chris@0 427
Chris@0 428 /**
Chris@0 429 * Prepares the input timezone value.
Chris@0 430 *
Chris@0 431 * Changes the timezone before trying to use it, if necessary.
Chris@0 432 * Most importantly, makes sure there is a valid timezone
Chris@0 433 * object before moving further.
Chris@0 434 *
Chris@0 435 * @param mixed $timezone
Chris@0 436 * Either a timezone name or a timezone object or NULL.
Chris@0 437 *
Chris@0 438 * @return \DateTimeZone
Chris@0 439 * The massaged time zone.
Chris@0 440 */
Chris@0 441 protected function prepareTimezone($timezone) {
Chris@0 442 // If the input timezone is a valid timezone object, use it.
Chris@0 443 if ($timezone instanceof \DateTimezone) {
Chris@0 444 $timezone_adjusted = $timezone;
Chris@0 445 }
Chris@0 446
Chris@0 447 // Allow string timezone input, and create a timezone from it.
Chris@0 448 elseif (!empty($timezone) && is_string($timezone)) {
Chris@0 449 $timezone_adjusted = new \DateTimeZone($timezone);
Chris@0 450 }
Chris@0 451
Chris@0 452 // Default to the system timezone when not explicitly provided.
Chris@0 453 // If the system timezone is missing, use 'UTC'.
Chris@0 454 if (empty($timezone_adjusted) || !$timezone_adjusted instanceof \DateTimezone) {
Chris@0 455 $system_timezone = date_default_timezone_get();
Chris@0 456 $timezone_name = !empty($system_timezone) ? $system_timezone : 'UTC';
Chris@0 457 $timezone_adjusted = new \DateTimeZone($timezone_name);
Chris@0 458 }
Chris@0 459
Chris@0 460 // We are finally certain that we have a usable timezone.
Chris@0 461 return $timezone_adjusted;
Chris@0 462 }
Chris@0 463
Chris@0 464 /**
Chris@0 465 * Prepares the input format value.
Chris@0 466 *
Chris@0 467 * Changes the input format before trying to use it, if necessary.
Chris@0 468 * Can be overridden to handle special cases.
Chris@0 469 *
Chris@0 470 * @param string $format
Chris@0 471 * A PHP format string.
Chris@0 472 *
Chris@0 473 * @return string
Chris@0 474 * The massaged PHP format string.
Chris@0 475 */
Chris@0 476 protected function prepareFormat($format) {
Chris@0 477 return $format;
Chris@0 478 }
Chris@0 479
Chris@0 480 /**
Chris@0 481 * Examines getLastErrors() to see what errors to report.
Chris@0 482 *
Chris@0 483 * Two kinds of errors are important: anything that DateTime
Chris@0 484 * considers an error, and also a warning that the date was invalid.
Chris@0 485 * PHP creates a valid date from invalid data with only a warning,
Chris@0 486 * 2011-02-30 becomes 2011-03-03, for instance, but we don't want that.
Chris@0 487 *
Chris@0 488 * @see http://php.net/manual/time.getlasterrors.php
Chris@0 489 */
Chris@0 490 public function checkErrors() {
Chris@0 491 $errors = \DateTime::getLastErrors();
Chris@0 492 if (!empty($errors['errors'])) {
Chris@0 493 $this->errors = array_merge($this->errors, $errors['errors']);
Chris@0 494 }
Chris@0 495 // Most warnings are messages that the date could not be parsed
Chris@0 496 // which causes it to be altered. For validation purposes, a warning
Chris@0 497 // as bad as an error, because it means the constructed date does
Chris@0 498 // not match the input value.
Chris@0 499 if (!empty($errors['warnings'])) {
Chris@0 500 $this->errors[] = 'The date is invalid.';
Chris@0 501 }
Chris@0 502
Chris@0 503 $this->errors = array_values(array_unique($this->errors));
Chris@0 504 }
Chris@0 505
Chris@0 506 /**
Chris@0 507 * Detects if there were errors in the processing of this date.
Chris@0 508 *
Chris@0 509 * @return bool
Chris@0 510 * TRUE if there were errors in the processing of this date, FALSE
Chris@0 511 * otherwise.
Chris@0 512 */
Chris@0 513 public function hasErrors() {
Chris@0 514 return (boolean) count($this->errors);
Chris@0 515 }
Chris@0 516
Chris@0 517 /**
Chris@0 518 * Gets error messages.
Chris@0 519 *
Chris@0 520 * Public function to return the error messages.
Chris@0 521 *
Chris@0 522 * @return array
Chris@0 523 * An array of errors encountered when creating this date.
Chris@0 524 */
Chris@0 525 public function getErrors() {
Chris@0 526 return $this->errors;
Chris@0 527 }
Chris@0 528
Chris@0 529 /**
Chris@0 530 * Creates an ISO date from an array of values.
Chris@0 531 *
Chris@0 532 * @param array $array
Chris@0 533 * An array of date values keyed by date part.
Chris@0 534 * @param bool $force_valid_date
Chris@0 535 * (optional) Whether to force a full date by filling in missing
Chris@0 536 * values. Defaults to FALSE.
Chris@0 537 *
Chris@0 538 * @return string
Chris@0 539 * The date as an ISO string.
Chris@0 540 */
Chris@0 541 public static function arrayToISO($array, $force_valid_date = FALSE) {
Chris@0 542 $array = static::prepareArray($array, $force_valid_date);
Chris@0 543 $input_time = '';
Chris@0 544 if ($array['year'] !== '') {
Chris@0 545 $input_time = static::datePad(intval($array['year']), 4);
Chris@0 546 if ($force_valid_date || $array['month'] !== '') {
Chris@0 547 $input_time .= '-' . static::datePad(intval($array['month']));
Chris@0 548 if ($force_valid_date || $array['day'] !== '') {
Chris@0 549 $input_time .= '-' . static::datePad(intval($array['day']));
Chris@0 550 }
Chris@0 551 }
Chris@0 552 }
Chris@0 553 if ($array['hour'] !== '') {
Chris@0 554 $input_time .= $input_time ? 'T' : '';
Chris@0 555 $input_time .= static::datePad(intval($array['hour']));
Chris@0 556 if ($force_valid_date || $array['minute'] !== '') {
Chris@0 557 $input_time .= ':' . static::datePad(intval($array['minute']));
Chris@0 558 if ($force_valid_date || $array['second'] !== '') {
Chris@0 559 $input_time .= ':' . static::datePad(intval($array['second']));
Chris@0 560 }
Chris@0 561 }
Chris@0 562 }
Chris@0 563 return $input_time;
Chris@0 564 }
Chris@0 565
Chris@0 566 /**
Chris@0 567 * Creates a complete array from a possibly incomplete array of date parts.
Chris@0 568 *
Chris@0 569 * @param array $array
Chris@0 570 * An array of date values keyed by date part.
Chris@0 571 * @param bool $force_valid_date
Chris@0 572 * (optional) Whether to force a valid date by filling in missing
Chris@0 573 * values with valid values or just to use empty values instead.
Chris@0 574 * Defaults to FALSE.
Chris@0 575 *
Chris@0 576 * @return array
Chris@0 577 * A complete array of date parts.
Chris@0 578 */
Chris@0 579 public static function prepareArray($array, $force_valid_date = FALSE) {
Chris@0 580 if ($force_valid_date) {
Chris@0 581 $now = new \DateTime();
Chris@0 582 $array += [
Chris@0 583 'year' => $now->format('Y'),
Chris@0 584 'month' => 1,
Chris@0 585 'day' => 1,
Chris@0 586 'hour' => 0,
Chris@0 587 'minute' => 0,
Chris@0 588 'second' => 0,
Chris@0 589 ];
Chris@0 590 }
Chris@0 591 else {
Chris@0 592 $array += [
Chris@0 593 'year' => '',
Chris@0 594 'month' => '',
Chris@0 595 'day' => '',
Chris@0 596 'hour' => '',
Chris@0 597 'minute' => '',
Chris@0 598 'second' => '',
Chris@0 599 ];
Chris@0 600 }
Chris@0 601 return $array;
Chris@0 602 }
Chris@0 603
Chris@0 604 /**
Chris@0 605 * Checks that arrays of date parts will create a valid date.
Chris@0 606 *
Chris@0 607 * Checks that an array of date parts has a year, month, and day,
Chris@0 608 * and that those values create a valid date. If time is provided,
Chris@0 609 * verifies that the time values are valid. Sort of an
Chris@0 610 * equivalent to checkdate().
Chris@0 611 *
Chris@0 612 * @param array $array
Chris@0 613 * An array of datetime values keyed by date part.
Chris@0 614 *
Chris@0 615 * @return bool
Chris@0 616 * TRUE if the datetime parts contain valid values, otherwise FALSE.
Chris@0 617 */
Chris@0 618 public static function checkArray($array) {
Chris@0 619 $valid_date = FALSE;
Chris@0 620 $valid_time = TRUE;
Chris@0 621 // Check for a valid date using checkdate(). Only values that
Chris@0 622 // meet that test are valid.
Chris@0 623 if (array_key_exists('year', $array) && array_key_exists('month', $array) && array_key_exists('day', $array)) {
Chris@0 624 if (@checkdate($array['month'], $array['day'], $array['year'])) {
Chris@0 625 $valid_date = TRUE;
Chris@0 626 }
Chris@0 627 }
Chris@0 628 // Testing for valid time is reversed. Missing time is OK,
Chris@0 629 // but incorrect values are not.
Chris@0 630 foreach (['hour', 'minute', 'second'] as $key) {
Chris@0 631 if (array_key_exists($key, $array)) {
Chris@0 632 $value = $array[$key];
Chris@0 633 switch ($key) {
Chris@0 634 case 'hour':
Chris@0 635 if (!preg_match('/^([1-2][0-3]|[01]?[0-9])$/', $value)) {
Chris@0 636 $valid_time = FALSE;
Chris@0 637 }
Chris@0 638 break;
Chris@0 639 case 'minute':
Chris@0 640 case 'second':
Chris@0 641 default:
Chris@0 642 if (!preg_match('/^([0-5][0-9]|[0-9])$/', $value)) {
Chris@0 643 $valid_time = FALSE;
Chris@0 644 }
Chris@0 645 break;
Chris@0 646 }
Chris@0 647 }
Chris@0 648 }
Chris@0 649 return $valid_date && $valid_time;
Chris@0 650 }
Chris@0 651
Chris@0 652 /**
Chris@0 653 * Pads date parts with zeros.
Chris@0 654 *
Chris@0 655 * Helper function for a task that is often required when working with dates.
Chris@0 656 *
Chris@0 657 * @param int $value
Chris@0 658 * The value to pad.
Chris@0 659 * @param int $size
Chris@0 660 * (optional) Size expected, usually 2 or 4. Defaults to 2.
Chris@0 661 *
Chris@0 662 * @return string
Chris@0 663 * The padded value.
Chris@0 664 */
Chris@0 665 public static function datePad($value, $size = 2) {
Chris@0 666 return sprintf("%0" . $size . "d", $value);
Chris@0 667 }
Chris@0 668
Chris@0 669 /**
Chris@0 670 * Formats the date for display.
Chris@0 671 *
Chris@0 672 * @param string $format
Chris@16 673 * Format accepted by date().
Chris@0 674 * @param array $settings
Chris@0 675 * - timezone: (optional) String timezone name. Defaults to the timezone
Chris@0 676 * of the date object.
Chris@0 677 *
Chris@0 678 * @return string|null
Chris@0 679 * The formatted value of the date or NULL if there were construction
Chris@0 680 * errors.
Chris@0 681 */
Chris@0 682 public function format($format, $settings = []) {
Chris@0 683
Chris@0 684 // If there were construction errors, we can't format the date.
Chris@0 685 if ($this->hasErrors()) {
Chris@0 686 return;
Chris@0 687 }
Chris@0 688
Chris@0 689 // Format the date and catch errors.
Chris@0 690 try {
Chris@0 691 // Clone the date/time object so we can change the time zone without
Chris@0 692 // disturbing the value stored in the object.
Chris@0 693 $dateTimeObject = clone $this->dateTimeObject;
Chris@0 694 if (isset($settings['timezone'])) {
Chris@0 695 $dateTimeObject->setTimezone(new \DateTimeZone($settings['timezone']));
Chris@0 696 }
Chris@0 697 $value = $dateTimeObject->format($format);
Chris@0 698 }
Chris@0 699 catch (\Exception $e) {
Chris@0 700 $this->errors[] = $e->getMessage();
Chris@0 701 }
Chris@0 702
Chris@0 703 return $value;
Chris@0 704 }
Chris@0 705
Chris@14 706 /**
Chris@14 707 * Sets the default time for an object built from date-only data.
Chris@14 708 *
Chris@14 709 * The default time for a date without time can be anything, so long as it is
Chris@14 710 * consistently applied. If we use noon, dates in most timezones will have the
Chris@14 711 * same value for in both the local timezone and UTC.
Chris@14 712 */
Chris@14 713 public function setDefaultDateTime() {
Chris@14 714 $this->dateTimeObject->setTime(12, 0, 0);
Chris@14 715 }
Chris@14 716
Chris@17 717 /**
Chris@17 718 * Gets a clone of the proxied PHP \DateTime object wrapped by this class.
Chris@17 719 *
Chris@17 720 * @return \DateTime
Chris@17 721 * A clone of the wrapped PHP \DateTime object.
Chris@17 722 */
Chris@17 723 public function getPhpDateTime() {
Chris@17 724 return clone $this->dateTimeObject;
Chris@17 725 }
Chris@17 726
Chris@0 727 }