Created
August 13, 2023 10:49
-
-
Save svandragt/6d8fed043879bb83b33a29303fdf556f to your computer and use it in GitHub Desktop.
Timestamp data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// mock get_option / update_option using global state | |
require_once( 'mock.php' ); | |
/** | |
* Timestamp a value. | |
* update_option( $name, stamp( $value ) ); | |
* | |
* @param int|null $timestamp now, or provided time() compatible timestamp. | |
* | |
* @return string JSON encoded stamped data. | |
*/ | |
function stamp( mixed $value, int $timestamp = null ) : string { | |
if ( is_null( $timestamp ) ) { | |
$timestamp = time(); | |
} | |
$a = [ | |
'ts' => $timestamp, | |
'value' => $value, | |
]; | |
return json_encode( $a ); | |
} | |
/** | |
* Return a stamped value. | |
* [ $age, $value ] = stamped( get_option( $name, $default ) ); | |
* | |
* @param string $json Data encoded by stamp(). | |
* | |
* @return array [ | |
* $age int Age in seconds. | |
* $value mixed Original data. | |
* ] | |
*/ | |
function stamped( string $json ) : array { | |
$a = json_decode( $json, true ); | |
$a['age'] = time() - (int) $a['ts']; | |
return [ $a['age'], $a['value'] ]; | |
} | |
$name = 'test_data'; | |
while ( true ) { | |
$default = stamp( null, 0 ); | |
[ $age, $valued ] = stamped( get_option( $name, $default ) ); | |
printf( 'age: %d; value: %s' . PHP_EOL, $age, $valued ); | |
if ( $age > 13 ) { | |
printf('> write(%d > %d)...' . PHP_EOL, $age, 13); | |
$value = random_int( 0, 1000 ); | |
update_option( $name, stamp( $value ) ); | |
} | |
sleep( random_int( 1, 5 ) ); | |
} |
Author
svandragt
commented
Aug 13, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment