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 all commits
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
53 changes: 53 additions & 0 deletions dt-reports/reports.php
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,59 @@ public static function get( $value, $type ) : array {
return $report;
}

/**
* List reports filtered by where clauses
*
* @param array $where An assoc array of key, value pairs
*
* The value parts of the array should be arrays, with 'value' => $value. This allows for adding functionality like operators etc.
*/
public static function list( $where = [] ) {
global $wpdb;
$report = [];

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

foreach ( $where as $key => $details ) {
if ( !is_array( $details ) || !isset( $details['value'] ) ) {
return new WP_Error( 'missing-value-type', 'value key is missing for ' . $key );
}
$value = $details['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 {
return new WP_Error( 'invalid-value-type', ' $value is of type ' . gettype( $value ) . ' but should be a string or number' );
}
$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