PHPackages                             aeliot/env-resolver - 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. aeliot/env-resolver

ActiveLibrary

aeliot/env-resolver
===================

Resolver of environment variables

1.0.2(4mo ago)0228↓45%1MITPHPPHP ^8.2CI passing

Since Jan 1Pushed 4mo agoCompare

[ Source](https://github.com/Aeliot-Tm/env-resolver)[ Packagist](https://packagist.org/packages/aeliot/env-resolver)[ RSS](/packages/aeliot-env-resolver/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)DependenciesVersions (4)Used By (1)

Env Resolver
============

[](#env-resolver)

[![Automated Testing](https://github.com/Aeliot-Tm/env-resolver/actions/workflows/automated_testing.yml/badge.svg?branch=main)](https://github.com/Aeliot-Tm/env-resolver/actions/workflows/automated_testing.yml?query=branch%3Amain)[![Security Audit](https://github.com/Aeliot-Tm/env-resolver/actions/workflows/security-audit.yaml/badge.svg?branch=main)](https://github.com/Aeliot-Tm/env-resolver/actions/workflows/security-audit.yaml?query=branch%3Amain)[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](https://opensource.org/licenses/MIT)

A powerful PHP library for resolving environment variables, constants, files, and other data sources using a flexible chain of modifiers. Inspired by Symfony's env processors but works standalone without framework dependencies.

It helps you to keep configs clean without commiting of sensitive data. Just store instructions which environment variable use while running. They look like `%env(MY_VAR)%`.

Features
--------

[](#features)

- **Chain modifiers** - Combine multiple transformations: `json:base64:env:MY_VAR`
- **Nested placeholders** - Support for `%env(file:%env(PATH_VAR)%)%`
- **Escaping** - Use `%%` to output literal `%` characters
- **Multiple data sources** - Environment variables, constants, files, PHP includes
- **Type casting** - Convert to int, float, bool, string, JSON, CSV
- **Encoding/Decoding** - Base64, URL encoding, query string parsing
- **Extensible** - Custom post-processors for resolved values

Installation
------------

[](#installation)

```
composer require aeliot/env-resolver
```

Requirements
------------

[](#requirements)

- PHP 8.2 or higher

Quick Start
-----------

[](#quick-start)

### String Processing with Placeholders

[](#string-processing-with-placeholders)

```
use Aeliot\EnvResolver\Service\StringProcessor;

$processor = new StringProcessor();

$_ENV['HOST'] = 'localhost';
$_ENV['PORT'] = '5432';

$config = 'postgres://%env(HOST)%:%env(PORT)%/database';
$result = $processor->process($config);
// Result: 'postgres://localhost:5432/database'
```

It allows to process entire config:

```
use Aeliot\EnvResolver\Service\StringProcessor;

$preparedConfig = (new StringProcessor())->process(file_get_contents('/path/to/config.yaml'));
// Result: all instructions '%env(MY_ENV_VAR)%' resolved to
```

Modifiers
---------

[](#modifiers)

Modifiers are chained using `:` separator and processed from right to left.

### Data Sources

[](#data-sources)

ModifierDescriptionExample`env`Environment variable (default)`env:MY_VAR` or just `MY_VAR``const`PHP constant`const:MY_CONST``file`File contents`file:/path/to/file.txt``require`PHP file return value`require:/path/to/config.php``direct`Direct/literal value`direct:my_value`### Type Casting

[](#type-casting)

ModifierDescriptionExample`int`Cast to integer`int:MY_VAR``float`Cast to float`float:MY_VAR``bool`Cast to boolean`bool:MY_VAR``not`Negate boolean`not:bool:MY_VAR``string`Cast to string`string:float:MY_VAR`### Encoding/Decoding

[](#encodingdecoding)

ModifierDescriptionExample`base64`Base64 decode`base64:MY_VAR``json`JSON decode`json:MY_VAR``query_string`Parse query string`query_string:MY_VAR``strcsv`Parse CSV string`strcsv:MY_VAR``url`Parse URL into components`url:MY_VAR``urlencode`URL encode`urlencode:MY_VAR`### String Operations

[](#string-operations)

ModifierDescriptionExample`trim`Trim whitespace`trim:MY_VAR`### Complex Types

[](#complex-types)

ModifierDescriptionExample`key`Get array key`key:username:json:MY_VAR``enum`Convert to BackedEnum`enum:App\Status:MY_VAR`Examples
--------

[](#examples)

### Basic Usage

[](#basic-usage)

```
use Aeliot\EnvResolver\Service\Resolver;

$resolver = new Resolver();

// Simple environment variable
$_ENV['DATABASE_URL'] = 'mysql://localhost/mydb';
$value = $resolver->resolve('DATABASE_URL');
// Result: 'mysql://localhost/mydb'

// Explicit env modifier
$value = $resolver->resolve('env:DATABASE_URL');
// Result: 'mysql://localhost/mydb'
```

### Chained Modifiers

[](#chained-modifiers)

```
// Base64 encoded JSON in environment variable
$_ENV['CONFIG'] = 'eyJkYiI6Im15c3FsIiwicG9ydCI6MzMwNn0='; // {"db":"mysql","port":3306}

$resolver = new Resolver();

// Decode base64, then parse JSON, then get 'port' key, then cast to int
$port = $resolver->resolve('int:key:port:json:base64:CONFIG');
// Result: 3306 (integer)
```

### Nested Placeholders

[](#nested-placeholders)

```
$_ENV['CONFIG_FILE_PATH'] = '/etc/myapp/database.conf';

$processor = new StringProcessor();

// Inner placeholder resolves first, then outer uses the result
$config = '%env(file:%env(CONFIG_FILE_PATH)%)%';
$result = $processor->process($config);
// Result: contents of /etc/myapp/database.conf
```

### Escaping Percent Signs

[](#escaping-percent-signs)

```
$processor = new StringProcessor();

$_ENV['DISCOUNT'] = '25';

$result = $processor->process('Get %env(DISCOUNT)%%% off!');
// Result: 'Get 25% off!'

// Double %% becomes single %
$result = $processor->process('100%% complete');
// Result: '100% complete'

// Escape entire placeholder
$result = $processor->process('Use %%env(VAR)%% syntax');
// Result: 'Use %env(VAR)% syntax'
```

### Custom Post-Processor

[](#custom-post-processor)

```
$processor = new StringProcessor();

$_ENV['POSITION_CONFIG'] = 'eyJwYXRoIjoiL3BhdGgvdG8vZmlsZSIsImxpbmUiOiAxMjd9';

// Default: non-scalar values are JSON encoded
$result = $processor->process('%env(json:base64:POSITION_CONFIG)%');
// Result: '{"path":"/path/to/file","line": 127}'

// Custom: join array elements
$result = $processor->process(
    '%env(json:base64:direct:POSITION_CONFIG)%',
    static function (mixed $value, string $heap): string {
        if ('json:base64:direct:POSITION_CONFIG' === $heap){
            $value = implode(', ', $value);
        }
        return \is_string($value) ? $value : json_encode($value, \JSON_THROW_ON_ERROR);
    }
);
// Result: '/path/to/file:127'
```

Similarly, you may return tilda (`~`) for `null`-values when process YAML.

### Reading from Files

[](#reading-from-files)

```
$resolver = new Resolver();

// Read file contents
$content = $resolver->resolve('file:/etc/ssl/certs/ca.pem');

// Read file path from env, then read file
$_ENV['CERT_PATH'] = '/etc/ssl/certs/ca.pem';
$content = $resolver->resolve('file:env:CERT_PATH');

// Require PHP file that returns a value
$config = $resolver->resolve('require:/path/to/config.php');
```

### URL Parsing

[](#url-parsing)

```
$_ENV['DATABASE_URL'] = 'mysql://user:pass@localhost:3306/mydb?charset=utf8';

$resolver = new Resolver();

$params = $resolver->resolve('url:DATABASE_URL');
// Result: [
//     'scheme' => 'mysql',
//     'host' => 'localhost',
//     'port' => 3306,
//     'user' => 'user',
//     'pass' => 'pass',
//     'path' => 'mydb',
//     'query' => 'charset=utf8',
//     'fragment' => null,
// ]

// Get specific part
$host = $resolver->resolve('key:host:url:DATABASE_URL');
// Result: 'localhost'
```

### Working with Enums

[](#working-with-enums)

```
enum Status: string {
    case ACTIVE = 'active';
    case INACTIVE = 'inactive';
}

$_ENV['USER_STATUS'] = 'active';

$resolver = new Resolver();
$status = $resolver->resolve('enum:Status:USER_STATUS');
// Result: Status::ACTIVE
```

Error Handling
--------------

[](#error-handling)

The library throws typed exceptions for different error conditions:

ExceptionCondition`EnvFoundException`Environment variable or constant not found`FileNotFoundException`File does not exist or is not readable`InvalidValueException`Value cannot be processed (invalid JSON, etc.)`InvalidNameException`Invalid variable/constant name`InvalidEnumException`Class is not a BackedEnum`NotSupportedEnumCaseException`Enum case does not exist`InvalidHeapException`Invalid modifier chain syntax`RuntimeException`General runtime errorsAll exceptions implement `EnvResolverExceptionInterface`.

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

[](#contributing)

Check code quality before the creating of PR.

```
# All checks
composer check-all

# Individual checks
composer cs-fixer-check  # Code style
composer phpstan         # Static analysis
composer require-check   # Dependency check
composer unused          # Unused dependencies

# Run with Docker
docker compose run --rm php-cli php tools/phpunit.phar -c .scripts/phpunit/phpunit.xml
```

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance75

Regular maintenance activity

Popularity15

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 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

3

Last Release

134d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/56d81f2702c20990da8d701ba1083e398c94cfcadfdd27b1a90e7791aac92053?d=identicon)[aeliot-tm](/maintainers/aeliot-tm)

---

Top Contributors

[![Aeliot-Tm](https://avatars.githubusercontent.com/u/8513062?v=4)](https://github.com/Aeliot-Tm "Aeliot-Tm (53 commits)")

---

Tags

envenv-resolverenvironment-variablesenvenv-processorenv-resolver

### Embed Badge

![Health badge](/badges/aeliot-env-resolver/health.svg)

```
[![Health](https://phpackages.com/badges/aeliot-env-resolver/health.svg)](https://phpackages.com/packages/aeliot-env-resolver)
```

###  Alternatives

[vlucas/phpdotenv

Loads environment variables from `.env` to `getenv()`, `$\_ENV` and `$\_SERVER` automagically.

13.5k602.4M5.4k](/packages/vlucas-phpdotenv)[symfony/dotenv

Registers environment variables from a .env file

3.8k226.7M2.3k](/packages/symfony-dotenv)[jbzoo/utils

Collection of PHP functions, mini classes and snippets for everyday developer's routine life.

8321.5M36](/packages/jbzoo-utils)[helhum/dotenv-connector

Makes it possible to set environment variables for composer projects.

1594.6M34](/packages/helhum-dotenv-connector)[oscarotero/env

Simple library to consume environment variables

9411.4M152](/packages/oscarotero-env)[ffraenz/private-composer-installer

A composer install helper for private packages

2331.7M5](/packages/ffraenz-private-composer-installer)

PHPackages © 2026

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