name = $name; $this->status = self::STATUS_PENDING; $this->payload = $payload; $this->extra_data = $extra_data; $this->created_at = date( 'Y-m-d H:i:s' ); // phpcs:ignore $this->save(); } /** * Save the event to DB for processing * @return void */ private function save() { // We need at very least the name. if ( empty( $this->name ) ) { return; } // Ensure table exists before any DB operations. // This is a performant check using static + option caching. MonsterInsights_Tracking::maybe_create_table(); global $wpdb; $table_name = MonsterInsights_Tracking::get_db_table_name(); $data = [ 'name' => $this->name, 'status' => $this->status, 'payload' => serialize( apply_filters( 'monsterinsights_tracking_event_payload', $this->payload, $this->name ) ), 'extra_data' => serialize( apply_filters( 'monsterinsights_tracking_event_extra_data', $this->extra_data, $this->name ) ), 'attempts' => $this->attempts, 'last_error' => $this->last_error, 'created_at' => $this->created_at, ]; if ( !$this->exists_in_db() ) { $wpdb->insert( $table_name, $data ); $this->id = $wpdb->insert_id; } else { $wpdb->update( $table_name, $data, array( 'id' => $this->id ) ); } } /** * Get the id of the event * @return int|null */ public function get_id() { return $this->id; } /** * Updates the last error for the event and saves it. * * @param mixed $error The error to be serialized and stored. * @param bool $increaseAttempts Optional. Whether to increment the attempts counter. Defaults to true. * * @return void */ public function update_error( $error, $increaseAttempts = true ) { $this->last_error = serialize($error); if ( $increaseAttempts ) { $this->attempts ++; } $this->save(); } /** * Delete event from DB. Should be called after being tracked successfully * * @return void */ public function delete() { // Ensure table exists before any DB operations. // This is a performant check using static + option caching. MonsterInsights_Tracking::maybe_create_table(); global $wpdb; $table_name = MonsterInsights_Tracking::get_db_table_name(); $wpdb->delete( $table_name, array( 'id' => $this->id ) ); } /** * Whether the event is saved in DB * @return bool */ public function exists_in_db() { return null !== $this->id; } /** * @inheritdoc */ #[\ReturnTypeWillChange] public function jsonSerialize() { $json = [ 'client_event_id' => $this->id, 'event_name' => $this->name, 'timestamp' => strtotime( $this->created_at ), 'payload' => $this->payload, ]; return array_merge( $json, $this->extra_data ); } }