|
| 1 | +package com.mapk.kmapper |
| 2 | + |
| 3 | +import com.mapk.annotations.KGetterAlias |
| 4 | +import com.mapk.annotations.KGetterIgnore |
| 5 | +import com.mapk.core.ArgumentBucket |
| 6 | +import com.mapk.core.KFunctionForCall |
| 7 | +import com.mapk.core.getAliasOrName |
| 8 | +import com.mapk.core.isUseDefaultArgument |
| 9 | +import com.mapk.core.toKConstructor |
| 10 | +import java.lang.IllegalArgumentException |
| 11 | +import kotlin.reflect.KClass |
| 12 | +import kotlin.reflect.KFunction |
| 13 | +import kotlin.reflect.KParameter |
| 14 | +import kotlin.reflect.KProperty1 |
| 15 | +import kotlin.reflect.KVisibility |
| 16 | +import kotlin.reflect.full.findAnnotation |
| 17 | +import kotlin.reflect.full.memberProperties |
| 18 | +import kotlin.reflect.jvm.jvmName |
| 19 | + |
| 20 | +class BoundKMapper<S : Any, D : Any> private constructor( |
| 21 | + private val function: KFunctionForCall<D>, |
| 22 | + src: KClass<S>, |
| 23 | + parameterNameConverter: (String) -> String = { it } |
| 24 | +) { |
| 25 | + constructor(function: KFunction<D>, src: KClass<S>, parameterNameConverter: (String) -> String = { it }) : this( |
| 26 | + KFunctionForCall(function), src, parameterNameConverter |
| 27 | + ) |
| 28 | + |
| 29 | + constructor(clazz: KClass<D>, src: KClass<S>, parameterNameConverter: (String) -> String = { it }) : this( |
| 30 | + clazz.toKConstructor(), src, parameterNameConverter |
| 31 | + ) |
| 32 | + |
| 33 | + private val parameters: List<BoundParameterForMap<S>> |
| 34 | + |
| 35 | + init { |
| 36 | + val srcPropertiesMap: Map<String, KProperty1<S, *>> = |
| 37 | + src.memberProperties |
| 38 | + .filter { |
| 39 | + // アクセス可能かつignoreされてないもののみ抽出 |
| 40 | + !(it.visibility != KVisibility.PUBLIC) && |
| 41 | + it.getter.annotations.none { annotation -> annotation is KGetterIgnore } |
| 42 | + }.associateBy { it.getter.findAnnotation<KGetterAlias>()?.value ?: it.name } |
| 43 | + |
| 44 | + parameters = function.parameters |
| 45 | + .filter { it.kind != KParameter.Kind.INSTANCE && !it.isUseDefaultArgument() } |
| 46 | + .mapNotNull { |
| 47 | + val temp = srcPropertiesMap[parameterNameConverter(it.getAliasOrName()!!)]?.let { property -> |
| 48 | + BoundParameterForMap(it, property) |
| 49 | + } |
| 50 | + |
| 51 | + // 必須引数に対応するプロパティがsrcに定義されていない場合エラー |
| 52 | + if (temp == null && !it.isOptional) { |
| 53 | + throw IllegalArgumentException("Property ${it.name!!} is not declared in ${src.jvmName}.") |
| 54 | + } |
| 55 | + |
| 56 | + temp |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + fun map(src: S): D { |
| 61 | + val bucket: ArgumentBucket = function.getArgumentBucket() |
| 62 | + |
| 63 | + parameters.forEach { |
| 64 | + bucket.putIfAbsent(it.param, it.map(src)) |
| 65 | + } |
| 66 | + |
| 67 | + return function.call(bucket) |
| 68 | + } |
| 69 | +} |
0 commit comments