time(), 'type' => sanitize_key( $type ), 'message' => sanitize_text_field( $message ), ); if ( count( $log ) > self::MAX ) { $log = array_slice( $log, -self::MAX ); } update_option( self::OPTION, $log, false ); } /** * @return array */ public static function all() { $log = get_option( self::OPTION, array() ); return is_array( $log ) ? $log : array(); } /** * Newest-first slice, optional type filter. * * @param int $limit Max rows. * @param string|null $type Type filter or empty for all. * @return array */ public static function recent( $limit = 50, $type = null ) { $events = array_reverse( self::all() ); $type = $type ? sanitize_key( $type ) : ''; if ( $type ) { $events = array_values( array_filter( $events, function ( $ev ) use ( $type ) { return isset( $ev['type'] ) && $ev['type'] === $type; } ) ); } $limit = max( 1, min( self::MAX, (int) $limit ) ); return array_slice( $events, 0, $limit ); } /** * Distinct types present in the log. * * @return string[] */ public static function types() { $types = array(); foreach ( self::all() as $ev ) { if ( ! empty( $ev['type'] ) ) { $types[ $ev['type'] ] = true; } } $keys = array_keys( $types ); sort( $keys ); return $keys; } /** * Empty the log. */ public static function clear() { delete_option( self::OPTION ); } /** * Human label for a type key. * * @param string $type Type. * @return string */ public static function type_label( $type ) { $map = array( 'purge_all' => __( 'Purge all', 'qw-optimize' ), 'purge_url' => __( 'Purge URL', 'qw-optimize' ), 'purge' => __( 'Purge', 'qw-optimize' ), 'missed_schedule' => __( 'Missed schedule', 'qw-optimize' ), 'unpublish' => __( 'Unpublish', 'qw-optimize' ), 'media' => __( 'Media', 'qw-optimize' ), 'preload' => __( 'Preload', 'qw-optimize' ), 'cdn' => __( 'CDN', 'qw-optimize' ), 'settings' => __( 'Settings', 'qw-optimize' ), ); $type = sanitize_key( $type ); return isset( $map[ $type ] ) ? $map[ $type ] : $type; } }