tech.carcadex.kotlinbukkitkit.architecture.extensions.ExDependency.kt Maven / Gradle / Ivy
The newest version!
/*
ORIGINAL PACKAGE: package br.com.devsrsouza.kotlinbukkitapi.architecture
ORIGINAL REPOSITORY: https://github.com/DevSrSouza/KotlinBukkitAPI
AUTHOR: https://github.com/DevSrSouza
Thanks DevSrSouza for KotlinBukkitAPI.
*/
package tech.carcadex.kotlinbukkitkit.architecture.extensions
import tech.carcadex.kotlinbukkitkit.architecture.KotlinPlugin
import org.bukkit.plugin.Plugin
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
/**
* Delegate that returns the plugin dependency if the plugin is installed in the server
* otherwise, returns null
*/
public inline fun KotlinPlugin.softDepend(
pluginName: String,
): SoftDependencyDelegate = softDepend(T::class, pluginName)
public fun KotlinPlugin.softDepend(
type: KClass,
pluginName: String,
): SoftDependencyDelegate =
SoftDependencyDelegate(
pluginName,
type,
)
/**
* Delegate that returns the plugin dependency, disable the plugin if the plugin
* is not available.
*/
public inline fun KotlinPlugin.depend(
pluginName: String,
): DependencyDelegate = depend(T::class, pluginName)
public fun KotlinPlugin.depend(
type: KClass,
pluginName: String,
): DependencyDelegate =
DependencyDelegate(pluginName, type)
public class DependencyDelegate(
public val pluginName: String,
public val type: KClass,
) : ReadOnlyProperty {
private var isDisabled: Boolean = false
private var cache: T? = null
override fun getValue(
thisRef: KotlinPlugin,
property: KProperty<*>,
): T {
if (cache == null) {
val plugin = thisRef.server.pluginManager.getPlugin(pluginName)
if (plugin != null) {
if (type.isInstance(plugin)) {
cache = plugin as T
} else {
thisRef.server.pluginManager.disablePlugin(thisRef)
error(
"Invalid plugin dependency with the name $pluginName: " +
"The plugin do not match main class with ${type.qualifiedName}.",
)
}
} else {
thisRef.server.pluginManager.disablePlugin(thisRef)
error("Missing plugin dependency: $pluginName")
}
}
return cache!!
}
}
public class SoftDependencyDelegate(
public val pluginName: String,
public val type: KClass,
) : ReadOnlyProperty {
private var alreadySearch: Boolean = false
private var cache: T? = null
override fun getValue(
thisRef: KotlinPlugin,
property: KProperty<*>,
): T? {
if (!alreadySearch) {
val plugin = thisRef.server.pluginManager.getPlugin(pluginName) ?: return null
alreadySearch = true
if (type.isInstance(plugin)) {
cache = plugin as T
} else {
thisRef.server.pluginManager.disablePlugin(thisRef)
error(
"Invalid plugin dependency with the name $pluginName: " +
"The plugin do not match main class with ${type.qualifiedName}.",
)
}
}
return cache
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy