__( 'is', 'fillnova' ), 'is_not' => __( 'is not', 'fillnova' ), 'contains' => __( 'contains', 'fillnova' ), 'not_contains' => __( 'does not contain', 'fillnova' ), 'gt' => __( 'greater than', 'fillnova' ), 'lt' => __( 'less than', 'fillnova' ), 'empty' => __( 'is empty', 'fillnova' ), 'not_empty' => __( 'is not empty', 'fillnova' ), ); } /** * Sanitize a conditions object. * * @param mixed $c Conditions. * @return array */ public static function sanitize( $c ) { $c = (array) $c; $ops = array_keys( self::operators() ); $out = array( 'enabled' => ! empty( $c['enabled'] ), 'action' => isset( $c['action'] ) && 'hide' === $c['action'] ? 'hide' : 'show', 'match' => isset( $c['match'] ) && 'any' === $c['match'] ? 'any' : 'all', 'rules' => array(), ); foreach ( (array) fillnova_arr( $c, 'rules', array() ) as $r ) { $r = (array) $r; if ( empty( $r['field'] ) ) { continue; } $out['rules'][] = array( 'field' => sanitize_key( $r['field'] ), 'operator' => isset( $r['operator'] ) && in_array( $r['operator'], $ops, true ) ? $r['operator'] : 'is', 'value' => isset( $r['value'] ) ? sanitize_text_field( (string) $r['value'] ) : '', ); } return $out; } /** * Is the field visible given the submitted values? * * @param array $field Field. * @param array $values Values by field id. * @return bool */ public static function is_visible( $field, $values ) { $c = isset( $field['conditions'] ) ? $field['conditions'] : null; if ( empty( $c['enabled'] ) || empty( $c['rules'] ) ) { return true; } $results = array(); foreach ( $c['rules'] as $rule ) { $v = isset( $values[ $rule['field'] ] ) ? $values[ $rule['field'] ] : ''; $results[] = self::check( $v, $rule['operator'], $rule['value'] ); } $pass = 'any' === $c['match'] ? in_array( true, $results, true ) : ! in_array( false, $results, true ); return 'show' === $c['action'] ? $pass : ! $pass; } /** * Evaluate one rule. * * @param mixed $value Value. * @param string $operator Operator. * @param string $target Target. * @return bool */ public static function check( $value, $operator, $target ) { $list = is_array( $value ) ? array_map( 'strval', array_values( $value ) ) : array( (string) $value ); $str = strtolower( implode( ', ', $list ) ); $t = strtolower( (string) $target ); switch ( $operator ) { case 'is': return in_array( $t, array_map( 'strtolower', $list ), true ) || $str === $t; case 'is_not': return ! in_array( $t, array_map( 'strtolower', $list ), true ) && $str !== $t; case 'contains': return '' !== $t && false !== strpos( $str, $t ); case 'not_contains': return '' === $t || false === strpos( $str, $t ); case 'gt': return is_numeric( $str ) && is_numeric( $t ) && (float) $str > (float) $t; case 'lt': return is_numeric( $str ) && is_numeric( $t ) && (float) $str < (float) $t; case 'empty': return '' === trim( $str ); case 'not_empty': return '' !== trim( $str ); } return false; } }