Download the PHP package eurym3d0n/elephenv without Composer
On this page you can find all versions of the php package eurym3d0n/elephenv. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download eurym3d0n/elephenv
More information about eurym3d0n/elephenv
Files in eurym3d0n/elephenv
Package elephenv
Short Description A modern, strictly-typed PHP 8.2+ environment loader with fluent validation, type inference, integrity checking, and structured error rendering.
License MIT
Homepage https://fox-trotte.fr
Informations about the package elephenv
Elephenv
A modern, strictly-typed PHP 8.2+ environment loader with fluent validation, type inference, integrity checking, and structured error rendering.
Table of Contents
- Overview
- Why Elephenv
- Comparison Table
- Requirements
- Installation
- Quick Start
- Global Helper Functions
.envFile Syntax- Loading Sources
- Type Casting
- Variable Interpolation
- Array Notation
- Validation
- Fluent Value API
- Integrity Checking
- Security Guards
- Error Rendering
- Repository API
- Extending Elephenv
- Testing
- Contributing
- License
Overview
Elephenv is a PHP library for loading, parsing, validating, and exposing
environment variables from .env files. It is built for PHP 8.2+, enforces
declare(strict_types=1) throughout, and is organized around explicit contracts
in Elephenv\Contracts so that every component can be replaced or extended
without touching the core.
Unlike most .env loaders, Elephenv treats environment configuration as a
first-class concern:
- Values are automatically cast to native PHP types (
bool,int,float,null). - Validation is composable and collects all violations before throwing.
- A fluent
EnvValuewrapper exposes each value with chainable assertions and transformations. - A structured error renderer produces readable output for both HTTP and CLI without additional configuration.
Why Elephenv
Most PHP .env loaders solve a narrow problem: read a file and populate $_ENV.
Elephenv solves the broader problem of making environment configuration safe,
correct, and expressive at every stage of an application's lifecycle.
Correctness by default.
String values are automatically inferred and cast to their native PHP types
(bool, int, float, null) without opt-in. A variable whose raw value is
"true" is stored as true, not the string "true". This eliminates an entire
class of bugs where application code must defensively re-parse strings from
getenv().
Fail loudly and completely.
Validation collects every violation that occurs during a loading pass before
throwing. A single ValidationException describes every failing constraint,
giving you a complete picture instead of one-at-a-time failures to debug.
Fluent, type-safe access.
Elephenv::value('KEY') returns an EnvValue wrapper that chains validation,
transformation, and casting methods. No more (int) env('PORT') scattered across
your codebase.
Security-aware.
The loader enforces a configurable maximum file size and inspects POSIX
permissions on every .env file it reads. Files readable by group or world
trigger a warning by default and a hard exception in strict mode.
Fully injectable.
Every major component implements a contract defined in Elephenv\Contracts.
The runtime container (exposed via Elephenv::swap()) accepts custom
implementations for the loader, repository, caster, integrity checker, and error
renderer, making every part testable and replaceable in isolation.
Structured error rendering.
When an exception is raised during loading, Elephenv can render a styled HTML
page (HTTP) or a formatted CLI output without any additional setup. The
rendering pipeline is fully replaceable via ErrorRendererInterface.
Comparison Table
The table below compares Elephenv against the three most widely used PHP environment loaders as of 2026.
| Feature | Elephenv | vlucas/phpdotenv | symfony/dotenv | josegonzalez/dotenv |
|---|---|---|---|---|
| PHP version requirement | 8.2+ | 7.4+ | 7.2+ | 5.4+ |
| Strict types throughout | Yes | No | No | No |
| Interface-driven contracts (full) | Yes | No | No | No |
| Swappable runtime services | Yes | No | No | No |
| Automatic type casting | Yes (native) | No | No | No |
Injectable caster (CasterInterface) |
Yes | No | No | No |
Fluent value wrapper (EnvValue) |
Yes | No | No | No |
Composable validation (RuleSet) |
Yes | Partial | No | No |
| All violations collected before throw | Yes | No | No | No |
| Custom validation callback | Yes | No | No | No |
| PCRE pattern validation | Yes | No | No | No |
RuleSet merge / composition |
Yes | No | No | No |
Array notation keys (DB[host]) |
Yes | No | No | No |
| Injectable array flattener | Yes | No | No | No |
Variable interpolation (${VAR}) |
Yes | Yes | Yes | Partial |
| Recursive multi-pass interpolation | Yes | No | No | No |
| Cycle detection in interpolation | Yes | No | No | No |
| Interpolation callback | Yes | No | No | No |
| Load from raw string | Yes | No | Yes | No |
| Load multiple files | Yes | Partial | No | No |
Skip missing files (loadIfExists) |
Yes | Yes | Yes | No |
set() / forget() / clear() |
Yes | No | No | No |
Integrity checker (.env.example) |
Yes | Yes | No | No |
| File size security guard | Yes | No | No | No |
| POSIX permission security guard | Yes | No | No | No |
| HTML error renderer | Yes | No | No | No |
| CLI error renderer | Yes | No | No | No |
| Replaceable error renderer | Yes | No | No | No |
Singleton facade with reset() |
Yes | No | No | No |
Global env() helper |
Yes | No | No | No |
Requirements
- PHP 8.2 or higher
- The
mbstringextension (for multibyte-safe string handling) - Composer
Installation
Quick Start
Using the Env facade alias:
Global Helper Functions
Elephenv automatically registers a set of global helper functions that expose
the most common facade operations without the Elephenv:: prefix. They are
available immediately after installation with no additional configuration.
Each function is guarded by function_exists() to coexist safely with any
framework that already defines its own implementation. The first definition
loaded by the runtime wins.
Available helpers
What is not exposed as a global helper
Bootstrap and infrastructure methods are intentionally excluded.
Keeping them on Elephenv:: preserves their semantic weight at call
sites — seeing Elephenv::checkIntegrity() in a bootstrap file
immediately signals a critical startup operation in a way that a short
global alias would not.
Excluded methods include load(), loadIfExists(), loadMany(),
loadString(), swap(), reset(), checkIntegrity(),
setErrorRenderer(), and setComplexExportMode().
.env File Syntax
Elephenv supports a clean, standard .env file syntax.
Basic assignment
Quoted values
- Double-quoted values expand escape sequences (
\n,\t,\r,\\,\",\$). - Single-quoted values are treated as literals — no escape processing.
Empty and null values
Variables defined without a value are resolved as null. Use the empty sentinel
for an explicit empty string.
Comments
Comments can be placed on a line by themselves or inline after a value (if not inside quotes).
Export prefix
The optional export keyword is silently stripped, allowing the same file to be
sourced by shell scripts:
Loading Sources
Single file
Throws FileNotFoundException when the file does not exist and
SecurityException when a security guard is violated.
Single file, optional
Returns an empty array silently when the file is absent.
Multiple files
Files are merged in order. Later files override earlier ones for duplicate keys.
By default, missing paths are silently skipped. Pass skipMissing: false via
options to make every path required.
Raw string
Useful in test suites or when configuration is sourced from a remote store.
Value callback
Transform every resolved value before it is stored in the repository:
Type Casting
By default, every string value is inspected and cast to its native PHP type before being stored. No configuration is required.
Raw .env value |
PHP type | PHP value |
|---|---|---|
true, yes, on, 1 |
bool |
true |
false, no, off, 0 |
bool |
false |
null, nil, none |
null |
null |
empty |
string |
'' |
42 |
int |
42 |
-7 |
int |
-7 |
3.14 |
float |
3.14 |
1.5e3 |
float |
1500.0 |
"hello world" |
string |
'hello world' |
Casting can be disabled per load call:
Note The string
"0"is cast tofalse(bool), not0(int), because boolean detection takes precedence over integer detection. If you need the integer0, disable casting or cast the value explicitly using the fluent API:Elephenv::value('MY_VAR')->toInt().
The casting strategy is injectable via CasterInterface. A custom caster can
be registered at bootstrap or swapped in for tests:
Variable Interpolation
Placeholders in the form ${VAR} or $VAR are resolved against previously
loaded variables. Resolution is recursive: if a resolved value itself
contains placeholders, they are expanded in subsequent passes. Circular
references (A -> B -> A) are detected and broken by returning an empty string.
Custom override map
Provide additional key-value pairs that take precedence over the repository during placeholder resolution:
Interpolation callback
Transform every resolved placeholder value before substitution:
Recursion depth
Interpolation is recursive up to 10 levels deep by default. The depth limit
is configurable via the Interpolator constructor:
Cycle detection
Circular references are automatically detected and resolved to an empty string to prevent infinite loops:
Array Notation
Keys using bracket notation are automatically inflated into nested PHP arrays after the loading pass. Flat bracket-notation keys are removed from the repository after inflation so that only the nested form remains accessible.
The inflation strategy is injectable via ArrayFlattenerInterface:
Validation
Validation rules are composed using a fluent RuleSet builder and passed
as a map of variable name to RuleSet in the rules option. All violations
from every variable are collected before a ValidationException is thrown,
so a single loading call reports all problems at once.
Built-in rules
Allowing empty strings
When allowEmpty() is present, notEmptyString() is silently skipped
regardless of its position in the chain:
Custom callback rule
Custom rule class
Implement ValidatorInterface and register with add():
Composing rule sets
Base rule sets can be merged into more specific ones to avoid repetition:
Handling violations
Fluent Value API
Elephenv::value() returns an EnvValue instance wrapping the resolved value.
Validation methods throw immediately on failure; transformation and casting
methods return $this for chaining.
Default value
Transformation
Bulk assignment
Applying a full RuleSet
Raw value access
Type casting methods
Type inspection methods
Side-effect assignment and context
Variables written during a chain are tracked internally and accessible via
context() after the chain completes.
Integrity Checking
The integrity checker compares the variable names declared in a .env.example
reference file against the active repository. It throws IntegrityException
when any required variable is absent, reporting all missing names at once.
The .env.example file follows the same format as a regular .env file.
Values are irrelevant; only the variable names are checked.
Listing required names without running a check:
A custom integrity checker can be injected at bootstrap:
Security Guards
File size
The loader rejects any file larger than 1 MiB (1 048 576 bytes) by default.
This prevents loading unexpectedly large files that could exhaust memory.
The limit is configurable via the EnvLoader constructor:
POSIX permissions
On non-Windows systems, the loader inspects file permissions before reading.
Files readable by the group or by others (world-readable) trigger a PHP warning
by default. When strict mode is enabled, the same condition throws a
SecurityException instead:
The guard is skipped entirely on Windows where POSIX permissions do not apply.
Error Rendering
When an exception is raised inside Elephenv::load() and its variants,
Elephenv invokes the active error renderer before re-throwing the exception.
This allows a styled error page (HTTP) or formatted terminal output (CLI) to
appear without manual try/catch blocks in bootstrap code.
The default renderer is assembled lazily from getcwd() . '/views'. To use
a custom views directory or package version string:
To replace the renderer with a completely custom implementation:
Repository API
The EnvironmentRepository propagates all writes to $_ENV and $_SERVER.
Resolution falls back through $_ENV, $_SERVER, and getenv() for variables
set outside of Elephenv.
Accessing the repository directly:
Writing and removing variables via the facade shortcuts:
Seeding the repository with initial values at construction:
Extending Elephenv
Every major component is backed by a contract in the Elephenv\Contracts
namespace. Custom implementations can be injected at the singleton level via
Elephenv::swap().
| Contract | Default Implementation | Purpose |
|---|---|---|
LoaderInterface |
EnvLoader |
Parses .env sources and populates the repo |
RepositoryInterface |
EnvironmentRepository |
Stores and resolves environment variables |
CasterInterface |
Inferrer |
Detects and casts raw string values |
ArrayFlattenerInterface |
ArrayFlattener |
Inflates bracket-notation keys into arrays |
IntegrityCheckerInterface |
IntegrityChecker |
Compares repo against .env.example |
ParserInterface |
LineParser |
Tokenises individual .env lines |
InterpolatorInterface |
Interpolator |
Resolves ${VAR} placeholders recursively |
ValidatorInterface |
Rule classes | Validates a single constraint |
ErrorRendererInterface |
ErrorRenderer |
Renders exceptions and terminates execution |
Swapping multiple services at once:
Testing
Elephenv is designed to be fully testable. The reset() method clears the
singleton and the error renderer between test cases:
Load configuration from a raw string to avoid reliance on files on disk:
Inject an isolated repository pre-seeded with test values:
Disable process termination in the error renderer by swapping in a custom
renderer that throws exceptions instead of calling exit():
Write and remove variables at runtime for per-test overrides:
Contributing
Contributions are welcome. Please open an issue to discuss your proposal before
submitting a pull request. All code must pass PHPStan at maximum level and
follow the project coding standard (run composer cs).
License
Elephenv is open-source software released under the MIT License.
See the LICENSE file for the full terms.