Skip to content

Latest commit

 

History

History
132 lines (99 loc) · 3.75 KB

File metadata and controls

132 lines (99 loc) · 3.75 KB

LibCommons Examples

This directory keeps practical examples for the public LibCommons API. The examples are intentionally small and dependency-light so they also work when LibCommons is loaded as an EasyLibrary classpath package.

Complete Example Files

  • plugin_settings_summary.php combines config-like arrays, data files, path checks, validation, formatted numbers, durations and diagnostics into one operator-facing summary.

These files are linted by the repository quality workflow. Keep them concise, copyable and free of plugin-specific secrets.

Config-style arrays

use imperazim\commons\collection\Arr;

$config = [];
Arr::set($config, 'features.packages.enabled', true);

if (Arr::get($config, 'features.packages.enabled', false)) {
    // Enable package-related behavior.
}

$players = [
    ['name' => 'Steve', 'team' => 'red', 'coins' => 1500],
    ['name' => 'Alex', 'team' => 'blue', 'coins' => 250],
];

$names = Arr::pluck($players, 'name');
$byTeam = Arr::groupBy($players, 'team');
$richest = Arr::first(Arr::sortBy($players, 'coins', descending: true));

Player-facing command text

use imperazim\commons\number\Number;
use imperazim\commons\text\Text;
use imperazim\commons\time\Duration;

$sender->sendMessage(Text::colorize('&aCoins: &f' . Number::compact(15300)));
$sender->sendMessage('Cooldown: ' . Duration::formatShort(Duration::minutes(5)));
$sender->sendMessage(Text::progressBar(0.65, segments: 10));

Safe input checks

use imperazim\commons\validation\Validator;

if (!Validator::minecraftUsername($name)) {
    $sender->sendMessage('Invalid username.');
    return;
}

if (!Validator::semver($packageVersion)) {
    throw new InvalidArgumentException('Invalid package version.');
}

Explicit result values

use imperazim\commons\result\Option;
use imperazim\commons\result\Result;

$displayName = Option::fromNullable($config['display-name'] ?? null)
    ->filter(static fn(string $value): bool => trim($value) !== '')
    ->map(static fn(string $value): string => ucfirst($value))
    ->unwrapOr('Server');

$write = Result::capture(static function() use ($path): void {
    if (file_put_contents($path, 'ok') === false) {
        throw new RuntimeException('file_put_contents returned false');
    }
})
    ->mapError(static fn(string $error): string => 'Could not save file: ' . $error);

if ($write->isError()) {
    $logger->warning($write->errorMessage() ?? 'Unknown write error.');
}

Plugin-owned data files

use imperazim\commons\filesystem\DataFile;
use imperazim\commons\filesystem\Path;

$settings = DataFile::at(Path::join($plugin->getDataFolder(), 'settings.json'));
$settings->ensure([
    'enabled' => true,
    'server' => ['motd' => 'Welcome'],
]);

$settings->set('server.motd', 'Crystal Lobby');
$motd = $settings->get('server.motd', 'Welcome');

Path checks before writing

use imperazim\commons\filesystem\Path;

$base = $plugin->getDataFolder();
$target = Path::normalize(Path::join($base, 'cache', '..', 'cache', 'index.json'));

if (!Path::isWithin($base, $target)) {
    throw new RuntimeException('Refusing to write outside plugin data.');
}

Migration from old EasyLibrary helpers

use imperazim\commons\collection\Arr;
use imperazim\commons\filesystem\DataFile;
use imperazim\commons\filesystem\Path;
use imperazim\commons\number\Number;
use imperazim\commons\text\Text;
use imperazim\commons\time\Duration;
use imperazim\commons\validation\Validator;

$file = DataFile::at(Path::join($plugin->getDataFolder(), 'config.json'));
$name = Arr::get($file->read(), 'server.name', 'EasyLibrary');
$slug = Text::slug($name);
$cooldown = Duration::formatShort(300);
$coins = Number::compact(12000);
$valid = Validator::filename($slug . '.json');