PHPackages                             vilnisgr/env-editor - 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. [Validation &amp; Sanitization](/categories/validation)
4. /
5. vilnisgr/env-editor

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

vilnisgr/env-editor
===================

Modern PHP 8.3 library for programmatically editing dotenv files. Preserve comments, formatting, and variable order while reading or writing .env files.

v1.0.0(6mo ago)22MITPHPPHP &gt;=8.3

Since Nov 15Pushed 6mo agoCompare

[ Source](https://github.com/VilnisGrinbergs2000/env-editor)[ Packagist](https://packagist.org/packages/vilnisgr/env-editor)[ RSS](/packages/vilnisgr-env-editor/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (1)Versions (2)Used By (0)

EnvEditor
=========

[](#enveditor)

### Advanced **.env Parser**, **Writer**, **Schema Validator**, and **Config Factory** for PHP

[](#advanced-env-parser-writer-schema-validator-and-config-factory-for-php)

 [![](https://camo.githubusercontent.com/1eb6fd7faf743bfeb0a0e4885437dee8ca0f90a4908b1ca5bd4219570ab76042/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e332532422d626c75653f7374796c653d666f722d7468652d6261646765)](https://camo.githubusercontent.com/1eb6fd7faf743bfeb0a0e4885437dee8ca0f90a4908b1ca5bd4219570ab76042/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e332532422d626c75653f7374796c653d666f722d7468652d6261646765) [![](https://camo.githubusercontent.com/7d735ce491a35f9cf1b7ee0b3e2f09fdce686dea4e62b55da9f6d4f9ea980f58/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5465737465642d3130302532352d737563636573733f7374796c653d666f722d7468652d6261646765)](https://camo.githubusercontent.com/7d735ce491a35f9cf1b7ee0b3e2f09fdce686dea4e62b55da9f6d4f9ea980f58/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5465737465642d3130302532352d737563636573733f7374796c653d666f722d7468652d6261646765) [![](https://camo.githubusercontent.com/153acf9dff19deb8abfc598c53bac50a4ceae0f5c83a552711060d3d78d2c057/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e3f7374796c653d666f722d7468652d6261646765)](https://camo.githubusercontent.com/153acf9dff19deb8abfc598c53bac50a4ceae0f5c83a552711060d3d78d2c057/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e3f7374796c653d666f722d7468652d6261646765)

EnvEditor is a **full-featured environment management toolkit** for modern PHP projects—
designed to replace fragile string-based `.env` handling with a **structured, validated, type-safe**, and **developer-friendly** system.

This documentation covers every part of the library in depth:

🔹 **Writer** (editing `.env` files with order control &amp; multiline support)
🔹 **Reader / Parser** (accurately parses any real-world dotenv file)
🔹 **Formatter** (ensures valid dotenv formatting &amp; escaping)
🔹 **Schema Validator** (required/optional keys, casting, rules, grouping)
🔹 **Rules Engine** (min/max/regex/length/in/custom)
🔹 **Config Factory (DTO Generator)** for type-safe config objects
🔹 **Vanilla PHP Integration Guide**
🔹 **Full examples for every method**

---

Features
========

[](#features)

Feature CategoryDescription**Parser**High-precision dotenv parser with strict key validation, escape handling, and export removal.**Writer**Smart writer with ordering, spacing, top/bottom, before/after insertion.**Multiline Support**Fully supports multiline values with proper quote detection and unescaping.**Comments**Preserves inline comments and full line comments exactly as they appear.**Atomic Saving**Safer writes using temp files to prevent corruption.**Casting**Built-in casting: `array`, `json`, `bool`, `float`, `int`.**Enum Casting**Convert values into backed PHP enums automatically.**Validation Rules**`min`, `max`, `regex`, `in`, `length`, custom callbacks.**Schema Groups**Namespaced schemas: e.g., `group('DB_', fn($db) => … )`.**DTO Factory**Build typed objects from env via `EnvConfigFactory`.**Env Loader**Loads validated env values into `putenv()`, `$_ENV`, and `$_SERVER`.**Test Coverage**Comprehensive test suite validating all core features.---

Installation
============

[](#installation)

```
composer require vilnisgr/env-editor

```

---

Usage Guide
===========

[](#usage-guide)

```
use VilnisGr\EnvEditor\Writer\DotenvWriter;

$writer = new DotenvWriter();
$writer->load('.env');

$writer->set('APP_ENV', 'production');
$writer->save();
```

---

1. DOTENV WRITER – FULL DOCUMENTATION &amp; TUTORIAL
====================================================

[](#1-dotenv-writer--full-documentation--tutorial)

1.1 Creating the writer
-----------------------

[](#11-creating-the-writer)

```
$writer = new DotenvWriter();
$writer->load('.env');
```

---

1.2 Setting / updating a key
----------------------------

[](#12-setting--updating-a-key)

```
$writer->set('APP_NAME', 'MyApp');
```

If the key exists, it's updated.
If not, it's added at the bottom.

---

1.3 Insert AFTER another key
----------------------------

[](#13-insert-after-another-key)

```
$writer->after('DB_HOST')->set('DB_PORT', '3306');
```

---

1.4 Insert BEFORE a key
-----------------------

[](#14-insert-before-a-key)

```
$writer->before('APP_ENV')->set('APP_NAME', 'NewName');
```

---

1.5 Spacing (adds blank lines before inserting)
-----------------------------------------------

[](#15-spacing-adds-blank-lines-before-inserting)

```
$writer->after('APP_ENV')->spacing(2)->set('API_KEY', 'xyz');
```

---

1.6 Insert at TOP or BOTTOM
---------------------------

[](#16-insert-at-top-or-bottom)

```
$writer->top()->set('HEADER', '1');
$writer->bottom()->set('FOOTER', '9');
```

---

1.7 Array-style positioning
---------------------------

[](#17-array-style-positioning)

```
$writer->set('TOKEN', 'abc', position: ['after' => 'API_KEY'], spacing: 1);
```

---

1.8 Remove a key
----------------

[](#18-remove-a-key)

```
$writer->remove('DB_USER');
```

---

1.9 Import multiple keys
------------------------

[](#19-import-multiple-keys)

```
$writer->import([
    'A' => '1',
    'B' => '2'
]);
```

---

1.10 Export env to array
------------------------

[](#110-export-env-to-array)

```
$array = $writer->toArray();
```

---

1.11 Save (atomic &amp; non-atomic)
-----------------------------------

[](#111-save-atomic--non-atomic)

```
$writer->save();                  // atomic
$writer->save(atomic: false);     // simple write
```

---

1.12 Preview without saving
---------------------------

[](#112-preview-without-saving)

```
echo $writer->preview();
```

---

1.13 Backup &amp; Restore
-------------------------

[](#113-backup--restore)

```
$writer->backup('.env.bak');
$writer->restore('.env.bak');
```

---

1.14 Diff
---------

[](#114-diff)

```
$diff = $writer->diff('.env.example');
```

Returns:

```
[
  'missing_in_current' => [...],
  'extra_in_current' => [...],
  'changed' => [
      KEY => ['current' => X, 'other' => Y]
  ]
]

```

---

1.15 Merge
----------

[](#115-merge)

```
$writer->merge('.env.example', overrideExisting: false);
```

overrideExisting:

- **false** (default): keep the value already in your current .env file.
- **true:** replace the value in your current .env with the value from the other file.

Example:
Current .env has : APP\_ENV=production
other file has : APP\_ENV=local

**merge(..., false)** -&gt; keeps the value from your current .env ("production")
**merge(..., true)** -&gt; replaces it with the value from the other file ("local")

---

2. DOTENV PARSER
================

[](#2-dotenv-parser)

Inline comments preserved
-------------------------

[](#inline-comments-preserved)

```
APP_NAME=MyApp # comment

```

export` keyword support
-----------------------

[](#export-keyword-support)

```
export APP_KEY=123

```

Multiline values
----------------

[](#multiline-values)

```
PRIVATE_KEY="-----BEGIN-----
LINE1
LINE2
-----END-----"

```

Escapes recognized
------------------

[](#escapes-recognized)

- \\n
- \\r
- \\t
- \\
- "

Key validation
--------------

[](#key-validation)

Key must match:

```
/^[A-Za-z0-9_.:-]+$/

```

---

3. VALUE FORMATTER
==================

[](#3-value-formatter)

Ensures correct `.env` formatting.

Auto-quotes values containing:
------------------------------

[](#auto-quotes-values-containing)

- spaces
- tabs
- newline
- `#`

Escape rules
------------

[](#escape-rules)

```
\ → \
" → \"

 → \n

 → \r
	 → \t

```

---

4. ENV LOADER
=============

[](#4-env-loader)

Loads parsed env into:

- putenv()
- $\_ENV
- $\_SERVER

### Example:

[](#example)

```
$loader = new EnvLoader('.env');
$loader->load(true);
```

---

5. ENV SCHEMA – COMPLETE VALIDATOR
==================================

[](#5-env-schema--complete-validator)

```
$schema = EnvSchema::make()
    ->required('APP_NAME', 'DB_HOST')
    ->optional('DEBUG', 'false')
    ->int('DB_PORT')
    ->bool('DEBUG');
```

---

Type Casts
----------

[](#type-casts)

MethodResult`int()`converts "123" → 123`float()`"1.5" → 1.5`bool()`"true" → true`array()`"a,b,c" → \['a','b','c'\]`json()`'{"a":1}' → \['a'=&gt;1\]`castEnum()`"A" → Enum::A---

Validation Rules
----------------

[](#validation-rules)

```
$rules = $schema->rules();

$rules->min('PORT', 1000);
$rules->max('PORT', 9000);
$rules->regex('API_KEY', '/^[A-Z]+$/');
$rules->in('APP_ENV', ['local','prod']);
$rules->length('TOKEN', 32);
```

---

Schema Groups
-------------

[](#schema-groups)

```
$schema->group('DB_', function (EnvSchema $db) {
    $db->required('HOST', 'USER');
    $db->optional('PORT', '3306')->int('PORT');
});
```

Generates:

- DB\_HOST
- DB\_USER
- DB\_PORT

---

6. CONFIG FACTORY – DTO BUILDER
===============================

[](#6-config-factory--dto-builder)

```
$factory = new EnvConfigFactory($schema, $writer);
$config = $factory->make(AppConfig::class);
```

```
final class AppConfig
{
    public function __construct(
      public string $appName,
      public int $dbPort,
      public bool $debug
    ) {}
}
```

---

7. VANILLA PHP INTEGRATION
==========================

[](#7-vanilla-php-integration)

AppConfig.php (DTO class)
-------------------------

[](#appconfigphp-dto-class)

```
final class AppConfig
{
    public function __construct(
        public string $appName,  // maps to APP_NAME
        public int    $dbPort,   // maps to DB_PORT
        public bool   $debug     // maps to DEBUG
    ) {}
}
```

Loading .env and creating config
--------------------------------

[](#loading-env-and-creating-config)

```
require 'vendor/autoload.php';

use VilnisGr\EnvEditor\Writer\DotenvWriter;
use VilnisGr\EnvEditor\Schema\EnvSchema;
use VilnisGr\EnvEditor\Schema\EnvConfigFactory;

$writer = new DotenvWriter();
$writer->load('.env');

$schema = EnvSchema::make()
    ->required('APP_NAME')
    ->int('DB_PORT')
    ->bool('DEBUG');

$config = (new EnvConfigFactory($schema, $writer))
    ->make(AppConfig::class);
```

Retrieving env values (3 different ways)
----------------------------------------

[](#retrieving-env-values-3-different-ways)

---

**1. From the writer (raw .env, uncasted)**

```
$env = $writer->toArray();
echo $env['APP_NAME'];
```

---

**2. From the typed DTO**

```
echo $config->appName;   // string
echo $config->dbPort;    // int
echo $config->debug;     // bool
```

---

**3. From PHP runtime environment (after EnvLoader)**

```
use VilnisGr\EnvEditor\Loader\EnvLoader;

$loader = new EnvLoader('.env');
$loader->load(true); // true = overwrite system env vars

echo getenv('APP_NAME');   // string
echo $_ENV['APP_NAME'];    // string
echo $_SERVER['APP_NAME']; // string
```

When to use which?
------------------

[](#when-to-use-which)

- **Writer** → for manipulating the .env file itself.
- **Config DTO** → for application configuration, type-safe, validated.
- **getenv() / $\_ENV** → when you need global system-level env variables.

---

8. FULL LIST OF ALL PUBLIC METHODS
==================================

[](#8-full-list-of-all-public-methods)

Writer Methods
--------------

[](#writer-methods)

MethodDescription`load()`Load a `.env` file into the writer.`set()`Add or update a key with optional position &amp; spacing.`remove()`Remove a key from the file.`save()`Save the file (atomic or non-atomic).`preview()`Get the output without writing to disk.`toArray()`Export all env entries as `key => value`.`import()`Import an associative array of values.`has()`Check if a key exists.`missingKeys()`Return keys missing from the file.`backup()`Create a backup of the env file.`restore()`Restore from a backup.`diff()`Compare against another env file.`merge()`Merge another env file into the current one.`after()`Insert the next `set()` after a specific key.`before()`Insert the next `set()` before a specific key.`top()`Insert the next `set()` at the top.`bottom()`Insert the next `set()` at the bottom.`spacing()`Add blank lines before inserting with `set()`.Schema Methods
--------------

[](#schema-methods)

MethodDescription`required()`Define keys that must appear in the env.`optional()`Define optional keys with default values.`cast()`Cast a key using a specific type (`int`, `bool`, etc.).`bool()`Convenience method: cast to boolean.`int()`Convenience method: cast to integer.`float()`Cast to float.`array()`Cast comma-separated lists to arrays.`json()`Cast values to decoded JSON arrays.`castEnum()`Cast value into a PHP backed enum.`rules()`Get the rules object for adding validation rules.`group()`Create grouped/namespaced schemas (e.g., `DB_HOST`).`validate()`Validate &amp; cast writer values based on schema.Rules Methods
-------------

[](#rules-methods)

MethodDescription`add()`Add a custom validation rule (callable).`validate()`Validate a value against all rules for a key.`min()`Require numeric value &gt;= minimum.`max()`Require numeric value &lt;= maximum.`in()`Require value to be in a fixed allow-list.`regex()`Require value to match a regular expression.`length()`Require string length to be between `[min,max]`.`export()`Export all rules for use in grouped schemas.ConfigFactory Methods
---------------------

[](#configfactory-methods)

MethodDescription`make()`Build a typed configuration DTO from validated environment variables.---

License, Author &amp; Support
=============================

[](#license-author--support)

EnvEditor - Complete .env Toolkit for PHP
Maintained by: VilnisGrinbergs2000
License: MIT (Free for commercial and private use)
Source Code &amp; Issues:

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance68

Regular maintenance activity

Popularity5

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 92.3% 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

Unknown

Total

1

Last Release

184d ago

### Community

Maintainers

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

---

Top Contributors

[![VilnisGrinbergs2000](https://avatars.githubusercontent.com/u/240248446?v=4)](https://github.com/VilnisGrinbergs2000 "VilnisGrinbergs2000 (12 commits)")[![vilnisgrinbergs](https://avatars.githubusercontent.com/u/141155995?v=4)](https://github.com/vilnisgrinbergs "vilnisgrinbergs (1 commits)")

---

Tags

atomic-writeconfig-dtoconfig-factoryconfiguration-librarydotenvdotenv-loaderdotenv-managerenv-editorenv-parserenv-schemaenv-writerenvironment-variablesmultiline-envphpphp-8-3validationschemavalidationconfigfluentenvdotenvdto

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/vilnisgr-env-editor/health.svg)

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

###  Alternatives

[opis/json-schema

Json Schema Validator for PHP

64736.9M186](/packages/opis-json-schema)[wendelladriel/laravel-validated-dto

Data Transfer Objects with validation for Laravel applications

759569.4k13](/packages/wendelladriel-laravel-validated-dto)[ashallendesign/laravel-config-validator

A package for validating your Laravel app's config.

217905.3k5](/packages/ashallendesign-laravel-config-validator)[romaricdrigon/metayaml

Using \[Yaml|Xml|json\] schemas files to validate \[Yaml|Xml|json\]

103306.5k8](/packages/romaricdrigon-metayaml)[lionix/envclient

Laravel environment client and console commands.

1621.5k](/packages/lionix-envclient)[evaisse/php-json-schema-generator

A JSON Schema Generator.

20298.5k1](/packages/evaisse-php-json-schema-generator)

PHPackages © 2026

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