Files
umbrix/lib/core/model/optional_range.dart

56 lines
1.5 KiB
Dart
Raw Normal View History

2024-02-15 19:39:35 +03:30
import 'package:dart_mappable/dart_mappable.dart';
import 'package:dartx/dartx.dart';
2024-02-17 11:58:34 +03:30
import 'package:freezed_annotation/freezed_annotation.dart';
2024-02-15 19:39:35 +03:30
import 'package:hiddify/core/localization/translations.dart';
part 'optional_range.mapper.dart';
@MappableClass()
class OptionalRange with OptionalRangeMappable {
const OptionalRange({this.min, this.max});
final int? min;
final int? max;
String format() => [min, max].whereNotNull().join("-");
String present(TranslationsEn t) =>
format().isEmpty ? t.general.notSet : format();
factory OptionalRange._fromString(
String input, {
bool allowEmpty = true,
}) =>
switch (input.split("-")) {
[final String val] when val.isEmpty && allowEmpty =>
const OptionalRange(),
[final String min] => OptionalRange(min: int.parse(min)),
[final String min, final String max] => OptionalRange(
min: int.parse(min),
max: int.parse(max),
),
_ => throw Exception("Invalid range: $input"),
};
static OptionalRange? tryParse(
String input, {
bool allowEmpty = false,
}) {
try {
return OptionalRange._fromString(input);
} catch (_) {
return null;
}
}
}
2024-02-17 11:58:34 +03:30
class OptionalRangeJsonConverter
implements JsonConverter<OptionalRange, String> {
const OptionalRangeJsonConverter();
2024-02-15 19:39:35 +03:30
@override
2024-02-17 11:58:34 +03:30
OptionalRange fromJson(String json) => OptionalRange._fromString(json);
2024-02-15 19:39:35 +03:30
@override
2024-02-17 11:58:34 +03:30
String toJson(OptionalRange object) => object.format();
2024-02-15 19:39:35 +03:30
}