Skip to content

Commit

Permalink
feat: add ad hoc transformers
Browse files Browse the repository at this point in the history
  • Loading branch information
Idane committed Jul 10, 2022
1 parent fb67786 commit 8998f34
Show file tree
Hide file tree
Showing 20 changed files with 420 additions and 283 deletions.
28 changes: 28 additions & 0 deletions shapeshift/src/main/kotlin/dev/krud/shapeshift/MappingStrategy.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* Copyright KRUD 2022
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

package dev.krud.shapeshift

enum class MappingStrategy {
/**
* A strategy that does nothing, used in override mapping strategies when there is no desire to override the default strategy
*/
NONE,

/**
* A strategy that maps all values
*/
MAP_ALL,

/**
* A strategy that maps only the values that are not null
*/
MAP_NOT_NULL
}
68 changes: 48 additions & 20 deletions shapeshift/src/main/kotlin/dev/krud/shapeshift/ShapeShift.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@
package dev.krud.shapeshift

import dev.krud.shapeshift.condition.Condition
import dev.krud.shapeshift.decorator.Decorator
import dev.krud.shapeshift.dto.MappingStructure
import dev.krud.shapeshift.dto.ObjectFieldTrio
import dev.krud.shapeshift.dto.ResolvedMappedField
import dev.krud.shapeshift.dto.TransformerCoordinates
import dev.krud.shapeshift.resolver.MappingResolver
import dev.krud.shapeshift.transformer.base.BaseFieldTransformer
import dev.krud.shapeshift.transformer.base.ClassPair
import dev.krud.shapeshift.transformer.base.FieldTransformer
import dev.krud.shapeshift.transformer.base.FieldTransformer.Companion.id
Expand All @@ -26,7 +28,8 @@ import java.lang.reflect.Field

class ShapeShift constructor(
transformersRegistrations: Set<TransformerRegistration<out Any, out Any>> = emptySet(),
val mappingResolvers: Set<MappingResolver> = setOf()
val mappingResolvers: Set<MappingResolver> = setOf(),
val defaultMappingStrategy: MappingStrategy
) {
internal val transformers: MutableList<TransformerRegistration<out Any, out Any>> = mutableListOf()
internal val transformersByNameCache: MutableMap<String, TransformerRegistration<out Any, out Any>> = mutableMapOf()
Expand All @@ -38,43 +41,43 @@ class ShapeShift constructor(
private val conditionCache: MutableMap<Class<out Condition<*>>, Condition<*>> = mutableMapOf()

init {
if (defaultMappingStrategy == MappingStrategy.NONE) {
error("Default mapping strategy cannot be NONE")
}
for (registration in transformersRegistrations) {
registerTransformer(registration)
}
}

inline fun <reified To : Any> map(fromObject: Any): To {
inline fun <reified To : Any, reified From : Any> map(fromObject: From): To {
return map(fromObject, To::class.java)
}

fun <To : Any> map(fromObject: Any, toClazz: Class<To>): To {
fun <From : Any, To : Any> map(fromObject: From, toClazz: Class<To>): To {
val toObject = toClazz.newInstance()
return map(fromObject, toObject)
}

private fun <To : Any> map(fromObject: Any, toObject: To): To {
private fun <From : Any, To : Any> map(fromObject: From, toObject: To): To {
val toClazz = toObject::class.java
val mappingStructure = getMappingStructure(fromObject::class.java, toClazz)

for (resolvedMappedField in mappingStructure.resolvedMappedFields) {
processMappedField(resolvedMappedField, fromObject, toObject)
mapField(fromObject, toObject, resolvedMappedField)
}

for (decorator in mappingStructure.decorators) {
decorator as Decorator<From, To>
decorator.decorate(fromObject, toObject)
}

return toObject
}

private fun <To : Any, From : Any> processMappedField(
resolvedMappedField: ResolvedMappedField,
fromObject: From,
toObject: To
) {
private fun <From : Any, To : Any> mapField(fromObject: From, toObject: To, resolvedMappedField: ResolvedMappedField) {
val fromPair = getFieldInstanceByNodes(resolvedMappedField.mapFromCoordinates, fromObject, SourceType.FROM) ?: return
val toPair = getFieldInstanceByNodes(resolvedMappedField.mapToCoordinates, toObject, SourceType.TO) ?: return
val transformerRegistration = getTransformer(resolvedMappedField.transformerCoordinates, fromPair, toPair)
mapField(fromPair, toPair, transformerRegistration, resolvedMappedField)
}

private fun mapField(fromPair: ObjectFieldTrio, toPair: ObjectFieldTrio, transformerRegistration: TransformerRegistration<*, *>, resolvedMappedField: ResolvedMappedField) {
fromPair.field.isAccessible = true
toPair.field.isAccessible = true
var value = fromPair.field.getValue(fromPair.target)
Expand All @@ -92,16 +95,38 @@ class ShapeShift constructor(
}
}

if (transformerRegistration != TransformerRegistration.EMPTY) {
if (resolvedMappedField.transformer != null) {
resolvedMappedField.transformer as BaseFieldTransformer<Any, Any>
value = resolvedMappedField.transformer.transform(fromPair.field, toPair.field, value, fromPair.target, toPair.target)
} else if (transformerRegistration != TransformerRegistration.EMPTY) {
val transformer = transformerRegistration.transformer as FieldTransformer<Any, Any>
value = transformer.transform(fromPair.field, toPair.field, value, fromPair.target, toPair.target)
}
if (value != null) {

val mappingStrategy: MappingStrategy

if (resolvedMappedField.overrideMappingStrategy != null && resolvedMappedField.overrideMappingStrategy != MappingStrategy.NONE) {
mappingStrategy = resolvedMappedField.overrideMappingStrategy
} else {
mappingStrategy = defaultMappingStrategy
}

val shouldMap = when (mappingStrategy) {
MappingStrategy.NONE -> error("Mapping strategy is set to NONE")
MappingStrategy.MAP_ALL -> true
MappingStrategy.MAP_NOT_NULL -> value != null
}

if (shouldMap) {
try {
if (!toPair.type.isAssignableFrom(value::class.java)) {
error("Type mismatch: Expected ${toPair.type} but got ${value::class.java}")
if (value == null) {
toPair.field.setValue(toPair.target, null)
} else {
if (!toPair.type.isAssignableFrom(value::class.java)) {
error("Type mismatch: Expected ${toPair.type} but got ${value::class.java}")
}
toPair.field.setValue(toPair.target, value)
}
toPair.field.setValue(toPair.target, value)
} catch (e: Exception) {
val newException =
IllegalStateException("Could not map value ${fromPair.field.name} of class ${fromPair.target.javaClass.simpleName} to ${toPair.field.name} of class ${toPair.target.javaClass.simpleName}: ${e.message}")
Expand Down Expand Up @@ -178,7 +203,10 @@ class ShapeShift constructor(
private fun getMappingStructure(fromClass: Class<*>, toClass: Class<*>): MappingStructure {
val key = fromClass to toClass
return mappingStructures.computeIfAbsent(key) {
MappingStructure(fromClass, toClass, mappingResolvers.flatMap { it.resolve(fromClass, toClass) })
val resolutions = mappingResolvers
.map { it.resolve(fromClass, toClass) }

MappingStructure(fromClass, toClass, resolutions.flatMap { it.resolvedMappedFields }, resolutions.flatMap { it.decorators })
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,18 @@ import dev.krud.shapeshift.transformer.base.FieldTransformer
class ShapeShiftBuilder {
private val transformers: MutableSet<TransformerRegistration<*, *>> = mutableSetOf()
private val resolvers: MutableSet<MappingResolver> = mutableSetOf()
private var defaultMappingStrategy: MappingStrategy = MappingStrategy.MAP_NOT_NULL

init {
withMappingResolver(ShapeShiftAnnotationMappingResolver())
}

fun withTransformer(fieldTransformer: FieldTransformer<*, *>, default: Boolean = false, name: String? = null): ShapeShiftBuilder {
fun withDefaultMappingStrategy(defaultMappingStrategy: MappingStrategy): ShapeShiftBuilder {
this.defaultMappingStrategy = defaultMappingStrategy
return this
}

fun withTransformer(fieldTransformer: FieldTransformer<out Any, out Any>, default: Boolean = false, name: String? = null): ShapeShiftBuilder {
transformers.add(TransformerRegistration(fieldTransformer, default, name))
return this
}
Expand All @@ -38,6 +44,6 @@ class ShapeShiftBuilder {
}

fun build(): ShapeShift {
return ShapeShift(transformers, resolvers)
return ShapeShift(transformers, resolvers, defaultMappingStrategy)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@

package dev.krud.shapeshift.condition

fun interface Condition<FromType : Any> {
fun isValid(originalValue: FromType?): Boolean
fun interface Condition<From : Any?> {
fun isValid(originalValue: From?): Boolean
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/*
* Copyright KRUD 2022
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

package dev.krud.shapeshift.decorator

fun interface Decorator<From : Any, To : Any> {
fun decorate(from: From, to: To)
}
Loading

0 comments on commit 8998f34

Please sign in to comment.