3 namespace Drupal\Core\Datetime\Element;
5 use Drupal\Core\Datetime\DrupalDateTime;
6 use Drupal\Core\Render\Element\FormElement;
9 * Provides a base class for date elements.
11 abstract class DateElementBase extends FormElement {
14 * Specifies the start and end year to use as a date range.
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.
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.
23 * @param string $string
24 * A min and max year string like '-3:+1' or '2000:2010' or '2000:+3'.
26 * (optional) A date object to test as a default value. Defaults to NULL.
29 * A numerically indexed array, containing the minimum and maximum year
30 * described by this pattern.
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);
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];
45 $min_year = $this_year;
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];
53 $max_year = $this_year;
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) {
60 $max_year = $min_year;
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);
69 return [$min_year, $max_year];