Oihana PHP

toml

Table of Contents

Functions

escapeTomlString()  : string
Escapes a value so it can be embedded in a TOML basic string.
resolveTomlConfig()  : array<string|int, mixed>
Resolves a TOML configuration file and merges it with a default configuration.
setTomlValue()  : string
Sets a string value in a TOML document, inside one table only, keeping the rest of the text.

Functions

escapeTomlString()

Escapes a value so it can be embedded in a TOML basic string.

escapeTomlString(string $value) : string

The returned value does not include the surrounding quotes. Backslashes and double quotes are escaped, and the control characters TOML forbids in a basic string are written as escape sequences: the ones with a shorthand (\b, \t, \n, \f, \r) use it, the others and DEL become \uXXXX.

Without this, a value holding a quote or a backslash — a password, typically — produces a document the TOML parser rejects, and the whole file becomes unreadable.

Parameters
$value : string

The raw value to escape.

Tags
see
https://toml.io/en/v1.0.0#string
example
use function oihana\files\toml\escapeTomlString;

echo escapeTomlString( 'pa"ss\word' ) ; // pa\"ss\\word
echo escapeTomlString( "two\nlines" ) ; // two\nlines
echo escapeTomlString( "\x01" ) ;       // \u0001
author

Marc Alcaraz (ekameleon)

since
1.7.0
Return values
string —

The escaped value, ready to be wrapped in double quotes.

resolveTomlConfig()

Resolves a TOML configuration file and merges it with a default configuration.

resolveTomlConfig(string|null $filePath[, array<string|int, mixed>|null $defaultConfig = [] ][, string|null $defaultPath = null ][, callable|null $init = null ]) : array<string|int, mixed>

This function attempts to load a TOML config file by:

  • Ensuring the file path ends with the .toml extension.
  • Resolving relative paths against the current working directory or a given base path.
  • Validating the existence of the file and directories.
  • Decoding the TOML content to an associative array.
  • Deep merging the decoded config with the provided default configuration.
  • Optionally applying an initialization callable to the merged configuration.

If $filePath is null or empty, only the default configuration is returned (possibly processed by $init).

Parameters
$filePath : string|null

Path to the TOML file. If null or empty, only default config is used.

$defaultConfig : array<string|int, mixed>|null = []

Default configuration array to merge with the TOML file contents.

$defaultPath : string|null = null

Base path used to resolve relative file paths when not absolute.

$init : callable|null = null

Optional callable that takes the merged config array as input and returns a processed config array. Signature: function(array): array.

Tags
throws
FileException

If the file path is invalid or the file does not exist.

DirectoryException

If the provided default path is invalid or not a directory.

TomlError

If the TOML content cannot be parsed.

author

Marc Alcaraz (ekameleon)

since
1.0.0
example
use function oihana\files\toml\resolveTomlConfig;

// Default config array
$defaultConfig =
[
    'database' =>
    [
        'host' => 'localhost',
        'port' => 3306,
    ],
    'debug' => false,
];

// Path to your TOML config file (can be relative or absolute)
$configFile = '/path/to/config'; // '.toml' appended automatically if missing

// Optional base path to resolve relative paths
$basePath = '/var/www/project/configs';

$init = function( array $config ): array
{
   // Custom post-processing of config, e.g. validation or transformation
   if (!isset($config['debug']))
   {
      $config['debug'] = true;
   }
   return $config;
};

try
{
   $config = resolveTomlConfig( $configFile , $defaultConfig , $basePath , $init ) ;
   print_r( $config ) ;
}
catch ( FileException $e )
{
   echo "File error: " . $e->getMessage();
}
catch ( DirectoryException $e )
{
    echo "Directory error: " . $e->getMessage();
}
catch ( TomlError $e )
{
    echo "TOML parsing error: " . $e->getMessage();
}
Return values
array<string|int, mixed> —

Merged (and optionally initialized) configuration array.

setTomlValue()

Sets a string value in a TOML document, inside one table only, keeping the rest of the text.

setTomlValue(string $content, string|null $section, string $key, string $value) : string

The replacement is anchored to the requested [section]: a key is only rewritten between that header and the next one. This matters because the same key name often recurs across tables — host or pass under [database], [smtp] and [mysql] — and an unanchored replacement silently overwrites unrelated credentials.

The document is edited as text, not parsed and written back, so nothing else moves: the alignment before = and any trailing comment are kept, and only the quoted value is swapped. When the key is absent, it is added at the end of its section, before the blank lines that close it; when the section itself is absent, it is added at the end of the document. Line endings follow the document's: CRLF when it has one, LF otherwise.

Scope: a key written as a single-line basic ("…") or literal ('…') string. A key holding a number, a boolean, an array or a multi-line string is not recognised, and a new line is added for it instead.

Parameters
$content : string

The TOML document.

$section : string|null

The table name (e.g. database, or app.database), compared without regard to case; null for the root table, above the first header.

$key : string

The key to set.

$value : string

The raw value. It is written as a basic string, escaped by escapeTomlString().

Tags
example
use function oihana\files\toml\setTomlValue;

$toml = "[database]\nhost = \"localhost\" # local\n\n[smtp]\nhost = \"mail\"\n" ;

echo setTomlValue( $toml , 'database' , 'host' , 'db.example.com' ) ;
// [database]
// host = "db.example.com" # local
//
// [smtp]
// host = "mail"
author

Marc Alcaraz (ekameleon)

since
1.7.0
Return values
string —

The updated document.

On this page

Search results