prefix . Accredible_Learndash_Admin_Database::AUTO_ISSUANCES_TABLE_NAME; } /** * Validate inserting or updating data. * * @throws Exception Exception containing the validation error message. * * @param array $data Inserting or updating data. * @param int $id ID of the record. */ public static function validate( $data, $id = null ) { parent::validate( $data, $id ); $post_id = array_key_exists( 'post_id', $data ) ? $data['post_id'] : null; $kind = array_key_exists( 'kind', $data ) ? $data['kind'] : null; if ( ! self::is_kind_valid( $kind ) ) { throw new Exception( esc_attr( $kind ) . ' is an invalid kind.' ); } if ( self::is_duplicate( $post_id, $kind, $id ) ) { $title = get_the_title( $post_id ); if ( empty( $title ) ) { $title = 'Post ID ' . $post_id; } throw new Exception( esc_attr( $title ) . ' already has the same kind of auto issuance.' ); } } /** * Check if the kind value is valid. * * @param string|null $kind Kind of the record. */ private static function is_kind_valid( $kind ) { return is_null( $kind ) || in_array( $kind, self::KINDS, true ); } /** * Check if the pair of the post_id & the kind is a duplicate. * * @param int|null $post_id Post ID of the record. * @param string|null $kind Kind of the record. * @param int|null $id ID of the record. */ private static function is_duplicate( $post_id, $kind, $id ) { $where_array = array(); $where_args = array(); // When updating the existing record. if ( ! empty( $id ) ) { $auto_issuance = static::get_row( 'id = %d', array( $id ) ); if ( empty( $post_id ) ) { $post_id = $auto_issuance->post_id; } if ( empty( $kind ) ) { $kind = $auto_issuance->kind; } array_push( $where_array, 'id != %d' ); array_push( $where_args, $id ); } array_push( $where_array, 'post_id = %d', 'kind = %s' ); array_push( $where_args, $post_id, $kind ); $duplicate_count = static::get_total_count( join( ' AND ', $where_array ), $where_args ); return $duplicate_count > 0; } } endif;