Oihana PHP

toml

Table of Contents

Functions

resolveTomlConfig()  : array<string|int, mixed>
Resolves a TOML configuration file and merges it with a default configuration.

Functions

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.

throws
DirectoryException

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

throws
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.


        
On this page

Search results