PHPackages                             setherator/variables - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. setherator/variables

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

setherator/variables
====================

The Setherator Variable management library. Manages and processes variable values with some additional magic.

1.0.3(6y ago)113MITPHPPHP ^7.4||^8.0

Since Apr 19Pushed 6y ago1 watchersCompare

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

READMEChangelog (4)Dependencies (3)Versions (5)Used By (0)

Variables
=========

[](#variables)

[![Latest Version on Packagist](https://camo.githubusercontent.com/36533186a9c122c622f4c934558b9c5226b1aeee9d88447f559e6073af207466/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73657468657261746f722f7661726961626c65732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/setherator/variables)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Build Status](https://camo.githubusercontent.com/01d7681db2752a6d7f401ed4358acac291c9739d2f29e4241e246771bf6504c5/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f636f6d2f73657468657261746f722f7661726961626c65732f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.com/setherator/variables)[![Code Quality](https://camo.githubusercontent.com/4ad879cbb29faae3b988452cc61f8f58b56dc457bf73dfc341fa2bbb43cbdd99/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f7175616c6974792f672f73657468657261746f722f7661726961626c65733f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/setherator/variables)[![Code Coverage](https://camo.githubusercontent.com/d2a30170419f88ac59bffdb8c5e23108a257de7c3ca9b7ed0b79d0b0dc4cd1e7/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f636f7665726167652f672f73657468657261746f722f7661726961626c65733f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/setherator/variables)[![Mutation testing badge](https://camo.githubusercontent.com/437d13df04d25d317e875bf851354f33a107824cddac719551bbd5ab266e501c/68747470733a2f2f696d672e736869656c64732e696f2f656e64706f696e743f7374796c653d666c61742d7371756172652675726c3d687474707325334125324625324662616467652d6170692e737472796b65722d6d757461746f722e696f2532466769746875622e636f6d25324673657468657261746f722532467661726961626c65732532466d6173746572)](https://dashboard.stryker-mutator.io/reports/github.com/setherator/variables/master)[![Total Downloads](https://camo.githubusercontent.com/03978163ee3489bfe49e7a2d5ea6cb6df74146377b39203fbe820534ebf39c12/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73657468657261746f722f7661726961626c65732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/setherator/variables/stats)

[![Email](https://camo.githubusercontent.com/e3e4a46ec999fd7bad8871d0ce2a60123a3b8a79f04c305bfb2b976482bbcfbb/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f656d61696c2d617572696d6173406e69656b69732e6c742d626c75652e7376673f7374796c653d666c61742d737175617265)](mailto:aurimas@niekis.lt)

The Setherator Variable management library. Manages and processes variable values with some additional magic.

Install
-------

[](#install)

Via Composer

```
$ composer require setherator/variables
```

Usage
-----

[](#usage)

A compilation of several use cases of `Variables` and it's helpers.

```
use Setherator\Variables\Variables;
use function Setherator\Variables\all;
use function Setherator\Variables\context;
use function Setherator\Variables\factory;
use function Setherator\Variables\logic;
use function Setherator\Variables\passthrough;
use function Setherator\Variables\ref;

$variables = new Variables();
$variables->setContext(['Prefix: ']);

$globalLogicState  = true;
$providedVariables = [
    'scalar'              => 'foo',
    // will execute closure and catch value
    'closure'             => fn() => 'closure Foo ' . random_int(1, 10),
    // Will be fetched at code load
    'ref'                 => ref('scalar', 'Not found'),
    // Will be only fetched when 'ref_on_get' is fetched
    'ref_on_get'          => fn() => ref('scalar'),
    // will return number increasing every time its fetched and 'Number: ' will be passed as argument to
    'factory'             => factory(
        function ($prefix) {
            static $i = 0;

            return $prefix . $i++;
        },
        function () {
            static $i = 0;

            return 'Number ' . $i++ . ': ';
        },
    ),
    // Will inject context values as arguments from Variables::getContext();
    'context'             => context(fn(string $prefix) => $prefix . random_int(1, 10)),
    'factory_context'     => factory(context(fn(string $prefix) => $prefix . random_int(1, 10))),
    'all'                 => all(
        fn() => 'First',
        fn() => 'Second',
        'Third'
    ),
    'logic'               => logic(
        fn() => 1,
        fn() => 'Condition: true',
        fn() => 'Condition: false',
    ),
    'logic_strict'        => logic(
        fn() => 1,
        fn() => 'Condition: true',
        fn() => 'Condition: false',
        true
    ),
    'logic_factory'       => factory(
        logic(
            function () use (&$globalLogicState) {
                return $globalLogicState;
            },
            function () use (&$globalLogicState) {
                $globalLogicState = !$globalLogicState;

                return 'Factory Condition: true';
            },
            function () use (&$globalLogicState) {
                $globalLogicState = !$globalLogicState;

                return 'Factory Condition: false';
            },
        )
    ),
    'passthrough'         => passthrough(
        Closure::fromCallable('strtoupper'),
        fn() => 'Passthrough: ' . ref('logic_factory'),
    ),
    'passthrough_factory' => factory(
        passthrough(
            Closure::fromCallable('strtoupper'),
            fn() => 'Passthrough Factory: ' . ref('logic_factory'),
        )
    ),
    'first' => first(
        0,
        'value'
    ),
];

$variables->add($providedVariables);

echo $variables->get('scalar') . PHP_EOL;
echo $variables->get('closure') . PHP_EOL;
echo $variables->get('closure') . PHP_EOL;
echo $variables->get('ref') . PHP_EOL;
echo $variables->get('ref_on_get') . PHP_EOL;
echo $variables->get('factory') . PHP_EOL;
echo $variables->get('factory') . PHP_EOL;
echo $variables->get('context') . PHP_EOL;
echo $variables->get('context') . PHP_EOL;
echo $variables->get('factory_context') . PHP_EOL;
echo $variables->get('factory_context') . PHP_EOL;
echo json_encode($variables->get('all')) . PHP_EOL;
echo $variables->get('logic') . PHP_EOL;
echo $variables->get('logic_strict') . PHP_EOL;
echo $variables->get('logic_factory') . PHP_EOL;
echo $variables->get('logic_factory') . PHP_EOL;
echo $variables->get('logic_factory') . PHP_EOL;
echo $variables->get('passthrough') . PHP_EOL;
echo $variables->get('passthrough') . PHP_EOL;
echo $variables->get('passthrough_factory') . PHP_EOL;
echo $variables->get('passthrough_factory') . PHP_EOL;
echo $variables->get('passthrough_factory') . PHP_EOL;
echo $variables->get('first') . PHP_EOL . PHP_EOL;

// Print all computed values
echo json_encode($variables->all(), JSON_PRETTY_PRINT) . PHP_EOL;

// Print all non computed values (Closures do not json encode)
echo json_encode($variables->all(false), JSON_PRETTY_PRINT) . PHP_EOL;
```

Will result in:

```

foo
closure Foo 4
closure Foo 4
Not found
foo
Number 0: 0
Number 1: 1
Prefix: 6
Prefix: 6
Prefix: 10
Prefix: 1
["First","Second","Third"]
Condition: true
Condition: false
Factory Condition: true
Factory Condition: false
Factory Condition: true
PASSTHROUGH: FACTORY CONDITION: FALSE
PASSTHROUGH: FACTORY CONDITION: FALSE
PASSTHROUGH FACTORY: FACTORY CONDITION: TRUE
PASSTHROUGH FACTORY: FACTORY CONDITION: FALSE
PASSTHROUGH FACTORY: FACTORY CONDITION: TRUE
value

{
    "scalar": "foo",
    "closure": "closure Foo 4",
    "ref": "Not found",
    "ref_on_get": "foo",
    "factory": "Number 2: 2",
    "context": "Prefix: 6",
    "factory_context": "Prefix: 8",
    "all": [
        "First",
        "Second",
        "Third"
    ],
    "logic": "Condition: true",
    "logic_strict": "Condition: false",
    "logic_factory": "Factory Condition: false",
    "passthrough": "PASSTHROUGH: FACTORY CONDITION: FALSE",
    "passthrough_factory": "PASSTHROUGH FACTORY: FACTORY CONDITION: TRUE",
    "first": "value"
}

{
    "scalar": "foo",
    "closure": "closure Foo 4",
    "ref": "Not found",
    "ref_on_get": "foo",
    "factory": {},
    "context": "Prefix: 6",
    "factory_context": {},
    "all": [
        "First",
        "Second",
        "Third"
    ],
    "logic": "Condition: true",
    "logic_strict": "Condition: false",
    "logic_factory": {},
    "passthrough": "PASSTHROUGH: FACTORY CONDITION: FALSE",
    "passthrough_factory": {},.
    "first": {}
}

```

Helpers
-------

[](#helpers)

A variable value can be any scalar, array, object type but also closure which will be executed and cached. To prevent caching value should implement `NonCacheableClosure` interface for e.g. `factory` helper function.

### Reference

[](#reference)

A function to fetch variable value from Variables instance. If not found `$default = null` will be returned. If raw value before evaluation required use `$raw = true`.

```
function ref(string $name, $default = null, bool $raw = false);
function reference(string $name, $default = null, bool $raw = false);
```

To fetch value at variable get time use these functions.

```
function refFn(string $name, $default = null, bool $raw = false);
function referenceFn(string $name, $default = null, bool $raw = false);
```

### Enviroment variable

[](#enviroment-variable)

A function to fetch environment variable. If not found `$default = null` will be returned.

```
function env(string $name, $default = null): string;
```

### Context

[](#context)

A function to wrap your closure and inject context from `Variables::getContext()`;

```
function context(Closure $closure, ...$args): Closure;Cacheable
```

Will return your closure wrapped with context variables + extra `$args` as arguments. `$args` will be evaluated using `Variables::parseValue()` function. It will behave as normal Variable value.

```
[
    'context_aware_variable' => context(
        function (Setherator $setherator, string $input) {
            // ... Your logic

            return 'Your typed input: ' . $input;
        },
        ask('Input')
    ),
]
```

**Attention**: Context returned closure does not accept any arguments.

### Factory

[](#factory)

A function to prevent your closue value from getting cached. Your closure will be called everytime value is accessed. `$args` will be passed as arguments to closure function. `$args` will be evaluated using `Variables::parseValue()` function. It will behave as normal Variable value.

```
function factory(Closure $closure, ...$args): NonCacheableClosure;
```

Will return a value which implements `NonCacheableClosure` interface and prevents it from caching and behave as your normal closure.

```
[
    'factory_value' => factory(
        function (string $input) {
            // ... Your logic

            return 'Your typed input: ' . $input;
        },
        ask('Input')
    ),
]
```

### All

[](#all)

A function to evaluate all values passed to arguments and return result as array.

```
function all(...$args): array
```

Will return an array of all `$args` evaluated.

```
[
    'all' => all(
        ask('Please provide project name'),
        ask('Please provide folder name')
    )
]
```

**Tip:** To evaluate all values at variable get time use function: `allFn(/* ... */)`.

### Logic

[](#logic)

A function to evaluate condition and decide which value to use. `$condtion`, `$true`, `$false` are evaluated using `Variables::parseValue()` function.

```
function logic($condition, $true, $false, bool $strict = false): Closure;
```

Will return a closure which will decide which `$true` or `$false` to return based on `$condition`

```
[
    'logic_based_value' => logic(
        fn() => askChoice('Please select app env', ['dev', 'prod']) !== 'dev',
        'Environement is production',
        fn() => 'Enviroment is dev and time is: ' . time()
    )
]
```

**Attention**: Logic returned closure does not accept any arguments.

### Passthrough

[](#passthrough)

A function which will pass all evaluted values as argumnents to closure.

```
function passthrough(Closure $closure, ...$args): Closure;
```

Will return a closure which will pass `$args` evaluated as arguments to Closure.

```
[
    'passthough_value' => passthrough(
        function (string $projectName, string $projectFolderName) {
            return 'Project "' . $projectName . '" at "' . $projectFolderName . '"';
        }
        ask('Please provide project name'),
        ask('Please provide project folder name')
    )
]
```

**Attention**: Passthrough returned closure does not accept any arguments.

### First

[](#first)

A function which return a first truthfull value from arguments. `$args` will be evaluated using `Variables::parseValue()` function.

```
function first(...$args);
```

**Tip:** To evaluate at variable get time use function: `firstFn(/* ... */)`.

Value Parsers
-------------

[](#value-parsers)

You can implement your own value parsers to be parsed when accessing variables value.

```
class JsonEncodeValue
{
    private $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    public function getValue()
    {
        return $this->value;
    }
}

class JsonEncodeValueParser implements ValueParserInterface
{
    public function supports($value): bool
    {
        return $value instanceof JsonEncodeValue;
    }

    public function parseValue($value, Variables $variables)
    {
        return json_encode($value->getValue());
    }
}

$variables = new Variables();
$variables->addValueParser(new JsonEncodeValueParser());

$variables->set('json', new JsonEncodeValue(['foo' => 'bar']);
$variables->get('json') // => {"foo":"bar"}
```

Testing
-------

[](#testing)

Run test cases

```
$ composer test
```

Run test cases with coverage (HTML format)

```
$ composer test-coverage
```

Run PHP style checker

```
$ composer cs-check
```

Run PHP style fixer

```
$ composer cs-fix
```

Run all continuous integration tests

```
$ composer ci-run
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CONDUCT](CONDUCT.md) for details.

License
-------

[](#license)

Please see [License File](LICENSE) for more information.

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~1 days

Total

4

Last Release

2217d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/770bae1f46ac2b4536db820b8642491c25e2e2fd44e761110269e4722679a80d?d=identicon)[aurimasniekis](/maintainers/aurimasniekis)

---

Top Contributors

[![aurimasniekis](https://avatars.githubusercontent.com/u/15481?v=4)](https://github.com/aurimasniekis "aurimasniekis (5 commits)")

---

Tags

variablessetherator

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/setherator-variables/health.svg)

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

###  Alternatives

[imliam/laravel-env-set-command

Set a .env file variable from the command line

118352.4k10](/packages/imliam-laravel-env-set-command)[msztorc/laravel-env

Laravel env helper commands

7855.4k](/packages/msztorc-laravel-env)[cekurte/environment

A library to get the values from environment variables and process to php data types

5884.0k7](/packages/cekurte-environment)[marabesi/laration

Easy package to list all variables in a Laravel application

4738.7k](/packages/marabesi-laration)[mirazmac/dotenvwriter

A PHP library to write values to .env (DotEnv) files

19129.3k7](/packages/mirazmac-dotenvwriter)

PHPackages © 2026

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