execute(CommandContext)
last analyzed

Size

Total Lines 1
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 1
c 0
b 0
f 0
1
package de.pewpewproject.lasertag.command;
2
3
import com.mojang.brigadier.Command;
4
import com.mojang.brigadier.context.CommandContext;
5
import de.pewpewproject.lasertag.LasertagMod;
6
import net.minecraft.server.command.ServerCommandSource;
7
import net.minecraft.text.Text;
8
import net.minecraft.util.Formatting;
9
10
import java.util.Optional;
11
12
/**
13
 * Abstract base class for all ServerCommands.
14
 * Catches all exceptions and handles responses in chat.
15
 *
16
 * @author Étienne Muser
17
 */
18
public abstract class ServerFeedbackCommand implements Command<ServerCommandSource> {
19
    /**
20
     * Exectues the command and gets the response message.
21
     * @param context The command context
22
     * @return Optional of the command feedback. If this is present, then this text will be printed.
23
     */
24
    protected abstract Optional<CommandFeedback> execute(CommandContext<ServerCommandSource> context);
25
26
    @Override
27
    public int run(CommandContext<ServerCommandSource> context) {
28
29
        try {
30
            // Execute command and get response
31
            var response = execute(context);
32
33
            // If response is present
34
            response.ifPresent(feedback -> {
35
                // Get the command source
36
                var source = context.getSource();
37
38
                // If should broadcast
39
                if (feedback.broadcast()) {
40
                    // Send broadcast
41
                    source.getServer().getPlayerManager().broadcast(feedback.text(), feedback.overlay());
42
                } else {
43
                    // Send response to player
44
                    source.getPlayer().sendMessage(feedback.text(), feedback.overlay());
45
                }
46
            });
47
        } // Rethrow command syntax exception
48
        catch (Exception e) {
49
            // Log the error
50
            LasertagMod.LOGGER.error("An error occured while executing a '" + this.getClass().getName() + "':", e);
51
52
            // Get the command source
53
            var source = context.getSource();
54
55
            // Send error message in chat
56
            source.getPlayer().sendMessage(Text.literal("An error occurred while executing that command. See the log for details.").formatted(Formatting.RED));
57
        }
58
59
        return SINGLE_SUCCESS;
60
    }
61
}
62