internal/toml
PHP 8.1+ TOML 1.0.0/1.1.0 parser and encoder. Parse TOML strings/files into PHP arrays or an AST, modify documents, and serialize back to TOML with round-trip support.
Installation:
composer require internal/toml
Requires PHP 8.1+.
First Use Case: Parse a TOML config file into a PHP array for immediate use:
use Internal\Toml\Toml;
$config = Toml::parseToArray(file_get_contents('config.toml'));
// Access config values like $config['database']['host']
Where to Look First:
Toml::parseToArray() (for reading) and Toml::encode() (for writing).Toml::parse() for programmatic TOML manipulation (e.g., modifying nodes before encoding).config/ arrays or JSON/YAML configs with TOML files.// config/database.toml
[mysql]
host = "localhost"
port = 3306
// In PHP:
$dbConfig = Toml::parseToArray(file_get_contents(config_path('database.toml')));
DB::connection($dbConfig['mysql']);
config() helper with a custom loader:
Config::addLoader('toml', function ($path) {
return Toml::parseToArray(file_get_contents($path));
}, 10); // High priority
$featureFlags = [
'new_dashboard' => ['enabled' => true, 'environments' => ['prod', 'staging']],
];
$toml = (string) Toml::encode($featureFlags);
file_put_contents('feature-flags.toml', $toml);
Str::of() for pretty-printing:
$toml = Str::of(Toml::encode($data))->indent(4);
$document = Toml::parse(file_get_contents('config.toml'));
$data = $document->toArray();
$data['version'] = '2.0.0'; // Modify
$updatedToml = (string) Toml::encode($data);
file_put_contents('config.toml', $updatedToml);
$document->nodes) to add comments or metadata before encoding.toml-validator).use BetterU\TomlValidator\Validator;
$validator = new Validator();
$isValid = $validator->validate(file_get_contents('config.toml'), $schema);
if (!$isValid) {
throw new \RuntimeException('Invalid TOML config');
}
public function boot()
{
$config = Toml::parseToArray(config_path('app.toml'));
$this->app->singleton('config.cache', function () use ($config) {
return new ConfigCache($config);
});
}
$toml = (string) Toml::encode([
'command' => $this->argument('name'),
'description' => $this->option('description'),
]);
$this->info($toml);
$legacyJson = json_decode(file_get_contents('old-config.json'), true);
$toml = (string) Toml::encode($legacyJson);
file_put_contents('config.toml', $toml);
.env.toml):
$envConfig = Toml::parseToArray(file_get_contents('.env.toml'));
config(['app.debug' => $envConfig['debug'] ?? false]);
PHP 8.1+ Requirement:
composer.json constraints.TOML 1.1 vs. 1.0 Quirks:
true/false booleans) may behave unexpectedly in older parsers. This package fully supports 1.1, but legacy tools might not.Toml::encode() to generate 1.0-compatible output if interoperability is critical:
$toml = (string) Toml::encode($data, Toml::ENCODE_TOML_1_0);
Floating-Point Precision:
float, which may lose precision. For exact decimals, use strings:
# config.toml
precision_value = "123.456789" # Stored as string
Comments and Whitespace:
Toml::encode() does not preserve comments by default. Use the AST for comment retention:
$document = Toml::parse($tomlWithComments);
$document->addComment('New comment', $someNode);
$toml = (string) $document;
DateTime Handling:
DateTime objects to ISO 8601 strings, but parsing expects strict TOML datetime formats (e.g., 1979-05-27T07:32:00Z).$date = (new DateTime('now'))->format(DateTime::ATOM);
$data = ['event_date' => $date];
Arrays of Tables:
[[servers]]) are encoded as nested arrays, but parsing may flatten them unexpectedly.Toml::parse() to inspect the AST structure:
$document = Toml::parse($toml);
foreach ($document->nodes as $node) {
if ($node instanceof TableArray) {
// Handle array of tables
}
}
File Encoding:
file_get_contents() with FILE_UTF8 flag or mb_convert_encoding():
$toml = mb_convert_encoding(file_get_contents('config.toml'), 'UTF-8');
Validate TOML Syntax: Use the AST to debug parsing issues:
try {
$document = Toml::parse($toml);
} catch (\Internal\Toml\Exception\ParseError $e) {
echo "Error at line {$e->getLine()}: {$e->getMessage()}";
}
Inspect AST Structure: Dump the AST to understand node types:
$document = Toml::parse($toml);
dump(get_class($document->nodes[0])); // e.g., Entry, Table, TableArray
Round-Trip Debugging: Verify format preservation:
$originalToml = 'key = 0xDEADBEEF';
$document = Toml::parse($originalToml);
$roundTripToml = (string) $document;
assert($originalToml === $roundTripToml, 'Format not preserved!');
Performance:
How can I help you explore Laravel packages today?