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