You are here

public static function DateTimePlus::checkArray in Drupal 8

Same name and namespace in other branches
  1. 9 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.

2 calls to DateTimePlus::checkArray()
DateTimePlus::createFromArray in core/lib/Drupal/Component/Datetime/DateTimePlus.php
Creates a date object from an array of date parts.
DateTimePlusTest::testCheckArray in core/tests/Drupal/Tests/Component/Datetime/DateTimePlusTest.php
Tests DateTimePlus::checkArray().

File

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

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. An empty value, either a string or a 0, is not
  // a valid value.
  if (!empty($array['year']) && !empty($array['month']) && !empty($array['day'])) {
    $valid_date = checkdate($array['month'], $array['day'], $array['year']);
  }

  // Testing for valid time is reversed. Missing time is OK,
  // but incorrect values are not.
  foreach ([
    '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;
}