Skip to content

Instantly share code, notes, and snippets.

@svandragt
Created August 13, 2023 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svandragt/6d8fed043879bb83b33a29303fdf556f to your computer and use it in GitHub Desktop.
Save svandragt/6d8fed043879bb83b33a29303fdf556f to your computer and use it in GitHub Desktop.
Timestamp data
<?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 ) );
}
@svandragt
Copy link
Author

age: 1691923207; value:
> write(1691923207 > 13)...
age: 2; value: 136
age: 6; value: 136
age: 9; value: 136
age: 12; value: 136
age: 14; value: 136
> write(14 > 13)...
age: 3; value: 31
age: 5; value: 31
age: 10; value: 31
age: 14; value: 31
> write(14 > 13)...
age: 1; value: 827
age: 5; value: 827
age: 6; value: 827
^C

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment