Skip to content

Commit

Permalink
Refactor conversion logic
Browse files Browse the repository at this point in the history
Moved the conversion logic from `PropertiesProvider` to a new `Conversion` utility class. This simplifies `PropertiesProvider` and makes conversion logic reusable across different parts of the application.
  • Loading branch information
TanVD committed Jul 24, 2024
1 parent 278cebe commit f6cbdd4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 15 deletions.
Original file line number Diff line number Diff line change
@@ -1,29 +1,20 @@
package tanvd.konfy.properties

import tanvd.konfy.conversion.ConversionService
import tanvd.konfy.properties.utils.Conversion
import tanvd.konfy.provider.ConfigProvider
import tanvd.konfy.utils.toTypedArray
import java.lang.reflect.Type
import java.util.Properties
import java.util.*

class PropertiesProvider(private val properties: Properties) : ConfigProvider() {
override fun <N : Any> fetch(key: String, type: Type): N? {
val value = properties[key]?.toString() ?: return null
when {
(type is Class<*> && type.isArray) -> {
val values = value.split(",").map { it.trim() }
val converted = values.map { ConversionService.convert(it, type.componentType) }
return converted.toTypedArray(type.componentType) as N?
}

else -> {
val converted = ConversionService.convert(value, type)
return converted as N?
}
}
return Conversion.convert(value, type) as N?
}

companion object {
/**
* Read properties from [value] string and return corresponding [PropertiesProvider]
*/
fun from(value: String): PropertiesProvider {
val properties = Properties()
properties.load(value.byteInputStream())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package tanvd.konfy.properties.utils

import tanvd.konfy.conversion.ConversionService
import tanvd.konfy.utils.toTypedArray
import java.lang.reflect.Type

object Conversion {
fun <N : Any> convert(value: String, type: Type): N? {
when {
(type is Class<*> && type.isArray) -> {
val values = value.split(",").map { it.trim() }
val converted = values.map { ConversionService.convert(it, type.componentType) }
return converted.toTypedArray(type.componentType) as N?
}

else -> {
return ConversionService.convert(value, type) as N?
}
}
}
}

0 comments on commit f6cbdd4

Please sign in to comment.