AnnotationArgument.fromExpression constructor

AnnotationArgument.fromExpression(
  1. Expression expression
)

Implementation

factory AnnotationArgument.fromExpression(Expression expression) {
  final source = expression.toSource();
  final type = expression.staticType;
  final element = type?.element;

  if (element == null || type == null) {
    throw ArgumentError(
      'The argument expression has not been resolved yet...',
    );
  }

  var isInjectable = false;
  final parents = switch (element) {
    ClassElement(:final allSupertypes) => [...allSupertypes],
    _ => <InterfaceType>[],
  };
  while (parents.isNotEmpty) {
    final parent = parents.removeLast();
    if (parent is ClassElement) continue;

    if (parent.getDisplayString() == (Inject).name) {
      isInjectable = true;
      break;
    }
  }

  String parameterName;
  bool isRequired;

  if (expression.parent case Expression(
    correspondingParameter: final param?,
  )) {
    parameterName =
        param.name3 ?? (throw Exception('Parameter name is null'));
    isRequired = param.isRequiredNamed;
  } else if (expression case Expression(
    correspondingParameter: final param?,
  )) {
    parameterName =
        param.name3 ?? (throw Exception('Parameter name is null'));
    isRequired = param.isRequiredNamed;
  } else if (expression.parent case NamedExpression(
    name: Label(:final label),
  )) {
    parameterName = label.name;
    isRequired = false;
  } else {
    throw ArgumentError('Invalid expression');
  }

  return AnnotationArgument(
    parameterName: parameterName,
    type: switch (expression.correspondingParameter?.type ??
        expression.staticType) {
      final e? => ServerType.fromType(e),
      _ => throw Exception('Expression has not been resolved yet...'),
    },
    isRequired: isRequired,
    source: source,
    element: element,
    isInjectable: isInjectable,
  );
}