Chris@0: format(static::FORMAT), $datetime->getTimezone(), $settings); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Creates a date object from an array of date parts. Chris@0: * Chris@0: * Converts the input value into an ISO date, forcing a full ISO Chris@0: * date even if some values are missing. Chris@0: * Chris@0: * @param array $date_parts Chris@0: * An array of date parts, like ('year' => 2014, 'month' => 4). Chris@0: * @param mixed $timezone Chris@0: * (optional) \DateTimeZone object, time zone string or NULL. NULL uses the Chris@0: * default system time zone. Defaults to NULL. Chris@0: * @param array $settings Chris@0: * (optional) A keyed array for settings, suitable for passing on to Chris@0: * __construct(). Chris@0: * Chris@0: * @return static Chris@0: * A new DateTimePlus object. Chris@0: * Chris@0: * @throws \InvalidArgumentException Chris@0: * If the array date values or value combination is not correct. Chris@0: */ Chris@0: public static function createFromArray(array $date_parts, $timezone = NULL, $settings = []) { Chris@0: $date_parts = static::prepareArray($date_parts, TRUE); Chris@0: if (static::checkArray($date_parts)) { Chris@0: // Even with validation, we can end up with a value that the Chris@0: // DateTime class won't handle, like a year outside the range Chris@0: // of -9999 to 9999, which will pass checkdate() but Chris@0: // fail to construct a date object. Chris@0: $iso_date = static::arrayToISO($date_parts); Chris@0: return new static($iso_date, $timezone, $settings); Chris@0: } Chris@0: else { Chris@0: throw new \InvalidArgumentException('The array contains invalid values.'); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Creates a date object from timestamp input. Chris@0: * Chris@0: * The timezone of a timestamp is always UTC. The timezone for a Chris@0: * timestamp indicates the timezone used by the format() method. Chris@0: * Chris@0: * @param int $timestamp Chris@0: * A UNIX timestamp. Chris@0: * @param mixed $timezone Chris@0: * @see __construct() Chris@0: * @param array $settings Chris@0: * @see __construct() Chris@0: * Chris@0: * @return static Chris@0: * A new DateTimePlus object. Chris@0: * Chris@0: * @throws \InvalidArgumentException Chris@0: * If the timestamp is not numeric. Chris@0: */ Chris@0: public static function createFromTimestamp($timestamp, $timezone = NULL, $settings = []) { Chris@0: if (!is_numeric($timestamp)) { Chris@0: throw new \InvalidArgumentException('The timestamp must be numeric.'); Chris@0: } Chris@0: $datetime = new static('', $timezone, $settings); Chris@0: $datetime->setTimestamp($timestamp); Chris@0: return $datetime; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Creates a date object from an input format. Chris@0: * Chris@0: * @param string $format Chris@0: * PHP date() type format for parsing the input. This is recommended Chris@0: * to use things like negative years, which php's parser fails on, or Chris@0: * any other specialized input with a known format. If provided the Chris@0: * date will be created using the createFromFormat() method. Chris@0: * @see http://php.net/manual/datetime.createfromformat.php Chris@0: * @param mixed $time Chris@0: * @see __construct() Chris@0: * @param mixed $timezone Chris@0: * @see __construct() Chris@0: * @param array $settings Chris@0: * - validate_format: (optional) Boolean choice to validate the Chris@0: * created date using the input format. The format used in Chris@0: * createFromFormat() allows slightly different values than format(). Chris@0: * Using an input format that works in both functions makes it Chris@0: * possible to a validation step to confirm that the date created Chris@0: * from a format string exactly matches the input. This option Chris@0: * indicates the format can be used for validation. Defaults to TRUE. Chris@0: * @see __construct() Chris@0: * Chris@0: * @return static Chris@0: * A new DateTimePlus object. Chris@0: * Chris@0: * @throws \InvalidArgumentException Chris@0: * If the a date cannot be created from the given format. Chris@0: * @throws \UnexpectedValueException Chris@0: * If the created date does not match the input value. Chris@0: */ Chris@0: public static function createFromFormat($format, $time, $timezone = NULL, $settings = []) { Chris@0: if (!isset($settings['validate_format'])) { Chris@0: $settings['validate_format'] = TRUE; Chris@0: } Chris@0: Chris@0: // Tries to create a date from the format and use it if possible. Chris@0: // A regular try/catch won't work right here, if the value is Chris@0: // invalid it doesn't return an exception. Chris@0: $datetimeplus = new static('', $timezone, $settings); Chris@0: Chris@0: $date = \DateTime::createFromFormat($format, $time, $datetimeplus->getTimezone()); Chris@0: if (!$date instanceof \DateTime) { Chris@0: throw new \InvalidArgumentException('The date cannot be created from a format.'); Chris@0: } Chris@0: else { Chris@0: // Functions that parse date is forgiving, it might create a date that Chris@0: // is not exactly a match for the provided value, so test for that by Chris@0: // re-creating the date/time formatted string and comparing it to the input. For Chris@0: // instance, an input value of '11' using a format of Y (4 digits) gets Chris@0: // created as '0011' instead of '2011'. Chris@0: if ($date instanceof DateTimePlus) { Chris@0: $test_time = $date->format($format, $settings); Chris@0: } Chris@0: elseif ($date instanceof \DateTime) { Chris@0: $test_time = $date->format($format); Chris@0: } Chris@0: $datetimeplus->setTimestamp($date->getTimestamp()); Chris@0: $datetimeplus->setTimezone($date->getTimezone()); Chris@0: Chris@0: if ($settings['validate_format'] && $test_time != $time) { Chris@0: throw new \UnexpectedValueException('The created date does not match the input value.'); Chris@0: } Chris@0: } Chris@0: return $datetimeplus; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Constructs a date object set to a requested date and timezone. Chris@0: * Chris@0: * @param string $time Chris@0: * (optional) A date/time string. Defaults to 'now'. Chris@0: * @param mixed $timezone Chris@0: * (optional) \DateTimeZone object, time zone string or NULL. NULL uses the Chris@0: * default system time zone. Defaults to NULL. Note that the $timezone Chris@0: * parameter and the current timezone are ignored when the $time parameter Chris@0: * either is a UNIX timestamp (e.g. @946684800) or specifies a timezone Chris@0: * (e.g. 2010-01-28T15:00:00+02:00). Chris@14: * @see http://php.net/manual/datetime.construct.php Chris@0: * @param array $settings Chris@0: * (optional) Keyed array of settings. Defaults to empty array. Chris@0: * - langcode: (optional) String two letter language code used to control Chris@0: * the result of the format(). Defaults to NULL. Chris@0: * - debug: (optional) Boolean choice to leave debug values in the Chris@0: * date object for debugging purposes. Defaults to FALSE. Chris@0: */ Chris@0: public function __construct($time = 'now', $timezone = NULL, $settings = []) { Chris@0: Chris@0: // Unpack settings. Chris@0: $this->langcode = !empty($settings['langcode']) ? $settings['langcode'] : NULL; Chris@0: Chris@0: // Massage the input values as necessary. Chris@0: $prepared_time = $this->prepareTime($time); Chris@0: $prepared_timezone = $this->prepareTimezone($timezone); Chris@0: Chris@0: try { Chris@0: $this->errors = []; Chris@0: if (!empty($prepared_time)) { Chris@0: $test = date_parse($prepared_time); Chris@0: if (!empty($test['errors'])) { Chris@0: $this->errors = $test['errors']; Chris@0: } Chris@0: } Chris@0: Chris@0: if (empty($this->errors)) { Chris@0: $this->dateTimeObject = new \DateTime($prepared_time, $prepared_timezone); Chris@0: } Chris@0: } Chris@0: catch (\Exception $e) { Chris@0: $this->errors[] = $e->getMessage(); Chris@0: } Chris@0: Chris@0: // Clean up the error messages. Chris@0: $this->checkErrors(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Renders the timezone name. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: public function render() { Chris@0: return $this->format(static::FORMAT) . ' ' . $this->getTimeZone()->getName(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements the magic __call method. Chris@0: * Chris@0: * Passes through all unknown calls onto the DateTime object. Chris@0: * Chris@0: * @param string $method Chris@0: * The method to call on the decorated object. Chris@0: * @param array $args Chris@0: * Call arguments. Chris@0: * Chris@0: * @return mixed Chris@0: * The return value from the method on the decorated object. If the proxied Chris@0: * method call returns a DateTime object, then return the original Chris@0: * DateTimePlus object, which allows function chaining to work properly. Chris@0: * Otherwise, the value from the proxied method call is returned. Chris@0: * Chris@0: * @throws \Exception Chris@0: * Thrown when the DateTime object is not set. Chris@0: * @throws \BadMethodCallException Chris@0: * Thrown when there is no corresponding method on the DateTime object to Chris@0: * call. Chris@0: */ Chris@0: public function __call($method, array $args) { Chris@0: // @todo consider using assert() as per https://www.drupal.org/node/2451793. Chris@0: if (!isset($this->dateTimeObject)) { Chris@0: throw new \Exception('DateTime object not set.'); Chris@0: } Chris@0: if (!method_exists($this->dateTimeObject, $method)) { Chris@0: throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s()', get_class($this), $method)); Chris@0: } Chris@0: Chris@0: $result = call_user_func_array([$this->dateTimeObject, $method], $args); Chris@0: Chris@0: return $result === $this->dateTimeObject ? $this : $result; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the difference between two DateTimePlus objects. Chris@0: * Chris@0: * @param \Drupal\Component\Datetime\DateTimePlus|\DateTime $datetime2 Chris@0: * The date to compare to. Chris@0: * @param bool $absolute Chris@0: * Should the interval be forced to be positive? Chris@0: * Chris@0: * @return \DateInterval Chris@0: * A DateInterval object representing the difference between the two dates. Chris@0: * Chris@0: * @throws \BadMethodCallException Chris@0: * If the input isn't a DateTime or DateTimePlus object. Chris@0: */ Chris@0: public function diff($datetime2, $absolute = FALSE) { Chris@0: if ($datetime2 instanceof DateTimePlus) { Chris@0: $datetime2 = $datetime2->dateTimeObject; Chris@0: } Chris@0: if (!($datetime2 instanceof \DateTime)) { Chris@0: throw new \BadMethodCallException(sprintf('Method %s expects parameter 1 to be a \DateTime or \Drupal\Component\Datetime\DateTimePlus object', __METHOD__)); Chris@0: } Chris@0: return $this->dateTimeObject->diff($datetime2, $absolute); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements the magic __callStatic method. Chris@0: * Chris@0: * Passes through all unknown static calls onto the DateTime object. Chris@0: */ Chris@0: public static function __callStatic($method, $args) { Chris@0: if (!method_exists('\DateTime', $method)) { Chris@0: throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s()', get_called_class(), $method)); Chris@0: } Chris@0: return call_user_func_array(['\DateTime', $method], $args); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements the magic __clone method. Chris@0: * Chris@0: * Deep-clones the DateTime object we're wrapping. Chris@0: */ Chris@0: public function __clone() { Chris@0: $this->dateTimeObject = clone($this->dateTimeObject); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepares the input time value. Chris@0: * Chris@0: * Changes the input value before trying to use it, if necessary. Chris@0: * Can be overridden to handle special cases. Chris@0: * Chris@0: * @param mixed $time Chris@0: * An input value, which could be a timestamp, a string, Chris@0: * or an array of date parts. Chris@0: * Chris@0: * @return mixed Chris@0: * The massaged time. Chris@0: */ Chris@0: protected function prepareTime($time) { Chris@0: return $time; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepares the input timezone value. Chris@0: * Chris@0: * Changes the timezone before trying to use it, if necessary. Chris@0: * Most importantly, makes sure there is a valid timezone Chris@0: * object before moving further. Chris@0: * Chris@0: * @param mixed $timezone Chris@0: * Either a timezone name or a timezone object or NULL. Chris@0: * Chris@0: * @return \DateTimeZone Chris@0: * The massaged time zone. Chris@0: */ Chris@0: protected function prepareTimezone($timezone) { Chris@0: // If the input timezone is a valid timezone object, use it. Chris@0: if ($timezone instanceof \DateTimezone) { Chris@0: $timezone_adjusted = $timezone; Chris@0: } Chris@0: Chris@0: // Allow string timezone input, and create a timezone from it. Chris@0: elseif (!empty($timezone) && is_string($timezone)) { Chris@0: $timezone_adjusted = new \DateTimeZone($timezone); Chris@0: } Chris@0: Chris@0: // Default to the system timezone when not explicitly provided. Chris@0: // If the system timezone is missing, use 'UTC'. Chris@0: if (empty($timezone_adjusted) || !$timezone_adjusted instanceof \DateTimezone) { Chris@0: $system_timezone = date_default_timezone_get(); Chris@0: $timezone_name = !empty($system_timezone) ? $system_timezone : 'UTC'; Chris@0: $timezone_adjusted = new \DateTimeZone($timezone_name); Chris@0: } Chris@0: Chris@0: // We are finally certain that we have a usable timezone. Chris@0: return $timezone_adjusted; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepares the input format value. Chris@0: * Chris@0: * Changes the input format before trying to use it, if necessary. Chris@0: * Can be overridden to handle special cases. Chris@0: * Chris@0: * @param string $format Chris@0: * A PHP format string. Chris@0: * Chris@0: * @return string Chris@0: * The massaged PHP format string. Chris@0: */ Chris@0: protected function prepareFormat($format) { Chris@0: return $format; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Examines getLastErrors() to see what errors to report. Chris@0: * Chris@0: * Two kinds of errors are important: anything that DateTime Chris@0: * considers an error, and also a warning that the date was invalid. Chris@0: * PHP creates a valid date from invalid data with only a warning, Chris@0: * 2011-02-30 becomes 2011-03-03, for instance, but we don't want that. Chris@0: * Chris@0: * @see http://php.net/manual/time.getlasterrors.php Chris@0: */ Chris@0: public function checkErrors() { Chris@0: $errors = \DateTime::getLastErrors(); Chris@0: if (!empty($errors['errors'])) { Chris@0: $this->errors = array_merge($this->errors, $errors['errors']); Chris@0: } Chris@0: // Most warnings are messages that the date could not be parsed Chris@0: // which causes it to be altered. For validation purposes, a warning Chris@0: // as bad as an error, because it means the constructed date does Chris@0: // not match the input value. Chris@0: if (!empty($errors['warnings'])) { Chris@0: $this->errors[] = 'The date is invalid.'; Chris@0: } Chris@0: Chris@0: $this->errors = array_values(array_unique($this->errors)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Detects if there were errors in the processing of this date. Chris@0: * Chris@0: * @return bool Chris@0: * TRUE if there were errors in the processing of this date, FALSE Chris@0: * otherwise. Chris@0: */ Chris@0: public function hasErrors() { Chris@0: return (boolean) count($this->errors); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets error messages. Chris@0: * Chris@0: * Public function to return the error messages. Chris@0: * Chris@0: * @return array Chris@0: * An array of errors encountered when creating this date. Chris@0: */ Chris@0: public function getErrors() { Chris@0: return $this->errors; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Creates an ISO date from an array of values. Chris@0: * Chris@0: * @param array $array Chris@0: * An array of date values keyed by date part. Chris@0: * @param bool $force_valid_date Chris@0: * (optional) Whether to force a full date by filling in missing Chris@0: * values. Defaults to FALSE. Chris@0: * Chris@0: * @return string Chris@0: * The date as an ISO string. Chris@0: */ Chris@0: public static function arrayToISO($array, $force_valid_date = FALSE) { Chris@0: $array = static::prepareArray($array, $force_valid_date); Chris@0: $input_time = ''; Chris@0: if ($array['year'] !== '') { Chris@0: $input_time = static::datePad(intval($array['year']), 4); Chris@0: if ($force_valid_date || $array['month'] !== '') { Chris@0: $input_time .= '-' . static::datePad(intval($array['month'])); Chris@0: if ($force_valid_date || $array['day'] !== '') { Chris@0: $input_time .= '-' . static::datePad(intval($array['day'])); Chris@0: } Chris@0: } Chris@0: } Chris@0: if ($array['hour'] !== '') { Chris@0: $input_time .= $input_time ? 'T' : ''; Chris@0: $input_time .= static::datePad(intval($array['hour'])); Chris@0: if ($force_valid_date || $array['minute'] !== '') { Chris@0: $input_time .= ':' . static::datePad(intval($array['minute'])); Chris@0: if ($force_valid_date || $array['second'] !== '') { Chris@0: $input_time .= ':' . static::datePad(intval($array['second'])); Chris@0: } Chris@0: } Chris@0: } Chris@0: return $input_time; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Creates a complete array from a possibly incomplete array of date parts. Chris@0: * Chris@0: * @param array $array Chris@0: * An array of date values keyed by date part. Chris@0: * @param bool $force_valid_date Chris@0: * (optional) Whether to force a valid date by filling in missing Chris@0: * values with valid values or just to use empty values instead. Chris@0: * Defaults to FALSE. Chris@0: * Chris@0: * @return array Chris@0: * A complete array of date parts. Chris@0: */ Chris@0: public static function prepareArray($array, $force_valid_date = FALSE) { Chris@0: if ($force_valid_date) { Chris@0: $now = new \DateTime(); Chris@0: $array += [ Chris@0: 'year' => $now->format('Y'), Chris@0: 'month' => 1, Chris@0: 'day' => 1, Chris@0: 'hour' => 0, Chris@0: 'minute' => 0, Chris@0: 'second' => 0, Chris@0: ]; Chris@0: } Chris@0: else { Chris@0: $array += [ Chris@0: 'year' => '', Chris@0: 'month' => '', Chris@0: 'day' => '', Chris@0: 'hour' => '', Chris@0: 'minute' => '', Chris@0: 'second' => '', Chris@0: ]; Chris@0: } Chris@0: return $array; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Checks that arrays of date parts will create a valid date. Chris@0: * Chris@0: * Checks that an array of date parts has a year, month, and day, Chris@0: * and that those values create a valid date. If time is provided, Chris@0: * verifies that the time values are valid. Sort of an Chris@0: * equivalent to checkdate(). Chris@0: * Chris@0: * @param array $array Chris@0: * An array of datetime values keyed by date part. Chris@0: * Chris@0: * @return bool Chris@0: * TRUE if the datetime parts contain valid values, otherwise FALSE. Chris@0: */ Chris@0: public static function checkArray($array) { Chris@0: $valid_date = FALSE; Chris@0: $valid_time = TRUE; Chris@0: // Check for a valid date using checkdate(). Only values that Chris@0: // meet that test are valid. Chris@0: if (array_key_exists('year', $array) && array_key_exists('month', $array) && array_key_exists('day', $array)) { Chris@0: if (@checkdate($array['month'], $array['day'], $array['year'])) { Chris@0: $valid_date = TRUE; Chris@0: } Chris@0: } Chris@0: // Testing for valid time is reversed. Missing time is OK, Chris@0: // but incorrect values are not. Chris@0: foreach (['hour', 'minute', 'second'] as $key) { Chris@0: if (array_key_exists($key, $array)) { Chris@0: $value = $array[$key]; Chris@0: switch ($key) { Chris@0: case 'hour': Chris@0: if (!preg_match('/^([1-2][0-3]|[01]?[0-9])$/', $value)) { Chris@0: $valid_time = FALSE; Chris@0: } Chris@0: break; Chris@0: case 'minute': Chris@0: case 'second': Chris@0: default: Chris@0: if (!preg_match('/^([0-5][0-9]|[0-9])$/', $value)) { Chris@0: $valid_time = FALSE; Chris@0: } Chris@0: break; Chris@0: } Chris@0: } Chris@0: } Chris@0: return $valid_date && $valid_time; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Pads date parts with zeros. Chris@0: * Chris@0: * Helper function for a task that is often required when working with dates. Chris@0: * Chris@0: * @param int $value Chris@0: * The value to pad. Chris@0: * @param int $size Chris@0: * (optional) Size expected, usually 2 or 4. Defaults to 2. Chris@0: * Chris@0: * @return string Chris@0: * The padded value. Chris@0: */ Chris@0: public static function datePad($value, $size = 2) { Chris@0: return sprintf("%0" . $size . "d", $value); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Formats the date for display. Chris@0: * Chris@0: * @param string $format Chris@16: * Format accepted by date(). Chris@0: * @param array $settings Chris@0: * - timezone: (optional) String timezone name. Defaults to the timezone Chris@0: * of the date object. Chris@0: * Chris@0: * @return string|null Chris@0: * The formatted value of the date or NULL if there were construction Chris@0: * errors. Chris@0: */ Chris@0: public function format($format, $settings = []) { Chris@0: Chris@0: // If there were construction errors, we can't format the date. Chris@0: if ($this->hasErrors()) { Chris@0: return; Chris@0: } Chris@0: Chris@0: // Format the date and catch errors. Chris@0: try { Chris@0: // Clone the date/time object so we can change the time zone without Chris@0: // disturbing the value stored in the object. Chris@0: $dateTimeObject = clone $this->dateTimeObject; Chris@0: if (isset($settings['timezone'])) { Chris@0: $dateTimeObject->setTimezone(new \DateTimeZone($settings['timezone'])); Chris@0: } Chris@0: $value = $dateTimeObject->format($format); Chris@0: } Chris@0: catch (\Exception $e) { Chris@0: $this->errors[] = $e->getMessage(); Chris@0: } Chris@0: Chris@0: return $value; Chris@0: } Chris@0: Chris@14: /** Chris@14: * Sets the default time for an object built from date-only data. Chris@14: * Chris@14: * The default time for a date without time can be anything, so long as it is Chris@14: * consistently applied. If we use noon, dates in most timezones will have the Chris@14: * same value for in both the local timezone and UTC. Chris@14: */ Chris@14: public function setDefaultDateTime() { Chris@14: $this->dateTimeObject->setTime(12, 0, 0); Chris@14: } Chris@14: Chris@17: /** Chris@17: * Gets a clone of the proxied PHP \DateTime object wrapped by this class. Chris@17: * Chris@17: * @return \DateTime Chris@17: * A clone of the wrapped PHP \DateTime object. Chris@17: */ Chris@17: public function getPhpDateTime() { Chris@17: return clone $this->dateTimeObject; Chris@17: } Chris@17: Chris@0: }