Skip to content

Instantly share code, notes, and snippets.

@sudarshann
Created May 2, 2020 16:48
Show Gist options
  • Save sudarshann/07252cdeeee201e20ab56fd01967758d to your computer and use it in GitHub Desktop.
Save sudarshann/07252cdeeee201e20ab56fd01967758d to your computer and use it in GitHub Desktop.
public static function acf_validate_vocher_code_unique($valid, $value, $field, $input_name) {
// Bail early if value is already invalid.
if ($valid !== true) {
return $valid;
}
$result = self::validate_voucher_unqiue($value);
if( !empty($result) ){
return $result;
}
global $post;
$vochers = self::get_all_voucher_range($post->ID);
$result = self::validate_voucher_unqiue_all_tercarios($value, $vochers);
if (!empty($result)) {
return 'Overlapping Value for Voucher Codes. Overlap present in ' . $result;
} else {
return $valid;
}
return $valid;
}
public static function get_all_voucher_range($current_post) {
//get your custom posts ids as an array
$posts = get_posts(
array(
'post_type' => self::$post_type,
'post_status' => 'publish',
'posts_per_page' => -1,
'exclude' => array($current_post),
'fields' => 'ids'
)
);
$rows = [];
foreach ($posts as $post_id) {
$rows[$post_id] = get_field('voucher', $post_id);
}
return $rows;
}
public static function validate_voucher_unqiue($current_rows) {
$value_range = [];
foreach ($current_rows as $current_row) {
$current = array_values($current_row);
$current_start = $current[0];
$current_end = $current[1];
if($current_end < $current_start){
return 'End value should be bigger than Start Value';
}
/** This logic is worst for huge range of data **/
$value_range = array_merge ( $value_range, range($current_start, $current_end));
}
if (count($value_range) !== count(array_unique($value_range))){
return 'Overlapping Voucher codes range found in this range';
}
return false;
}
public static function validate_voucher_unqiue_all_tercarios($current_rows, $all_vouchers) {
foreach ($current_rows as $current_row) {
$current = array_values($current_row);
$current_start = $current[0];
$current_end = $current[1];
foreach ($all_vouchers as $post_id => $voucher) {
foreach ($voucher as $voucher_row) {
$start = $voucher_row['de'];
if (!empty($current_start) && !empty($current_end) && !empty($start)) {
if (($current_start <= $start) && ($start <= $current_end)) {
return get_edit_post_link($post_id);
}
}
$end = $voucher_row['ate'];
if (!empty($current_start) && !empty($current_end) && !empty($end)) {
if (($current_start <= $end) && ($end <= $current_end)) {
return get_edit_post_link($post_id);
}
}
}
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment