Add utility method to normalize numeric “between” parameters in REST API requests.

This commit is contained in:
Jeff Stieler 2019-01-08 17:41:24 -07:00
parent d9fd8568df
commit b15a4bc804
2 changed files with 62 additions and 2 deletions

View File

@ -1,6 +1,6 @@
<?php
/**
* Class for time interval handling for reports
* Class for time interval and numeric range handling for reports.
*
* @package WooCommerce Admin/Classes
*/
@ -8,7 +8,7 @@
defined( 'ABSPATH' ) || exit;
/**
* Date & time interval handling class for Reporting API.
* Date & time interval and numeric range handling class for Reporting API.
*/
class WC_Admin_Reports_Interval {
@ -474,4 +474,38 @@ class WC_Admin_Reports_Interval {
}
}
/**
* Normalize "*_between" parameters to "*_min" and "*_max".
*
* @param array $request Query params from REST API request.
* @param string|array $param_names One or more param names to handle. Should not include "_between" suffix.
* @return array Normalized query values.
*/
public static function normalize_between_params( $request, $param_names ) {
if ( ! is_array( $param_names ) ) {
$param_names = array( $param_names );
}
$normalized = array();
foreach ( $param_names as $param_name ) {
if ( empty( $request[ $param_name . '_between' ] ) ) {
continue;
}
$min_param = $param_name . '_min';
$max_param = $param_name . '_max';
$range = explode( ',', $request[ $param_name . '_between' ] );
if ( isset( $range[0] ) && is_numeric( $range[0] ) ) {
$normalized[ $min_param ] = $range[0];
}
if ( isset( $range[1] ) && is_numeric( $range[1] ) ) {
$normalized[ $max_param ] = $range[1];
}
}
return $normalized;
}
}

View File

@ -796,4 +796,30 @@ class WC_Tests_Reports_Interval_Stats extends WC_Unit_Test_Case {
}
}
/**
* Test function that normalizes *_between query parameters to *_min & *_max.
*/
public function test_normalize_between_params() {
$request = array(
'a_between' => 'malformed', // won't be normalized.
'b_between' => '1,5', // results in min=1, max=5.
'c_between' => ',6', // results in max=6.
'd_between' => '7', // results in min=7.
'e_between' => '8,', // results in min=8.
'f_between' => '10,12', // not in params, skipped.
'g_between' => '-1,a', // results in min=-1.
);
$params = array( 'a', 'b', 'c', 'd', 'e', 'g' );
$result = WC_Admin_Reports_Interval::normalize_between_params( $request, $params );
$expected = array(
'b_min' => '1',
'b_max' => '5',
'c_max' => '6',
'd_min' => '7',
'e_min' => '8',
'g_min' => '-1',
);
$this->assertEquals( $result, $expected );
}
}