/** * @Todo Separate this method to some DateTime Utils class * * @param string $value * @param string $pattern * @return DateTime * @throws DateTimeParseException */ private static function validateValue($value, $pattern) { $value = static::strip($value); if (($parsed = DateTime::createFromFormat($pattern, $value)) === FALSE) { throw new DateTimeParseException("Value does not match desired format: '{$pattern}'."); } $error = DateTime::getLastErrors(); if ($error['error_count'] > 0 || $error['warning_count'] > 0) { throw new DateTimeParseException('Invalid date given. ' . 'Errors: ' . implode(', ', $error['errors']) . ' ' . 'Warnings: ' . implode(', ', $error['warnings'])); } $strippedCrossCheckValue = static::strip($parsed->format($pattern)); if ($value !== $strippedCrossCheckValue) { throw new DateTimeParseException("Invalid date given. Check value does not match original. ['{$strippedCrossCheckValue}' !== '{$value}']"); } return $parsed; }
/** * @param string $value * @param string $pattern * @return DateTime * @throws DateTimeParseException */ protected function createFromFormat($value, $pattern) { $parsed = DateTime::createFromFormat($pattern, $value); $errors = DateTime::getLastErrors(); if ($parsed === FALSE || $errors['error_count'] > 0 || $errors['warning_count'] > 0) { $message = sprintf('Invalid date given. Errors: [%s], Warnings: [%s]', implode(', ', $errors['errors']), implode(', ', $errors['warnings'])); throw new DateTimeParseException(sprintf("Value does not match desired format: '%s'. Error message: '%s'", $pattern, $message)); } return $parsed; }