Skip to content

feat: add where function to dt-reports class #2484

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 27, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions dt-reports/reports.php
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,54 @@ public static function get( $value, $type ) : array {
return $report;
}

/**
* Get posts filtered by where clauses
*
* @param array $where An assoc array of key, value pairs
*/
public static function where( $where = [] ) {
global $wpdb;
$report = [];

$sql = '';
$args = [];

foreach ( $where as $key => $value ) {
$new_sql = '';
if ( !empty( $sql ) ) {
$new_sql .= ' AND';
} else {
$new_sql .= ' WHERE';
}

$new_sql .= $wpdb->prepare( ' %1$s = ', $key );

if ( is_numeric( $value ) ) {
$new_sql .= '%d';
} else if ( is_string( $value ) ) {
$new_sql .= '%s';
} else {
dt_write_log( __METHOD__ . ' $value is of type ' . gettype( $value ) . ' but should be a string or number' );
continue;
}
$sql .= $new_sql;
$args[] = $value;
}

//phpcs:ignore
$results = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->dt_reports $sql", $args ), ARRAY_A );
if ( ! empty( $results ) ) {
foreach ( $results as $index => $result ){
if ( isset( $result['payload'] ) ){
$results[$index]['payload'] = maybe_unserialize( $result['payload'] );
}
}
$report = $results;
}

return $report;
}

/**
* Delete report
*
Expand Down
Loading