PHPackages                             liutec/cfgtokenlib - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. liutec/cfgtokenlib

ActiveLibrary

liutec/cfgtokenlib
==================

PHP Configuration Token Resolver and Injection Library

v1.2.0(1y ago)36.6k↓50%3[2 PRs](https://github.com/eMAGTechLabs/cfgtokenlib/pulls)MITPHPPHP &gt;=8.3CI failing

Since May 26Pushed 1y ago6 watchersCompare

[ Source](https://github.com/eMAGTechLabs/cfgtokenlib)[ Packagist](https://packagist.org/packages/liutec/cfgtokenlib)[ RSS](/packages/liutec-cfgtokenlib/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (1)Versions (30)Used By (0)

ConfigToken Library
===================

[](#configtoken-library)

[![Build Status](https://camo.githubusercontent.com/414d40885ea44fe4d96685acd4c064e64c1b2e72904393fcaa43e3229c5ce037/68747470733a2f2f7472617669732d63692e6f72672f654d4147546563684c6162732f636667746f6b656e6c69622e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/eMAGTechLabs/cfgtokenlib) [![Scrutinizer Code Quality](https://camo.githubusercontent.com/ab170a0e217a9a9019431450e7cbf83de369b1e13bfa399ea88dc29899caece1/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f654d4147546563684c6162732f636667746f6b656e6c69622f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/eMAGTechLabs/cfgtokenlib/?branch=master) [![Code Coverage](https://camo.githubusercontent.com/a542f00424030111983e9a27f1c8916b34c86d16afe5b96e72532cd2566f6aca/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f654d4147546563684c6162732f636667746f6b656e6c69622f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/eMAGTechLabs/cfgtokenlib/?branch=master)

The ConfigToken library provides the following classes to aid in token parsing, value formatting and injection:

- **TokenParser**: configurable string parser class used to extract a collection of tokens.
- **TokenCollection**: generic token collection class used in conjunction with a given token resolver instance to resolve tokens to values and apply the given filters.
- **TokenInjector**: provides a method to inject the resolved token values collection back into the original string.

a set of interfaces and factories to create custom resolvers and filters:

- **TokenResolverInterface**: interface to create custom token value resolvers;
- **TokenFilterInterface**: interface to create custom token value filters;
- **TokenFilterFactory**: factory class used to hold and register token value filters.

and base classes to extend and customize two of the most common use-cases:

- **RegisteredTokenResolver**: resolves token values based on a given uni-dimensional associative array (token name =&gt; value).
- **ScopeTokenResolver**: resolves token values based on a given mutli-dimensional associative array.

The Token Parser
----------------

[](#the-token-parser)

The token parser may be used to parse strings and extract a collection of tokens based on a configurable regular expression.

```
$tokenParser = new TokenParser();
$tokens = $tokenParser->parseString($input);
```

or explicitly setting token delimiters and filter delimiters:

```
$tokenParser = new TokenParser('|', null, '[[', ']]');

// also possible via setters
$tokenParser
  ->setFilterDelimiter('|')
  ->setTokenPrefix('[[')
  ->setTokenSuffix(']]')
;

$tokens = $tokenParser->parseString($input);
```

or explicitly setting token regex and filter delimiters:

```
$tokenParser = new TokenParser('|', '/\[\[s+(.*?)\]\]/');

// also possible via setters
$tokenParser
    ->setFilterDelimiter('|')
    ->setTokenRegex('/\[\[s+(.*?)\]\]/')
;

$tokens = $tokenParser->parseString($input);
```

example input:

```
The [[attribute|lower]] [[color]] [[mammal|upper]] jumps over the [[target]].\n
The [[mammal]] is [[attribute]].

```

identified tokens:

```
[[attribute|lower]]
  token name: "attribute"
  filters: ["lower"]
  offsets: [4]

[[color]]
  token name: "color"
  offsets: [24]

[[mammal|upper]]
  token name: "mammal"
  filters: ["upper"]
  offsets: [34]

[[target]]
  token name: "target"
  offsets: [66]

[[mammal]]
  token name: "mammal"
  offsets: [82]

[[attribute]]
  token name: "attribute"
  offsets: [96]

```

The extracted tokens may later be resolved directly by setting their values.

```
$mammal = $tokens->findByName('mammal');
foreach ($mammal as $token) {
  $token
    ->setUnfilteredTokenValue('Fox')
    ->applyFilters()
  ;
}
$output = TokenInjector::injectString($input, $tokens);
```

```
The [[attribute|lower]] [[color]] FOX jumps over the [[target]].\n
The Fox is [[attribute]].

```

or by using a predefined or a custom TokenResolver.

```
$resolver = new RegisteredTokenResolver(
  array(
    'attribute' => 'QUICK',
    'color' => 'brown',
    'target' => 'lazy dog',
  )
);
$tokens->resolve($resolver);
$output = TokenInjector::injectString($output, $tokens);
```

```
The quick brown FOX jumps over the lazy dog.\n
The Fox is QUICK.

```

Injection may be done in multiple steps on the result string without the need of re-parsing the tokens.

Regardless of the method through which the token values are resolved, either custom or predefined value filters may be applied prior to injecting.

The Tree Compiler
-----------------

[](#the-tree-compiler)

The tree compiler may be used to merge together multiple structures through an inheritance-like pattern. In order for that to be possible, all structures must comply with a pre-determined schema.

### Tree Compiler Usage Example

[](#tree-compiler-usage-example)

```
$treeCompiler = new TreeCompiler();
$result = $treeCompiler->compileLocalFile('example.json');
$treeCompiler->save($result, 'result.json');
```

phrase.json

```
{
  "phrase": {
    "line1": "The [[attribute|lower]] [[color]] [[mammal|upper]] jumps over the [[target]].",
    "remove_me": "This line must be removed",
    "line2": "The [[mammal]] is [[attribute]]."
  }
}
```

example.json

```
{
  "include": {
    "a": {
      "type": "file",
      "src": "./phrase.json"
      "resolve": [
        {
          "type": "registered",
          "values": {
            "attribute": "QUICK",
            "color": "brown",
            "target": "lazy dog"
          }
        }
      ]
    }
  },
  "remove": {
    "phrase": {
      "remove_me": null
    }
  },
  "add": {
    "phrase": {
      "line3": "The end."
    }
  }
}
```

result.json

```
{
  "phrase": {
    "line1": "The quick brown FOX jumps over the lazy dog.",
	"line2": "The Fox is QUICK.",
    "line3": "The end."
  }
}
```

### Input structure schema (associative array):

[](#input-structure-schema-associative-array)

- ***include***: optional. First to be processed if present. Associative array describing the included external references and include groups;
    - **xref**: required. Associative array describing the included structures from external references;

        - &lt;xref name&gt;: required. String. The local declared name of the external reference;
            - **type**: required. String. The type of the external reference. Possible values are:
                - *file*: local file external
                    - &lt;file path&gt;: the path to a local file; either absolute (/) or relative to the current file (./).
                - *url*: url external reference;
                    - &lt;url&gt;: the URL to a HTTP accessible remote file. If the response Content-Type does not match a known XrefResolver then the file extension in the URL path will be used to determine the appropriate de-serializer.
                - *inline*: inline data having the same structure schema.
                - *&lt;custom&gt;*: custom external reference handling class registered with **XrefResolverFactory**;
            - **src**: required if type not inline. The string describing the location of the xref formatted according to *type* (see above);
            - **resolve**: optional. Ordered list of resolver settings. This key describes the token resolvers and the values used to replace the tokens in the structure fetched from the external reference. If more than one, the resolvers will be used in the given order.
                - *&lt;unnamed resolver settings&gt;*: required. Associative array describing the configuration of the token resolvers.

                    - **type**: required. String. The type identifying the token resolver's class. Possible values are:

                        - *registered*|*&lt;custom resolver extending RegisteredTokenResolver&gt;*
                        - *scope*|*&lt;custom resolver extending ScopeTokenResolver&gt;*
                    - **options**: String. The options to set on the TokenResolverClass. Options common to all resolvers are:

                        - ***ignore-unknown-tokens***: boolean. Default `true`. If `false`, a compile error will be raised if the resolver encounters an unknown token. For chaining resolvers, this value must be `true` for all except the last.
                        - ***ignore-unknown-filters***: boolean. Default `true`. If `false`, a compile error will be raised if the resolver encounters an unknown token value filter.
                        - ***token-regex***: string. Default `"/\[\[+(.*?)\]\]/"`. The regular expression used to identify the tokens. If specified, the resolver will ignore *token-prefix* and *token-suffix*.
                        - ***token-prefix***: optional. String. Default `"[["`. The token prefix for the default regular expression. For simple tokens that do not need to override *token-regex* but just alter the start delimiter.
                        - ***token-suffix***: optional. String. Default `"]]"`. The token suffix for the default regular expression. For simple tokens that do not need to override *token-regex* but just alter the ending delimiter.
                        - ***token-filter-delimiter***\*: string. Default `"|"`. The character/string used to delimit multiple token value filters in the token name (eg. `[[token_name|lower|dot]]`)

                        The following options are available for token resolvers extending the **ScopeTokenResolver** base class:

                        - **scope-token-name**: required. String. The token name to identify the resolver's scope. (eg. for scope-token-name = json-a `[[json-a:object.value]]`)
                        - ***scope-token-name-delimiter***\*: optional. String. Default `":"`. The character/string used to delimit the scope token name from the scope value path.
                        - ***scope-token-level-delimiter***\*: optional. String. Default `"."`. The character/string used to delimit the levels in the scope value path. (eg. if set to `"->"` the following will match `[[json:object->value]]`

                        \**Note that all delimiters used inside the token must be different .*

                    Only one of the following keys is required (if both are present, the compiler will raise a syntax error):

                    - ***values***: associative array containing the name-value pairs that form the scope of the token resolver.
                    - ***values-xref***: associative array describing the type and source of the external reference that holds the name-value pairs that form the scope of the token resolver.
                        - **type**: required. String. The type of the external reference. (see above)
                        - **src**: required. The string describing the location of the xref formatted according to *type* (see above);

                    *The scope values may only be nested for scope token resolvers.*
    - **main**: ordered list of external reference names to include if no specific include group requested. This group may only be ommited if there is only one Xref in the ***include*** section.
    - *&lt;include group name&gt;*: named include groups represented by ordered lists of external reference names;
- ***remove***: optional. Second to be processed if present. Associative array describing the keys to be removed from the result obtained by merging the included structures;
- ***add***: optional. Last to be processed if present. Associative array describing the keys to be added / overridden in the result obtained by merging the included structures;

If the ***include***, ***remove*** and ***add*** keys are missing from the first level of the structure then all keys will be considered to belong under the ***add*** key.

```
{
  "include": {
    "xref": {
      "": {
        "type": "file|url|git|",
        "src": "||[|]",
        "resolve": [
          {
            "type": "registered|custom",
            "options": {
              "ignore-unknown-tokens": true,
              "ignore-unknown-filters": true,
              "token-regex": "/\[\[+(.*?)\]\]/",
              "token-prefix": "[[",
              "token-suffix": "]]",
              "token-filter-delimiter": "|"
            },
            "values": {
              "": "",
              "": ""
            },
            "values-xref": {
              "type": "file|url|git|",
              "src": "||[|]"
            }
          }, {
            "type": "scope|custom",
            "options": {
              "ignore-unknown-tokens": true,
              "ignore-unknown-filters": true,
              "token-regex": "/\[\[+(.*?)\]\]/",
              "token-prefix": "[[",
              "token-suffix": "]]",
              "token-filter-delimiter": "|",
              "scope-token-name": "",
              "scope-token-name-delimiter": ":",
              "scope-token-level-delimiter": "."
            },
            "values": {
              "": "",
              "": {
                "": {
                  "": ""
                },
              },
              "": ""
            },
            "values-xref": {
              "type": "...",
              "src": "...",
            }
          }
        ]
      }
    },
    "main": [
      "",
      ""
    ],
    "": [
      "",
      ""
    ]
  },
  "remove": {
  },
  "add": {
  }
}
```

###  Health Score

45

—

FairBetter than 93% of packages

Maintenance35

Infrequent updates — may be unmaintained

Popularity23

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity89

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 97.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~140 days

Recently: every ~687 days

Total

25

Last Release

650d ago

Major Versions

v1.1.8 → v2.0.0.x-dev2016-01-25

PHP version history (3 changes)v1.0.0PHP &gt;=5.4.0

v1.0.1PHP &gt;=5.3.3

v1.2.0PHP &gt;=8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/39eb00e570469bdff93ae4a0d6aa3fe6698d443e622c36784cfb5aded8ee9019?d=identicon)[emagtechlabsadmin](/maintainers/emagtechlabsadmin)

![](https://www.gravatar.com/avatar/d43c65c9ab0cb462f4f484bed2930cc56a234bcab08a82f9ed891556621aa8ec?d=identicon)[liutec](/maintainers/liutec)

---

Top Contributors

[![liutec](https://avatars.githubusercontent.com/u/3606208?v=4)](https://github.com/liutec "liutec (82 commits)")[![alinilie](https://avatars.githubusercontent.com/u/6566710?v=4)](https://github.com/alinilie "alinilie (2 commits)")

---

Tags

cfgtokentoken inject

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/liutec-cfgtokenlib/health.svg)

```
[![Health](https://phpackages.com/badges/liutec-cfgtokenlib/health.svg)](https://phpackages.com/packages/liutec-cfgtokenlib)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
