Oihana PHP

formatDocument.php

Table of Contents

Functions

formatDocument()  : array<string|int, mixed>|object
Recursively formats all string values in a document (array or object) by replacing placeholders with their corresponding values found in the root document.

Functions

formatDocument()

Recursively formats all string values in a document (array or object) by replacing placeholders with their corresponding values found in the root document.

formatDocument(array<string|int, mixed>|object $document[, string $prefix = '{{' ][, string $suffix = '}}' ][, string $separator = '.' ][, string|null $pattern = null ][, callable|null $formatter = null ][, bool $preserveMissing = false ]) : array<string|int, mixed>|object

This function uses the formatFromDocument() helper to replace placeholders in string values using values from the root document. It supports nested keys with a custom separator (default is '.').

Placeholders are defined by a prefix and suffix (default '{{' and '}}'), e.g. "{{key.subkey}}". If a referenced key does not exist, the placeholder is replaced with an empty string by default, or preserved as-is if preserveMissing is set to true.

Example:

$config =
[
    'dir'    => '/var/www/project',
    'htdocs' => '{{dir}}/htdocs',
    'env'    => 'production',
    'config' =>
     [
        'production' => [ 'url' => 'https://example.com' ]
     ],
    'api' => '{{config.{{env}}.url}}/api' ,
    'wordpress' => [
        'server' => [
            'subdomain' => 'www',
            'domain' => 'example.com',
            'url' => 'https://{{wordpress.server.subdomain}}.{{wordpress.server.domain}}/'
        ]
    ]
];
$formatted = formatDocument($config);

echo $formatted['htdocs'] ; // outputs: /var/www/project/htdocs
echo $formatted['wordpress']['server']['url'] ; // outputs: https://www.example.com/

$formatted = formatDocument($config);
echo $formatted['api']; // outputs: https://example.com/api
Parameters
$document : array<string|int, mixed>|object

The document (array or object) to recursively format.

$prefix : string = '{{'

Placeholder prefix (default '{{').

$suffix : string = '}}'

Placeholder suffix (default '}}').

$separator : string = '.'

Separator used in nested keys (default '.').

$pattern : string|null = null

Optional regex pattern to match placeholders.

$formatter : callable|null = null

Optional custom formatter callable.

$preserveMissing : bool = false

If true, unresolved placeholders will be preserved (default false).

Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>|object

A new formatted document with same structure and class.


        
On this page

Search results