diff --git a/packages/google_identity_services_web/lib/src/js_interop/shared.dart b/packages/google_identity_services_web/lib/src/js_interop/shared.dart index a56450383261..111706b7368e 100644 --- a/packages/google_identity_services_web/lib/src/js_interop/shared.dart +++ b/packages/google_identity_services_web/lib/src/js_interop/shared.dart @@ -2,12 +2,27 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/// Attempts to retrieve an enum value from [haystack] if [needle] is not null. + +/// Attempts to retrieve the enum value from [haystack] whose name matches [needle], or returns `null` if not found. +/// +/// This is a safe utility method that performs a reverse lookup on an enum +/// by comparing the string [needle] with each value’s [Enum.name]. +/// +/// Example: +/// ```dart +/// enum AuthMethod { google, facebook, apple } +/// +/// final result = maybeEnum('google', AuthMethod.values); // AuthMethod.google +/// final invalid = maybeEnum('github', AuthMethod.values); // null +/// ``` T? maybeEnum(String? needle, List haystack) { - if (needle == null) { - return null; + if (needle == null) return null; + for (final T value in haystack) { + if (value.name == needle) { + return value; + } } - return haystack.byName(needle); + return null; } /// The type of several functions from the library, that don't receive diff --git a/packages/google_identity_services_web/test/maybe_enum_test.dart b/packages/google_identity_services_web/test/maybe_enum_test.dart new file mode 100644 index 000000000000..f3be5e6c7d4a --- /dev/null +++ b/packages/google_identity_services_web/test/maybe_enum_test.dart @@ -0,0 +1,20 @@ +import 'package:google_identity_services_web/src/js_interop/shared.dart'; +import 'package:test/test.dart'; + +enum AuthMethod { google, facebook, apple } + +void main() { + group('maybeEnum', () { + test('returns correct enum when match is found', () { + expect(maybeEnum('google', AuthMethod.values), AuthMethod.google); + }); + + test('returns null when needle is null', () { + expect(maybeEnum(null, AuthMethod.values), isNull); + }); + + test('returns null when needle does not match', () { + expect(maybeEnum('github', AuthMethod.values), isNull); + }); + }); +}