time(), 'geo' => $geo, 'seo' => $seo, ); if ( count( $points ) > self::CAP ) { // Keep the baseline and the newest; drop from just after the start, // which is the stretch nobody reads. $first = array_shift( $points ); $points = array_slice( $points, count( $points ) - ( self::CAP - 1 ) ); array_unshift( $points, $first ); } update_post_meta( $post_id, self::META, $points ); } /** * The series for one post, oldest first. * * @param int $post_id Post. * @return array */ public static function read( int $post_id ): array { $raw = get_post_meta( $post_id, self::META, true ); if ( ! is_array( $raw ) ) { return array(); } $out = array(); foreach ( $raw as $point ) { if ( ! is_array( $point ) || ! isset( $point['t'] ) ) { continue; } $out[] = array( 't' => (int) $point['t'], 'geo' => (int) ( $point['geo'] ?? 0 ), 'seo' => (int) ( $point['seo'] ?? 0 ), ); } return $out; } /** * The one sentence a page can make from its own history. * * Null until there are two points: with one reading there is a score and * no story, and "+0 since today" is worse than saying nothing. * * @param int $post_id Post. * @return array{geo:int, seo:int, since:int, points:int, series:array}|null */ public static function change( int $post_id ): ?array { $points = self::read( $post_id ); if ( count( $points ) < 2 ) { return null; } $first = $points[0]; $last = $points[ count( $points ) - 1 ]; return array( 'geo' => (int) $last['geo'] - (int) $first['geo'], 'seo' => (int) $last['seo'] - (int) $first['seo'], 'since' => (int) $first['t'], 'points' => count( $points ), // The GEO series alone, for a sparkline that has to fit in a row. 'series' => array_map( static fn( array $p ): int => (int) $p['geo'], $points ), ); } }