diff --git a/lib/src/gateway/gateway.dart b/lib/src/gateway/gateway.dart index ccc2c11bc..226a8ca0c 100644 --- a/lib/src/gateway/gateway.dart +++ b/lib/src/gateway/gateway.dart @@ -382,7 +382,7 @@ class Gateway extends GatewayManager with EventParser { guildId: guildId, action: client.guilds[guildId].autoModerationRules.parseAutoModerationAction(raw['action'] as Map), ruleId: Snowflake.parse(raw['rule_id']!), - triggerType: TriggerType.parse(raw['rule_trigger_type'] as int), + triggerType: TriggerType(raw['rule_trigger_type'] as int), userId: Snowflake.parse(raw['user_id']!), channelId: maybeParse(raw['channel_id'], Snowflake.parse), messageId: maybeParse(raw['message_id'], Snowflake.parse), @@ -951,7 +951,7 @@ class Gateway extends GatewayManager with EventParser { (Map raw) => PartialUser(id: Snowflake.parse(raw['id']!), manager: client.users), ), guildId: maybeParse(raw['guild_id'], Snowflake.parse), - status: maybeParse(raw['status'], UserStatus.parse), + status: maybeParse(raw['status'], UserStatus.new), activities: maybeParseMany(raw['activities'], parseActivity), clientStatus: maybeParse(raw['client_status'], parseClientStatus), ); @@ -1029,6 +1029,7 @@ class Gateway extends GatewayManager with EventParser { InteractionType.modalSubmit => InteractionCreateEvent(gateway: this, interaction: interaction as ModalSubmitInteraction), InteractionType.applicationCommandAutocomplete => InteractionCreateEvent(gateway: this, interaction: interaction as ApplicationCommandAutocompleteInteraction), + InteractionType() => throw StateError('Unknown interaction type: ${interaction.type}'), } as InteractionCreateEvent>; } diff --git a/lib/src/http/managers/application_command_manager.dart b/lib/src/http/managers/application_command_manager.dart index 2b9013e0a..e79a70d7c 100644 --- a/lib/src/http/managers/application_command_manager.dart +++ b/lib/src/http/managers/application_command_manager.dart @@ -38,7 +38,7 @@ abstract class ApplicationCommandManager extends Manager { return ApplicationCommand( id: Snowflake.parse(raw['id']!), manager: this, - type: ApplicationCommandType.parse(raw['type'] as int? ?? 1), + type: ApplicationCommandType(raw['type'] as int? ?? 1), applicationId: Snowflake.parse(raw['application_id']!), guildId: maybeParse(raw['guild_id'], Snowflake.parse), name: raw['name'] as String, @@ -59,8 +59,8 @@ abstract class ApplicationCommandManager extends Manager { defaultMemberPermissions: maybeParse(raw['default_member_permissions'], (String raw) => Permissions(int.parse(raw))), hasDmPermission: raw['dm_permission'] as bool?, isNsfw: raw['nsfw'] as bool?, - integrationTypes: maybeParseMany(raw['integration_types'], ApplicationIntegrationType.parse) ?? [ApplicationIntegrationType.guildInstall], - contexts: maybeParseMany(raw['contexts'], InteractionContextType.parse), + integrationTypes: maybeParseMany(raw['integration_types'], ApplicationIntegrationType.new) ?? [ApplicationIntegrationType.guildInstall], + contexts: maybeParseMany(raw['contexts'], InteractionContextType.new), version: Snowflake.parse(raw['version']!), ); } @@ -68,7 +68,7 @@ abstract class ApplicationCommandManager extends Manager { /// Parse a [CommandOption] from [raw]. CommandOption parseApplicationCommandOption(Map raw) { return CommandOption( - type: CommandOptionType.parse(raw['type'] as int), + type: CommandOptionType(raw['type'] as int), name: raw['name'] as String, nameLocalizations: maybeParse( raw['name_localizations'], @@ -86,7 +86,7 @@ abstract class ApplicationCommandManager extends Manager { isRequired: raw['required'] as bool?, choices: maybeParseMany(raw['choices'], parseOptionChoice), options: maybeParseMany(raw['options'], parseApplicationCommandOption), - channelTypes: maybeParseMany(raw['channel_types'], ChannelType.parse), + channelTypes: maybeParseMany(raw['channel_types'], ChannelType.new), minValue: raw['min_value'] as num?, maxValue: raw['max_value'] as num?, minLength: raw['min_length'] as int?, @@ -234,7 +234,7 @@ class GuildApplicationCommandManager extends ApplicationCommandManager { CommandPermission parseCommandPermission(Map raw) { return CommandPermission( id: Snowflake.parse(raw['id']!), - type: CommandPermissionType.parse(raw['type'] as int), + type: CommandPermissionType(raw['type'] as int), hasPermission: raw['permission'] as bool, ); } diff --git a/lib/src/http/managers/application_manager.dart b/lib/src/http/managers/application_manager.dart index f2e373178..018fe87ff 100644 --- a/lib/src/http/managers/application_manager.dart +++ b/lib/src/http/managers/application_manager.dart @@ -65,7 +65,7 @@ class ApplicationManager { raw['integration_types_config'], (Map config) => { for (final MapEntry(:key, :value) in config.entries) - ApplicationIntegrationType.parse(int.parse(key)): parseApplicationIntegrationTypeConfiguration(value as Map) + ApplicationIntegrationType(int.parse(key)): parseApplicationIntegrationTypeConfiguration(value as Map) }, ), roleConnectionsVerificationUrl: maybeParse(raw['role_connections_verification_url'], Uri.parse), @@ -87,7 +87,7 @@ class ApplicationManager { /// Parse a [TeamMember] from [raw]. TeamMember parseTeamMember(Map raw) { return TeamMember( - membershipState: TeamMembershipState.parse(raw['membership_state'] as int), + membershipState: TeamMembershipState(raw['membership_state'] as int), teamId: Snowflake.parse(raw['team_id']!), user: PartialUser(id: Snowflake.parse((raw['user'] as Map)['id']!), manager: client.users), role: TeamMemberRole.parse(raw['role'] as String), @@ -112,7 +112,7 @@ class ApplicationManager { /// Parse a [ApplicationRoleConnectionMetadata] from [raw]. ApplicationRoleConnectionMetadata parseApplicationRoleConnectionMetadata(Map raw) { return ApplicationRoleConnectionMetadata( - type: ConnectionMetadataType.parse(raw['type'] as int), + type: ConnectionMetadataType(raw['type'] as int), key: raw['key'] as String, name: raw['name'] as String, localizedNames: maybeParse( @@ -132,7 +132,7 @@ class ApplicationManager { return Sku( manager: this, id: Snowflake.parse(raw['id']!), - type: SkuType.parse(raw['type'] as int), + type: SkuType(raw['type'] as int), applicationId: Snowflake.parse(raw['application_id']!), name: raw['name'] as String, slug: raw['slug'] as String, diff --git a/lib/src/http/managers/audit_log_manager.dart b/lib/src/http/managers/audit_log_manager.dart index 39cf5faab..ae8d533c2 100644 --- a/lib/src/http/managers/audit_log_manager.dart +++ b/lib/src/http/managers/audit_log_manager.dart @@ -24,7 +24,7 @@ class AuditLogManager extends ReadOnlyManager { targetId: maybeParse(raw['target_id'], Snowflake.parse), changes: maybeParseMany(raw['changes'], parseAuditLogChange), userId: maybeParse(raw['user_id'], Snowflake.parse), - actionType: AuditLogEvent.parse(raw['action_type'] as int), + actionType: AuditLogEvent(raw['action_type'] as int), options: maybeParse(raw['options'], parseAuditLogEntryInfo), reason: raw['reason'] as String?, ); @@ -53,7 +53,7 @@ class AuditLogManager extends ReadOnlyManager { membersRemoved: raw['members_removed'] as String?, messageId: maybeParse(raw['message_id'], Snowflake.parse), roleName: raw['role_name'] as String?, - overwriteType: maybeParse(raw['type'], (String raw) => PermissionOverwriteType.parse(int.parse(raw))), + overwriteType: maybeParse(raw['type'], (String raw) => PermissionOverwriteType(int.parse(raw))), integrationType: raw['integration_type'] as String?, ); } diff --git a/lib/src/http/managers/auto_moderation_manager.dart b/lib/src/http/managers/auto_moderation_manager.dart index 58f9acc89..1e074b9d2 100644 --- a/lib/src/http/managers/auto_moderation_manager.dart +++ b/lib/src/http/managers/auto_moderation_manager.dart @@ -25,8 +25,8 @@ class AutoModerationManager extends Manager { guildId: Snowflake.parse(raw['guild_id']!), name: raw['name'] as String, creatorId: Snowflake.parse(raw['creator_id']!), - eventType: AutoModerationEventType.parse(raw['event_type'] as int), - triggerType: TriggerType.parse(raw['trigger_type'] as int), + eventType: AutoModerationEventType(raw['event_type'] as int), + triggerType: TriggerType(raw['trigger_type'] as int), metadata: parseTriggerMetadata(raw['trigger_metadata'] as Map), actions: parseMany(raw['actions'] as List, parseAutoModerationAction), isEnabled: raw['enabled'] as bool, @@ -40,7 +40,7 @@ class AutoModerationManager extends Manager { return TriggerMetadata( keywordFilter: maybeParseMany(raw['keyword_filter']), regexPatterns: maybeParseMany(raw['regex_patterns']), - presets: maybeParseMany(raw['presets'], KeywordPresetType.parse), + presets: maybeParseMany(raw['presets'], KeywordPresetType.new), allowList: maybeParseMany(raw['allow_list']), mentionTotalLimit: raw['mention_total_limit'] as int?, isMentionRaidProtectionEnabled: raw['mention_raid_protection_enabled'] as bool?, @@ -50,7 +50,7 @@ class AutoModerationManager extends Manager { /// Parse a [AutoModerationAction] from [raw]. AutoModerationAction parseAutoModerationAction(Map raw) { return AutoModerationAction( - type: ActionType.parse(raw['type'] as int), + type: ActionType(raw['type'] as int), metadata: maybeParse(raw['metadata'], parseActionMetadata), ); } diff --git a/lib/src/http/managers/channel_manager.dart b/lib/src/http/managers/channel_manager.dart index f1bdff46e..79a327ac2 100644 --- a/lib/src/http/managers/channel_manager.dart +++ b/lib/src/http/managers/channel_manager.dart @@ -64,7 +64,7 @@ class ChannelManager extends ReadOnlyManager { @override Channel parse(Map raw, {Snowflake? guildId}) { - final type = ChannelType.parse(raw['type'] as int); + final type = ChannelType(raw['type'] as int); final parsers = { ChannelType.guildText: parseGuildTextChannel, @@ -139,7 +139,7 @@ class ChannelManager extends ReadOnlyManager { rateLimitPerUser: maybeParse(raw['rate_limit_per_user'], (value) => value == 0 ? null : Duration(seconds: value)), rtcRegion: raw['rtc_region'] as String?, userLimit: raw['user_limit'] == 0 ? null : raw['user_limit'] as int?, - videoQualityMode: maybeParse(raw['video_quality_mode'], VideoQualityMode.parse) ?? VideoQualityMode.auto, + videoQualityMode: maybeParse(raw['video_quality_mode'], VideoQualityMode.new) ?? VideoQualityMode.auto, ); } @@ -305,7 +305,7 @@ class ChannelManager extends ReadOnlyManager { rateLimitPerUser: maybeParse(raw['rate_limit_per_user'], (value) => value == 0 ? null : Duration(seconds: value)), rtcRegion: raw['rtc_region'] as String?, userLimit: raw['user_limit'] == 0 ? null : raw['user_limit'] as int?, - videoQualityMode: maybeParse(raw['video_quality_mode'], VideoQualityMode.parse) ?? VideoQualityMode.auto, + videoQualityMode: maybeParse(raw['video_quality_mode'], VideoQualityMode.new) ?? VideoQualityMode.auto, ); } @@ -324,7 +324,7 @@ class ChannelManager extends ReadOnlyManager { return ForumChannel( id: Snowflake.parse(raw['id']!), manager: this, - defaultLayout: maybeParse(raw['default_forum_layout'], ForumLayout.parse), + defaultLayout: maybeParse(raw['default_forum_layout'], ForumLayout.new), topic: raw['topic'] as String?, rateLimitPerUser: maybeParse(raw['rate_limit_per_user'], (value) => value == 0 ? null : Duration(seconds: value)), lastThreadId: maybeParse(raw['last_message_id'], Snowflake.parse), @@ -332,7 +332,7 @@ class ChannelManager extends ReadOnlyManager { flags: ChannelFlags(raw['flags'] as int), availableTags: parseMany(raw['available_tags'] as List, parseForumTag), defaultReaction: maybeParse(raw['default_reaction_emoji'], parseDefaultReaction), - defaultSortOrder: maybeParse(raw['default_sort_order'], ForumSort.parse), + defaultSortOrder: maybeParse(raw['default_sort_order'], ForumSort.new), // Discord doesn't seem to include this field if the default 3 day expiration is used (3 days = 4320 minutes) defaultAutoArchiveDuration: Duration(minutes: raw['default_auto_archive_duration'] as int? ?? 4320), defaultThreadRateLimitPerUser: @@ -359,7 +359,7 @@ class ChannelManager extends ReadOnlyManager { flags: ChannelFlags(raw['flags'] as int), availableTags: parseMany(raw['available_tags'] as List, parseForumTag), defaultReaction: maybeParse(raw['default_reaction_emoji'], parseDefaultReaction), - defaultSortOrder: maybeParse(raw['default_sort_order'], ForumSort.parse), + defaultSortOrder: maybeParse(raw['default_sort_order'], ForumSort.new), // Discord doesn't seem to include this field if the default 3 day expiration is used (3 days = 4320 minutes) defaultAutoArchiveDuration: Duration(minutes: raw['default_auto_archive_duration'] as int? ?? 4320), defaultThreadRateLimitPerUser: @@ -376,7 +376,7 @@ class ChannelManager extends ReadOnlyManager { PermissionOverwrite parsePermissionOverwrite(Map raw) { return PermissionOverwrite( id: Snowflake.parse(raw['id']!), - type: PermissionOverwriteType.parse(raw['type'] as int), + type: PermissionOverwriteType(raw['type'] as int), allow: Permissions(int.parse(raw['allow'] as String)), deny: Permissions(int.parse(raw['deny'] as String)), ); @@ -436,7 +436,7 @@ class ChannelManager extends ReadOnlyManager { guildId: Snowflake.parse(raw['guild_id']!), channelId: Snowflake.parse(raw['channel_id']!), topic: raw['topic'] as String, - privacyLevel: PrivacyLevel.parse(raw['privacy_level'] as int), + privacyLevel: PrivacyLevel(raw['privacy_level'] as int), scheduledEventId: maybeParse(raw['guild_scheduled_event_id'], Snowflake.parse), ); } diff --git a/lib/src/http/managers/entitlement_manager.dart b/lib/src/http/managers/entitlement_manager.dart index 9eb211884..44b6c4ac4 100644 --- a/lib/src/http/managers/entitlement_manager.dart +++ b/lib/src/http/managers/entitlement_manager.dart @@ -30,7 +30,7 @@ class EntitlementManager extends ReadOnlyManager { userId: maybeParse(raw['user_id'], Snowflake.parse), guildId: maybeParse(raw['guild_id'], Snowflake.parse), applicationId: Snowflake.parse(raw['application_id']!), - type: EntitlementType.parse(raw['type'] as int), + type: EntitlementType(raw['type'] as int), isConsumed: raw['consumed'] as bool? ?? false, isDeleted: raw['deleted'] as bool? ?? false, startsAt: maybeParse(raw['starts_at'], DateTime.parse), diff --git a/lib/src/http/managers/gateway_manager.dart b/lib/src/http/managers/gateway_manager.dart index 2ee4ad8a1..84e776c1e 100644 --- a/lib/src/http/managers/gateway_manager.dart +++ b/lib/src/http/managers/gateway_manager.dart @@ -45,7 +45,7 @@ abstract class GatewayManager { // No fields are validated server-side. Expect errors. return Activity( name: raw['name'] as String, - type: ActivityType.parse(raw['type'] as int), + type: ActivityType(raw['type'] as int), url: tryParse(raw['url'], Uri.parse), createdAt: tryParse(raw['created_at'], DateTime.fromMillisecondsSinceEpoch), timestamps: tryParse(raw['timestamps'], parseActivityTimestamps), @@ -103,9 +103,9 @@ abstract class GatewayManager { ClientStatus parseClientStatus(Map raw) { return ClientStatus( - desktop: maybeParse(raw['desktop'], UserStatus.parse), - mobile: maybeParse(raw['mobile'], UserStatus.parse), - web: maybeParse(raw['web'], UserStatus.parse), + desktop: maybeParse(raw['desktop'], UserStatus.new), + mobile: maybeParse(raw['mobile'], UserStatus.new), + web: maybeParse(raw['web'], UserStatus.new), ); } diff --git a/lib/src/http/managers/guild_manager.dart b/lib/src/http/managers/guild_manager.dart index 20a75f981..d93aa1b23 100644 --- a/lib/src/http/managers/guild_manager.dart +++ b/lib/src/http/managers/guild_manager.dart @@ -59,12 +59,12 @@ class GuildManager extends Manager { afkTimeout: Duration(seconds: raw['afk_timeout'] as int), isWidgetEnabled: raw['widget_enabled'] as bool? ?? false, widgetChannelId: maybeParse(raw['widget_channel_id'], Snowflake.parse), - verificationLevel: VerificationLevel.parse(raw['verification_level'] as int), - defaultMessageNotificationLevel: MessageNotificationLevel.parse(raw['default_message_notifications'] as int), - explicitContentFilterLevel: ExplicitContentFilterLevel.parse(raw['explicit_content_filter'] as int), + verificationLevel: VerificationLevel(raw['verification_level'] as int), + defaultMessageNotificationLevel: MessageNotificationLevel(raw['default_message_notifications'] as int), + explicitContentFilterLevel: ExplicitContentFilterLevel(raw['explicit_content_filter'] as int), roleList: parseMany(raw['roles'] as List, this[id].roles.parse), features: parseGuildFeatures(raw['features'] as List), - mfaLevel: MfaLevel.parse(raw['mfa_level'] as int), + mfaLevel: MfaLevel(raw['mfa_level'] as int), applicationId: maybeParse(raw['application_id'], Snowflake.parse), systemChannelId: maybeParse(raw['system_channel_id'], Snowflake.parse), systemChannelFlags: SystemChannelFlags(raw['system_channel_flags'] as int), @@ -74,7 +74,7 @@ class GuildManager extends Manager { vanityUrlCode: raw['vanity_url_code'] as String?, description: raw['description'] as String?, bannerHash: raw['banner'] as String?, - premiumTier: PremiumTier.parse(raw['premium_tier'] as int), + premiumTier: PremiumTier(raw['premium_tier'] as int), premiumSubscriptionCount: raw['premium_subscription_count'] as int?, preferredLocale: Locale.parse(raw['preferred_locale'] as String), publicUpdatesChannelId: maybeParse(raw['public_updates_channel_id'], Snowflake.parse), @@ -83,7 +83,7 @@ class GuildManager extends Manager { approximateMemberCount: raw['approximate_member_count'] as int?, approximatePresenceCount: raw['approximate_presence_count'] as int?, welcomeScreen: maybeParse(raw['welcome_screen'], parseWelcomeScreen), - nsfwLevel: NsfwLevel.parse(raw['nsfw_level'] as int), + nsfwLevel: NsfwLevel(raw['nsfw_level'] as int), hasPremiumProgressBarEnabled: raw['premium_progress_bar_enabled'] as bool, emojiList: parseMany(raw['emojis'] as List, this[id].emojis.parse), stickerList: parseMany(raw['stickers'] as List? ?? [], this[id].stickers.parse), @@ -263,7 +263,7 @@ class GuildManager extends Manager { OnboardingPrompt parseOnboardingPrompt(Map raw, {Snowflake? guildId}) { return OnboardingPrompt( id: Snowflake.parse(raw['id']!), - type: OnboardingPromptType.parse(raw['type'] as int), + type: OnboardingPromptType(raw['type'] as int), options: parseMany(raw['options'] as List, (Map raw) => parseOnboardingPromptOption(raw, guildId: guildId)), title: raw['title'] as String, isSingleSelect: raw['single_select'] as bool, @@ -534,7 +534,7 @@ class GuildManager extends Manager { ); final response = await client.httpHandler.executeSafe(request); - return MfaLevel.parse((response.jsonBody as Map)['level'] as int); + return MfaLevel((response.jsonBody as Map)['level'] as int); } /// Fetch the prune count in a guild. diff --git a/lib/src/http/managers/integration_manager.dart b/lib/src/http/managers/integration_manager.dart index f3aacc721..51b3fe69c 100644 --- a/lib/src/http/managers/integration_manager.dart +++ b/lib/src/http/managers/integration_manager.dart @@ -29,7 +29,7 @@ class IntegrationManager extends ReadOnlyManager { isSyncing: raw['syncing'] as bool?, roleId: maybeParse(raw['role_id'], Snowflake.parse), enableEmoticons: raw['enable_emoticons'] as bool?, - expireBehavior: maybeParse(raw['expire_behavior'], IntegrationExpireBehavior.parse), + expireBehavior: maybeParse(raw['expire_behavior'], IntegrationExpireBehavior.new), expireGracePeriod: maybeParse(raw['expire_grace_period'], (int value) => Duration(days: value)), user: maybeParse(raw['user'], client.users.parse), account: parseIntegrationAccount(raw['account'] as Map), diff --git a/lib/src/http/managers/interaction_manager.dart b/lib/src/http/managers/interaction_manager.dart index a1d3266fd..d6ecb89f8 100644 --- a/lib/src/http/managers/interaction_manager.dart +++ b/lib/src/http/managers/interaction_manager.dart @@ -33,7 +33,8 @@ class InteractionManager { InteractionManager(this.client, {required this.applicationId}); Interaction parse(Map raw) { - final type = InteractionType.parse(raw['type'] as int); + final type = InteractionType(raw['type'] as int); + final guildId = maybeParse(raw['guild_id'], Snowflake.parse); final channelId = maybeParse(raw['channel_id'], Snowflake.parse); final id = Snowflake.parse(raw['id']!); @@ -57,10 +58,10 @@ class InteractionManager { final authorizingIntegrationOwners = maybeParse( raw['authorizing_integration_owners'], (Map map) => { - for (final MapEntry(:key, :value) in map.entries) ApplicationIntegrationType.parse(int.parse(key)): Snowflake.parse(value!), + for (final MapEntry(:key, :value) in map.entries) ApplicationIntegrationType(int.parse(key)): Snowflake.parse(value!), }, ); - final context = maybeParse(raw['context'], InteractionContextType.parse); + final context = maybeParse(raw['context'], InteractionContextType.new); return switch (type) { InteractionType.ping => PingInteraction( @@ -167,6 +168,7 @@ class InteractionManager { authorizingIntegrationOwners: authorizingIntegrationOwners, context: context, ), + InteractionType() => throw StateError('Unknown interaction type: $type'), } as Interaction; } @@ -174,7 +176,7 @@ class InteractionManager { return ApplicationCommandInteractionData( id: Snowflake.parse(raw['id']!), name: raw['name'] as String, - type: ApplicationCommandType.parse(raw['type'] as int), + type: ApplicationCommandType(raw['type'] as int), resolved: maybeParse(raw['resolved'], (Map raw) => parseResolvedData(raw, guildId: guildId, channelId: channelId)), options: maybeParseMany(raw['options'], parseInteractionOption), // This guild_id is the ID of the guild the command is registered in, so it may be null even if the command was executed in a guild. @@ -239,7 +241,7 @@ class InteractionManager { InteractionOption parseInteractionOption(Map raw) { return InteractionOption( name: raw['name'] as String, - type: CommandOptionType.parse(raw['type'] as int), + type: CommandOptionType(raw['type'] as int), value: raw['value'], options: maybeParseMany(raw['options'], parseInteractionOption), isFocused: raw['focused'] as bool?, @@ -249,7 +251,7 @@ class InteractionManager { MessageComponentInteractionData parseMessageComponentInteractionData(Map raw, {Snowflake? guildId, Snowflake? channelId}) { return MessageComponentInteractionData( customId: raw['custom_id'] as String, - type: MessageComponentType.parse(raw['component_type'] as int), + type: MessageComponentType(raw['component_type'] as int), values: maybeParseMany(raw['values']), resolved: maybeParse(raw['resolved'], (Map raw) => parseResolvedData(raw, guildId: guildId, channelId: channelId)), ); diff --git a/lib/src/http/managers/invite_manager.dart b/lib/src/http/managers/invite_manager.dart index cc74bc37f..6bfd1cab2 100644 --- a/lib/src/http/managers/invite_manager.dart +++ b/lib/src/http/managers/invite_manager.dart @@ -30,7 +30,7 @@ class InviteManager { guild: guild, channel: PartialChannel(id: Snowflake.parse((raw['channel'] as Map)['id']!), manager: client.channels), inviter: maybeParse(raw['inviter'], client.users.parse), - targetType: maybeParse(raw['target_type'], TargetType.parse), + targetType: maybeParse(raw['target_type'], TargetType.new), targetUser: maybeParse(raw['target_user'], client.users.parse), targetApplication: maybeParse( raw['target_application'], diff --git a/lib/src/http/managers/message_manager.dart b/lib/src/http/managers/message_manager.dart index a86788d37..fec8b6ea7 100644 --- a/lib/src/http/managers/message_manager.dart +++ b/lib/src/http/managers/message_manager.dart @@ -68,7 +68,7 @@ class MessageManager extends Manager { nonce: raw['nonce'] /* as int | String */, isPinned: raw['pinned'] as bool, webhookId: webhookId, - type: MessageType.parse(raw['type'] as int), + type: MessageType(raw['type'] as int), activity: maybeParse(raw['activity'], parseMessageActivity), application: maybeParse( raw['application'], @@ -101,7 +101,7 @@ class MessageManager extends Manager { id: Snowflake.parse(raw['id']!), manager: client.channels, guildId: Snowflake.parse(raw['guild_id']!), - type: ChannelType.parse(raw['type'] as int), + type: ChannelType(raw['type'] as int), name: raw['name'] as String, ); } @@ -221,7 +221,7 @@ class MessageManager extends Manager { MessageActivity parseMessageActivity(Map raw) { return MessageActivity( - type: MessageActivityType.parse(raw['type'] as int), + type: MessageActivityType(raw['type'] as int), partyId: raw['party_id'] as String?, ); } @@ -245,14 +245,14 @@ class MessageManager extends Manager { } MessageComponent parseMessageComponent(Map raw) { - final type = MessageComponentType.parse(raw['type'] as int); + final type = MessageComponentType(raw['type'] as int); return switch (type) { MessageComponentType.actionRow => ActionRowComponent( components: parseMany(raw['components'] as List, parseMessageComponent), ), MessageComponentType.button => ButtonComponent( - style: ButtonStyle.parse(raw['style'] as int), + style: ButtonStyle(raw['style'] as int), label: raw['label'] as String?, emoji: maybeParse(raw['emoji'], client.guilds[Snowflake.zero].emojis.parse), customId: raw['custom_id'] as String?, @@ -262,7 +262,7 @@ class MessageManager extends Manager { ), MessageComponentType.textInput => TextInputComponent( customId: raw['custom_id'] as String, - style: maybeParse(raw['style'], TextInputStyle.parse), + style: maybeParse(raw['style'], TextInputStyle.new), label: raw['label'] as String?, minLength: raw['min_length'] as int?, maxLength: raw['max_length'] as int?, @@ -279,13 +279,14 @@ class MessageManager extends Manager { type: type, customId: raw['custom_id'] as String, options: maybeParseMany(raw['options'], parseSelectMenuOption), - channelTypes: maybeParseMany(raw['channel_types'], ChannelType.parse), + channelTypes: maybeParseMany(raw['channel_types'], ChannelType.new), placeholder: raw['placeholder'] as String?, defaultValues: maybeParseMany(raw['default_values'], parseSelectMenuDefaultValue), minValues: raw['min_values'] as int?, maxValues: raw['max_values'] as int?, isDisabled: raw['disabled'] as bool?, ), + MessageComponentType() => throw StateError('Unknown message component type: $type'), }; } @@ -302,7 +303,7 @@ class MessageManager extends Manager { SelectMenuDefaultValue parseSelectMenuDefaultValue(Map raw) { return SelectMenuDefaultValue( id: Snowflake.parse(raw['id']!), - type: SelectMenuDefaultValueType.parse(raw['type'] as String), + type: SelectMenuDefaultValueType(raw['type'] as String), ); } @@ -313,7 +314,7 @@ class MessageManager extends Manager { // ignore: deprecated_member_use_from_same_package return MessageInteraction( id: Snowflake.parse(raw['id']!), - type: InteractionType.parse(raw['type'] as int), + type: InteractionType(raw['type'] as int), name: raw['name'] as String, user: user, member: maybeParse( @@ -326,11 +327,11 @@ class MessageManager extends Manager { MessageInteractionMetadata parseMessageInteractionMetadata(Map raw) { return MessageInteractionMetadata( id: Snowflake.parse(raw['id']!), - type: InteractionType.parse(raw['type'] as int), + type: InteractionType(raw['type'] as int), userId: Snowflake.parse(raw['user_id']!), authorizingIntegrationOwners: { for (final MapEntry(:key, :value) in (raw['authorizing_integration_owners'] as Map).entries) - ApplicationIntegrationType.parse(int.parse(key)): Snowflake.parse(value!), + ApplicationIntegrationType(int.parse(key)): Snowflake.parse(value!), }, originalResponseMessageId: maybeParse(raw['original_response_message_id'], Snowflake.parse), interactedMessageId: maybeParse(raw['interacted_message_id'], Snowflake.parse), @@ -373,7 +374,7 @@ class MessageManager extends Manager { answers: parseMany(raw['answers'] as List, parsePollAnswer), endsAt: maybeParse(raw['expiry'] as String?, DateTime.parse), allowsMultiselect: raw['allow_multiselect'] as bool, - layoutType: PollLayoutType.parse(raw['layout_type'] as int), + layoutType: PollLayoutType(raw['layout_type'] as int), results: maybeParse(raw['results'], parsePollResults), ); } diff --git a/lib/src/http/managers/scheduled_event_manager.dart b/lib/src/http/managers/scheduled_event_manager.dart index 24fddda85..a0611945a 100644 --- a/lib/src/http/managers/scheduled_event_manager.dart +++ b/lib/src/http/managers/scheduled_event_manager.dart @@ -32,9 +32,9 @@ class ScheduledEventManager extends Manager { description: raw['description'] as String?, scheduledStartTime: DateTime.parse(raw['scheduled_start_time'] as String), scheduledEndTime: maybeParse(raw['scheduled_end_time'], DateTime.parse), - privacyLevel: PrivacyLevel.parse(raw['privacy_level'] as int), - status: EventStatus.parse(raw['status'] as int), - type: ScheduledEntityType.parse(raw['entity_type'] as int), + privacyLevel: PrivacyLevel(raw['privacy_level'] as int), + status: EventStatus(raw['status'] as int), + type: ScheduledEntityType(raw['entity_type'] as int), entityId: maybeParse(raw['entity_id'], Snowflake.parse), metadata: maybeParse(raw['entity_metadata'], parseEntityMetadata), creator: maybeParse(raw['creator'], client.users.parse), diff --git a/lib/src/http/managers/sticker_manager.dart b/lib/src/http/managers/sticker_manager.dart index 3762c46d8..e4dd15c10 100644 --- a/lib/src/http/managers/sticker_manager.dart +++ b/lib/src/http/managers/sticker_manager.dart @@ -30,7 +30,7 @@ class GuildStickerManager extends Manager { description: raw['description'] as String?, tags: raw['tags'] as String, type: StickerType.parse(raw['type'] as int), - formatType: StickerFormatType.parse(raw['format_type'] as int), + formatType: StickerFormatType(raw['format_type'] as int), available: raw['available'] as bool? ?? false, guildId: Snowflake.parse(raw['guild_id']!), user: ((raw['user'] ?? {}) as Map)['id'] != null ? client.users[Snowflake.parse((raw['user'] as Map)['id']!)] : null, @@ -127,7 +127,7 @@ class GlobalStickerManager extends ReadOnlyManager { description: raw['description'] as String?, tags: raw['tags'] as String, type: StickerType.parse(raw['type'] as int), - formatType: StickerFormatType.parse(raw['format_type'] as int), + formatType: StickerFormatType(raw['format_type'] as int), available: raw['available'] as bool? ?? false, user: ((raw['user'] ?? {}) as Map)['id'] != null ? client.users[Snowflake.parse((raw['user'] as Map)['id']!)] : null, sortValue: raw['sort_value'] as int?, @@ -138,7 +138,7 @@ class GlobalStickerManager extends ReadOnlyManager { return StickerItem( id: Snowflake.parse(raw['id']!), name: raw['name'] as String, - formatType: StickerFormatType.parse(raw['format_type'] as int), + formatType: StickerFormatType(raw['format_type'] as int), ); } diff --git a/lib/src/http/managers/user_manager.dart b/lib/src/http/managers/user_manager.dart index 5115fd108..ce903a67b 100644 --- a/lib/src/http/managers/user_manager.dart +++ b/lib/src/http/managers/user_manager.dart @@ -52,7 +52,7 @@ class UserManager extends ReadOnlyManager { accentColor: hasAccentColor ? DiscordColor(raw['accent_color'] as int) : null, locale: hasLocale ? Locale.parse(raw['locale'] as String) : null, flags: hasFlags ? UserFlags(raw['flags'] as int) : null, - nitroType: hasPremiumType ? NitroType.parse(raw['premium_type'] as int) : NitroType.none, + nitroType: hasPremiumType ? NitroType(raw['premium_type'] as int) : NitroType.none, publicFlags: hasPublicFlags ? UserFlags(raw['public_flags'] as int) : null, avatarDecorationHash: raw['avatar_decoration'] as String?, ); @@ -77,7 +77,7 @@ class UserManager extends ReadOnlyManager { isFriendSyncEnabled: raw['friend_sync'] as bool, showActivity: raw['show_activity'] as bool, isTwoWayLink: raw['two_way_link'] as bool, - visibility: ConnectionVisibility.parse(raw['visibility'] as int), + visibility: ConnectionVisibility(raw['visibility'] as int), ); } diff --git a/lib/src/http/managers/webhook_manager.dart b/lib/src/http/managers/webhook_manager.dart index 24b15855e..e24bae0c1 100644 --- a/lib/src/http/managers/webhook_manager.dart +++ b/lib/src/http/managers/webhook_manager.dart @@ -30,7 +30,7 @@ class WebhookManager extends Manager { return Webhook( id: Snowflake.parse(raw['id']!), manager: this, - type: WebhookType.parse(raw['type'] as int), + type: WebhookType(raw['type'] as int), guildId: maybeParse(raw['guild_id'], Snowflake.parse), channelId: maybeParse(raw['channel_id'], Snowflake.parse), user: maybeParse(raw['user'], client.users.parse), diff --git a/lib/src/models/application.dart b/lib/src/models/application.dart index 3f07fb798..809ac57a0 100644 --- a/lib/src/models/application.dart +++ b/lib/src/models/application.dart @@ -9,6 +9,7 @@ import 'package:nyxx/src/models/sku.dart'; import 'package:nyxx/src/models/snowflake.dart'; import 'package:nyxx/src/models/team.dart'; import 'package:nyxx/src/models/user/user.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/flags.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; @@ -183,28 +184,18 @@ class Application extends PartialApplication { ); } -enum ApplicationIntegrationType { +final class ApplicationIntegrationType extends EnumLike { /// App is installable to servers. - guildInstall._(0), + static const guildInstall = ApplicationIntegrationType(0); /// App is installable to users. - userInstall._(1); + static const userInstall = ApplicationIntegrationType(1); - /// The value of this [ApplicationIntegrationType]. - final int value; - - const ApplicationIntegrationType._(this.value); + /// @nodoc + const ApplicationIntegrationType(super.value); - /// Parse an [ApplicationIntegrationType] from an [int]. - /// - /// The [value] must be a valid application integration type. - factory ApplicationIntegrationType.parse(int value) => ApplicationIntegrationType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown ApplicationIntegrationType', value), - ); - - @override - String toString() => 'ApplicationIntegrationType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + ApplicationIntegrationType.parse(int value) : this(value); } /// Flags for an [Application]. @@ -326,29 +317,19 @@ class ApplicationRoleConnectionMetadata with ToStringHelper { } /// The type of an [ApplicationRoleConnectionMetadata]. -enum ConnectionMetadataType { - integerLessThanOrEqual._(1), - integerGreaterThanOrEqual._(2), - integerEqual._(3), - integerNotEqual._(4), - dateTimeLessThanOrEqual._(5), - dateTimeGreaterThanOrEqual._(6), - booleanEqual._(7), - booleanNotEqual._(8); - - /// The value of this [ConnectionMetadataType]. - final int value; - - const ConnectionMetadataType._(this.value); - - /// Parse a [ConnectionMetadataType] from an [int]. - /// - /// The [value] must be a valid connection metadata type. - factory ConnectionMetadataType.parse(int value) => ConnectionMetadataType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown connection metadata type', value), - ); - - @override - String toString() => 'ConnectionMetadataType($value)'; +final class ConnectionMetadataType extends EnumLike { + static const integerLessThanOrEqual = ConnectionMetadataType(1); + static const integerGreaterThanOrEqual = ConnectionMetadataType(2); + static const integerEqual = ConnectionMetadataType(3); + static const integerNotEqual = ConnectionMetadataType(4); + static const dateTimeLessThanOrEqual = ConnectionMetadataType(5); + static const dateTimeGreaterThanOrEqual = ConnectionMetadataType(6); + static const booleanEqual = ConnectionMetadataType(7); + static const booleanNotEqual = ConnectionMetadataType(8); + + /// @nodoc + const ConnectionMetadataType(super.value); + + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + ConnectionMetadataType.parse(int value) : this(value); } diff --git a/lib/src/models/channel/channel.dart b/lib/src/models/channel/channel.dart index e455b02cc..1928300a1 100644 --- a/lib/src/models/channel/channel.dart +++ b/lib/src/models/channel/channel.dart @@ -2,6 +2,7 @@ import 'package:nyxx/src/builders/builder.dart'; import 'package:nyxx/src/http/managers/channel_manager.dart'; import 'package:nyxx/src/models/snowflake.dart'; import 'package:nyxx/src/models/snowflake_entity/snowflake_entity.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/flags.dart'; /// A partial [Channel] object. @@ -48,61 +49,51 @@ abstract class Channel extends PartialChannel { } /// The type of a channel. -enum ChannelType { +final class ChannelType extends EnumLike { /// A text channel in a [Guild]. - guildText._(0), + static const guildText = ChannelType(0); /// A DM channel with a single other recipient. - dm._(1), + static const dm = ChannelType(1); /// A voice channel in a [Guild]. - guildVoice._(2), + static const guildVoice = ChannelType(2); /// A DM channel with multiple recipients. - groupDm._(3), + static const groupDm = ChannelType(3); /// A category in a [Guild]. - guildCategory._(4), + static const guildCategory = ChannelType(4); /// An announcement channel in a [Guild]. - guildAnnouncement._(5), + static const guildAnnouncement = ChannelType(5); /// A [Thread] in an announcement channel. - announcementThread._(10), + static const announcementThread = ChannelType(10); /// A public thread. - publicThread._(11), + static const publicThread = ChannelType(11); /// A private thread. - privateThread._(12), + static const privateThread = ChannelType(12); /// A stage channel in a [Guild]. - guildStageVoice._(13), + static const guildStageVoice = ChannelType(13); /// A [Guild] directory. - guildDirectory._(14), + static const guildDirectory = ChannelType(14); /// A forum channel in a [Guild]. - guildForum._(15), + static const guildForum = ChannelType(15); /// A media channel in a [Guild]. - guildMedia._(16); + static const guildMedia = ChannelType(16); - /// The value of this [ChannelType]. - final int value; - - const ChannelType._(this.value); - - /// Parse a [ChannelType] from a [value]. - /// - /// The [value] must be a valid channel type. - factory ChannelType.parse(int value) => ChannelType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown channel type', value), - ); + /// @nodoc + const ChannelType(super.value); - @override - String toString() => 'ChannelType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + ChannelType.parse(int value) : this(value); } /// A set of flags applied to channels. diff --git a/lib/src/models/channel/stage_instance.dart b/lib/src/models/channel/stage_instance.dart index b18f1b28a..a67170738 100644 --- a/lib/src/models/channel/stage_instance.dart +++ b/lib/src/models/channel/stage_instance.dart @@ -6,6 +6,7 @@ import 'package:nyxx/src/models/guild/guild.dart'; import 'package:nyxx/src/models/guild/scheduled_event.dart'; import 'package:nyxx/src/models/snowflake.dart'; import 'package:nyxx/src/models/snowflake_entity/snowflake_entity.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; /// {@template stage_instance} /// Information about a live stage. @@ -58,19 +59,13 @@ class StageInstance extends SnowflakeEntity { } /// The privacy level of a [StageInstance]. -enum PrivacyLevel { - public._(1), - guildOnly._(2); +final class PrivacyLevel extends EnumLike { + static const public = PrivacyLevel(1); + static const guildOnly = PrivacyLevel(2); - final int value; - - const PrivacyLevel._(this.value); + /// @nodoc + const PrivacyLevel(super.value); - /// Parse a [PrivacyLevel] from an [int]. - /// - /// The [value] must be a valid privacy level. - factory PrivacyLevel.parse(int value) => PrivacyLevel.values.firstWhere( - (level) => level.value == value, - orElse: () => throw FormatException('Unknown privacy level', value), - ); + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + PrivacyLevel.parse(int value) : this(value); } diff --git a/lib/src/models/channel/types/forum.dart b/lib/src/models/channel/types/forum.dart index 79ece2592..57a1c3f56 100644 --- a/lib/src/models/channel/types/forum.dart +++ b/lib/src/models/channel/types/forum.dart @@ -12,6 +12,7 @@ import 'package:nyxx/src/models/invite/invite_metadata.dart'; import 'package:nyxx/src/models/permission_overwrite.dart'; import 'package:nyxx/src/models/snowflake.dart'; import 'package:nyxx/src/models/webhook.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; /// {@template forum_channel} @@ -184,46 +185,26 @@ class DefaultReaction with ToStringHelper { } /// The sorting order in a [ForumChannel]. -enum ForumSort { - latestActivity._(0), - creationDate._(1); +final class ForumSort extends EnumLike { + static const latestActivity = ForumSort(0); + static const creationDate = ForumSort(1); - /// The value of this forum sort. - final int value; - - const ForumSort._(this.value); - - /// Parse a [ForumSort] from an [int]. - /// - /// The [value] must be a valid forum sort. - factory ForumSort.parse(int value) => ForumSort.values.firstWhere( - (sort) => sort.value == value, - orElse: () => throw FormatException('Unknown forum sort', value), - ); + /// @nodoc + const ForumSort(super.value); - @override - String toString() => 'ForumSort($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + ForumSort.parse(int value) : this(value); } /// The layout in a [ForumChannel]. -enum ForumLayout { - notSet._(0), - listView._(1), - galleryView._(2); +final class ForumLayout extends EnumLike { + static const notSet = ForumLayout(0); + static const listView = ForumLayout(1); + static const galleryView = ForumLayout(2); - /// The value of this forum layout. - final int value; - - const ForumLayout._(this.value); - - /// Parse a [ForumLayout] from an [int]. - /// - /// The [value] must be a valid forum layout. - factory ForumLayout.parse(int value) => ForumLayout.values.firstWhere( - (layout) => layout.value == value, - orElse: () => throw FormatException('Unknown forum layout', value), - ); + /// @nodoc + const ForumLayout(super.value); - @override - String toString() => 'ForumLayout($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + ForumLayout.parse(int value) : this(value); } diff --git a/lib/src/models/channel/voice_channel.dart b/lib/src/models/channel/voice_channel.dart index aed347644..e83202ced 100644 --- a/lib/src/models/channel/voice_channel.dart +++ b/lib/src/models/channel/voice_channel.dart @@ -1,4 +1,5 @@ import 'package:nyxx/src/models/channel/channel.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; /// A voice channel. abstract class VoiceChannel implements Channel { @@ -16,26 +17,16 @@ abstract class VoiceChannel implements Channel { } /// The quality mode of cameras in a [VoiceChannel]. -enum VideoQualityMode { +final class VideoQualityMode extends EnumLike { /// Automatic. - auto._(1), + static const auto = VideoQualityMode(1); /// 720p. - full._(2); + static const full = VideoQualityMode(2); - /// The value of this [VideoQualityMode]. - final int value; + /// @nodoc + const VideoQualityMode(super.value); - const VideoQualityMode._(this.value); - - /// Parse a [VideoQualityMode] from an [int]. - /// - /// [value] must be a valid [VideoQualityMode]. - factory VideoQualityMode.parse(int value) => VideoQualityMode.values.firstWhere( - (mode) => mode.value == value, - orElse: () => throw FormatException('Unknown VideoQualityMode', value), - ); - - @override - String toString() => 'VideoQualityMode($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + VideoQualityMode.parse(int value) : this(value); } diff --git a/lib/src/models/commands/application_command.dart b/lib/src/models/commands/application_command.dart index 3dd49b312..878c2cd50 100644 --- a/lib/src/models/commands/application_command.dart +++ b/lib/src/models/commands/application_command.dart @@ -8,6 +8,7 @@ import 'package:nyxx/src/models/locale.dart'; import 'package:nyxx/src/models/permissions.dart'; import 'package:nyxx/src/models/snowflake.dart'; import 'package:nyxx/src/models/snowflake_entity/snowflake_entity.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; /// A partial [ApplicationCommand]. class PartialApplicationCommand extends WritableSnowflakeEntity { @@ -100,24 +101,19 @@ class ApplicationCommand extends PartialApplicationCommand { } /// The type of an [ApplicationCommand]. -enum ApplicationCommandType { - chatInput._(1), - user._(2), - message._(3); +final class ApplicationCommandType extends EnumLike { + /// A chat input command. + static const chatInput = ApplicationCommandType(1); - /// The value of this [ApplicationCommandType]. - final int value; + /// A user command. + static const user = ApplicationCommandType(2); - const ApplicationCommandType._(this.value); + /// A message command. + static const message = ApplicationCommandType(3); - /// Parse an [ApplicationCommandType] from an [int]. - /// - /// The [value] must be a valid application command type. - factory ApplicationCommandType.parse(int value) => ApplicationCommandType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown application command type', value), - ); + /// @nodoc + const ApplicationCommandType(super.value); - @override - String toString() => 'ApplicationCommandType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + ApplicationCommandType.parse(int value) : this(value); } diff --git a/lib/src/models/commands/application_command_option.dart b/lib/src/models/commands/application_command_option.dart index d1cbbf076..4b7931068 100644 --- a/lib/src/models/commands/application_command_option.dart +++ b/lib/src/models/commands/application_command_option.dart @@ -1,6 +1,7 @@ import 'package:nyxx/src/models/channel/channel.dart'; import 'package:nyxx/src/models/locale.dart'; import 'package:nyxx/src/models/snowflake_entity/snowflake_entity.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; /// {@template command_option} @@ -70,34 +71,24 @@ class CommandOption with ToStringHelper { } /// The type of a [CommandOption]. -enum CommandOptionType { - subCommand._(1), - subCommandGroup._(2), - string._(3), - integer._(4), - boolean._(5), - user._(6), - channel._(7), - role._(8), - mentionable._(9), - number._(10), - attachment._(11); - - /// The value of this [CommandOptionType]. - final int value; - - const CommandOptionType._(this.value); - - /// Parse a [CommandOptionType] from an [int]. - /// - /// The [value] must be a valid command option type. - factory CommandOptionType.parse(int value) => CommandOptionType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown command option type', value), - ); - - @override - String toString() => 'CommandOptionType($value)'; +final class CommandOptionType extends EnumLike { + static const subCommand = CommandOptionType(1); + static const subCommandGroup = CommandOptionType(2); + static const string = CommandOptionType(3); + static const integer = CommandOptionType(4); + static const boolean = CommandOptionType(5); + static const user = CommandOptionType(6); + static const channel = CommandOptionType(7); + static const role = CommandOptionType(8); + static const mentionable = CommandOptionType(9); + static const number = CommandOptionType(10); + static const attachment = CommandOptionType(11); + + /// @nodoc + const CommandOptionType(super.value); + + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + CommandOptionType.parse(int value) : this(value); } /// {@template command_option_choice} diff --git a/lib/src/models/commands/application_command_permissions.dart b/lib/src/models/commands/application_command_permissions.dart index b6b0a9fad..d149a54dc 100644 --- a/lib/src/models/commands/application_command_permissions.dart +++ b/lib/src/models/commands/application_command_permissions.dart @@ -4,6 +4,7 @@ import 'package:nyxx/src/models/commands/application_command.dart'; import 'package:nyxx/src/models/guild/guild.dart'; import 'package:nyxx/src/models/snowflake.dart'; import 'package:nyxx/src/models/snowflake_entity/snowflake_entity.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; /// {@template command_permissions} @@ -74,24 +75,19 @@ class CommandPermission with ToStringHelper { } /// The type of a [CommandPermission]. -enum CommandPermissionType { - role._(1), - user._(2), - channel._(3); +final class CommandPermissionType extends EnumLike { + /// The permission applies to a role. + static const role = CommandPermissionType(1); - /// The value of this [CommandPermissionType]. - final int value; + /// The permission applies to a user. + static const user = CommandPermissionType(2); - const CommandPermissionType._(this.value); + /// The permission applies to a channel. + static const channel = CommandPermissionType(3); - /// Parse a [CommandPermissionType] from an [int]. - /// - /// The [value] must be a valid command permission type. - factory CommandPermissionType.parse(int value) => CommandPermissionType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown command permission type', value), - ); + /// @nodoc + const CommandPermissionType(super.value); - @override - String toString() => 'CommandPermissionType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + CommandPermissionType.parse(int value) : this(value); } diff --git a/lib/src/models/entitlement.dart b/lib/src/models/entitlement.dart index 6001fccb1..0bd042ba9 100644 --- a/lib/src/models/entitlement.dart +++ b/lib/src/models/entitlement.dart @@ -4,6 +4,7 @@ import 'package:nyxx/src/models/guild/guild.dart'; import 'package:nyxx/src/models/snowflake.dart'; import 'package:nyxx/src/models/snowflake_entity/snowflake_entity.dart'; import 'package:nyxx/src/models/user/user.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; /// A partial [Entitlement]. class PartialEntitlement extends ManagedSnowflakeEntity { @@ -76,40 +77,33 @@ class Entitlement extends PartialEntitlement { } /// The type of an [Entitlement]. -enum EntitlementType { +final class EntitlementType extends EnumLike { /// Entitlement was purchased by user. - purchase._(1), + static const EntitlementType purchase = EntitlementType(1); /// Entitlement was granted by Discord Nitro subscription. - premiumSubscription._(2), + static const EntitlementType premiumSubscription = EntitlementType(2); /// Entitlement was gifted by developer. - developerGift._(3), + static const EntitlementType developerGift = EntitlementType(3); /// Entitlement was purchased by a dev in application test mode. - testModePurchase._(4), + static const EntitlementType testModePurchase = EntitlementType(4); /// Entitlement was granted when the SKU was free. - freePurchase._(5), + static const EntitlementType freePurchase = EntitlementType(5); /// Entitlement was gifted by another user. - userGift._(6), + static const EntitlementType userGift = EntitlementType(6); /// Entitlement was claimed by user for free as a Nitro Subscriber. - premiumPurchase._(7), + static const EntitlementType premiumPurchase = EntitlementType(7); /// Entitlement was purchased as an app subscription. - applicationSubscription._(8); + static const EntitlementType applicationSubscription = EntitlementType(8); - final int value; + const EntitlementType(super.value); - const EntitlementType._(this.value); - - factory EntitlementType.parse(int value) => EntitlementType.values.firstWhere( - (element) => element.value == value, - orElse: () => throw FormatException('Unknown entitlement type', value), - ); - - @override - String toString() => 'EntitlementType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + EntitlementType.parse(int value) : this(value); } diff --git a/lib/src/models/guild/audit_log.dart b/lib/src/models/guild/audit_log.dart index 359d7ae1d..431f703b4 100644 --- a/lib/src/models/guild/audit_log.dart +++ b/lib/src/models/guild/audit_log.dart @@ -7,6 +7,7 @@ import 'package:nyxx/src/models/permission_overwrite.dart'; import 'package:nyxx/src/models/snowflake.dart'; import 'package:nyxx/src/models/snowflake_entity/snowflake_entity.dart'; import 'package:nyxx/src/models/user/user.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; /// A partial [AuditLogEntry]. @@ -81,79 +82,69 @@ class AuditLogChange with ToStringHelper { } /// The type of event an [AuditLogEntry] represents. -enum AuditLogEvent { - guildUpdate._(1), - channelCreate._(10), - channelUpdate._(11), - channelDelete._(12), - channelOverwriteCreate._(13), - channelOverwriteUpdate._(14), - channelOverwriteDelete._(15), - memberKick._(20), - memberPrune._(21), - memberBanAdd._(22), - memberBanRemove._(23), - memberUpdate._(24), - memberRoleUpdate._(25), - memberMove._(26), - memberDisconnect._(27), - botAdd._(28), - roleCreate._(30), - roleUpdate._(31), - roleDelete._(32), - inviteCreate._(40), - inviteUpdate._(41), - inviteDelete._(42), - webhookCreate._(50), - webhookUpdate._(51), - webhookDelete._(52), - emojiCreate._(60), - emojiUpdate._(61), - emojiDelete._(62), - messageDelete._(72), - messageBulkDelete._(73), - messagePin._(74), - messageUnpin._(75), - integrationCreate._(80), - integrationUpdate._(81), - integrationDelete._(82), - stageInstanceCreate._(83), - stageInstanceUpdate._(84), - stageInstanceDelete._(85), - stickerCreate._(90), - stickerUpdate._(91), - stickerDelete._(92), - guildScheduledEventCreate._(100), - guildScheduledEventUpdate._(101), - guildScheduledEventDelete._(102), - threadCreate._(110), - threadUpdate._(111), - threadDelete._(112), - applicationCommandPermissionUpdate._(121), - autoModerationRuleCreate._(140), - autoModerationRuleUpdate._(141), - autoModerationRuleDelete._(142), - autoModerationBlockMessage._(143), - autoModerationFlagToChannel._(144), - autoModerationUserCommunicationDisabled._(145), - creatorMonetizationRequestCreated._(150), - creatorMonetizationTermsAccepted._(151); - - /// The value of this [AuditLogEvent]. - final int value; - - const AuditLogEvent._(this.value); - - /// Parse an [AuditLogEvent] from an [int]. - /// - /// The [value] must be a valid audit log event. - factory AuditLogEvent.parse(int value) => AuditLogEvent.values.firstWhere( - (event) => event.value == value, - orElse: () => throw FormatException('Unknown audit log event', value), - ); +final class AuditLogEvent extends EnumLike { + static const guildUpdate = AuditLogEvent(1); + static const channelCreate = AuditLogEvent(10); + static const channelUpdate = AuditLogEvent(11); + static const channelDelete = AuditLogEvent(12); + static const channelOverwriteCreate = AuditLogEvent(13); + static const channelOverwriteUpdate = AuditLogEvent(14); + static const channelOverwriteDelete = AuditLogEvent(15); + static const memberKick = AuditLogEvent(20); + static const memberPrune = AuditLogEvent(21); + static const memberBanAdd = AuditLogEvent(22); + static const memberBanRemove = AuditLogEvent(23); + static const memberUpdate = AuditLogEvent(24); + static const memberRoleUpdate = AuditLogEvent(25); + static const memberMove = AuditLogEvent(26); + static const memberDisconnect = AuditLogEvent(27); + static const botAdd = AuditLogEvent(28); + static const roleCreate = AuditLogEvent(30); + static const roleUpdate = AuditLogEvent(31); + static const roleDelete = AuditLogEvent(32); + static const inviteCreate = AuditLogEvent(40); + static const inviteUpdate = AuditLogEvent(41); + static const inviteDelete = AuditLogEvent(42); + static const webhookCreate = AuditLogEvent(50); + static const webhookUpdate = AuditLogEvent(51); + static const webhookDelete = AuditLogEvent(52); + static const emojiCreate = AuditLogEvent(60); + static const emojiUpdate = AuditLogEvent(61); + static const emojiDelete = AuditLogEvent(62); + static const messageDelete = AuditLogEvent(72); + static const messageBulkDelete = AuditLogEvent(73); + static const messagePin = AuditLogEvent(74); + static const messageUnpin = AuditLogEvent(75); + static const integrationCreate = AuditLogEvent(80); + static const integrationUpdate = AuditLogEvent(81); + static const integrationDelete = AuditLogEvent(82); + static const stageInstanceCreate = AuditLogEvent(83); + static const stageInstanceUpdate = AuditLogEvent(84); + static const stageInstanceDelete = AuditLogEvent(85); + static const stickerCreate = AuditLogEvent(90); + static const stickerUpdate = AuditLogEvent(91); + static const stickerDelete = AuditLogEvent(92); + static const guildScheduledEventCreate = AuditLogEvent(100); + static const guildScheduledEventUpdate = AuditLogEvent(101); + static const guildScheduledEventDelete = AuditLogEvent(102); + static const threadCreate = AuditLogEvent(110); + static const threadUpdate = AuditLogEvent(111); + static const threadDelete = AuditLogEvent(112); + static const applicationCommandPermissionUpdate = AuditLogEvent(121); + static const autoModerationRuleCreate = AuditLogEvent(140); + static const autoModerationRuleUpdate = AuditLogEvent(141); + static const autoModerationRuleDelete = AuditLogEvent(142); + static const autoModerationBlockMessage = AuditLogEvent(143); + static const autoModerationFlagToChannel = AuditLogEvent(144); + static const autoModerationUserCommunicationDisabled = AuditLogEvent(145); + static const creatorMonetizationRequestCreated = AuditLogEvent(150); + static const creatorMonetizationTermsAccepted = AuditLogEvent(151); - @override - String toString() => 'AuditLogEvent($value)'; + /// @nodoc + const AuditLogEvent(super.value); + + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + AuditLogEvent.parse(int value) : this(value); } /// {@template audit_log_entry_info} diff --git a/lib/src/models/guild/auto_moderation.dart b/lib/src/models/guild/auto_moderation.dart index cb0177a39..99a9156eb 100644 --- a/lib/src/models/guild/auto_moderation.dart +++ b/lib/src/models/guild/auto_moderation.dart @@ -8,6 +8,7 @@ import 'package:nyxx/src/models/role.dart'; import 'package:nyxx/src/models/snowflake.dart'; import 'package:nyxx/src/models/snowflake_entity/snowflake_entity.dart'; import 'package:nyxx/src/models/user/user.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; /// A partial [AutoModerationRule]. @@ -83,62 +84,42 @@ class AutoModerationRule extends PartialAutoModerationRule { } /// The type of event on which an [AutoModerationRule] triggers. -enum AutoModerationEventType { +final class AutoModerationEventType extends EnumLike { /// When a member sends or edits a message in the guild. - messageSend._(1), + static const messageSend = AutoModerationEventType(1); /// When a member edits their profile. - memberUpdate._(2); + static const memberUpdate = AutoModerationEventType(2); - /// The value of this [AutoModerationEventType]. - final int value; - - const AutoModerationEventType._(this.value); - - /// Parse an [AutoModerationEventType] from an [int]. - /// - /// The [value] must be a valid auto moderation event type. - factory AutoModerationEventType.parse(int value) => AutoModerationEventType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown auto moderation event type', value), - ); + /// @nodoc + const AutoModerationEventType(super.value); - @override - String toString() => 'AutoModerationEventType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + AutoModerationEventType.parse(int value) : this(value); } /// The type of a trigger for an [AutoModerationRule] -enum TriggerType { +final class TriggerType extends EnumLike { /// Check if content contains words from a user defined list of keywords. - keyword._(1), + static const keyword = TriggerType(1); /// Check if content represents generic spam. - spam._(3), + static const spam = TriggerType(3); /// Check if content contains words from internal pre-defined wordsets. - keywordPreset._(4), + static const keywordPreset = TriggerType(4); /// Check if content contains more unique mentions than allowed. - mentionSpam._(5), + static const mentionSpam = TriggerType(5); /// Check if member profile contains words from a user defined list of keywords. - memberProfile._(6); + static const memberProfile = TriggerType(6); - /// The value of this [TriggerType]. - final int value; - - const TriggerType._(this.value); - - /// Parse an [TriggerType] from an [int]. - /// - /// The [value] must be a valid trigger type. - factory TriggerType.parse(int value) => TriggerType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown trigger type', value), - ); + /// @nodoc + const TriggerType(super.value); - @override - String toString() => 'TriggerType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + TriggerType.parse(int value) : this(value); } /// {@template trigger_metadata} @@ -189,26 +170,16 @@ class TriggerMetadata with ToStringHelper implements TriggerMetadataBuilder { } /// A preset list of trigger keywords for an [AutoModerationRule]. -enum KeywordPresetType { - profanity._(1), - sexualContent._(2), - slurs._(3); +final class KeywordPresetType extends EnumLike { + static const profanity = KeywordPresetType(1); + static const sexualContent = KeywordPresetType(2); + static const slurs = KeywordPresetType(3); - /// The value of this [KeywordPresetType]. - final int value; - - const KeywordPresetType._(this.value); - - /// Parse an [KeywordPresetType] from an [int]. - /// - /// The [value] must be a valid keyword preset type. - factory KeywordPresetType.parse(int value) => KeywordPresetType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown keyword preset type', value), - ); + /// @nodoc + const KeywordPresetType(super.value); - @override - String toString() => 'KeywordPresetType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + KeywordPresetType.parse(int value) : this(value); } /// {@template auto_moderation_action} @@ -238,27 +209,17 @@ class AutoModerationAction with ToStringHelper implements AutoModerationActionBu } /// The type of action for an [AutoModerationAction]. -enum ActionType { - blockMessage._(1), - sendAlertMessage._(2), - timeout._(3), - blockMemberInteraction._(4); +final class ActionType extends EnumLike { + static const blockMessage = ActionType(1); + static const sendAlertMessage = ActionType(2); + static const timeout = ActionType(3); + static const blockMemberInteraction = ActionType(4); - /// The value of this [ActionType]. - final int value; - - const ActionType._(this.value); - - /// Parse an [ActionType] from an [int]. - /// - /// The [value] must be a valid action type. - factory ActionType.parse(int value) => ActionType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown action type', value), - ); + /// @nodoc + const ActionType(super.value); - @override - String toString() => 'ActionType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + ActionType.parse(int value) : this(value); } /// {@template action_metadata} diff --git a/lib/src/models/guild/guild.dart b/lib/src/models/guild/guild.dart index 37dea7ef8..d6af7f0a9 100644 --- a/lib/src/models/guild/guild.dart +++ b/lib/src/models/guild/guild.dart @@ -42,6 +42,7 @@ import 'package:nyxx/src/models/sticker/guild_sticker.dart'; import 'package:nyxx/src/models/user/user.dart'; import 'package:nyxx/src/models/voice/voice_region.dart'; import 'package:nyxx/src/models/voice/voice_state.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/flags.dart'; /// A partial [Guild]. @@ -466,73 +467,43 @@ class Guild extends UserGuild { } /// The verification level for a guild. -enum VerificationLevel { - none._(0), - low._(1), - medium._(2), - high._(3), - veryHigh._(4); +final class VerificationLevel extends EnumLike { + static const none = VerificationLevel(0); + static const low = VerificationLevel(1); + static const medium = VerificationLevel(2); + static const high = VerificationLevel(3); + static const veryHigh = VerificationLevel(4); - /// The value of this verification level. - final int value; - - const VerificationLevel._(this.value); - - /// Parses a [VerificationLevel] from an [int]. - /// - /// The [value] must be a valid verification level. - factory VerificationLevel.parse(int value) => VerificationLevel.values.firstWhere( - (level) => level.value == value, - orElse: () => throw FormatException('Invalid verification level', value), - ); + /// @nodoc + const VerificationLevel(super.value); - @override - String toString() => 'VerificationLevel($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + VerificationLevel.parse(int value) : this(value); } /// The level at which message notifications are sent in a guild. -enum MessageNotificationLevel { - allMessages._(0), - onlyMentions._(1); - - /// The value of this message notification level. - final int value; +final class MessageNotificationLevel extends EnumLike { + static const allMessages = MessageNotificationLevel(0); + static const onlyMentions = MessageNotificationLevel(1); - const MessageNotificationLevel._(this.value); - - /// Parses a [MessageNotificationLevel] from an [int]. - /// - /// The [value] must be a valid message notification level. - factory MessageNotificationLevel.parse(int value) => MessageNotificationLevel.values.firstWhere( - (level) => level.value == value, - orElse: () => throw FormatException('Invalid message notification level', value), - ); + /// @nodoc + const MessageNotificationLevel(super.value); - @override - String toString() => 'MessageNotificationLevel($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + MessageNotificationLevel.parse(int value) : this(value); } /// The level of explicit content filtering in a guild. -enum ExplicitContentFilterLevel { - disabled._(0), - membersWithoutRoles._(1), - allMembers._(2); - - /// The value of this explicit content filter level. - final int value; +final class ExplicitContentFilterLevel extends EnumLike { + static const disabled = ExplicitContentFilterLevel(0); + static const membersWithoutRoles = ExplicitContentFilterLevel(1); + static const allMembers = ExplicitContentFilterLevel(2); - const ExplicitContentFilterLevel._(this.value); - - /// Parses an [ExplicitContentFilterLevel] from an [int]. - /// - /// The [value] must be a valid explicit content filter level. - factory ExplicitContentFilterLevel.parse(int value) => ExplicitContentFilterLevel.values.firstWhere( - (level) => level.value == value, - orElse: () => throw FormatException('Invalid explicit content filter level', value), - ); + /// @nodoc + const ExplicitContentFilterLevel(super.value); - @override - String toString() => 'ExplicitContentFilterLevel($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + ExplicitContentFilterLevel.parse(int value) : this(value); } /// Features that can be enabled in certain guilds. @@ -705,25 +676,15 @@ class GuildFeatures extends Flags { } /// The MFA level required for moderators of a guild. -enum MfaLevel { - none._(0), - elevated._(1); - - /// The value of this MFA level. - final int value; - - const MfaLevel._(this.value); +final class MfaLevel extends EnumLike { + static const none = MfaLevel(0); + static const elevated = MfaLevel(1); - /// Parses an [MfaLevel] from an [int]. - /// - /// The [value] must be a valid mfa level. - factory MfaLevel.parse(int value) => MfaLevel.values.firstWhere( - (level) => level.value == value, - orElse: () => throw FormatException('Invalid mfa level', value), - ); + /// @nodoc + const MfaLevel(super.value); - @override - String toString() => 'MfaLevel($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + MfaLevel.parse(int value) : this(value); } /// The configuration of a guild's system channel. @@ -769,49 +730,29 @@ class SystemChannelFlags extends Flags { } /// The premium tier of a guild. -enum PremiumTier { - none._(0), - one._(1), - two._(2), - three._(3); +final class PremiumTier extends EnumLike { + static const none = PremiumTier(0); + static const one = PremiumTier(1); + static const two = PremiumTier(2); + static const three = PremiumTier(3); - /// The value of this tier. - final int value; + /// nodoc + const PremiumTier(super.value); - const PremiumTier._(this.value); - - /// Parses a [PremiumTier] from an [int]. - /// - /// The [value] must be a valid premium tier. - factory PremiumTier.parse(int value) => PremiumTier.values.firstWhere( - (level) => level.value == value, - orElse: () => throw FormatException('Invalid premium tier', value), - ); - - @override - String toString() => 'PremiumTier($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + PremiumTier.parse(int value) : this(value); } /// The NSFW level of a guild. -enum NsfwLevel { - unset._(0), - explicit._(1), - safe._(2), - ageRestricted._(3); - - /// The value of this NSFW level. - final int value; +final class NsfwLevel extends EnumLike { + static const unset = NsfwLevel(0); + static const explicit = NsfwLevel(1); + static const safe = NsfwLevel(2); + static const ageRestricted = NsfwLevel(3); - const NsfwLevel._(this.value); + /// nodoc + const NsfwLevel(super.value); - /// Parses an [NsfwLevel] from an [int]. - /// - /// The [value] must be a valid nsfw level. - factory NsfwLevel.parse(int value) => NsfwLevel.values.firstWhere( - (level) => level.value == value, - orElse: () => throw FormatException('Invalid nsfw level', value), - ); - - @override - String toString() => 'NsfwLevel($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + NsfwLevel.parse(int value) : this(value); } diff --git a/lib/src/models/guild/integration.dart b/lib/src/models/guild/integration.dart index 3a1e59e9a..29dfc504f 100644 --- a/lib/src/models/guild/integration.dart +++ b/lib/src/models/guild/integration.dart @@ -3,6 +3,7 @@ import 'package:nyxx/src/models/role.dart'; import 'package:nyxx/src/models/snowflake.dart'; import 'package:nyxx/src/models/snowflake_entity/snowflake_entity.dart'; import 'package:nyxx/src/models/user/user.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; /// A partial [Integration]. @@ -94,25 +95,15 @@ class Integration extends PartialIntegration { } /// The behavior of an integration when a member's subscription expires. -enum IntegrationExpireBehavior { - removeRole._(0), - kick._(1); +final class IntegrationExpireBehavior extends EnumLike { + static const removeRole = IntegrationExpireBehavior(0); + static const kick = IntegrationExpireBehavior(1); - /// TThe value of this [IntegrationExpireBehavior]. - final int value; - - const IntegrationExpireBehavior._(this.value); - - /// Parse an [IntegrationExpireBehavior] from an [int]. - /// - /// The [value] must be a valid integration expire behavior. - factory IntegrationExpireBehavior.parse(int value) => IntegrationExpireBehavior.values.firstWhere( - (behavior) => behavior.value == value, - orElse: () => throw FormatException('Unknown integration expire behavior', value), - ); + /// @nodoc + const IntegrationExpireBehavior(super.value); - @override - String toString() => 'IntegrationExpireBehavior($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + IntegrationExpireBehavior.parse(int value) : this(value); } /// {@template integration_account} diff --git a/lib/src/models/guild/onboarding.dart b/lib/src/models/guild/onboarding.dart index 85eebdeef..333937945 100644 --- a/lib/src/models/guild/onboarding.dart +++ b/lib/src/models/guild/onboarding.dart @@ -3,6 +3,7 @@ import 'package:nyxx/src/models/channel/channel.dart'; import 'package:nyxx/src/models/emoji.dart'; import 'package:nyxx/src/models/guild/guild.dart'; import 'package:nyxx/src/models/snowflake.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; /// {@template onboarding} @@ -82,25 +83,15 @@ class OnboardingPrompt with ToStringHelper { } /// The type of an [Onboarding] prompt. -enum OnboardingPromptType { - multipleChoice._(0), - dropdown._(1); +final class OnboardingPromptType extends EnumLike { + static const multipleChoice = OnboardingPromptType(0); + static const dropdown = OnboardingPromptType(1); - /// The value of this [OnboardingPromptType]. - final int value; - - const OnboardingPromptType._(this.value); + /// @nodoc + const OnboardingPromptType(super.value); - /// Parse an [OnboardingPromptType] from an [int]. - /// - /// The [value] must be a valid onboarding prompt type. - factory OnboardingPromptType.parse(int value) => OnboardingPromptType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown onboarding prompt type', value), - ); - - @override - String toString() => 'OnboardingPromptType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + OnboardingPromptType.parse(int value) : this(value); } /// {@template onboarding_prompt_option} diff --git a/lib/src/models/guild/scheduled_event.dart b/lib/src/models/guild/scheduled_event.dart index 225182a2d..3f0fd0031 100644 --- a/lib/src/models/guild/scheduled_event.dart +++ b/lib/src/models/guild/scheduled_event.dart @@ -8,6 +8,7 @@ import 'package:nyxx/src/models/guild/member.dart'; import 'package:nyxx/src/models/snowflake.dart'; import 'package:nyxx/src/models/snowflake_entity/snowflake_entity.dart'; import 'package:nyxx/src/models/user/user.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; /// A partial [ScheduledEvent]. @@ -117,50 +118,30 @@ class ScheduledEvent extends PartialScheduledEvent { } /// The status of a [ScheduledEvent]. -enum EventStatus { - scheduled._(1), - active._(2), - completed._(3), - cancelled._(4); +final class EventStatus extends EnumLike { + static const scheduled = EventStatus(1); + static const active = EventStatus(2); + static const completed = EventStatus(3); + static const cancelled = EventStatus(4); - /// TThe value of this [EventStatus]. - final int value; - - const EventStatus._(this.value); - - /// Parse an [EventStatus] from an [int]. - /// - /// The [value] must be a valid event status. - factory EventStatus.parse(int value) => EventStatus.values.firstWhere( - (status) => status.value == value, - orElse: () => throw FormatException('Unknown event status', value), - ); + /// @nodoc + const EventStatus(super.value); - @override - String toString() => 'EventStatus($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + EventStatus.parse(int value) : this(value); } /// The type of the entity associated with a [ScheduledEvent]. -enum ScheduledEntityType { - stageInstance._(1), - voice._(2), - external._(3); +final class ScheduledEntityType extends EnumLike { + static const stageInstance = ScheduledEntityType(1); + static const voice = ScheduledEntityType(2); + static const external = ScheduledEntityType(3); - /// The value of this [ScheduledEntityType]. - final int value; - - const ScheduledEntityType._(this.value); - - /// Parse a [ScheduledEntityType] from an [int]. - /// - /// The [value] must be a valid scheduled entity type. - factory ScheduledEntityType.parse(int value) => ScheduledEntityType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown scheduled entity type', value), - ); + /// @nodoc + const ScheduledEntityType(super.value); - @override - String toString() => 'ScheduledEntityType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + ScheduledEntityType.parse(int value) : this(value); } /// {@template entity_metadata} diff --git a/lib/src/models/interaction.dart b/lib/src/models/interaction.dart index 4adbe8020..c52246087 100644 --- a/lib/src/models/interaction.dart +++ b/lib/src/models/interaction.dart @@ -19,37 +19,28 @@ import 'package:nyxx/src/models/permissions.dart'; import 'package:nyxx/src/models/role.dart'; import 'package:nyxx/src/models/snowflake.dart'; import 'package:nyxx/src/models/user/user.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; /// A context indicating whether command can be used in DMs, groups, or guilds. /// /// External references: /// * Discord API Reference: https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-object-interaction-context-types -enum InteractionContextType { +final class InteractionContextType extends EnumLike { /// Interaction can be used within servers. - guild._(0), + static const InteractionContextType guild = InteractionContextType(0); /// Interaction can be used within DMs with the app's bot user. - botDm._(1), + static const InteractionContextType botDm = InteractionContextType(1); /// Interaction can be used within Group DMs and DMs other than the app's bot user. - privateChannel._(2); + static const InteractionContextType privateChannel = InteractionContextType(2); - /// The value of this [InteractionContextType]. - final int value; - - const InteractionContextType._(this.value); - - /// Parse an [InteractionContextType] from an [int]. - /// - /// The [value] must be a valid interaction context type. - factory InteractionContextType.parse(int value) => InteractionContextType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown InteractionContextType', value), - ); + /// @nodoc + const InteractionContextType(super.value); - @override - String toString() => 'InteractionContextType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + InteractionContextType.parse(int value) : this(value); } /// {@template interaction} @@ -427,28 +418,18 @@ class ApplicationCommandAutocompleteInteraction extends Interaction InteractionType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown interaction type', value), - ); +final class InteractionType extends EnumLike { + static const ping = InteractionType(1); + static const applicationCommand = InteractionType(2); + static const messageComponent = InteractionType(3); + static const applicationCommandAutocomplete = InteractionType(4); + static const modalSubmit = InteractionType(5); - @override - String toString() => 'InteractionType($value)'; + /// @nodoc + const InteractionType(super.value); + + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + InteractionType.parse(int value) : this(value); } /// {@template application_command_interaction_data} diff --git a/lib/src/models/invite/invite.dart b/lib/src/models/invite/invite.dart index fb4200ac5..9582d7dc4 100644 --- a/lib/src/models/invite/invite.dart +++ b/lib/src/models/invite/invite.dart @@ -3,6 +3,7 @@ import 'package:nyxx/src/models/channel/channel.dart'; import 'package:nyxx/src/models/guild/guild.dart'; import 'package:nyxx/src/models/guild/scheduled_event.dart'; import 'package:nyxx/src/models/user/user.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; /// {@template invite} @@ -69,26 +70,13 @@ class Invite with ToStringHelper { } /// The type of an [Invite]'s target. -enum TargetType { - /// The invite is targeting a stream. - stream._(1), +final class TargetType extends EnumLike { + static const stream = TargetType(1); + static const embeddedApplication = TargetType(2); - /// The invite is targeting an embedded application. - embeddedApplication._(2); - - /// The value of this [TargetType]. - final int value; - - /// Parse a [TargetType] from an [int]. - /// - /// The [value] must be a valid target type. - factory TargetType.parse(int value) => TargetType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown TargetType', value), - ); - - const TargetType._(this.value); + /// @nodoc + const TargetType(super.value); - @override - String toString() => 'TargetType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + TargetType.parse(int value) : this(value); } diff --git a/lib/src/models/locale.dart b/lib/src/models/locale.dart index 061742cbb..fde9b2623 100644 --- a/lib/src/models/locale.dart +++ b/lib/src/models/locale.dart @@ -51,11 +51,8 @@ enum Locale { /// /// [identifier] must be a string containing an identifier matching [Locale.identifier] for one of /// the listed locales. - factory Locale.parse(String identifier) => Locale.values.firstWhere( - (locale) => locale.identifier == identifier, + factory Locale.parse(String identifier) => values.firstWhere( + (loc) => loc.identifier == identifier, orElse: () => throw FormatException('Unknown Locale', identifier), ); - - @override - String toString() => 'Locale($identifier)'; } diff --git a/lib/src/models/message/activity.dart b/lib/src/models/message/activity.dart index 0f6c72ba5..173e823be 100644 --- a/lib/src/models/message/activity.dart +++ b/lib/src/models/message/activity.dart @@ -1,3 +1,4 @@ +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; /// {@template message_activity} @@ -25,25 +26,15 @@ class MessageActivity with ToStringHelper { /// /// External references: /// * Discord API Reference: https://discord.com/developers/docs/resources/channel#message-object-message-activity-types -enum MessageActivityType { - join._(1), - spectate._(2), - listen._(3), - joinRequest._(5); +final class MessageActivityType extends EnumLike { + static const join = MessageActivityType(1); + static const spectate = MessageActivityType(2); + static const listen = MessageActivityType(3); + static const joinRequest = MessageActivityType(5); - /// The value of this [MessageActivityType]. - final int value; - - const MessageActivityType._(this.value); - - /// Parse a [MessageActivityType] from an [int]. - /// - /// [value] must be a valid message activity type. - factory MessageActivityType.parse(int value) => MessageActivityType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown MessageActivityType', value), - ); + /// @nodoc + const MessageActivityType(super.value); - @override - String toString() => 'MessageActivityType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + MessageActivityType.parse(int value) : this(value); } diff --git a/lib/src/models/message/component.dart b/lib/src/models/message/component.dart index 2cf556af1..ae7698a92 100644 --- a/lib/src/models/message/component.dart +++ b/lib/src/models/message/component.dart @@ -1,34 +1,25 @@ import 'package:nyxx/src/models/channel/channel.dart'; import 'package:nyxx/src/models/emoji.dart'; import 'package:nyxx/src/models/snowflake.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; /// The type of a [MessageComponent]. -enum MessageComponentType { - actionRow._(1), - button._(2), - stringSelect._(3), - textInput._(4), - userSelect._(5), - roleSelect._(6), - mentionableSelect._(7), - channelSelect._(8); - - /// The value of this [MessageComponentType]. - final int value; - - const MessageComponentType._(this.value); - - /// Parse a [MessageComponentType] from an [int]. - /// - /// The [value] must be a valid message component type. - factory MessageComponentType.parse(int value) => MessageComponentType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown message component type', value), - ); +final class MessageComponentType extends EnumLike { + static const actionRow = MessageComponentType(1); + static const button = MessageComponentType(2); + static const stringSelect = MessageComponentType(3); + static const textInput = MessageComponentType(4); + static const userSelect = MessageComponentType(5); + static const roleSelect = MessageComponentType(6); + static const mentionableSelect = MessageComponentType(7); + static const channelSelect = MessageComponentType(8); - @override - String toString() => 'MessageComponentType($value)'; + /// @nodoc + const MessageComponentType(super.value); + + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + MessageComponentType.parse(int value) : this(value); } /// A component in a [Message]. @@ -90,29 +81,19 @@ class ButtonComponent extends MessageComponent { } /// The style of a [ButtonComponent]. -enum ButtonStyle { - primary._(1), - secondary._(2), - success._(3), - danger._(4), - link._(5), - premium._(6); - - /// The value of this [ButtonStyle]. - final int value; +final class ButtonStyle extends EnumLike { + static const primary = ButtonStyle(1); + static const secondary = ButtonStyle(2); + static const success = ButtonStyle(3); + static const danger = ButtonStyle(4); + static const link = ButtonStyle(5); + static const premium = ButtonStyle(6); - const ButtonStyle._(this.value); - - /// Parse a [ButtonStyle] from an [int]. - /// - /// The [value] must be a valid button style. - factory ButtonStyle.parse(int value) => ButtonStyle.values.firstWhere( - (style) => style.value == value, - orElse: () => throw FormatException('Unknown button style', value), - ); + /// @nodoc + const ButtonStyle(super.value); - @override - String toString() => 'ButtonStyle($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + ButtonStyle.parse(int value) : this(value); } /// A dropdown menu in which users can select from on or more choices. @@ -164,23 +145,16 @@ class SelectMenuComponent extends MessageComponent { } /// The type of a [SelectMenuDefaultValue]. -enum SelectMenuDefaultValueType { - user._('user'), - role._('role'), - channel._('channel'); +final class SelectMenuDefaultValueType extends EnumLike { + static const user = SelectMenuDefaultValueType('user'); + static const role = SelectMenuDefaultValueType('role'); + static const channel = SelectMenuDefaultValueType('channel'); - /// The value of this [SelectMenuDefaultValue]. - final String value; - - const SelectMenuDefaultValueType._(this.value); + /// @nodoc + const SelectMenuDefaultValueType(super.value); - /// Parse a [SelectMenuDefaultValueType] from a [String]. - /// - /// The [value] must be a valid select menu default value type. - factory SelectMenuDefaultValueType.parse(String value) => SelectMenuDefaultValueType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown select menu default value type', value), - ); + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + SelectMenuDefaultValueType.parse(String value) : this(value); } /// A default value in a [SelectMenuComponent]. @@ -268,23 +242,13 @@ class TextInputComponent extends MessageComponent { } /// The type of a [TextInputComponent]. -enum TextInputStyle { - short._(1), - paragraph._(2); - - /// The value of this [TextInputStyle]. - final int value; +final class TextInputStyle extends EnumLike { + static const short = TextInputStyle(1); + static const paragraph = TextInputStyle(2); - const TextInputStyle._(this.value); - - /// Parse a [TextInputComponent] from an [int]. - /// - /// The [value] must beb a valid text input style. - factory TextInputStyle.parse(int value) => TextInputStyle.values.firstWhere( - (style) => style.value == value, - orElse: () => throw FormatException('Unknown text input style', value), - ); + /// @nodoc + const TextInputStyle(super.value); - @override - String toString() => 'TextInputStyle($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + TextInputStyle.parse(int value) : this(value); } diff --git a/lib/src/models/message/message.dart b/lib/src/models/message/message.dart index 1b0c6de90..12ba221e2 100644 --- a/lib/src/models/message/message.dart +++ b/lib/src/models/message/message.dart @@ -21,6 +21,7 @@ import 'package:nyxx/src/models/snowflake_entity/snowflake_entity.dart'; import 'package:nyxx/src/models/sticker/sticker.dart'; import 'package:nyxx/src/models/user/user.dart'; import 'package:nyxx/src/models/webhook.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/flags.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; @@ -252,58 +253,48 @@ class Message extends PartialMessage { /// /// External references: /// * Discord API Reference: https://discord.com/developers/docs/resources/channel#message-object-message-types -enum MessageType { - normal._(0), - recipientAdd._(1), - recipientRemove._(2), - call._(3), - channelNameChange._(4), - channelIconChange._(5), - channelPinnedMessage._(6), - userJoin._(7), - guildBoost._(8), - guildBoostTier1._(9), - guildBoostTier2._(10), - guildBoostTier3._(11), - channelFollowAdd._(12), - guildDiscoveryDisqualified._(14), - guildDiscoveryRequalified._(15), - guildDiscoveryGracePeriodInitialWarning._(16), - guildDiscoveryGracePeriodFinalWarning._(17), - threadCreated._(18), - reply._(19), - chatInputCommand._(20), - threadStarterMessage._(21), - guildInviteReminder._(22), - contextMenuCommand._(23), - autoModerationAction._(24), - roleSubscriptionPurchase._(25), - interactionPremiumUpsell._(26), - stageStart._(27), - stageEnd._(28), - stageSpeaker._(29), - stageTopic._(31), - guildApplicationPremiumSubscription._(32), - guildIncidentAlertModeEnabled._(36), - guildIncidentAlertModeDisabled._(37), - guildIncidentReportRaid._(38), - guildIncidentReportFalseAlarm._(39); - - /// The value of this [MessageType]. - final int value; - - const MessageType._(this.value); - - /// Parse a [MessageType] from an [int]. - /// - /// [value] must be a valid [MessageType]. - factory MessageType.parse(int value) => MessageType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown MessageType', value), - ); +final class MessageType extends EnumLike { + static const normal = MessageType(0); + static const recipientAdd = MessageType(1); + static const recipientRemove = MessageType(2); + static const call = MessageType(3); + static const channelNameChange = MessageType(4); + static const channelIconChange = MessageType(5); + static const channelPinnedMessage = MessageType(6); + static const userJoin = MessageType(7); + static const guildBoost = MessageType(8); + static const guildBoostTier1 = MessageType(9); + static const guildBoostTier2 = MessageType(10); + static const guildBoostTier3 = MessageType(11); + static const channelFollowAdd = MessageType(12); + static const guildDiscoveryDisqualified = MessageType(14); + static const guildDiscoveryRequalified = MessageType(15); + static const guildDiscoveryGracePeriodInitialWarning = MessageType(16); + static const guildDiscoveryGracePeriodFinalWarning = MessageType(17); + static const threadCreated = MessageType(18); + static const reply = MessageType(19); + static const chatInputCommand = MessageType(20); + static const threadStarterMessage = MessageType(21); + static const guildInviteReminder = MessageType(22); + static const contextMenuCommand = MessageType(23); + static const autoModerationAction = MessageType(24); + static const roleSubscriptionPurchase = MessageType(25); + static const interactionPremiumUpsell = MessageType(26); + static const stageStart = MessageType(27); + static const stageEnd = MessageType(28); + static const stageSpeaker = MessageType(29); + static const stageTopic = MessageType(31); + static const guildApplicationPremiumSubscription = MessageType(32); + static const guildIncidentAlertModeEnabled = MessageType(36); + static const guildIncidentAlertModeDisabled = MessageType(37); + static const guildIncidentReportRaid = MessageType(38); + static const guildIncidentReportFalseAlarm = MessageType(39); - @override - String toString() => 'MessageType($value)'; + /// @nodoc + const MessageType(super.value); + + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + MessageType.parse(int value) : this(value); } /// Flags that can be applied to a [Message]. diff --git a/lib/src/models/message/poll.dart b/lib/src/models/message/poll.dart index ad26e04fe..b2cfa8653 100644 --- a/lib/src/models/message/poll.dart +++ b/lib/src/models/message/poll.dart @@ -1,29 +1,20 @@ import 'package:nyxx/src/models/emoji.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; /// A layout type indicating how poll looks. /// /// External references: /// * Discord API Reference: https://discord.com/developers/docs/resources/poll#layout-type -enum PollLayoutType { +final class PollLayoutType extends EnumLike { /// The default layout type. - defaultLayout._(1); + static const defaultLayout = PollLayoutType(1); - /// The value of this [PollLayoutType]. - final int value; - - const PollLayoutType._(this.value); - - /// Parse an [PollLayoutType] from an [int]. - /// - /// The [value] must be a valid poll layout type. - factory PollLayoutType.parse(int value) => PollLayoutType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown PollLayoutType', value), - ); + /// @nodoc + const PollLayoutType(super.value); - @override - String toString() => 'PollLayoutType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + PollLayoutType.parse(int value) : this(value); } /// {@template poll_media} diff --git a/lib/src/models/permission_overwrite.dart b/lib/src/models/permission_overwrite.dart index 30fae0d63..a77638130 100644 --- a/lib/src/models/permission_overwrite.dart +++ b/lib/src/models/permission_overwrite.dart @@ -1,5 +1,6 @@ import 'package:nyxx/src/models/permissions.dart'; import 'package:nyxx/src/models/snowflake.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; /// {@template permission_overwrite} @@ -42,26 +43,16 @@ class PermissionOverwrite with ToStringHelper { } /// The type of a permission overwrite. -enum PermissionOverwriteType { +final class PermissionOverwriteType extends EnumLike { /// The overwrite applies to a [Role]'s permissions. - role._(0), + static const role = PermissionOverwriteType(0); /// The overwrite applies to a [Member]'s permissions. - member._(1); + static const member = PermissionOverwriteType(1); - /// The value of this type. - final int value; - - const PermissionOverwriteType._(this.value); - - /// Parse a [PermissionOverwriteType] from a [value]. - /// - /// The [value] must be a valid [PermissionOverwriteType]. - factory PermissionOverwriteType.parse(int value) => PermissionOverwriteType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown PermissionOverwriteType', value), - ); + /// @nodoc + const PermissionOverwriteType(super.value); - @override - String toString() => 'PermissionOverwriteType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + PermissionOverwriteType.parse(int value) : this(value); } diff --git a/lib/src/models/presence.dart b/lib/src/models/presence.dart index 1de6ad7c6..16027174b 100644 --- a/lib/src/models/presence.dart +++ b/lib/src/models/presence.dart @@ -1,5 +1,6 @@ import 'package:nyxx/src/models/emoji.dart'; import 'package:nyxx/src/models/snowflake.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/flags.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; @@ -22,27 +23,17 @@ class ClientStatus with ToStringHelper { } /// The status of a client. -enum UserStatus { - online._('online'), - idle._('idle'), - dnd._('dnd'), - offline._('offline'); - - /// The value of this [UserStatus]. - final String value; - - const UserStatus._(this.value); - - /// Parse a [UserStatus] from a [String]. - /// - /// The [value] must be a valid user status. - factory UserStatus.parse(String value) => UserStatus.values.firstWhere( - (status) => status.value == value, - orElse: () => throw FormatException('Unknown user status', value), - ); - - @override - String toString() => 'UserStatus($value)'; +final class UserStatus extends EnumLike { + static const online = UserStatus('online'); + static const dnd = UserStatus('dnd'); + static const idle = UserStatus('idle'); + static const offline = UserStatus('offline'); + + /// @nodoc + const UserStatus(super.value); + + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + UserStatus.parse(String value) : this(value); } /// {@template activity} @@ -116,29 +107,18 @@ class Activity with ToStringHelper { } /// The type of an activity. -enum ActivityType { - game._(0), - streaming._(1), - listening._(2), - watching._(3), - custom._(4), - competing._(5); - - /// The value of this [ActivityType]. - final int value; - - const ActivityType._(this.value); - - /// Parse an [ActivityType] from an [int]. - /// - /// The [value] must be a valid activity type. - factory ActivityType.parse(int value) => ActivityType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown activity type', value), - ); - - @override - String toString() => 'ActivityType($value)'; +final class ActivityType extends EnumLike { + static const game = ActivityType(0); + static const streaming = ActivityType(1); + static const listening = ActivityType(2); + static const watching = ActivityType(3); + static const custom = ActivityType(4); + static const competing = ActivityType(5); + + const ActivityType(super.value); + + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + ActivityType.parse(int value) : this(value); } /// {@template activity_timestamps} diff --git a/lib/src/models/sku.dart b/lib/src/models/sku.dart index cfbcda741..2d7ea3952 100644 --- a/lib/src/models/sku.dart +++ b/lib/src/models/sku.dart @@ -1,6 +1,7 @@ import 'package:nyxx/src/http/managers/application_manager.dart'; import 'package:nyxx/src/models/application.dart'; import 'package:nyxx/src/models/snowflake.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/flags.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; @@ -46,29 +47,24 @@ class Sku with ToStringHelper { } /// The type of an [Sku]. -enum SkuType { +final class SkuType extends EnumLike { /// Durable one-time purchase. - durable._(2), + static const durable = SkuType(2); /// Consumable one-time purchase. - consumable._(3), - subscription._(5), - subscriptionGroup._(6); + static const consumable = SkuType(3); - final int value; + /// Subscription. + static const subscription = SkuType(5); - const SkuType._(this.value); + /// Subscription group. + static const subscriptionGroup = SkuType(6); - /// Parse an [SkuType] from an [int]. - /// - /// The [value] must be a valid sku type. - factory SkuType.parse(int value) => SkuType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown SKU type', value), - ); + /// @nodoc + const SkuType(super.value); - @override - String toString() => 'SkuType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + SkuType.parse(int value) : this(value); } /// Flags applied to an [Sku]. diff --git a/lib/src/models/sticker/sticker.dart b/lib/src/models/sticker/sticker.dart index 01aceb6d7..be4e35571 100644 --- a/lib/src/models/sticker/sticker.dart +++ b/lib/src/models/sticker/sticker.dart @@ -1,48 +1,28 @@ import 'package:nyxx/src/models/snowflake_entity/snowflake_entity.dart'; import 'package:nyxx/src/models/user/user.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; -enum StickerType { - standard._(1), - guild._(2); +final class StickerType extends EnumLike { + static const standard = StickerType(1); + static const guild = StickerType(2); - /// The value of this [StickerType]. - final int value; - - const StickerType._(this.value); - - /// Parse a [StickerType] from a [value]. - /// - /// The [value] must be a valid sticker type - factory StickerType.parse(int value) => StickerType.values.firstWhere( - (state) => state.value == value, - orElse: () => throw FormatException('Unknown sticker type', value), - ); + /// @nodoc + const StickerType(super.value); - @override - String toString() => 'StickerType($value)'; + StickerType.parse(int value) : this(value); } -enum StickerFormatType { - png._(1), - apng._(2), - lottie._(3), - gif._(4); +final class StickerFormatType extends EnumLike { + static const png = StickerFormatType(1); + static const apng = StickerFormatType(2); + static const lottie = StickerFormatType(3); + static const gif = StickerFormatType(4); - /// The value of this [StickerFormatType]. - final int value; - - const StickerFormatType._(this.value); - - /// Parse a [StickerFormatType] from a [value]. - /// - /// The [value] must be a valid sticker format type - factory StickerFormatType.parse(int value) => StickerFormatType.values.firstWhere( - (state) => state.value == value, - orElse: () => throw FormatException('Unknown sticker format type', value), - ); + /// @nodoc + const StickerFormatType(super.value); - @override - String toString() => 'StickerFormatType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + StickerFormatType.parse(int value) : this(value); } /// Mixin with shared properties with stickers diff --git a/lib/src/models/team.dart b/lib/src/models/team.dart index 4e15f3eef..24a176a7a 100644 --- a/lib/src/models/team.dart +++ b/lib/src/models/team.dart @@ -3,6 +3,7 @@ import 'package:nyxx/src/http/managers/application_manager.dart'; import 'package:nyxx/src/http/route.dart'; import 'package:nyxx/src/models/snowflake.dart'; import 'package:nyxx/src/models/user/user.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; /// {@template team} @@ -81,46 +82,27 @@ class TeamMember with ToStringHelper { } /// The status of a member in a [Team]. -enum TeamMembershipState { - invited._(1), - accepted._(2); +final class TeamMembershipState extends EnumLike { + /// The user has been invited to the team. + static const invited = TeamMembershipState(1); - /// The value of this [TeamMembershipState]. - final int value; + /// The user has accepted the invitation to the team. + static const accepted = TeamMembershipState(2); - const TeamMembershipState._(this.value); - - /// Parse a [TeamMembershipState] from a [value]. - /// - /// The [value] must be a valid team membership state. - factory TeamMembershipState.parse(int value) => TeamMembershipState.values.firstWhere( - (state) => state.value == value, - orElse: () => throw FormatException('Unknown team membership state', value), - ); + /// @nodoc + const TeamMembershipState(super.value); - @override - String toString() => 'TeamMembershipState($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + TeamMembershipState.parse(int value) : this(value); } /// The role of a [TeamMember]. -enum TeamMemberRole { - admin._('admin'), - developer._('developer'), - readOnly._('read_only'); - - /// The value of this [TeamMemberRole]. - final String value; - - const TeamMemberRole._(this.value); - - /// Parse a [TeamMemberRole] from a [String]. - /// - /// The [value] must be a valid team member role. - factory TeamMemberRole.parse(String value) => TeamMemberRole.values.firstWhere( - (role) => role.value == value, - orElse: () => throw FormatException('Unknown team member role', value), - ); - - @override - String toString() => 'TeamMemberRole($value)'; +final class TeamMemberRole extends EnumLike { + static const admin = TeamMemberRole('admin'); + static const developer = TeamMemberRole('developer'); + static const readOnly = TeamMemberRole('read_only'); + + const TeamMemberRole(super.value); + + TeamMemberRole.parse(String value) : this(value); } diff --git a/lib/src/models/user/connection.dart b/lib/src/models/user/connection.dart index 426f202aa..97c8e7008 100644 --- a/lib/src/models/user/connection.dart +++ b/lib/src/models/user/connection.dart @@ -1,4 +1,5 @@ import 'package:nyxx/src/models/guild/integration.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/to_string_helper/to_string_helper.dart'; /// A link to an account on a service other than Discord. @@ -91,36 +92,23 @@ enum ConnectionType { /// Parse a string to a [ConnectionType]. /// /// The [value] must be a string containing a valid [ConnectionType.value]. - factory ConnectionType.parse(String value) => ConnectionType.values.firstWhere( + factory ConnectionType.parse(String value) => values.firstWhere( (type) => type.value == value, orElse: () => throw FormatException('Unknown ConnectionType', value), ); - - @override - String toString() => 'ConnectionType($name)'; } /// The visibility level of a connection. /// /// External references: /// * Discord API Reference: https://discord.com/developers/docs/resources/user#connection-object-visibility-types -enum ConnectionVisibility { - none._(0), - everyone._(1); - - /// THe value of this connection visibility level. - final int value; - - const ConnectionVisibility._(this.value); +final class ConnectionVisibility extends EnumLike { + static const none = ConnectionVisibility(0); + static const everyone = ConnectionVisibility(1); - /// Parse an integer value to a [ConnectionVisibility]. - /// - /// The [value] must be a valid [ConnectionVisibility]. - factory ConnectionVisibility.parse(int value) => ConnectionVisibility.values.firstWhere( - (visibility) => visibility.value == value, - orElse: () => throw FormatException('Unknown ConnectionVisibility', value), - ); + /// @nodoc + const ConnectionVisibility(super.value); - @override - String toString() => 'ConnectionVisibility($name)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + ConnectionVisibility.parse(int value) : this(value); } diff --git a/lib/src/models/user/user.dart b/lib/src/models/user/user.dart index 60a0ffe0a..3d19f2fc6 100644 --- a/lib/src/models/user/user.dart +++ b/lib/src/models/user/user.dart @@ -6,6 +6,7 @@ import 'package:nyxx/src/models/discord_color.dart'; import 'package:nyxx/src/models/locale.dart'; import 'package:nyxx/src/models/message/author.dart'; import 'package:nyxx/src/models/snowflake_entity/snowflake_entity.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; import 'package:nyxx/src/utils/flags.dart'; /// A partial [User] object. @@ -227,25 +228,15 @@ class UserFlags extends Flags { } /// The types of Discord Nitro subscription a user can have. -enum NitroType { - none._(0), - classic._(1), - nitro._(2), - basic._(3); - - /// The value of this [NitroType]. - final int value; - - const NitroType._(this.value); - - /// Parse an integer from the API to a [NitroType]. - /// - /// The [value] must be a valid nitro type. - factory NitroType.parse(int value) => NitroType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown NitroType', value), - ); +final class NitroType extends EnumLike { + static const none = NitroType(0); + static const classic = NitroType(1); + static const nitro = NitroType(2); + static const basic = NitroType(3); - @override - String toString() => 'NitroType($value)'; + /// @nodoc + const NitroType(super.value); + + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + NitroType.parse(int value) : this(value); } diff --git a/lib/src/models/webhook.dart b/lib/src/models/webhook.dart index 8ed2c416f..81ae36e20 100644 --- a/lib/src/models/webhook.dart +++ b/lib/src/models/webhook.dart @@ -11,6 +11,7 @@ import 'package:nyxx/src/models/snowflake.dart'; import 'package:nyxx/src/models/snowflake_entity/snowflake_entity.dart'; import 'package:nyxx/src/http/managers/webhook_manager.dart'; import 'package:nyxx/src/models/user/user.dart'; +import 'package:nyxx/src/utils/enum_like.dart'; /// A partial [Webhook]. class PartialWebhook extends WritableSnowflakeEntity { @@ -173,29 +174,19 @@ class Webhook extends PartialWebhook { } /// The type of a [Webhook]. -enum WebhookType { +final class WebhookType extends EnumLike { /// A webhook which sends messages to a channel using a [Webhook.token]. - incoming._(1), + static const incoming = WebhookType(1); /// An internal webhook used to manage Channel Followers. - channelFollower._(2), + static const channelFollower = WebhookType(2); /// A webhook for use with interactions. - application._(3); + static const application = WebhookType(3); - /// The value of this webhook type. - final int value; - - const WebhookType._(this.value); - - /// Parse a [WebhookType] from a [value]. - /// - /// The [value] must be a valid webhook type. - factory WebhookType.parse(int value) => WebhookType.values.firstWhere( - (type) => type.value == value, - orElse: () => throw FormatException('Unknown webhook type', value), - ); + /// @nodoc + const WebhookType(super.value); - @override - String toString() => 'WebhookType($value)'; + @Deprecated('The .parse() constructor is deprecated. Use the unnamed constructor instead.') + WebhookType.parse(int value) : this(value); } diff --git a/lib/src/utils/enum_like.dart b/lib/src/utils/enum_like.dart new file mode 100644 index 000000000..f16c7b45b --- /dev/null +++ b/lib/src/utils/enum_like.dart @@ -0,0 +1,16 @@ +base class EnumLike> { + /// The value this enum-like holds. + final T value; + + /// @nodoc + const EnumLike(this.value); + + @override + String toString() => '$runtimeType($value)'; + + @override + int get hashCode => value.hashCode; + + @override + bool operator ==(Object other) => identical(this, other) || (other is U && other.value == value); +}