getClassResolver function

Future<ClassResolver?> getClassResolver(
  1. GeneratorCtx ctx,
  2. ExecutableElement element
)

Implementation

Future<ClassResolver?> getClassResolver(
  GeneratorCtx ctx,
  ExecutableElement element,
) async {
  final classAnnot = _classResolverTypeChecker
      .firstAnnotationOfExact(element.enclosingElement);

  String? instantiateCode = classAnnot == null
      ? null
      : classAnnot.getField('instantiateCode')?.toStringValue() ??
          ctx.config.instantiateCode;
  if (classAnnot != null && instantiateCode == null) {
    final parent = element.enclosingElement as ClassElement;
    final ref = parent.getGetter('ref');
    if (ref == null) {
      throw Exception(
        'You should provide a way to access an'
        ' instance of $ClassResolver ${parent.name}.',
      );
    } else if (!ref.isStatic) {
      throw Exception(
        'Getter "ref" of $ClassResolver ${parent.name} should be static.',
      );
    } else if (!const TypeChecker.fromRuntime(ScopedRef)
        .isAssignableFromType(ref.returnType)) {
      throw Exception(
        'Getter "ref" of $ClassResolver ${parent.name} should return a $ScopedRef.',
      );
    }
    instantiateCode = '${parent.name}.${ref.name}.get(ctx)!';
  }
  if (instantiateCode != null) {
    instantiateCode = instantiateCode.replaceAll(
      '{{name}}',
      element.enclosingElement.name!,
    );
  }

  return classAnnot == null
      ? null
      : ClassResolver(
          fieldName: classAnnot.getField('fieldName')?.toStringValue(),
          instantiateCode: instantiateCode,
        );
}