public static function DateTimePlus::checkArray

public static DateTimePlus::checkArray($array)

Checks that arrays of date parts will create a valid date.

Checks that an array of date parts has a year, month, and day, and that those values create a valid date. If time is provided, verifies that the time values are valid. Sort of an equivalent to checkdate().

Parameters

array $array: An array of datetime values keyed by date part.

Return value

bool TRUE if the datetime parts contain valid values, otherwise FALSE.

File

core/lib/Drupal/Component/Datetime/DateTimePlus.php, line 567

Class

DateTimePlus
Wraps DateTime().

Namespace

Drupal\Component\Datetime

Code

public static function checkArray($array) {
  $valid_date = FALSE;
  $valid_time = TRUE;
  // Check for a valid date using checkdate(). Only values that
  // meet that test are valid.
  if (array_key_exists('year', $array) && array_key_exists('month', $array) && array_key_exists('day', $array)) {
    if (@checkdate($array['month'], $array['day'], $array['year'])) {
      $valid_date = TRUE;
    }
  }
  // Testing for valid time is reversed. Missing time is OK,
  // but incorrect values are not.
  foreach (array('hour', 'minute', 'second') as $key) {
    if (array_key_exists($key, $array)) {
      $value = $array[$key];
      switch ($key) {
        case 'hour':
          if (!preg_match('/^([1-2][0-3]|[01]?[0-9])$/', $value)) {
            $valid_time = FALSE;
          }
          break;
        case 'minute':
        case 'second':
        default:
          if (!preg_match('/^([0-5][0-9]|[0-9])$/', $value)) {
            $valid_time = FALSE;
          }
          break;
      }
    }
  }
  return $valid_date && $valid_time;
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Component!Datetime!DateTimePlus.php/function/DateTimePlus::checkArray/8.1.x