Version 1
[yaffs-website] / web / core / lib / Drupal / Core / Datetime / Element / DateElementBase.php
1 <?php
2
3 namespace Drupal\Core\Datetime\Element;
4
5 use Drupal\Core\Datetime\DrupalDateTime;
6 use Drupal\Core\Render\Element\FormElement;
7
8 /**
9  * Provides a base class for date elements.
10  */
11 abstract class DateElementBase extends FormElement {
12
13   /**
14    * Specifies the start and end year to use as a date range.
15    *
16    * Handles a string like -3:+3 or 2001:2010 to describe a dynamic range of
17    * minimum and maximum years to use in a date selector.
18    *
19    * Centers the range around the current year, if any, but expands it far enough
20    * so it will pick up the year value in the field in case the value in the field
21    * is outside the initial range.
22    *
23    * @param string $string
24    *   A min and max year string like '-3:+1' or '2000:2010' or '2000:+3'.
25    * @param object $date
26    *   (optional) A date object to test as a default value. Defaults to NULL.
27    *
28    * @return array
29    *   A numerically indexed array, containing the minimum and maximum year
30    *   described by this pattern.
31    */
32   protected static function datetimeRangeYears($string, $date = NULL) {
33     $datetime = new DrupalDateTime();
34     $this_year = $datetime->format('Y');
35     list($min_year, $max_year) = explode(':', $string);
36
37     // Valid patterns would be -5:+5, 0:+1, 2008:2010.
38     $plus_pattern = '@[\+|\-][0-9]{1,4}@';
39     $year_pattern = '@^[0-9]{4}@';
40     if (!preg_match($year_pattern, $min_year, $matches)) {
41       if (preg_match($plus_pattern, $min_year, $matches)) {
42         $min_year = $this_year + $matches[0];
43       }
44       else {
45         $min_year = $this_year;
46       }
47     }
48     if (!preg_match($year_pattern, $max_year, $matches)) {
49       if (preg_match($plus_pattern, $max_year, $matches)) {
50         $max_year = $this_year + $matches[0];
51       }
52       else {
53         $max_year = $this_year;
54       }
55     }
56     // We expect the $min year to be less than the $max year. Some custom values
57     // for -99:+99 might not obey that.
58     if ($min_year > $max_year) {
59       $temp = $max_year;
60       $max_year = $min_year;
61       $min_year = $temp;
62     }
63     // If there is a current value, stretch the range to include it.
64     $value_year = $date instanceof DrupalDateTime ? $date->format('Y') : '';
65     if (!empty($value_year)) {
66       $min_year = min($value_year, $min_year);
67       $max_year = max($value_year, $max_year);
68     }
69     return [$min_year, $max_year];
70   }
71
72 }