self::DEFAULT_THRESHOLDS, 'min_cluster_size' => self::DEFAULT_MIN_CLUSTER_SIZE, ); } /** * Validates settings coming from the form or the database. * * @param array $input Raw values: thresholds (3 numbers), min_cluster_size. * * @return array{thresholds: float[], min_cluster_size: int}|WP_Error */ public static function sanitize( array $input ) { $thresholds = $input['thresholds'] ?? null; if ( ! is_array( $thresholds ) || 3 !== count( $thresholds ) ) { return new WP_Error( 'invalid_thresholds', __( 'Enter three similarity thresholds.', 'creator-assistant-categories' ) ); } $values = array(); foreach ( array_values( $thresholds ) as $threshold ) { // Round first: the saved value is the rounded one, so 0.996 would // be stored as 1.0 and 0.004 as 0.0, both outside the open range. $rounded = is_numeric( $threshold ) ? round( (float) $threshold, 2 ) : 0.0; if ( $rounded <= 0 || $rounded >= 1 ) { return new WP_Error( 'invalid_thresholds', __( 'Every threshold must be a number between 0 and 1.', 'creator-assistant-categories' ) ); } $values[] = $rounded; } if ( ! ( $values[0] < $values[1] && $values[1] < $values[2] ) ) { return new WP_Error( 'invalid_thresholds', __( 'Each level needs a higher threshold than the one above it.', 'creator-assistant-categories' ) ); } // A whole number only: casting would silently turn 2.7 into 2. $size = filter_var( $input['min_cluster_size'] ?? null, FILTER_VALIDATE_INT, array( 'options' => array( 'min_range' => 1, 'max_range' => self::MAX_MIN_CLUSTER_SIZE, ), ) ); if ( false === $size ) { return new WP_Error( 'invalid_min_cluster_size', /* translators: %d: the largest accepted value. */ sprintf( __( 'The minimum number of articles per category must be between 1 and %d.', 'creator-assistant-categories' ), self::MAX_MIN_CLUSTER_SIZE ) ); } return array( 'thresholds' => $values, 'min_cluster_size' => $size, ); } /** * Saves already sanitized settings. Not autoloaded: read only by the admin * page and when an analysis starts. * * @param array{thresholds: float[], min_cluster_size: int} $settings Sanitized settings. * * @return void */ public static function save( array $settings ): void { update_option( Config::SETTINGS_OPTION, $settings, false ); } }