annotate core/lib/Drupal/Component/Datetime/DateTimePlus.php @ 6:875880e46745

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