susina/param-resolver

Resolve parameters inside a configuration array

v0.5 2024-08-12 08:36 UTC

This package is auto-updated.

Last update: 2024-09-17 13:30:00 UTC


README

Test Suite Test Coverage Maintainability

ParamResolver is a small class to resolve parameters in configuration arrays. It's heavily inspired on Symfony ParameterBag class.

Installation

Install the library via composer:

composer require susina/param-resolver

Usage

In a configuration array, it can be useful to define some parameters.

A parameter is a previously defined property, put between % special character. When ParamResolver found a parameter, it simply replaces its placeholder with the previously defined value. In the following example, suppose you have a json configuration file:

// configuration.json
{
    "library": {
        "project": "AwesomeProject"
    },
    "paths": {
        "projectDir": "/home/%project%"
    }
}

First of all you have to convert it into an array, then you can resolve the parameters:

<?php declare(strict_types=1);

    use Susina\ParamResolver\ParamResolver;

    //load and convert into an array
    $array = json_decode('configuration.json');

    //resolve the parameters
    $resolved = ParamResolver::create()->resolve($array);

    //print the resolved array or else
    echo json_encode($resolved);

Now the json content is the following:

{
    "library": {
        "project": "AwesomeProject"
    },
    "paths": {
        "projectDir": "/home/AwesomeProject"
    }
}

You can escape the special character % by doubling it:

// configuration.json
{
    "discounts": {
        "jeans": "20%%"
    }
}

jeans property now contains the string '20%'.

Note: Both keys and values of your array can contain parameters.

Special parameters: environment variables

The string env is used to specify an environment variable.

Many hosts give services or credentials via environment variables and you can use them in your configuration file via env.variable syntax. In example, let’s suppose to have the following environment variables:

<?php

$_ENV['host']   = '192.168.0.54'; //Database host name
$_ENV['dbName'] = 'myDB'; //Database name

In your (yaml) configuration file you can write:

database:
  connections:
      default:
          adapter: mysql
          dsn: mysql:host=%env.host%;dbname=%env.dbName%

and, after processing, it becomes:

database:
  connections:
      default:
          adapter: mysql
          dsn: mysql:host=192.168.0.54;dbname=myDB

Issues

If you find a bug or any other issue, please report it on Github.

Contributing

Please, see CONTRIBUTING.md

Licensing

This library is released under Apache-2.0 license.