fromElement static method

ServerLifecycleComponentMethod? fromElement(
  1. MethodElement object, {
  2. Map<String, DartType> typeSubstitutions = const {},
})

Implementation

static ServerLifecycleComponentMethod? fromElement(
  MethodElement object, {
  Map<String, DartType> typeSubstitutions = const {},
}) {
  if (!object.isPublic || object.isStatic) {
    return null;
  }

  final name = object.name;

  final returnTypeAlias = object.returnType.alias?.element.name;
  String returnType;
  var isFuture = false;
  String? exceptionType;

  final importPaths = <String>{};

  final params = object.formalParameters
      .map(
        (param) => ServerParam.fromElement(
          param,
          typeSubstitutions: typeSubstitutions,
        ),
      )
      .toList();

  if (returnTypeAlias != null && aliasReturnTypes.contains(returnTypeAlias)) {
    returnType = returnTypeAlias;
  } else if (object.returnType case final InterfaceType type
      when type.isAnyFuture) {
    isFuture = true;
    final typeArg = type.typeArguments.first;

    final resolveReturnType = typeArg.getDisplayString();

    returnType = switch (typeArg) {
      InterfaceType() => typeArg.alias?.element.name ?? resolveReturnType,
      _ => resolveReturnType,
    };

    if (returnType.startsWith((ExceptionCatcherResult).name)) {
      throw ArgumentError('Exception types cannot be a Future type');
    }

    if (returnType == (Response).name && _hasNextResponseParam(params)) {
      returnType = wrapperResult;
    }
  } else {
    returnType = object.returnType.getDisplayString();

    if (object.returnType case final InterfaceType type
        when returnType.startsWith((ExceptionCatcherResult).name)) {
      returnType = (ExceptionCatcherResult).name;
      final exceptionElement = substituteType(
        type.typeArguments.single,
        typeSubstitutions,
      );
      exceptionType = exceptionElement.getDisplayString();
      if (exceptionElement.element?.library?.uri case final Uri uri) {
        importPaths.add(uri.toString());
      }
    }
  }

  if (!returnTypes.contains(returnType)) {
    return null;
  }

  if (name == null) {
    throw Exception('Method name is null');
  }

  return ServerLifecycleComponentMethod(
    name: name,
    isFuture: isFuture,
    returnType: returnType,
    parameters: params,
    exceptionType: exceptionType,
    import: ServerImports(importPaths),
  );
}