Skip to content

Commit

Permalink
Update CMB2_Type_Text_Datetime_Timestamp_Timezone to also use our CMB…
Browse files Browse the repository at this point in the history
…2_Utils::get_datetime_from_value helper
  • Loading branch information
jtsternberg committed Mar 29, 2024
1 parent 332afbf commit a4e92e3
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 52 deletions.
55 changes: 4 additions & 51 deletions includes/types/CMB2_Type_Text_Datetime_Timestamp_Timezone.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,12 @@ public function render( $args = array() ) {
$args['value'] = '';
}

$datetime = is_serialized( $args['value'] )
// Ok, we need to unserialize the value
// -- back-compat for older field values with serialized DateTime objects.
? self::unserialize_datetime( $args['value'] )
: self::json_to_datetime( $args['value'] );

$value = $tzstring = '';
$datetime = CMB2_Utils::get_datetime_from_value( $args['value'] );
$value = '';
$tzstring = '';

if ( $datetime && $datetime instanceof DateTime ) {
$tz = $datetime->getTimezone();
$tzstring = $tz->getName();
$tzstring = $datetime->getTimezone()->getName();
$value = $datetime->getTimestamp();
}

Expand All @@ -67,46 +62,4 @@ public function render( $args = array() ) {
$datetime_timestamp . "\n" . $select
);
}

/**
* Unserialize a datetime value string.
*
* This is a back-compat method for older field values with serialized DateTime objects.
*
* @since 2.11.0
*
* @param string $date_value The serialized datetime value.
*
* @return DateTime|null
*/
public static function unserialize_datetime( $date_value ) {
$datetime = @unserialize( trim( $date_value ), array( 'allowed_classes' => array( 'DateTime' ) ) );

return $datetime && $datetime instanceof DateTime ? $datetime : null;
}

/**
* Convert a json datetime value string to a DateTime object.
*
* @since 2.11.0
*
* @param string $json_string The json value string.
*
* @return DateTime|null
*/
public static function json_to_datetime( $json_string ) {
$json = json_decode( $json_string );

// Check if json decode was successful
if ( json_last_error() !== JSON_ERROR_NONE ) {
return null;
}

// If so, convert to DateTime object.
return self::unserialize_datetime( str_replace(
'stdClass',
'DateTime',
serialize( $json )
) );
}
}
2 changes: 1 addition & 1 deletion tests/test-cmb-types.php
Original file line number Diff line number Diff line change
Expand Up @@ -1124,7 +1124,7 @@ public function test_save_group() {
$date_values[] = '';
} else {
$timestamp = $datetime->setTimezone( new DateTimeZone( $tzstring ) )->getTimestamp();
$date_values[] = serialize( $datetime );
$date_values[] = json_encode( $datetime );
}
}
}
Expand Down

0 comments on commit a4e92e3

Please sign in to comment.