You are here

public static function DateTimePlus::checkArray in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/lib/Drupal/Component/Datetime/DateTimePlus.php \Drupal\Component\Datetime\DateTimePlus::checkArray()

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.

1 call to DateTimePlus::checkArray()
DateTimePlus::createFromArray in core/lib/Drupal/Component/Datetime/DateTimePlus.php
Creates a date object from an array of date parts.

File

core/lib/Drupal/Component/Datetime/DateTimePlus.php, line 513
Contains \Drupal\Component\Datetime\DateTimePlus.

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;
}