Search by

presentkim / config-reader

PresentKim

Typed, validating reader for plugin config values of axolotl-pm/PocketMine-MP

Package info

github.com/presentkim-pm/config-reader

pkg:composer/presentkim/config-reader

Statistics

Installs: 94

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

1.4.0 2026-12-03 09:35 UTC

This package is auto-updated.

Last update: 2026-12-03 09:36:09 UTC


README

Packagist CI Stars License


Logo

config-reader

Typed, validating reader for plugin config values of axolotl-pm/PocketMine-MP

Packagist ยท Changelog ยท Report a bug ยท Request a feature

$reader = ConfigReader::fromConfig($this->getConfig());
$updateDelay = $reader->ticks("update-delay", 0.25, min: 1);  // 0.25 seconds -> 5 ticks
$maxCommands = $reader->int("max-commands", 100, min: 0);
$reader->logWarnings($this->getLogger());                     // 'max-commands' must be an integer, using ...

๐Ÿ“ฆ Installation

composer require presentkim/config-reader
Requirement Version
Server axolotl-pm/PocketMine-MP (fork of PocketMine-MP 5)
PHP 8.4 or newer

Using it in a plugin: plugins built from presentkim-pm/plugin-template bundle Composer libraries into the phar with shaded namespaces at release, so composer require is all a plugin needs.

๐Ÿš€ Quick start

# config.yml
update-delay: 0.25        # [float: seconds]
max-commands: 100         # [int]
command:
  name: "chunkloader"
  aliases: ["cl"]
item: "minecraft:torch"
use kim\present\configreader\ConfigReader;

$reader = ConfigReader::fromConfig($this->getConfig());

$updateDelay = $reader->ticks("update-delay", 0.25, min: 1);   // int ticks, rounded up
$maxCommands = $reader->int("max-commands", 100, min: 0);

$command = $reader->section("command");                        // warnings say 'command.name'
$name = $command->string("name", "chunkloader");
$aliases = $command->stringList("aliases");

$item = $reader->item("item", VanillaBlocks::TORCH()->asItem());

$reader->logWarnings($this->getLogger());

Reading never throws for a bad value:

  • A missing value (or null) returns the default without a warning.
  • A value of the wrong type returns the default with a warning.
  • A value out of range is clamped into the range with a warning.

Every warning names the full key of the value, like 'command.name' must be a string, using the default value "chunkloader". Sections share the warnings of the reader they come from, so one logWarnings() call logs them all.

๐Ÿณ Environment variables

A reader made with ConfigReader::fromPlugin($this) reads an environment variable before the config for every value, like the relaxed binding of Spring Boot. Servers that share one config, like Docker containers of a scale-out, can change a value per server (or for all of them) without changing the file.

$reader = ConfigReader::fromPlugin($this);   // = fromConfig($this->getConfig())->withEnv($this->getName())

The name of the variable is the plugin name and the full key joined with _, uppercased, with . (and any other character that is not a letter, digit or _) turned into _ and - removed:

Plugin Key Environment variable
ChunkLoader update-delay CHUNKLOADER_UPDATEDELAY
ChunkLoader command.name CHUNKLOADER_COMMAND_NAME
ChunkLoader command.aliases CHUNKLOADER_COMMAND_ALIASES
# docker-compose.yml
services:
  lobby:
    environment:
      CHUNKLOADER_UPDATEDELAY: "1.5"
      CHUNKLOADER_COMMAND_ALIASES: "cl, loader"
  • The plugin name prefix keeps the variables of plugins apart, and away from system variables like PATH. Pass your own prefix with fromPlugin($this, "MY_PREFIX") or withEnv("MY_PREFIX") if two plugins share a name. A prefix must have a letter or digit and only ASCII characters.
  • Values are strings, read with the same rules as the config: "1.5" is a number, "yes"/"off"/"1"/"0" are booleans. A variable set to an empty string (FOO=) is set, to an empty value.
  • A list is separated with commas ("cl, loader"), or a JSON array when an entry has a comma, like an SNBT item or SQL ('["{Name:\"minecraft:apple\",Count:3b}", "torch"]'). An empty variable is an empty list.
  • A bad value falls back to the default like a bad config value, and the warning names the variable: 'update-delay' (environment variable CHUNKLOADER_UPDATEDELAY) must be a number, ...
  • logWarnings() also logs each variable that was applied, by name and never by value: 'update-delay' is set by environment variable CHUNKLOADER_UPDATEDELAY. getAppliedEnv() returns them.
  • Variables override values; they do not add keys to getKeys(), are not in getAll(), and cannot replace a whole section(). Read single values of a map with the key, like $section->int($name, 0).
  • Keys with characters other than ASCII (like ์ƒ์ ) are never read from the environment, since their names would collide. Names can still collide like in Spring Boot: max-count and maxcount, or a.b and a_b, have the same variable, so avoid such keys side by side.
  • fromConfig() and fromArray() do not read the environment, so existing plugins behave the same until they move to fromPlugin().
  • A variable ending in _FILE is read from the file it names (without the trailing line break, at most 1 MiB), like Docker secrets: CHUNKLOADER_COMMAND_NAME_FILE=/run/secrets/name. If the file cannot be read, reading the value throws a RuntimeException, so a missing secret stops the plugin instead of silently using another password. The plain variable wins (with a warning) if both are set.

Shared sections (libdb, libasynql)

A section that many plugins have, like the database: section of libdb, can be configured once for all plugins with a shared prefix. withSharedEnv() on the section adds variables named after the key inside the section, read after the variables of the plugin and before the config. resolve() returns the section as an array with the variables applied, converted to the types of the values, so a strict library gets 3306 and not "3306":

$reader = ConfigReader::fromPlugin($this);
$database = $reader->section("database")->withSharedEnv("LIBDB")->resolve(self::DEFAULT_DATABASE_CONFIG);
$reader->logWarnings($this->getLogger());          // before create(), so the warnings are logged even if it throws
$this->db = Database::create($this, $database);

resolve() can only set keys that the config has, and an old config.yml (or a section with commented out keys, like ssl) does not have them all. Pass the default values of the library as $defaults, so their keys can be set too. A variable of the prefixes of the section that matches no key, like a typo, is warned about instead of ignored: Environment variable LIBDB_MYSQL_HOTS matches no key of 'database', ignoring it.

private const array DEFAULT_DATABASE_CONFIG = [
    "type" => "sqlite",
    "sqlite" => ["file" => "data.sqlite"],
    "mysql" => ["host" => "127.0.0.1", "port" => 3306, "username" => "root", "password" => "", "schema" => "pmmp",
                "ssl" => false, "init-commands" => []],
    "worker-limit" => 1
];
# docker-compose.yml: every plugin uses the same MySQL server, each with its own schema
services:
  lobby:
    environment:
      LIBDB_TYPE: mysql
      LIBDB_MYSQL_HOST: mysql
      LIBDB_MYSQL_USERNAME: pmmp
      LIBDB_MYSQL_PASSWORD_FILE: /run/secrets/mysql-password
      LIBDB_MYSQL_INITCOMMANDS: '["SET time_zone = ''+00:00''", "SET sql_mode = ''STRICT_ALL_TABLES''"]'
      CHUNKLOADER_DATABASE_MYSQL_SCHEMA: chunkloader   # one plugin can still override a shared value

For mysql.host of the database section of ChunkLoader, the reader looks in this order:

  1. CHUNKLOADER_DATABASE_MYSQL_HOST (and ..._FILE)
  2. LIBDB_MYSQL_HOST (and ..._FILE)
  3. the config, then $defaults

resolve() details:

  • A variable is converted to the type of the value (int, float, bool, string, or a list of them). If it cannot be, the config value is kept with a warning that shows neither value, like 'database.mysql.port' (environment variable LIBDB_MYSQL_PORT) must be an integer, keeping the config value.
  • Values without a variable are kept exactly as they are.
  • Empty entries of a list are skipped with a warning, so "SET a = 1," is one command. Write SQL lists as a JSON array, since SQL often has commas.
  • A section (like ssl: {ca: ...}) cannot be set by one variable: setting LIBDB_MYSQL_SSL then is warned about. Set its keys instead (LIBDB_MYSQL_SSL_CA).
  • withSharedEnv() must be called on a section, not the root reader, or the names would include the section name.

๐Ÿ“– API reference

All classes are in kim\present\configreader.

Method Description
ConfigReader::fromConfig(Config $config) Reader of all the values of a config
ConfigReader::fromArray(array $data, string $path = "") Reader of the given data, $path prefixes the keys in warnings
ConfigReader::fromPlugin(PluginBase $plugin, ?string $envPrefix) Reader of the plugin config that reads environment variables first
withEnv(string $prefix, ?array $env = null) : ConfigReader Same values, environment variables first ($env replaces getenv() in tests)
withSharedEnv(string $prefix, ?array $env = null) : ConfigReader Also reads variables of a shared prefix, keyed relative to this reader
resolve(array $defaults = []) : array All values with the variables applied, converted to the value types
getEnvName(key), getEnvNames(key), getEnv(key) : ?string The plugin variable name of a key, all its names in order, and its value
getAppliedEnv() : array<string, string> The variables applied so far, by the full key they set
int(key, int $default, ?int $min, ?int $max) : int Integer, also from numeric strings and floats without a fraction
float(key, float $default, ?float $min, ?float $max) : float Finite number, also from integers and numeric strings
ticks(key, float $defaultSeconds, int $min = 0, ?int $max) : int Seconds in the config, converted to ticks (rounded up). $min/$max in ticks
bool(key, bool $default) : bool Boolean, also from "true", "yes", "on", "1", "false", "no", "off", "0"
string(key, string $default, bool $allowEmpty = false) : string String, also from numbers
choice(key, array $choices, string $default) : string One of the choices, ignoring case
stringList(key, array $default = [], bool $allowEmpty = false) List of strings, invalid entries skipped
item(key, ?Item $default = null) : ?Item Item from its name (torch, minecraft:torch, legacy 50:0) or SNBT
itemList(key) : list<Item> Items from a list of names, invalid names skipped
section(key) : ConfigReader Reader of a nested section, sharing the warnings
has(key), get(key), getKeys(), getAll() Raw access, e.g. to iterate a map of item names
warn(key, string $message) Adds your own warning about a value, with the full key
getWarnings() : list<string>, logWarnings(\Logger $logger) The warnings so far; logWarnings() logs them and the applied variables
ConfigReader::secondsToTicks(float $seconds) : int Seconds to ticks, rounded up so a positive time is never 0 ticks
ConfigReader::parseItem(string $name) : ?Item Item from its name or SNBT, null if there is none
ConfigReader::toEnvName(string $key) : string Key to variable form: command.max-count โ†’ COMMAND_MAXCOUNT

An item value that starts with { is read as SNBT with SnbtItemSerializer, so the count, custom name, lore and enchantments of the item can be written in the config too:

reward: '{Name:"minecraft:diamond_sword",Count:1b,tag:{display:{Name:"Excalibur"}}}'

Example of a map of item names, with a warning of your own:

$levels = $reader->section("item-light-levels");
foreach($levels->getKeys() as $name){
    $item = ConfigReader::parseItem($name);
    if($item === null){
        $levels->warn($name, "is not a valid item name, ignoring it");
        continue;
    }
    $registry->set($item, $levels->int($name, 0, min: 0, max: 15));
}

๐Ÿงช Development

composer install --ignore-platform-req='ext-*'
composer analyse
composer test

The server's native extensions are not needed for the tests, so ext-* requirements are ignored on install.

๐Ÿ“„ License

Distributed under the MIT License. See LICENSE for more information.