-
Notifications
You must be signed in to change notification settings - Fork 387
/
enum_helper.dart
83 lines (67 loc) · 2.27 KB
/
enum_helper.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/element/type.dart';
import 'package:source_gen/source_gen.dart';
import 'package:source_helper/source_helper.dart';
import '../enum_utils.dart';
import '../json_key_utils.dart';
import '../type_helper.dart';
final simpleExpression = RegExp('^[a-zA-Z_]+\$');
class EnumHelper extends TypeHelper<TypeHelperContextWithConfig> {
const EnumHelper();
@override
String? serialize(
DartType targetType,
String expression,
TypeHelperContextWithConfig context,
) {
final memberContent = enumValueMapFromType(targetType);
if (memberContent == null) {
return null;
}
context.addMember(memberContent);
if (targetType.isNullableType ||
enumFieldWithNullInEncodeMap(targetType) == true) {
return '${constMapName(targetType)}[$expression]';
} else {
return '${constMapName(targetType)}[$expression]!';
}
}
@override
String? deserialize(
DartType targetType,
String expression,
TypeHelperContextWithConfig context,
bool defaultProvided,
) {
final memberContent = enumValueMapFromType(targetType);
if (memberContent == null) {
return null;
}
final jsonKey = jsonKeyForField(context.fieldElement, context.config);
if (!targetType.isNullableType &&
jsonKey.unknownEnumValue == jsonKeyNullForUndefinedEnumValueFieldName) {
// If the target is not nullable,
throw InvalidGenerationSourceError(
'`$jsonKeyNullForUndefinedEnumValueFieldName` cannot be used with '
'`JsonKey.unknownEnumValue` unless the field is nullable.',
element: context.fieldElement,
);
}
String functionName;
if (targetType.isNullableType || defaultProvided) {
functionName = r'$enumDecodeNullable';
} else {
functionName = r'$enumDecode';
}
context.addMember(memberContent);
final args = [
constMapName(targetType),
expression,
if (jsonKey.unknownEnumValue != null)
'unknownValue: ${jsonKey.unknownEnumValue}',
];
return '$functionName(${args.join(', ')})';
}
}