1+ package app.simplecloud.plugin.api.shared.pattern
2+
3+ import app.simplecloud.controller.api.ControllerApi
4+ import app.simplecloud.controller.shared.group.Group
5+
6+ /* *
7+ * @author Niklas Nieberler
8+ */
9+
10+ class ServerPatternIdentifier (
11+ private val pattern : String = " <group_name>-<numerical_id>" ,
12+ regexPattern : String = pattern
13+ .replace("<group_name>", "(? <groupName>[a-zA-Z ]+)")
14+ .replace("<numerical_id>", "(? <numericalId>\\d+)"),
15+ private val controllerApi : ControllerApi .Coroutine = ControllerApi .createCoroutineApi()
16+ ) {
17+
18+ private val regex = Regex (regexPattern)
19+
20+ /* *
21+ * Gets the group and numerical id matching the [pattern] in a [Pair]
22+ * @param name the server name
23+ * @param customRegex custom regex pattern
24+ */
25+ fun parse (name : String , customRegex : Regex ? = null): Pair <String , Int > {
26+ val matchResult = customRegex?.matchEntire(name) ? : this .regex.matchEntire(name)
27+ if (matchResult == null )
28+ throw IllegalArgumentException (" $name does not match the pattern" )
29+
30+ val groupName = matchResult.groups[" groupName" ]?.value
31+ ? : throw IllegalArgumentException (" Group name not found" )
32+ val numericalId = matchResult.groups[" numericalId" ]?.value?.toInt()
33+ ? : throw IllegalArgumentException (" Numerical ID not found" )
34+ return Pair (groupName, numericalId)
35+ }
36+
37+ /* *
38+ * Gets the [Group] by the matching [pattern]
39+ * @param name the server name
40+ */
41+ suspend fun getGroup (name : String ): Group ? {
42+ val groupName = parse(name).first
43+ return this .controllerApi.getGroups().getGroupByName(groupName)
44+ }
45+
46+ /* *
47+ * Gets the numerical id by the matching [pattern]
48+ * @param name the server name
49+ */
50+ fun getNumericalId (name : String ): Int {
51+ return parse(name).second
52+ }
53+
54+ }
0 commit comments