Created
August 18, 2014 13:53
-
-
Save mattheu/7f2c0b7325e218eabb90 to your computer and use it in GitHub Desktop.
Sanitization/Validation Helper Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class CFO_Sanitize { | |
public static function sanitize_array( $fields, $data ) { | |
$clean_data = array(); | |
foreach ( $fields as $field ) { | |
if ( ! isset( $field[ 'sanitize_callback' ] ) ) { | |
continue; | |
} | |
if ( isset( $data[ $field['node'] ] ) ) { | |
$dirty_value = $data[ $field['node'] ]; | |
if ( isset( $field['parse_callback'] ) ) { | |
$dirty_value = call_user_func( $field['parse_callback'], $dirty_value ); | |
} | |
$clean_data[ $field['node'] ] = call_user_func( $field['sanitize_callback'], $dirty_value ); | |
} elseif ( array_key_exists( 'default', $field ) ) { | |
$clean_data[ $field['node'] ] = $field['default']; | |
} | |
} | |
return $clean_data; | |
} | |
protected static function sanitize_numeric_array( $data ) { | |
return array_map( 'absint', $data ); | |
} | |
} | |
$raw_data = array( | |
'test1' => '<script>alert(\'bad_data\');</script>', | |
'test2' => 'Good Data', | |
'test3' => 'Invalid Data', | |
'test4' => 'matthew@matth.com', | |
'test5' => 'matthew at matth . eu', | |
'test7' => array( 1, 'test' ), | |
); | |
$field_data = array( | |
array( | |
'node' => 'test1', | |
'sanitize_callback' => 'sanitize_text_field', | |
), | |
array( | |
'node' => 'test2', | |
'sanitize_callback' => 'sanitize_text_field', | |
), | |
array( | |
'node' => 'test4', | |
'sanitize_callback' => 'sanitize_email', | |
), | |
array( | |
'node' => 'test5', | |
'sanitize_callback' => 'sanitize_email', | |
), | |
array( | |
'node' => 'test6', | |
'sanitize_callback' => 'sanitize_text_field', | |
'default' => __( 'Recommended from CFO.com' ), | |
), | |
array( | |
'node' => 'test7', | |
'sanitize_callback' => array( 'CFO_Sanitize', 'sanitize_numeric_array' ), | |
'default' => __( 'Recommended from CFO.com' ), | |
), | |
); | |
hm( CFO_Sanitize::sanitize_array( $field_data, $raw_data ) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment