All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.trendyol.kediatr.MappingDependencyProvider.kt Maven / Gradle / Ivy

@file:Suppress("UNCHECKED_CAST")

package com.trendyol.kediatr

import java.lang.reflect.ParameterizedType

/**
 * Dependency provider that uses a map to resolve dependencies.
 * @param handlerMap A map that contains the handlers.
 * The key is the handler class and the value is the handler instance.
 * @see DependencyProvider
 */
class MappingDependencyProvider(
  private val handlerMap: HashMap, Any>
) : DependencyProvider {
  override fun  getSingleInstanceOf(clazz: Class): T = handlerMap[clazz] as T

  override fun  getSubTypesOf(clazz: Class): Collection> = handlerMap.keys
    .filter { isCompatibleType(it, clazz) }
    .map { it as Class }

  private fun  isCompatibleType(
    handler: Class<*>,
    interfaceOrBaseClass: Class
  ): Boolean = when {
    interfaceOrBaseClass.isAssignableFrom(handler) -> true
    handler.genericInterfaces
      .filterIsInstance()
      .any { it.rawType == interfaceOrBaseClass } -> true

    else -> when (val superclass = handler.genericSuperclass) {
      is ParameterizedType -> {
        val inheritedHandler = superclass.rawType as Class<*>
        inheritedHandler.genericInterfaces
          .filterIsInstance()
          .any { it.rawType == interfaceOrBaseClass }
      }

      is Class<*> -> interfaceOrBaseClass.isAssignableFrom(superclass)
      else -> false
    }
  }

  companion object {
    /**
     * Creates a mediator with the given handlers.
     * @param handlers The handlers to be used by the mediator. Can also be [PipelineBehavior] instances.
     * @return A mediator instance.
     */
    fun createMediator(handlers: List = emptyList()): Mediator {
      val provider = MappingDependencyProvider(handlers.associateBy { it.javaClass } as HashMap, Any>)
      val mediator = MediatorBuilder(provider).build()
      return mediator
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy