| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* Class WpStream_Log_Entry |
| 5 |
* |
| 6 |
* Represents a single log entry in the WpStream logging system. |
| 7 |
*/ |
| 8 |
class WpStream_Logger { |
| 9 |
/** |
| 10 |
* The option name where the logs are stored in wp_options |
| 11 |
* |
| 12 |
* @var string |
| 13 |
*/ |
| 14 |
private $option_name = 'wpstream_logs'; |
| 15 |
|
| 16 |
/** |
| 17 |
* Maximum number of logs to store |
| 18 |
*/ |
| 19 |
private $max_logs = 100; |
| 20 |
|
| 21 |
|
| 22 |
public function __construct() { |
| 23 |
} |
| 24 |
|
| 25 |
/** |
| 26 |
* Add a log entry to the logs |
| 27 |
* |
| 28 |
* @param WpStream_Log_Entry $entry Log entry object |
| 29 |
* |
| 30 |
* @return bool True on success, false on failure |
| 31 |
*/ |
| 32 |
public function add( $entry ): bool { |
| 33 |
if ( ! ($entry instanceof WpStream_Log_Entry) ) { |
| 34 |
return false; |
| 35 |
} |
| 36 |
|
| 37 |
$logs = $this->getAll(); |
| 38 |
|
| 39 |
$log_data = [ |
| 40 |
'timestamp' => $entry->timestamp, |
| 41 |
'type' => $entry->type, |
| 42 |
'description' => $entry->description, |
| 43 |
]; |
| 44 |
|
| 45 |
array_unshift( $logs, $log_data ); |
| 46 |
|
| 47 |
if ( count( $logs ) > $this->max_logs ) { |
| 48 |
$logs = array_slice( $logs, 0, $this->max_logs ); |
| 49 |
} |
| 50 |
|
| 51 |
return update_option( $this->option_name, $logs ); |
| 52 |
} |
| 53 |
|
| 54 |
/** |
| 55 |
* Get all logs |
| 56 |
* |
| 57 |
* @return array Array of log entries |
| 58 |
*/ |
| 59 |
public function getAll(): array { |
| 60 |
$logs = get_option( $this->option_name, array() ); |
| 61 |
|
| 62 |
return is_array( $logs ) ? $logs : array(); |
| 63 |
} |
| 64 |
|
| 65 |
/** |
| 66 |
* Clear logs older than 30 days |
| 67 |
* |
| 68 |
* @return bool True on success, false otherwise |
| 69 |
*/ |
| 70 |
public function clear_old_logs(): bool { |
| 71 |
$logs = $this->getAll(); |
| 72 |
|
| 73 |
$one_month_ago = time() - (30 * DAY_IN_SECONDS); |
| 74 |
$filtered_logs = array_filter( $logs, function( $log ) use ( $one_month_ago ) { |
| 75 |
return $log['timestamp'] >= $one_month_ago; |
| 76 |
}); |
| 77 |
|
| 78 |
return update_option( $this->option_name, $filtered_logs ); |
| 79 |
} |
| 80 |
} |